Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the code snippet: <|code_start|> limit=limit, sort_keys=sort_keys, sort_dirs=sort_dirs, fields=fields, filters=filters ) return self._list(url % query_string, response_key='tasks') def get(self, id): self._ensure_not_empty(id=id) return self._get('/tasks/%s' % id) def get_task_sub_executions(self, id, errors_only='', max_depth=-1): task_sub_execs_path = '/tasks/%s/executions%s' params = '?max_depth=%s&errors_only=%s' % (max_depth, errors_only) return self._list( task_sub_execs_path % (id, params), response_key='executions', returned_res_cls=executions.Execution ) def rerun(self, task_ex_id, reset=True, env=None): url = '/tasks/%s' % task_ex_id body = { 'id': task_ex_id, 'state': 'RUNNING', <|code_end|> , generate the next line using the imports in this file: from oslo_serialization import jsonutils from mistralclient.api import base from mistralclient.api.v2 import executions and context (functions, classes, or occasionally code) from other files: # Path: mistralclient/api/base.py # class Resource(object): # class ResourceManager(object): # class APIException(Exception): # def __init__(self, manager, data): # def _set_defaults(self): # def _set_attributes(self): # def to_dict(self): # def __str__(self): # def _check_items(obj, searches): # def extract_json(response, response_key): # def __init__(self, http_client, enforce_raw_definitions=False): # def get_contents_if_file(self, contents_or_file_name): # def find(self, **kwargs): # def list(self): # def _build_query_params(marker=None, limit=None, sort_keys=None, # sort_dirs=None, fields=None, filters=None, # scope=None, namespace=None): # def _ensure_not_empty(self, **kwargs): # def _validate(self, url, data, response_key=None, dump_json=True, # headers=None, is_iter_resp=False): # def _create(self, url, data, response_key=None, dump_json=True, # headers=None, is_iter_resp=False, resp_status_ok=201, # as_class=True): # def _update(self, url, data, response_key=None, dump_json=True, # headers=None, is_iter_resp=False): # def _list(self, url, response_key=None, headers=None, # returned_res_cls=None): # def _get(self, url, response_key=None, headers=None): # def _delete(self, url, headers=None): # def _raise_api_exception(resp): # def get_json(response): # def __init__(self, error_code=None, error_message=None): # # Path: mistralclient/api/v2/executions.py # class Execution(base.Resource): # class ExecutionManager(base.ResourceManager): # def create(self, wf_identifier='', namespace='', # workflow_input=None, description='', source_execution_id=None, # **params): # def update(self, id, state, description=None, env=None): # def list(self, task=None, marker='', limit=None, sort_keys='', # sort_dirs='', fields='', **filters): # def get(self, id): # def get_ex_sub_executions(self, id, errors_only='', max_depth=-1): # def delete(self, id, force=None): # def get_report(self, id, errors_only=True, max_depth=None, # statistics_only=False): . Output only the next line.
'reset': reset
Predict the next line after this snippet: <|code_start|> def send_ladder_emails(): # search current season ladders that have result in last 24 hours season = Season.objects.latest('start_date') print(season) ladders = season.ladder_set.all() # iterate through subscriptions and send email <|code_end|> using the current file's imports: import datetime from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.template.loader import get_template from ladder.models import Season, LadderSubscription from tennis.settings import SUBSCRIPTION_EMAIL and any relevant context from other files: # Path: ladder/models.py # class Season(models.Model): # name = models.CharField(max_length=150) # start_date = models.DateField('Start date') # end_date = models.DateField('End date') # season_round = models.IntegerField() # # class Meta: # ordering = ['-start_date',] # # def __str__(self): # return str(self.start_date.year) + ' Round ' + str(self.season_round) # # def get_stats(self): # """ # Generates the season stats # """ # player_count = 0 # results_count = 0 # total_games_count = 0.0 # for ladder in self.ladder_set.all(): # player_count += ladder.league_set.count() # results_count += ladder.result_set.count() / 2 # total_games_count += (ladder.league_set.count() * (ladder.league_set.count() - 1)) / 2 # # percentage_played = (results_count / total_games_count) * 100 # # return { # 'divisions': self.ladder_set.count(), # 'percentage_played': "{0:.2f}".format(percentage_played), # 'total_games_count': total_games_count, # 'results_count': results_count, # 'player_count': player_count # } # # def get_leader_stats(self, user): # """ # Generates the list of leaders for current season # """ # current_leaders = {} # # for ladder in self.ladder_set.all(): # current_leaders[ladder.id] = ladder.get_leader(user=user) # # return { # 'current_leaders': current_leaders, # } # # def get_progress(self): # """ # Query how many games have been played so far. # """ # results = Result.objects.raw(""" # SELECT ladder_result.id, ladder_id, season_id, date_added, COUNT(*) AS added_count # FROM ladder_result LEFT JOIN ladder_ladder # ON ladder_result.ladder_id=ladder_ladder.id # WHERE season_id = %s GROUP BY DATE(date_added) # ORDER BY DATE(date_added) ASC; # """, [self.id]) # # leagues = League.objects.raw(""" # SELECT ladder_league.id, COUNT(*) AS player_count # FROM ladder_league LEFT JOIN ladder_ladder # ON ladder_league.ladder_id=ladder_ladder.id # WHERE season_id = %s GROUP BY ladder_id; # """, [self.id]) # # played = [] # played_days = [] # played_cumulative = [] # played_cumulative_count = 0 # latest_result = False # # for result in results: # played.append(result.added_count) # played_days.append((result.date_added - self.start_date).days) # # played_cumulative_count += result.added_count / 2 # played_cumulative.append(played_cumulative_count) # latest_result = result.date_added # # total_matches = 0 # for league in leagues: # total_matches += (league.player_count-1) * league.player_count / 2 # # return { # "season_days": [0, (self.end_date - self.start_date).days], # "season_total_matches": [0, total_matches], # "played_days": played_days, # "played": played, # "played_cumulative": played_cumulative, # "latest_result": latest_result.strftime("%B %d, %Y") if latest_result else "-" # } # # class LadderSubscription(models.Model): # ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE) # user = models.ForeignKey(User, on_delete=models.CASCADE) # subscribed_at = models.DateField() # # def __str__(self): # return self.user.email # # Path: tennis/settings.py # SUBSCRIPTION_EMAIL = os.environ.get('SUBSCRIPTION_EMAIL') . Output only the next line.
for ladder in ladders:
Next line prediction: <|code_start|> def send_ladder_emails(): # search current season ladders that have result in last 24 hours season = Season.objects.latest('start_date') print(season) ladders = season.ladder_set.all() # iterate through subscriptions and send email for ladder in ladders: print(ladder) # check ladder has results date_from = datetime.datetime.now() - datetime.timedelta(days=1) if ladder.result_set.filter(date_added__gte=date_from).count() == 0: print('No results in past day') continue subscriptions = ladder.laddersubscription_set.all() <|code_end|> . Use current file imports: (import datetime from django.core.management.base import BaseCommand from django.core.mail import EmailMessage from django.template.loader import get_template from ladder.models import Season, LadderSubscription from tennis.settings import SUBSCRIPTION_EMAIL) and context including class names, function names, or small code snippets from other files: # Path: ladder/models.py # class Season(models.Model): # name = models.CharField(max_length=150) # start_date = models.DateField('Start date') # end_date = models.DateField('End date') # season_round = models.IntegerField() # # class Meta: # ordering = ['-start_date',] # # def __str__(self): # return str(self.start_date.year) + ' Round ' + str(self.season_round) # # def get_stats(self): # """ # Generates the season stats # """ # player_count = 0 # results_count = 0 # total_games_count = 0.0 # for ladder in self.ladder_set.all(): # player_count += ladder.league_set.count() # results_count += ladder.result_set.count() / 2 # total_games_count += (ladder.league_set.count() * (ladder.league_set.count() - 1)) / 2 # # percentage_played = (results_count / total_games_count) * 100 # # return { # 'divisions': self.ladder_set.count(), # 'percentage_played': "{0:.2f}".format(percentage_played), # 'total_games_count': total_games_count, # 'results_count': results_count, # 'player_count': player_count # } # # def get_leader_stats(self, user): # """ # Generates the list of leaders for current season # """ # current_leaders = {} # # for ladder in self.ladder_set.all(): # current_leaders[ladder.id] = ladder.get_leader(user=user) # # return { # 'current_leaders': current_leaders, # } # # def get_progress(self): # """ # Query how many games have been played so far. # """ # results = Result.objects.raw(""" # SELECT ladder_result.id, ladder_id, season_id, date_added, COUNT(*) AS added_count # FROM ladder_result LEFT JOIN ladder_ladder # ON ladder_result.ladder_id=ladder_ladder.id # WHERE season_id = %s GROUP BY DATE(date_added) # ORDER BY DATE(date_added) ASC; # """, [self.id]) # # leagues = League.objects.raw(""" # SELECT ladder_league.id, COUNT(*) AS player_count # FROM ladder_league LEFT JOIN ladder_ladder # ON ladder_league.ladder_id=ladder_ladder.id # WHERE season_id = %s GROUP BY ladder_id; # """, [self.id]) # # played = [] # played_days = [] # played_cumulative = [] # played_cumulative_count = 0 # latest_result = False # # for result in results: # played.append(result.added_count) # played_days.append((result.date_added - self.start_date).days) # # played_cumulative_count += result.added_count / 2 # played_cumulative.append(played_cumulative_count) # latest_result = result.date_added # # total_matches = 0 # for league in leagues: # total_matches += (league.player_count-1) * league.player_count / 2 # # return { # "season_days": [0, (self.end_date - self.start_date).days], # "season_total_matches": [0, total_matches], # "played_days": played_days, # "played": played, # "played_cumulative": played_cumulative, # "latest_result": latest_result.strftime("%B %d, %Y") if latest_result else "-" # } # # class LadderSubscription(models.Model): # ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE) # user = models.ForeignKey(User, on_delete=models.CASCADE) # subscribed_at = models.DateField() # # def __str__(self): # return self.user.email # # Path: tennis/settings.py # SUBSCRIPTION_EMAIL = os.environ.get('SUBSCRIPTION_EMAIL') . Output only the next line.
for subscription in subscriptions:
Here is a snippet: <|code_start|> class AddResultForm(forms.ModelForm): result = forms.IntegerField(min_value=0, max_value=8, label='Losing Result') # filter the player fields by ladder on init def __init__(self, ladder, *args, **kwargs): super(AddResultForm, self).__init__(*args, **kwargs) # populates the post self.fields['opponent'].queryset = self.fields['player'].queryset = Player.objects.filter(league__ladder=ladder) class Meta(object): model = Result <|code_end|> . Write the next line using the current file imports: from django import forms from ladder.models import Result, Player and context from other files: # Path: ladder/models.py # class Result(models.Model): # ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE) # player = models.ForeignKey(Player,on_delete=models.CASCADE, related_name='result_player') # opponent = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='result_opponent') # result = models.IntegerField() # date_added = models.DateField('Date added') # inaccurate_flag = models.BooleanField(default=None) # # def __str__(self): # return (self.player.first_name + ' ' + self.player.last_name) + ' vs ' + ( # self.opponent.first_name + ' ' + self.opponent.last_name) + (' score: ' + str(self.result)) # # class Player(models.Model): # first_name = models.CharField(max_length=100) # last_name = models.CharField(max_length=100) # user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True) # # def __str__(self): # return self.full_name(authenticated=False) # # def full_name(self, authenticated = False): # string = self.first_name # if self.last_name: # last_names = self.last_name.split() # if not authenticated: # last_names[-1] = last_names[-1][:1].capitalize() + '.' # abbreviate last name # string += ' ' + ' '.join(last_names) # # return string # # def player_stats(self): # """ # Calculates stats about the players historical performance. # """ # played = self.result_player.count() # won = float(self.result_player.filter(result=9).count()) # lost = played - won # more efficient than doing a count on the object # # # safe division (not by 0) # if played != 0: # win_rate = won / float(played) * 100.00 # # 2 points for winning, 1 for playing # additional_points = ((won * 2) + played) / played # else: # return { # 'played': "-", # 'win_rate': "- %", # 'average': "-" # } # # # work out the average with additional points # average = list(self.result_player.aggregate(Avg('result')).values())[0] # average_with_additional = average + additional_points # # leagues = self.league_set.filter(player=self) # # match_count = 0 # for league in leagues: # # count other players in ladder minus the player to get games # match_count += league.ladder.league_set.count() - 1 # # completion_rate = float(played) / float(match_count) * 100.00 # # return { # 'played': played, # 'win_rate': "{0:.2f} %".format(win_rate), # 'completion_rate': "{0:.2f} %".format(completion_rate), # 'average': "{0:.2f}".format(average_with_additional) # } , which may include functions, classes, or code. Output only the next line.
exclude = ['date_added', 'ladder']
Predict the next line after this snippet: <|code_start|> class AddResultForm(forms.ModelForm): result = forms.IntegerField(min_value=0, max_value=8, label='Losing Result') # filter the player fields by ladder on init def __init__(self, ladder, *args, **kwargs): super(AddResultForm, self).__init__(*args, **kwargs) # populates the post self.fields['opponent'].queryset = self.fields['player'].queryset = Player.objects.filter(league__ladder=ladder) <|code_end|> using the current file's imports: from django import forms from ladder.models import Result, Player and any relevant context from other files: # Path: ladder/models.py # class Result(models.Model): # ladder = models.ForeignKey(Ladder, on_delete=models.CASCADE) # player = models.ForeignKey(Player,on_delete=models.CASCADE, related_name='result_player') # opponent = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='result_opponent') # result = models.IntegerField() # date_added = models.DateField('Date added') # inaccurate_flag = models.BooleanField(default=None) # # def __str__(self): # return (self.player.first_name + ' ' + self.player.last_name) + ' vs ' + ( # self.opponent.first_name + ' ' + self.opponent.last_name) + (' score: ' + str(self.result)) # # class Player(models.Model): # first_name = models.CharField(max_length=100) # last_name = models.CharField(max_length=100) # user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True) # # def __str__(self): # return self.full_name(authenticated=False) # # def full_name(self, authenticated = False): # string = self.first_name # if self.last_name: # last_names = self.last_name.split() # if not authenticated: # last_names[-1] = last_names[-1][:1].capitalize() + '.' # abbreviate last name # string += ' ' + ' '.join(last_names) # # return string # # def player_stats(self): # """ # Calculates stats about the players historical performance. # """ # played = self.result_player.count() # won = float(self.result_player.filter(result=9).count()) # lost = played - won # more efficient than doing a count on the object # # # safe division (not by 0) # if played != 0: # win_rate = won / float(played) * 100.00 # # 2 points for winning, 1 for playing # additional_points = ((won * 2) + played) / played # else: # return { # 'played': "-", # 'win_rate': "- %", # 'average': "-" # } # # # work out the average with additional points # average = list(self.result_player.aggregate(Avg('result')).values())[0] # average_with_additional = average + additional_points # # leagues = self.league_set.filter(player=self) # # match_count = 0 # for league in leagues: # # count other players in ladder minus the player to get games # match_count += league.ladder.league_set.count() - 1 # # completion_rate = float(played) / float(match_count) * 100.00 # # return { # 'played': played, # 'win_rate': "{0:.2f} %".format(win_rate), # 'completion_rate': "{0:.2f} %".format(completion_rate), # 'average': "{0:.2f}".format(average_with_additional) # } . Output only the next line.
class Meta(object):
Predict the next line for this snippet: <|code_start|> router = routers.DefaultRouter() router.register('seasons', views.SeasonViewSet) router.register('players', views.PlayerViewSet) router.register('ladders', views.LadderViewSet) router.register('leagues', views.LeagueViewSet) router.register('results', views.ResultViewSet) <|code_end|> with the help of current file imports: from django.urls import include, path from rest_framework import routers from ladder.api import views and context from other files: # Path: ladder/api/views.py # class SeasonViewSet(viewsets.ModelViewSet): # class PlayerViewSet(viewsets.ModelViewSet): # class LadderViewSet(viewsets.ModelViewSet): # class LeagueViewSet(viewsets.ModelViewSet): # class ResultViewSet(viewsets.ModelViewSet): , which may contain function names, class names, or code. Output only the next line.
urlpatterns = [
Given the following code snippet before the placeholder: <|code_start|> # python manage.py shell < ladder/management/shell/import_users.py # format first_name, last_name, email players = [ ["John", "Doe", "jo@hn.doe"], ] group_object = Group.objects.get(name='player') for player in players: first_name = player[0] last_name = player[1] email = player[2] if not email: print(first_name + " " + last_name + ": No Email") continue if User.objects.filter(username=email).exists(): user_object = User.objects.get_by_natural_key(email) else: user_object = User( username=email, email=email, first_name=first_name, last_name=last_name, <|code_end|> , predict the next line using imports from the current file: from django.contrib.auth.models import User, Group from ladder.models import Player import uuid and context including class names, function names, and sometimes code from other files: # Path: ladder/models.py # class Player(models.Model): # first_name = models.CharField(max_length=100) # last_name = models.CharField(max_length=100) # user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, blank=True) # # def __str__(self): # return self.full_name(authenticated=False) # # def full_name(self, authenticated = False): # string = self.first_name # if self.last_name: # last_names = self.last_name.split() # if not authenticated: # last_names[-1] = last_names[-1][:1].capitalize() + '.' # abbreviate last name # string += ' ' + ' '.join(last_names) # # return string # # def player_stats(self): # """ # Calculates stats about the players historical performance. # """ # played = self.result_player.count() # won = float(self.result_player.filter(result=9).count()) # lost = played - won # more efficient than doing a count on the object # # # safe division (not by 0) # if played != 0: # win_rate = won / float(played) * 100.00 # # 2 points for winning, 1 for playing # additional_points = ((won * 2) + played) / played # else: # return { # 'played': "-", # 'win_rate': "- %", # 'average': "-" # } # # # work out the average with additional points # average = list(self.result_player.aggregate(Avg('result')).values())[0] # average_with_additional = average + additional_points # # leagues = self.league_set.filter(player=self) # # match_count = 0 # for league in leagues: # # count other players in ladder minus the player to get games # match_count += league.ladder.league_set.count() - 1 # # completion_rate = float(played) / float(match_count) * 100.00 # # return { # 'played': played, # 'win_rate': "{0:.2f} %".format(win_rate), # 'completion_rate': "{0:.2f} %".format(completion_rate), # 'average': "{0:.2f}".format(average_with_additional) # } . Output only the next line.
is_staff=False,
Given the following code snippet before the placeholder: <|code_start|> urlpatterns = [ re_path(r'^$', views.index, name='index'), re_path(r'^list/$', views.list_rounds, name='list'), re_path(r'^current/$', views.current_season_redirect, name='current'), # ex: /2013/round/1/ re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/$', views.season, name='season'), # ex: /2013/round/1/division/1-n re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/$', views.ladder, name='ladder'), # ex: /2013/round/1/division/1-n/add/ re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/add/$', views.add, name='add'), # ex: /2013/round/1/division/1-n/subscription/ re_path(r'^(?P<year>\d+)/round/(?P<season_round>\d+)/division/(?P<division_id>\w+)/subscription/$', views.ladder_subscription, name='ladder_subscription'), # ex: /head_to_head/1/vs/2 re_path(r'^head_to_head/(?P<player_id>\d+)/vs/(?P<opponent_id>\w+)/$', views.head_to_head, name='head_to_head'), # ex: /player/1/ re_path(r'^player/(?P<player_id>\d+)/$', views.player_history, name='player_history'), # ex: /player/ re_path(r'^player/search/$', views.player_search, name='player_search'), re_path(r'^player/h2h/(?P<player_id>\d+)/$', views.h2h_search, name='h2h_search'), re_path(r'^player/results/$', views.player_result, name='player_result'), re_path(r'^season/ajax/stats/$', views.season_ajax_stats, name='season_ajax_stats'), re_path(r'^season/ajax/progress/$', views.season_ajax_progress, name='season_ajax_progress'), re_path(r'^result/entry/$', views.result_entry, name='result_entry'), re_path(r'^result/entry/add/$', views.result_entry_add, name='result_entry_add'), <|code_end|> , predict the next line using imports from the current file: from django.urls import re_path from ladder import views and context including class names, function names, and sometimes code from other files: # Path: ladder/views.py # def index(request): # def list_rounds(request): # def current_season_redirect(request): # def season(request, year, season_round): # def ladder(request, year, season_round, division_id): # def ladder_subscription(request, year, season_round, division_id): # def add(request, year, season_round, division_id): # def player_history(request, player_id): # def head_to_head(request, player_id, opponent_id): # def player_result(request): # def player_search(request): # def h2h_search(request, player_id): # def season_ajax_stats(request): # def season_ajax_progress(request): # def result_entry(request): # def result_entry_add(request): . Output only the next line.
]
Given the code snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] <|code_end|> , generate the next line using the imports in this file: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context (functions, classes, or occasionally code) from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): . Output only the next line.
__license__ = "GPL"
Here is a snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Jesse Zaneveld" __email__ = "zaneveld@gmail.com" <|code_end|> . Write the next line using the current file imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): , which may include functions, classes, or code. Output only the next line.
__status__ = "Development"
Given snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" <|code_end|> , continue by predicting the next line. Consider current file imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): which might include code, classes, or functions. Output only the next line.
__maintainer__ = "Jesse Zaneveld"
Based on the snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" <|code_end|> , predict the immediate next line with the help of imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context (classes, functions, sometimes code) from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): . Output only the next line.
__version__ = "1.1.4"
Given the code snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" <|code_end|> , generate the next line using the imports in this file: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context (functions, classes, or occasionally code) from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): . Output only the next line.
__maintainer__ = "Jesse Zaneveld"
Continue the code snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] <|code_end|> . Use current file imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context (classes, functions, or code) from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): . Output only the next line.
__license__ = "GPL"
Continue the code snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Jesse Zaneveld" <|code_end|> . Use current file imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context (classes, functions, or code) from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): . Output only the next line.
__email__ = "zaneveld@gmail.com"
Given snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" <|code_end|> , continue by predicting the next line. Consider current file imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): which might include code, classes, or functions. Output only the next line.
__maintainer__ = "Jesse Zaneveld"
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Jesse Zaneveld" <|code_end|> , predict the next line using imports from the current file: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context including class names, function names, and sometimes code from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): . Output only the next line.
__email__ = "zaneveld@gmail.com"
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Jesse Zaneveld"] <|code_end|> with the help of current file imports: from cogent.util.unit_test import main, TestCase from cogent import LoadTree from cogent.parse.tree import DndParser from picrust.format_tree_and_trait_table import reformat_tree_and_trait_table,\ nexus_lines_from_tree,add_branch_length_to_root,\ set_min_branch_length,make_nexus_trees_block,\ filter_table_by_presence_in_tree,convert_trait_table_entries,\ yield_trait_table_fields,ensure_root_is_bifurcating,\ filter_tree_tips_by_presence_in_table,print_node_summary_table,\ add_to_filename,make_id_mapping_dict,make_translate_conversion_fn,\ make_char_translation_fn,remove_spaces, format_tree_node_names and context from other files: # Path: picrust/format_tree_and_trait_table.py # def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\ # input_trait_table_delimiter="\t", output_trait_table_delimiter="\t",\ # filter_table_by_tree_tips=True, convert_trait_floats_to_ints=False,\ # filter_tree_by_table_entries=True,convert_to_bifurcating=False,\ # add_branch_length_to_root=False, name_unnamed_nodes=True,\ # remove_whitespace_from_labels = True,replace_ambiguous_states=True,\ # replace_problematic_label_characters = True,min_branch_length=0.0001,\ # verbose=True): # def check_node_labels(input_tree,verbose=False): # def set_label_conversion_fns(remove_whitespace_from_labels=True,\ # replace_problematic_label_characters=True,verbose=False): # def set_value_conversion_fns(replace_ambiguous_states=True,\ # convert_trait_floats_to_ints=False,verbose=False): # def fix_tree_labels(tree,label_conversion_fns,verbose=False): # def make_internal_nodes_unique(tree,base_name='internal_node_%i'): # def format_tree_node_names(tree,label_formatting_fns=[]): # def nexus_lines_from_tree(tree): # def add_branch_length_to_root(tree, root_name ="root",root_length=0.0001): # def set_min_branch_length(tree,min_length= 0.0001): # def make_nexus_trees_block(tree): # def validate_trait_table_to_tree_mappings(tree,trait_table_ids,verbose=True): # def filter_table_by_presence_in_tree(tree,trait_table_fields,name_field_index = 0,delimiter="\t"): # def make_translate_conversion_fn(translation_dict): # def translate_conversion_fn(trait_value_field): # def make_char_translation_fn(translation_dict,deletion_chars=''): # def translate_conversion_fn(trait_value_field): # def remove_spaces(trait_label_field): # def convert_trait_table_entries(trait_table_fields,\ # label_conversion_fns=[str],value_conversion_fns = [float]): # def ensure_root_is_bifurcating(tree,root_name='root',verbose=False): # def filter_tree_tips_by_presence_in_table(tree,trait_table_fields,name_field_index = 0,\ # delimiter="\t",verbose=True): # def get_sub_tree(tree,tips_not_to_prune): # def print_node_summary_table(input_tree): # def add_to_filename(filename,new_suffix,delimiter="_"): # def make_id_mapping_dict(tree_to_trait_mappings): # def parse_id_mapping_file(file_lines,delimiter="\t"): # def remap_trait_table_organisms(trait_table_fields,trait_to_tree_mapping_dict,verbose=False): # def load_picrust_tree(tree_fp, verbose=False): # def load_tab_delimited_trait_table(trait_table_fp,verbose=False): , which may contain function names, class names, or code. Output only the next line.
__license__ = "GPL"
Given snippet: <|code_start|> script_info['required_options'] = [\ make_option('-i','--input_dir',type="existing_dirpath",help='directory containing one or more test datasets'),\ make_option('-t','--ref_tree',type="existing_filepath",help='reference tree that was used with make_test_datasets'),\ ] # Choices for choice options parallel_method_choices=['sge','torque','multithreaded'] predict_traits_choices =['asr_and_weighting','nearest_neighbor','random_neighbor'] asr_choices = ['ace_ml', 'ace_reml', 'ace_pic', 'wagner'] weighting_choices = ['linear','exponential','equal'] script_info['optional_options'] = [\ make_option('-o','--output_dir',type="new_dirpath",help='the output directory [default: <input_dir>]'),\ make_option('-j','--parallel_method',type='choice',\ help='Method for parallelization. Valid choices are: '+\ ', '.join(parallel_method_choices) + ' [default: %default]',\ choices=parallel_method_choices,default='multithreaded'),\ make_option('-m','--prediction_method',type='choice',\ help='Method for trait prediction. See predict_traits.py for full documentation. Valid choices are: '+\ ', '.join(predict_traits_choices) + ' [default: %default]',\ choices=predict_traits_choices,default='asr_and_weighting'),\ make_option('--with_confidence',action='store_true',default=False,\ help='If set, calculate confidence intervals with ace_ml or ace_reml, and use confidence intervals in trait prediction'),\ make_option('--with_accuracy',action='store_true',default=False,\ help='If set, calculate accuracy using the NSTI (nearest sequenced taxon index) during trait prediction'),\ make_option('-a','--asr_method',type='choice',\ help='Method for ancestral_state_reconstruction. See ancestral_state_reconstruction.py for full documentation. Valid choices are: '+\ ', '.join(asr_choices) + ' [default: %default]',\ choices=asr_choices,default='wagner'),\ <|code_end|> , continue by predicting the next line. Consider current file imports: from cogent.util.option_parsing import parse_command_line_parameters, make_option from glob import glob from picrust.util import make_output_dir_for_file,file_contains_nulls from cogent.app.util import get_tmp_filename from picrust.util import get_picrust_project_dir,make_output_dir from picrust.parallel import submit_jobs, wait_for_output_files from os.path import join,exists from os import remove from re import split and context: # Path: picrust/util.py # def make_output_dir_for_file(filepath): # """Create sub-directories for a new file if they don't already exist""" # dirpath = dirname(filepath) # if not isdir(dirpath) and not dirpath == '': # makedirs(dirpath) # # def file_contains_nulls(file): # """Checks given file for null characters. These are sometimes created on SGE clusters when system IO is overloaded.""" # # return '\x00' in open(file,'rb').read() # # Path: picrust/util.py # def get_picrust_project_dir(): # """ Returns the top-level PICRUST directory # """ # # Get the full path of util.py # current_file_path = abspath(__file__) # # Get the directory containing util.py # current_dir_path = dirname(current_file_path) # # Return the directory containing the directory containing util.py # return dirname(current_dir_path) # # def make_output_dir(dirpath, strict=False): # """Make an output directory if it doesn't exist # # Returns the path to the directory # dirpath -- a string describing the path to the directory # strict -- if True, raise an exception if dir already # exists # """ # dirpath = abspath(dirpath) # # #Check if directory already exists # if isdir(dirpath): # if strict == True: # err_str = "Directory '%s' already exists" % dirpath # raise IOError(err_str) # # return dirpath # try: # makedirs(dirpath) # except IOError,e: # err_str = "Could not create directory '%s'. Are permissions set correctly? Got error: '%s'" %e # raise IOError(err_str) # # return dirpath # # Path: picrust/parallel.py # def submit_jobs(path_to_cluster_jobs, jobs_fp, job_prefix,num_jobs=100,delay=0): # """ Submit the jobs to the queue using cluster_jobs.py # """ # cmd = '%s -d %s -n %s -ms %s %s' % (path_to_cluster_jobs, delay, num_jobs, jobs_fp, job_prefix) # stdout, stderr, return_value = system_call(cmd) # if return_value != 0: # msg = "\n\n*** Could not start parallel jobs. \n" +\ # "Command run was:\n %s\n" % cmd +\ # "Command returned exit status: %d\n" % return_value +\ # "Stdout:\n%s\nStderr\n%s\n" % (stdout,stderr) # raise RuntimeError, msg # # # Leave this comments in as they're useful for debugging. # # print 'Return value: %d\n' % return_value # # print 'STDOUT: %s\n' % stdout # # print 'STDERR: %s\n' % stderr # # def wait_for_output_files(files): # ''' Function waits until all files exist in the filesystem''' # #make a copy of the list # waiting_files=list(files) # # #wait until nothing left in the list # while(waiting_files): # #wait 30 seconds between each check # sleep(30) # #check each file and keep ones that don't yet exist # waiting_files=filter(lambda x: not exists(x),waiting_files) which might include code, classes, or functions. Output only the next line.
make_option('-w','--weighting_method',type='choice',\
Given the code snippet: <|code_start|>weighting_choices = ['linear','exponential','equal'] script_info['optional_options'] = [\ make_option('-o','--output_dir',type="new_dirpath",help='the output directory [default: <input_dir>]'),\ make_option('-j','--parallel_method',type='choice',\ help='Method for parallelization. Valid choices are: '+\ ', '.join(parallel_method_choices) + ' [default: %default]',\ choices=parallel_method_choices,default='multithreaded'),\ make_option('-m','--prediction_method',type='choice',\ help='Method for trait prediction. See predict_traits.py for full documentation. Valid choices are: '+\ ', '.join(predict_traits_choices) + ' [default: %default]',\ choices=predict_traits_choices,default='asr_and_weighting'),\ make_option('--with_confidence',action='store_true',default=False,\ help='If set, calculate confidence intervals with ace_ml or ace_reml, and use confidence intervals in trait prediction'),\ make_option('--with_accuracy',action='store_true',default=False,\ help='If set, calculate accuracy using the NSTI (nearest sequenced taxon index) during trait prediction'),\ make_option('-a','--asr_method',type='choice',\ help='Method for ancestral_state_reconstruction. See ancestral_state_reconstruction.py for full documentation. Valid choices are: '+\ ', '.join(asr_choices) + ' [default: %default]',\ choices=asr_choices,default='wagner'),\ make_option('-w','--weighting_method',type='choice',\ help='Method for weighting during trait prediction. See predict_traits.py for full documentation. Valid choices are: '+\ ', '.join(weighting_choices) + ' [default: %default]',\ choices=weighting_choices,default='exponential'),\ make_option('-n','--num_jobs',action='store',type='int',\ help='Number of jobs to be submitted. [default: %default]',\ default=100),\ make_option('--tmp-dir',type="new_dirpath",help='location to store intermediate files [default: <output_dir>]'),\ make_option('--force',action='store_true',default=False, help='run all jobs even if output files exist [default: %default]'),\ make_option('--check_for_null_files',action='store_true',default=False, help='check if pre-existing output files have null files. If so remove them and re-run. [default: %default]') <|code_end|> , generate the next line using the imports in this file: from cogent.util.option_parsing import parse_command_line_parameters, make_option from glob import glob from picrust.util import make_output_dir_for_file,file_contains_nulls from cogent.app.util import get_tmp_filename from picrust.util import get_picrust_project_dir,make_output_dir from picrust.parallel import submit_jobs, wait_for_output_files from os.path import join,exists from os import remove from re import split and context (functions, classes, or occasionally code) from other files: # Path: picrust/util.py # def make_output_dir_for_file(filepath): # """Create sub-directories for a new file if they don't already exist""" # dirpath = dirname(filepath) # if not isdir(dirpath) and not dirpath == '': # makedirs(dirpath) # # def file_contains_nulls(file): # """Checks given file for null characters. These are sometimes created on SGE clusters when system IO is overloaded.""" # # return '\x00' in open(file,'rb').read() # # Path: picrust/util.py # def get_picrust_project_dir(): # """ Returns the top-level PICRUST directory # """ # # Get the full path of util.py # current_file_path = abspath(__file__) # # Get the directory containing util.py # current_dir_path = dirname(current_file_path) # # Return the directory containing the directory containing util.py # return dirname(current_dir_path) # # def make_output_dir(dirpath, strict=False): # """Make an output directory if it doesn't exist # # Returns the path to the directory # dirpath -- a string describing the path to the directory # strict -- if True, raise an exception if dir already # exists # """ # dirpath = abspath(dirpath) # # #Check if directory already exists # if isdir(dirpath): # if strict == True: # err_str = "Directory '%s' already exists" % dirpath # raise IOError(err_str) # # return dirpath # try: # makedirs(dirpath) # except IOError,e: # err_str = "Could not create directory '%s'. Are permissions set correctly? Got error: '%s'" %e # raise IOError(err_str) # # return dirpath # # Path: picrust/parallel.py # def submit_jobs(path_to_cluster_jobs, jobs_fp, job_prefix,num_jobs=100,delay=0): # """ Submit the jobs to the queue using cluster_jobs.py # """ # cmd = '%s -d %s -n %s -ms %s %s' % (path_to_cluster_jobs, delay, num_jobs, jobs_fp, job_prefix) # stdout, stderr, return_value = system_call(cmd) # if return_value != 0: # msg = "\n\n*** Could not start parallel jobs. \n" +\ # "Command run was:\n %s\n" % cmd +\ # "Command returned exit status: %d\n" % return_value +\ # "Stdout:\n%s\nStderr\n%s\n" % (stdout,stderr) # raise RuntimeError, msg # # # Leave this comments in as they're useful for debugging. # # print 'Return value: %d\n' % return_value # # print 'STDOUT: %s\n' % stdout # # print 'STDERR: %s\n' % stderr # # def wait_for_output_files(files): # ''' Function waits until all files exist in the filesystem''' # #make a copy of the list # waiting_files=list(files) # # #wait until nothing left in the list # while(waiting_files): # #wait 30 seconds between each check # sleep(30) # #check each file and keep ones that don't yet exist # waiting_files=filter(lambda x: not exists(x),waiting_files) . Output only the next line.
]
Given the code snippet: <|code_start|> predict_traits_accuracy_out_fp=join(output_dir,'--'.join(['predict_traits',predict_traits_method,\ opts.weighting_method,'accuracy_metrics',test_id])) if opts.check_for_null_files and exists(predict_traits_out_fp) and file_contains_nulls(predict_traits_out_fp): if opts.verbose: print "Existing trait predictions file contains null characters. Will run it again after removing: "+predict_traits_out_fp remove(predict_traits_out_fp) if exists(predict_traits_out_fp) and not opts.force: if opts.verbose: print "Prediction file: {0} already exists. Skipping ASR and prediction for this organism".format(predict_traits_out_fp) continue output_files.append(predict_traits_out_fp) genome_id=split('--',test_id)[2] if predict_traits_method == 'nearest_neighbor': #don't do asr step predict_traits_cmd= """python {0} -i "{1}" -t "{2}" -g "{3}" -o "{4}" -m "{5}" """.format(predict_traits_script_fp, test_datasets[test_id][0], opts.ref_tree, genome_id, predict_traits_out_fp,predict_traits_method) jobs.write(predict_traits_cmd+"\n") else: #create the predict traits command predict_traits_cmd= """python {0} -i "{1}" -t "{2}" -r "{3}" -g "{4}" -o "{5}" -m "{6}" -w {7} """.format(predict_traits_script_fp,\ test_datasets[test_id][0], opts.ref_tree, asr_out_fp,genome_id, predict_traits_out_fp,predict_traits_method,opts.weighting_method) #Instruct predict_traits to use confidence intervals output by ASR if opts.with_confidence: confidence_param = ' -c "%s"' %(asr_params_out_fp) <|code_end|> , generate the next line using the imports in this file: from cogent.util.option_parsing import parse_command_line_parameters, make_option from glob import glob from picrust.util import make_output_dir_for_file,file_contains_nulls from cogent.app.util import get_tmp_filename from picrust.util import get_picrust_project_dir,make_output_dir from picrust.parallel import submit_jobs, wait_for_output_files from os.path import join,exists from os import remove from re import split and context (functions, classes, or occasionally code) from other files: # Path: picrust/util.py # def make_output_dir_for_file(filepath): # """Create sub-directories for a new file if they don't already exist""" # dirpath = dirname(filepath) # if not isdir(dirpath) and not dirpath == '': # makedirs(dirpath) # # def file_contains_nulls(file): # """Checks given file for null characters. These are sometimes created on SGE clusters when system IO is overloaded.""" # # return '\x00' in open(file,'rb').read() # # Path: picrust/util.py # def get_picrust_project_dir(): # """ Returns the top-level PICRUST directory # """ # # Get the full path of util.py # current_file_path = abspath(__file__) # # Get the directory containing util.py # current_dir_path = dirname(current_file_path) # # Return the directory containing the directory containing util.py # return dirname(current_dir_path) # # def make_output_dir(dirpath, strict=False): # """Make an output directory if it doesn't exist # # Returns the path to the directory # dirpath -- a string describing the path to the directory # strict -- if True, raise an exception if dir already # exists # """ # dirpath = abspath(dirpath) # # #Check if directory already exists # if isdir(dirpath): # if strict == True: # err_str = "Directory '%s' already exists" % dirpath # raise IOError(err_str) # # return dirpath # try: # makedirs(dirpath) # except IOError,e: # err_str = "Could not create directory '%s'. Are permissions set correctly? Got error: '%s'" %e # raise IOError(err_str) # # return dirpath # # Path: picrust/parallel.py # def submit_jobs(path_to_cluster_jobs, jobs_fp, job_prefix,num_jobs=100,delay=0): # """ Submit the jobs to the queue using cluster_jobs.py # """ # cmd = '%s -d %s -n %s -ms %s %s' % (path_to_cluster_jobs, delay, num_jobs, jobs_fp, job_prefix) # stdout, stderr, return_value = system_call(cmd) # if return_value != 0: # msg = "\n\n*** Could not start parallel jobs. \n" +\ # "Command run was:\n %s\n" % cmd +\ # "Command returned exit status: %d\n" % return_value +\ # "Stdout:\n%s\nStderr\n%s\n" % (stdout,stderr) # raise RuntimeError, msg # # # Leave this comments in as they're useful for debugging. # # print 'Return value: %d\n' % return_value # # print 'STDOUT: %s\n' % stdout # # print 'STDERR: %s\n' % stderr # # def wait_for_output_files(files): # ''' Function waits until all files exist in the filesystem''' # #make a copy of the list # waiting_files=list(files) # # #wait until nothing left in the list # while(waiting_files): # #wait 30 seconds between each check # sleep(30) # #check each file and keep ones that don't yet exist # waiting_files=filter(lambda x: not exists(x),waiting_files) . Output only the next line.
predict_traits_cmd = predict_traits_cmd + confidence_param
Here is a snippet: <|code_start|>#!/usr/bin/env python # File created on 1 Feb 2012 from __future__ import division __author__ = "Morgan Langille" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Morgan Langille","Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Morgan Langille" __email__ = "morgan.g.i.langille@gmail.com" __status__ = "Development" script_info = {} script_info['brief_description'] = "Runs genome evaluations on PICRUSt. " <|code_end|> . Write the next line using the current file imports: from cogent.util.option_parsing import parse_command_line_parameters, make_option from glob import glob from picrust.util import make_output_dir_for_file,file_contains_nulls from cogent.app.util import get_tmp_filename from picrust.util import get_picrust_project_dir,make_output_dir from picrust.parallel import submit_jobs, wait_for_output_files from os.path import join,exists from os import remove from re import split and context from other files: # Path: picrust/util.py # def make_output_dir_for_file(filepath): # """Create sub-directories for a new file if they don't already exist""" # dirpath = dirname(filepath) # if not isdir(dirpath) and not dirpath == '': # makedirs(dirpath) # # def file_contains_nulls(file): # """Checks given file for null characters. These are sometimes created on SGE clusters when system IO is overloaded.""" # # return '\x00' in open(file,'rb').read() # # Path: picrust/util.py # def get_picrust_project_dir(): # """ Returns the top-level PICRUST directory # """ # # Get the full path of util.py # current_file_path = abspath(__file__) # # Get the directory containing util.py # current_dir_path = dirname(current_file_path) # # Return the directory containing the directory containing util.py # return dirname(current_dir_path) # # def make_output_dir(dirpath, strict=False): # """Make an output directory if it doesn't exist # # Returns the path to the directory # dirpath -- a string describing the path to the directory # strict -- if True, raise an exception if dir already # exists # """ # dirpath = abspath(dirpath) # # #Check if directory already exists # if isdir(dirpath): # if strict == True: # err_str = "Directory '%s' already exists" % dirpath # raise IOError(err_str) # # return dirpath # try: # makedirs(dirpath) # except IOError,e: # err_str = "Could not create directory '%s'. Are permissions set correctly? Got error: '%s'" %e # raise IOError(err_str) # # return dirpath # # Path: picrust/parallel.py # def submit_jobs(path_to_cluster_jobs, jobs_fp, job_prefix,num_jobs=100,delay=0): # """ Submit the jobs to the queue using cluster_jobs.py # """ # cmd = '%s -d %s -n %s -ms %s %s' % (path_to_cluster_jobs, delay, num_jobs, jobs_fp, job_prefix) # stdout, stderr, return_value = system_call(cmd) # if return_value != 0: # msg = "\n\n*** Could not start parallel jobs. \n" +\ # "Command run was:\n %s\n" % cmd +\ # "Command returned exit status: %d\n" % return_value +\ # "Stdout:\n%s\nStderr\n%s\n" % (stdout,stderr) # raise RuntimeError, msg # # # Leave this comments in as they're useful for debugging. # # print 'Return value: %d\n' % return_value # # print 'STDOUT: %s\n' % stdout # # print 'STDERR: %s\n' % stderr # # def wait_for_output_files(files): # ''' Function waits until all files exist in the filesystem''' # #make a copy of the list # waiting_files=list(files) # # #wait until nothing left in the list # while(waiting_files): # #wait 30 seconds between each check # sleep(30) # #check each file and keep ones that don't yet exist # waiting_files=filter(lambda x: not exists(x),waiting_files) , which may include functions, classes, or code. Output only the next line.
script_info['script_description'] = "\
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python # File created on 15 Jul 2011 from __future__ import division __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2015, The PICRUSt Project" __credits__ = ["Jesse Zaneveld", "Morgan Langille"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Jesse Zaneveld" __email__ = "zaneveld@gmail.com" __status__ = "Development" <|code_end|> , predict the next line using imports from the current file: from os.path import splitext from string import maketrans from sys import getrecursionlimit,setrecursionlimit from cogent.parse.tree import DndParser from cogent.util.option_parsing import parse_command_line_parameters,\ make_option from picrust.parse import parse_trait_table,yield_trait_table_fields from util import PicrustNode import re and context including class names, function names, and sometimes code from other files: # Path: picrust/parse.py # def parse_trait_table(trait_table_lines,delimiter="\t",has_header=True): # """Return a header line, and a generator that will yield data fields # # trait_table_lines -- tab-seperated lines that may have newline characters # # if has_header is True, then the first non-blank, non-comment line # must be a header line of equal length to the number of columns, with # labels for the contents of each column. # # Comment lines (starting with '#') and blank lines will be ignored, # and won't show up in the output. # """ # header_line = None # if not has_header: # header_line = '' # else: # for i,line in enumerate(trait_table_lines): # if not line or line.startswith("#"): # continue # if i == 0: # header_line = line # break # if header_line is None: # raise RuntimeError("Could not find header line in input trait table lines. Was it skipped due to starting with a comment ('#') sign?") # #Now that we have the header (if present) yield_trait_table_fields # #can assume no header exists, and just parse data fields # return header_line, yield_trait_table_fields(trait_table_lines,\ # delimiter=delimiter,has_header=False) # # def yield_trait_table_fields(trait_table_lines,delimiter="\t",\ # skip_comment_lines=True,has_header=False): # """Yield fields from trait table lines # # The current definition for the header lines is as follows: # -- can't start with a comment # -- must be the first line # # """ # for i,line in enumerate(trait_table_lines): # # if line.startswith("#") and skip_comment_lines: # #ignore these and remove from outputs # continue # # if has_header and i == 0: # #header line has no fields and should be skipped # continue # # #Check for bad delimiters and try to intelligently warn user # #if they used the wrong delimiter # if delimiter and delimiter not in line: # delimiters_to_check = {"tab":"\t","space":"","comma":","} # possible_delimiters = [] # for delim in delimiters_to_check.keys(): # if delimiters_to_check[delim] in line: # possible_delimiters.append(delim) # error_line =\ # "Delimiter '%s' not in line. The following delimiters were found: %s. Is the correct delimiter one of these?" # raise RuntimeError(error_line % (delimiter,\ # ",".join(possible_delimiters))) # # # # fields = line.strip().split(delimiter) # yield fields . Output only the next line.
def reformat_tree_and_trait_table(tree,trait_table_lines,trait_to_tree_mapping,\
Next line prediction: <|code_start|>__license__ = "GPL" __url__ = "http://picrust.github.com" __version__ = "1.1.4" __maintainer__ = "Morgan Langille" __email__ = "morgan.g.i.langille@gmail.com" PROJECT_ROOT = os.path.dirname(os.path.abspath(picrust.__file__)) DATA_DIR = os.path.join(PROJECT_ROOT, 'data') BASE_URL = ( 'http://kronos.pharmacology.dal.ca/public_files/picrust/' 'picrust_precalculated_v1.1.4/' ) type_of_prediction_choices = ['ko', 'cog', 'rfam'] gg_version_choices = ['13_5', '18may2012'] FILES = { ('16s', '13_5'): '16S_13_5_precalculated.tab.gz', ('ko', '13_5'): 'ko_13_5_precalculated.tab.gz', ('cog', '13_5'): 'cog_13_5_precalculated.tab.gz', ('rfam', '13_5'): 'rfam_13_5_precalculated.tab.gz', ('16s_ci', '13_5'): '16S_13_5_precalculated_variances.tab.gz', ('ko_ci', '13_5'): 'ko_13_5_precalculated_variances.tab.gz', ('cog_ci', '13_5'): 'cog_13_5_precalculated_variances.tab.gz', ('rfam_ci', '13_5'): 'rfam_13_5_precalculated_variances.tab.gz', ('16s', '18may2012'): '16S_18may2012_precalculated.tab.gz', <|code_end|> . Use current file imports: (from future.moves.urllib.parse import urljoin from future.moves.urllib.request import urlopen, HTTPError from cogent.util.option_parsing import ( make_option, parse_command_line_parameters, ) from picrust.util import atomic_write import os import picrust) and context including class names, function names, or small code snippets from other files: # Path: picrust/util.py # @contextmanager # def atomic_write(file): # """ # Yields an open temporary file and renames to ``file`` on exit # # This context manager aims to make it more convenient to write to a file # only when the write operation has completed (e.g. downloading a file from # the internet). # # The yielded file will be open in 'wb' mode. # """ # dir_name, basename = split(file) # tmp_path = join(dir_name, '~{}'.format(basename)) # # try: # with open(tmp_path, 'wb') as f: # yield f # f.flush() # fsync(f.fileno()) # except: # remove(tmp_path) # raise # else: # rename(tmp_path, file) . Output only the next line.
('ko', '18may2012'): 'ko_18may2012_precalculated.tab.gz',
Predict the next line after this snippet: <|code_start|> """ actual,ci= ace_for_picrust(self.in_tree2_fp,self.in_trait3_fp, method="pic") expected=Table(['nodes','trait1','trait2'],[['14','2.9737','2.5436'],['12','1.2727','3'],['11','0.6667','3'],['10','5','2']]) self.assertEqual(actual.tostring(),expected.tostring()) in_tree1="""(((1:0.1,2:0.2)11:0.6,3:0.8)12:0.2,(4:0.3,D:0.4)10:0.5)14;""" in_tree2="""((('abc_123':0.1,2:0.2)11:0.6,3:0.8)12:0.2,('NC_2345':0.3,D:0.4)10:0.5)14;""" in_trait1="""tips trait1 trait2 1 1 3 2 0 3 3 2 3 4 5 2 D 5 2""" in_trait2="""tips trait1 1 1 2 0 3 2 4 5 D 5""" in_trait3="""tips trait1 trait2 abc_123 1 3 2 0 3 3 2 3 NC_2345 5 2 <|code_end|> using the current file's imports: from cogent.util.unit_test import TestCase, main from picrust.ace import ace_for_picrust from cogent.app.util import get_tmp_filename from cogent.util.misc import remove_files from cogent import LoadTable from cogent.util.table import Table and any relevant context from other files: # Path: picrust/ace.py # def ace_for_picrust(tree_path,trait_table_path,method='pic',HALT_EXEC=False): # '''Runs the Ace application controller given path of tree and trait table and returns a Table''' # #initialize Ace app controller # ace=Ace(HALT_EXEC=HALT_EXEC) # # tmp_output_count_path=get_tmp_filename() # tmp_output_prob_path=get_tmp_filename() # # #quote file names # tree_path='"{0}"'.format(tree_path) # trait_table_path='"{0}"'.format(trait_table_path) # # as_string = " ".join([tree_path,trait_table_path,method,tmp_output_count_path,tmp_output_prob_path]) # #Run ace here # result = ace(data=as_string) # # #Load the output into Table objects # try: # asr_table=LoadTable(filename=tmp_output_count_path,header=True,sep='\t') # except IOError: # raise RuntimeError,\ # ("R reported an error on stderr:" # " %s" % "\n".join(result["StdErr"].readlines())) # # asr_prob_table=LoadTable(filename=tmp_output_prob_path,header=True,sep='\t') # # #Remove tmp files # remove(tmp_output_count_path) # remove(tmp_output_prob_path) # # return asr_table,asr_prob_table . Output only the next line.
D 5 2"""
Based on the snippet: <|code_start|>script_info = {} script_info['brief_description'] = "Starts multiple jobs in parallel on multicore or multiprocessor systems." script_info['script_description'] = "This script is designed to start multiple jobs in parallel on systems with no queueing system, for example a multiple processor or multiple core laptop/desktop machine. This also serves as an example 'cluster_jobs' which users can use a template to define scripts to start parallel jobs in their environment." script_info['script_usage'] = [\ ("Example",\ "Start each command listed in test_jobs.txt in parallel. The run id for these jobs will be RUNID. ",\ "%prog -ms test_jobs.txt RUNID")] script_info['output_description']= "No output is created." script_info['required_options'] = [] script_info['optional_options'] = [\ make_option('-m','--make_jobs',action='store_true',\ help='make the job files [default: %default]'),\ make_option('-s','--submit_jobs',action='store_true',\ help='submit the job files [default: %default]'),\ make_option('-d','--delay',action='store',type='int',default=0, help='Number of seconds to pause between launching each job [default: %default]'), make_option('-n','--num_jobs',action='store',type='int',\ help='Number of jobs to group commands into. [default: %default]',\ default=4)\ ] script_info['version'] = __version__ script_info['disallow_positional_arguments'] = False def write_job_files(output_dir,commands,run_id,num_jobs=4): jobs_dir = '%s/jobs/' % output_dir job_fps = [] if not exists(jobs_dir): try: makedirs(jobs_dir) except OSError,e: <|code_end|> , predict the immediate next line with the help of imports: from cogent.util.option_parsing import parse_command_line_parameters, make_option from subprocess import Popen from os import makedirs, chmod, getenv, remove from os.path import exists from shutil import rmtree from stat import S_IRWXU from picrust.parallel import grouper from math import ceil and context (classes, functions, sometimes code) from other files: # Path: picrust/parallel.py # def grouper(iterable, n, fillvalue=None): # args = [iter(iterable)] * n # return izip_longest(*args, fillvalue=fillvalue) . Output only the next line.
raise OSError, "Error creating jobs directory in working dir: %s" % output_dir +\
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python from __future__ import division __author__ = "Morgan Langille" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Morgan Langille"] __license__ = "GPL" <|code_end|> with the help of current file imports: from collections import defaultdict from os import listdir from numpy import array,ravel,asarray from os.path import join,basename from cogent.util.option_parsing import parse_command_line_parameters,\ make_option from picrust.evaluate_test_datasets import calculate_accuracy_stats_from_observations from biom import load_table, Table from picrust.util import make_output_dir_for_file from random import shuffle and context from other files: # Path: picrust/evaluate_test_datasets.py # def calculate_accuracy_stats_from_observations(obs,exp,success_criterion='binary',\ # verbose=False): # """Return statistics derived from the confusion matrix # obs -- a list of floats representing observed values # exp -- a list of floats for expected values (same order as obs) # verbose -- print verbose output # """ # # tp,fp,fn,tn =\ # confusion_matrix_from_data(obs,exp,success_criterion=success_criterion,verbose=verbose) # # result =\ # calculate_accuracy_stats_from_confusion_matrix(tp,fp,fn,tn,verbose=verbose) # # result['sum_expected']=sum(exp) # result['sum_observed']=sum(obs) # # #pearson correlation (using new method from pycogent 1.5.3) # pearson_r,pearson_para_p,pearson_permuted_r,pearson_nonpara_p,pearson_ci =correlation_test(obs,exp,method='pearson',permutations=0) # result['pearson_r']=pearson_r # #result['pearson_permuted_r']=pearson_permuted_r # #result['pearson_nonpara_p']=pearson_nonpara_p # result['pearson_p']=pearson_para_p # #result['pearson_ci']=pearson_ci # result['pearson_r2']=pearson_r**2 # # #spearman correlation (using new method from pycogent 1.5.3) # spearman_r,spearman_para_p,spearman_permuted_r,spearman_nonpara_p,spearman_ci =correlation_test(obs,exp,method='spearman',permutations=0) # result['spearman_r']=spearman_r # #result['spearman_permuted_r']=spearman_permuted_r # #result['spearman_nonpara_p']=spearman_nonpara_p # result['spearman_p']=spearman_para_p # #result['spearman_ci']=spearman_ci # result['spearman_r2']=spearman_r**2 # # #add in correlations (old) # #pearson_r,pearson_t_prob =correlation(obs,exp) # #result['pearson']=pearson_r # #result['pearson_prob']=pearson_t_prob # #result['pearson_r2']=pearson_r**2 # # #spearman_r,spearman_t_prob =spearman_correlation(obs,exp) # #result['spearman']=spearman_r # #result['spearman_prob']=spearman_t_prob # #result['spearman_r2']=spearman_r**2 # return result # # Path: picrust/util.py # def make_output_dir_for_file(filepath): # """Create sub-directories for a new file if they don't already exist""" # dirpath = dirname(filepath) # if not isdir(dirpath) and not dirpath == '': # makedirs(dirpath) , which may contain function names, class names, or code. Output only the next line.
__version__ = "1.1.4"
Continue the code snippet: <|code_start|>#!/usr/bin/env python # File created on 22 Feb 2012 from __future__ import division __author__ = "Greg Caporaso" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Greg Caporaso","Jesse Zaneveld","Morgan Langille"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Greg Caporaso" __email__ = "gregcaporaso@gmail.com" __status__ = "Development" <|code_end|> . Use current file imports: from cogent.util.option_parsing import parse_command_line_parameters, make_option from biom import load_table from picrust.predict_metagenomes import predict_metagenomes, calc_nsti from picrust.util import make_output_dir_for_file, write_biom_table, scale_metagenomes from os import path from numpy import around import gzip and context (classes, functions, or code) from other files: # Path: picrust/predict_metagenomes.py # def predict_metagenomes(otu_table, genome_table, verbose=False, # whole_round=True): # """ Predict metagenomes from OTU table and genome table. Can optionally # set verbose for more information printed to screen. Also, can prevent # rounding to nearest whole numbers by setting whole_round=False. # """ # # otu_data,genome_data,overlapping_otus = extract_otu_and_genome_data(otu_table,genome_table) # # matrix multiplication to get the predicted metagenomes # new_data = dot(array(otu_data).T,array(genome_data)).T # # if whole_round: # #Round counts to nearest whole numbers # new_data = around(new_data) # # # return the result as a sparse biom table - the sample ids are now the # # sample ids from the otu table, and the observation ids are now the # # functions (i.e., observations) from the genome table # # # While constructing the new table, we need to preserve metadata about the samples from the OTU table, # #and metadata about the gene functions from the genome table # result_table=table_from_template(new_data,otu_table.ids(), # genome_table.ids(axis='observation'), # sample_metadata_source=otu_table, # observation_metadata_source=genome_table, # verbose=verbose) # # return result_table # # def calc_nsti(otu_table,genome_table,weighted=True): # """Calculate the weighted Nearest Sequenced Taxon Index for ids # otu_table -- a .biom OTU table object # genome_table -- the corresponding set of PICRUST per-OTU genome predictions # weighted -- if True, normalize by OTU abundance # """ # # # identify the overlapping otus that can be used to calculate the NSTI # overlapping_otus = get_overlapping_ids(otu_table,genome_table) # total = 0.0 # n = 0.0 # observation_ids = otu_table.ids() # for obs_id in overlapping_otus: # obs_id_idx = genome_table.index(obs_id, axis='sample') # curr_nsti = float(genome_table.metadata()[obs_id_idx]['NSTI']) # if weighted: # curr_counts = otu_table.data(obs_id, axis='observation') # total += curr_counts*curr_nsti # n += curr_counts # else: # total += curr_nsti # n += 1 # # result=total/n # # return observation_ids,result # # Path: picrust/util.py # def make_output_dir_for_file(filepath): # """Create sub-directories for a new file if they don't already exist""" # dirpath = dirname(filepath) # if not isdir(dirpath) and not dirpath == '': # makedirs(dirpath) # # def write_biom_table(biom_table, biom_table_fp, compress=True, # write_hdf5=HAVE_H5PY, format_fs=None): # """Writes a BIOM table to the specified filepath # # Parameters # ---------- # biom_table : biom.Table # The table object to write out # biom_table_fp : str # The path to the output file # compress : bool, optional # Defaults to ``True``. If True, built-in compression on the output HDF5 # file will be enabled. This option is only relevant if ``write_hdf5`` is # ``True``. # write_hdf5 : bool, optional # Defaults to ``True`` if H5PY is installed and to ``False`` if H5PY is # not installed. If ``True`` the output biom table will be written as an # HDF5 binary file, otherwise it will be a JSON string. # format_fs : dict, optional # Formatting functions to be passed to `Table.to_hdf5` # # Notes # ----- # This code was adapted from QIIME 1.9 # """ # generated_by = "PICRUSt " + __version__ # # if write_hdf5: # with biom_open(biom_table_fp, 'w') as biom_file: # biom_table.to_hdf5(biom_file, generated_by, compress, # format_fs=format_fs) # else: # with open(biom_table_fp, 'w') as biom_file: # biom_table.to_json(generated_by, biom_file) # # def scale_metagenomes(metagenome_table,scaling_factors): # """ scale metagenomes from metagenome table and scaling factors # """ # transform_sample_f = make_sample_transformer(scaling_factors) # new_metagenome_table = metagenome_table.transform(transform_sample_f) # return new_metagenome_table . Output only the next line.
script_info = {}
Based on the snippet: <|code_start|>#!/usr/bin/env python # File created on 22 Feb 2012 from __future__ import division __author__ = "Greg Caporaso" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Greg Caporaso"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Greg Caporaso" __email__ = "gregcaporaso@gmail.com" __status__ = "Development" <|code_end|> , predict the immediate next line with the help of imports: from cogent.util.unit_test import TestCase, main from picrust.parse import extract_ids_from_table, parse_asr_confidence_output and context (classes, functions, sometimes code) from other files: # Path: picrust/parse.py # def extract_ids_from_table(table_lines,delimiter="\t",header_start_string="#",id_field_idx=0): # """Return a list of ids from a tab-delimited table # # table_lines -- an iterable collection of lines # delimiter -- the delimiter for fields in a line # header_start_string -- the string (if any) marking header lines # that should be skipped. # # NOTE: this works with legacy QIIME OTU tables (amongst others) # # """ # header, id_fields = parse_trait_table(table_lines,delimiter=delimiter,has_header=False) # result = [] # for f in id_fields: # result.append(f[id_field_idx]) # return result # # def parse_asr_confidence_output(table_lines,param_names=['loglik','sigma'],format='sigma'): # """Return reconstruction parameters from reconstruction table # # # """ # min_value_dict = {} # max_value_dict = {} # params = {} # column_mapping = {} # for i,line in enumerate(table_lines): # if i == 0: # #Header line, skip it # column_names = line.split("\t")[1:] # for i in range(len(column_names)): # column_mapping[column_names[i]] = i # continue # fields = line.split("\t") # if fields[0] in param_names: # vals = fields[1].split("|") # valid_vals = [] # for val in vals: # if val == "NaN": # valid_vals.append(None) # else: # valid_vals.append(float(val)) # params[fields[0]]=valid_vals # continue # organism_name = fields[0] # data_fields = fields[1:] # #print "data_fields:",data_fields # min_vals = map(float,[f.split("|")[0] for f in data_fields]) # max_vals = map(float,[f.split("|")[1] for f in data_fields]) # min_value_dict[organism_name]=min_vals # max_value_dict[organism_name]=max_vals # #print "min_val_dict:",min_value_dict # return min_value_dict,max_value_dict,params,column_mapping . Output only the next line.
class ParseTests(TestCase):
Predict the next line after this snippet: <|code_start|>otu_table_lines =[\ '# QIIME v1.3.0 OTU table',\ '#OTU ID\tS1\tS2\tS3\tS4\tS5\tS6\tS7\tS8\tS9\tConsensus Lineage',\ '39\t0\t0\t1\t0\t0\t5\t3\t0\t1\tArchaea;Euryarchaeota;Halobacteria;Halobacteriales;Halobacteriaceae',\ '238\t0\t1\t5\t6\t0\t1\t5\t2\t3\tArchaea;Euryarchaeota',\ '277\t0\t0\t2\t0\t0\t0\t0\t5\t1\tArchaea;Euryarchaeota',\ '1113\t0\t0\t0\t0\t1\t5\t0\t0\t0\tArchaea;Euryarchaeota;Halobacteria;Halobacteriales;Halobacteriaceae',\ '1206\t0\t0\t3\t2\t0\t1\t0\t0\t0\tArchaea;Euryarchaeota',\ '1351\t0\t0\t0\t0\t0\t0\t1\t11\t5\tArchaea;Euryarchaeota',\ '1637\t0\t3\t0\t2\t0\t0\t0\t3\t0\tArchaea;Euryarchaeota',\ '2043\t0\t0\t0\t1\t0\t0\t1\t0\t0\tArchaea;Euryarchaeota;Halobacteria;Halobacteriales;Halobacteriaceae;Halorubrum',\ '3472\t0\t0\t2\t0\t0\t0\t0\t2\t1\tArchaea;Euryarchaeota',\ '3757\t0\t0\t1\t2\t0\t3\t0\t0\t0\tArchaea',\ '4503\t0\t0\t0\t0\t0\t1\t1\t0\t0\tArchaea;Euryarchaeota;Halobacteria;Halobacteriales;Halobacteriaceae',\ '4546\t0\t3\t0\t3\t0\t0\t9\t6\t2\tArchaea;Euryarchaeota',\ '5403\t1\t2\t1\t1\t0\t1\t0\t1\t3\tArchaea;Euryarchaeota',\ '5479\t0\t0\t1\t1\t0\t0\t0\t0\t0\tArchaea'] counts_f1 = """GG_OTU_1 2 GG_OTU_2 4 GG_OTU_3 1""" counts_bad1 = """GG_OTU_1 hello GG_OTU_2 4 GG_OTU_3 1""" counts_bad2 = """GG_OTU_1 42 GG_OTU_2 4 GG_OTU_3 0""" <|code_end|> using the current file's imports: from cogent.util.unit_test import TestCase, main from picrust.parse import extract_ids_from_table, parse_asr_confidence_output and any relevant context from other files: # Path: picrust/parse.py # def extract_ids_from_table(table_lines,delimiter="\t",header_start_string="#",id_field_idx=0): # """Return a list of ids from a tab-delimited table # # table_lines -- an iterable collection of lines # delimiter -- the delimiter for fields in a line # header_start_string -- the string (if any) marking header lines # that should be skipped. # # NOTE: this works with legacy QIIME OTU tables (amongst others) # # """ # header, id_fields = parse_trait_table(table_lines,delimiter=delimiter,has_header=False) # result = [] # for f in id_fields: # result.append(f[id_field_idx]) # return result # # def parse_asr_confidence_output(table_lines,param_names=['loglik','sigma'],format='sigma'): # """Return reconstruction parameters from reconstruction table # # # """ # min_value_dict = {} # max_value_dict = {} # params = {} # column_mapping = {} # for i,line in enumerate(table_lines): # if i == 0: # #Header line, skip it # column_names = line.split("\t")[1:] # for i in range(len(column_names)): # column_mapping[column_names[i]] = i # continue # fields = line.split("\t") # if fields[0] in param_names: # vals = fields[1].split("|") # valid_vals = [] # for val in vals: # if val == "NaN": # valid_vals.append(None) # else: # valid_vals.append(float(val)) # params[fields[0]]=valid_vals # continue # organism_name = fields[0] # data_fields = fields[1:] # #print "data_fields:",data_fields # min_vals = map(float,[f.split("|")[0] for f in data_fields]) # max_vals = map(float,[f.split("|")[1] for f in data_fields]) # min_value_dict[organism_name]=min_vals # max_value_dict[organism_name]=max_vals # #print "min_val_dict:",min_value_dict # return min_value_dict,max_value_dict,params,column_mapping . Output only the next line.
if __name__ == "__main__":
Based on the snippet: <|code_start|>#!/usr/bin/env python # File created on 22 Feb 2012 from __future__ import division __author__ = "Greg Caporaso" __copyright__ = "Copyright 2015, The PICRUSt Project" <|code_end|> , predict the immediate next line with the help of imports: from numpy import abs,compress, dot, array, around, asarray,empty,zeros, sum as numpy_sum,sqrt,apply_along_axis from biom.table import Table from biom.parse import parse_biom_table, get_axis_indices, direct_slice_data, direct_parse_key from picrust.predict_traits import variance_of_weighted_mean,calc_confidence_interval_95 and context (classes, functions, sometimes code) from other files: # Path: picrust/predict_traits.py # def variance_of_weighted_mean(weights, variances, per_sample_axis=1): # """Calculate the standard deviation of a weighted average # # weights -- a numpy array of floats representing the weights # in the weighted average. Can be 1D or 2D (see per_sample_axis) # # variances -- a numpy array of variances for each observation (in # the same order as variance # # axis_for_samples -- which axis to sum down to stay within samples. # this value is ignored unless the array is 2d. # # This can be a little confusing, so consider this example: # If this is a 1D array, it is just handled asa single sample. # # If it is a 2D array, then multiple weighted averages will be calculated # for each column. Lets say we set axis_for_samples equal to 1. # (axis = axis_for_samples). # # Now, if we wanted to simultaneously # calculate the variance of the weighted average for: # # case1: weights = [0.5,0.5], variances = [1.0,2.0] # case2: weights = [0.1,0.9], variances = [1000.0,2000.0] # # We would supply the following numpy arrays: # weights = [[0.5,0.5],[1.0,2.0]] # variances = [[1.0,2.0],[1000.0,2000.0]] # # Notes: # Formula from http://en.wikipedia.org/wiki/Weighted_mean # # The variance of the weighted mean is: # sqrt(sum(stdev_squared * weight_squared)) # # Variance is standard deviation squared, so we use that instead # """ # if variances.shape != weights.shape: # raise ValueError("Shape of variances (%s) doesn't match shape of weights (%s)" %(str(variances.shape),str(weights.shape))) # if len(variances.shape) > 2: # raise ValueError("Must supply a 1D or 2D array for variance. Shape of supplied array was: %s" % str(variancs.shape)) # if len(variances.shape) == 1: # per_sample_axis = None # #Ensure weights are normalized # # if per_sample_axis is not None: # normalized_weights = apply_along_axis(normalize_axis, per_sample_axis, weights) # else: # normalized_weights = normalize_axis(weights) # squared_weights = weights**2 # # return sqrt(sum(squared_weights*variances, axis=per_sample_axis)) # # def calc_confidence_interval_95(predictions,variances,round_CI=True,\ # min_val=0.0,max_val=None): # """Calc the 95% confidence interval given predictions and variances""" # stdev = sqrt(variances) # pred = predictions # CI_95 = 1.96*stdev # lower_95_CI = pred - CI_95 # upper_95_CI = pred + CI_95 # if round_CI: # lower_95_CI = around(lower_95_CI) # upper_95_CI = around(upper_95_CI) # if min_val is not None: # lower_95_CI = numpy_max(min_val,lower_95_CI) # upper_95_CI = numpy_max(min_val,upper_95_CI) # # if max_val is not None: # lower_95_CI = numpy_min(max_val,lower_95_CI) # upper_95_CI = numpy_min(max_val,upper_95_CI) # # return lower_95_CI,upper_95_CI . Output only the next line.
__credits__ = ["Greg Caporaso", "Jesse Zaneveld", "Morgan Langille"]
Given snippet: <|code_start|>#!/usr/bin/env python # File created on 27 Feb 2012 from __future__ import division __author__ = "Morgan Langille" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Morgan Langille"] __license__ = "GPL" <|code_end|> , continue by predicting the next line. Consider current file imports: from cogent.util.unit_test import TestCase, main from picrust.count import wagner_for_picrust, parse_wagner_parsimony_output from cogent.app.util import get_tmp_filename from cogent.util.misc import remove_files from cogent import LoadTable from cogent.util.table import Table and context: # Path: picrust/count.py # def wagner_for_picrust(tree_path,trait_table_path,gain=None,max_paralogs=None,HALT_EXEC=False): # '''Runs count application controller given path of tree and trait table and returns a Table''' # #initialize Count app controller # count=Count(HALT_EXEC=HALT_EXEC) # # #set the parameters # if gain: # count.Parameters['-gain'].on(gain) # if max_paralogs: # count.Parameters['-max_paralogs'].on(max_paralogs) # # ###Have to manipulate the trait table some. Need to transpose it and strip ids surrounded in quotes. # table = LoadTable(filename=trait_table_path,header=True,sep='\t') # # #get the first column (containing row ids) # genome_ids = table.getRawData(table.Header[0]) # #remove single quotes from the id if they exist # genome_ids=[str(id).strip('\'') for id in genome_ids] # #transpose the matrix # table = table.transposed(new_column_name=table.Header[0]) # #Change the headers # table=table.withNewHeader(table.Header[1:],genome_ids) # #write the modified table to a tmp file # tmp_table_path =get_tmp_filename() # table.writeToFile(tmp_table_path,sep='\t') # # #Run Count here # result = count(data=(tree_path,tmp_table_path)) # # #Remove tmp file # remove(tmp_table_path) # # #tree=LoadTree(tree_path) # tree=DndParser(open(tree_path)) # # #parse the results into a Cogent Table # asr_table= parse_wagner_parsimony_output(result["StdOut"].readlines(),remove_num_tips=len(tree.tips())) # # #transpose the table # asr_table = asr_table.transposed(new_column_name='nodes') # # return asr_table # # def parse_wagner_parsimony_output(raw_output_with_comments,remove_num_tips=0): # '''Parses wagner parsimony output from Count and returns a Cogent Table object''' # # #keep only lines with actual ASR count information # #throw away first 2 columns and last 4 columns (these are extra stuff from Count) # filtered_output=[x.split('\t')[1:-4] for x in raw_output_with_comments if x[0:8] == '# FAMILY'] # # if(remove_num_tips): # #remove columns that contain trait data for tips (not internal node data) # filtered_output=[[x[0]]+ x[remove_num_tips+1:] for x in filtered_output] # # # #Take the first row as the header and the rest as rows in the table # table=Table(filtered_output[0],filtered_output[1:]) # return table which might include code, classes, or functions. Output only the next line.
__version__ = "1.1.4"
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # File created on 09 Jan 2013 from __future__ import division __author__ = "Daniel McDonald" __copyright__ = "Copyright 2011-2013, The PICRUSt Project" __credits__ = ["Daniel McDonald", "Morgan Langille", "Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Daniel McDonald" __email__ = "mcdonadt@colorado.edu" __status__ = "Development" script_info = {} script_info['brief_description'] = "Collapse table data to a specified level in a hierarchy." script_info['script_description'] = "This script collapses hierarchical data to a specified level. For instance, often it is useful to examine KEGG results from a higher level within the pathway hierarchy. Many genes are sometimes involved in multiple pathways, and in these circumstances (also know as a one-to-many relationship), the gene is counted for each pathway. This has a side effect of increasing the total count of genes in the table." script_info['script_usage'] = [\ ("","Collapse predicted metagenome using KEGG Pathway metadata.","""%prog -i predicted_metagenomes.biom -c KEGG_Pathways -l 3 -o predicted_metagenomes.L3.biom"""),\ ("","Change output to tab-delimited format (instead of BIOM).","""%prog -f -i predicted_metagenomes.biom -c KEGG_Pathways -l 3 -o predicted_metagenomes.L3.txt"""),\ ("","Collapse COG Categories.","""%prog -i cog_predicted_metagenomes.biom -c COG_Category -l 2 -o cog_predicted_metagenomes.L2.biom"""),\ ("","Collapse predicted metagenome using taxonomy metadata (not one-to-many).","""%prog -i observation_table.biom -c taxonomy -l 1 -o observation_table.L1.biom"""),\ ] script_info['output_description']= "Output table is contains gene counts at a higher level within a hierarchy." script_info['required_options'] = [\ make_option('-i','--input_fp',type="existing_filepath",help='the predicted metagenome table'),\ <|code_end|> using the current file's imports: import json import h5py from cogent.util.option_parsing import parse_command_line_parameters, make_option from biom import load_table from biom.table import vlen_list_of_str_formatter from picrust.util import write_biom_table and any relevant context from other files: # Path: picrust/util.py # def write_biom_table(biom_table, biom_table_fp, compress=True, # write_hdf5=HAVE_H5PY, format_fs=None): # """Writes a BIOM table to the specified filepath # # Parameters # ---------- # biom_table : biom.Table # The table object to write out # biom_table_fp : str # The path to the output file # compress : bool, optional # Defaults to ``True``. If True, built-in compression on the output HDF5 # file will be enabled. This option is only relevant if ``write_hdf5`` is # ``True``. # write_hdf5 : bool, optional # Defaults to ``True`` if H5PY is installed and to ``False`` if H5PY is # not installed. If ``True`` the output biom table will be written as an # HDF5 binary file, otherwise it will be a JSON string. # format_fs : dict, optional # Formatting functions to be passed to `Table.to_hdf5` # # Notes # ----- # This code was adapted from QIIME 1.9 # """ # generated_by = "PICRUSt " + __version__ # # if write_hdf5: # with biom_open(biom_table_fp, 'w') as biom_file: # biom_table.to_hdf5(biom_file, generated_by, compress, # format_fs=format_fs) # else: # with open(biom_table_fp, 'w') as biom_file: # biom_table.to_json(generated_by, biom_file) . Output only the next line.
make_option('-o','--output_fp',type='new_filepath', help='the resulting table'),
Given the code snippet: <|code_start|> action='store_true', help='suppress script usage tests [default: %default]', default=False), make_option('--unittest_glob', help='wildcard pattern to match tests to run [default: run all]', default=None), make_option('--script_usage_tests', help='comma-separated list of tests to run [default: run all]', default=None), ] script_info['version'] = __version__ script_info['help_on_no_arguments'] = False def main(): option_parser, opts, args =\ parse_command_line_parameters(**script_info) if (opts.suppress_unit_tests and opts.suppress_script_usage_tests): option_parser.error("You're suppressing both test types. Nothing to run.") test_dir = abspath(dirname(__file__)) unittest_good_pattern = re.compile('OK\s*$') application_not_found_pattern = re.compile('ApplicationNotFoundError') python_name = 'python' bad_tests = [] missing_application_tests = [] # Run through all of PICRUSt's unit tests, and keep track of any files which # fail unit tests. <|code_end|> , generate the next line using the imports in this file: from os import walk, environ from sys import exit from os.path import join, abspath, dirname, exists, split from glob import glob from picrust.util import get_picrust_project_dir, system_call from cogent.util.option_parsing import parse_command_line_parameters, make_option from qiime.test import run_script_usage_tests import re import cogent.util.unit_test as unittest and context (functions, classes, or occasionally code) from other files: # Path: picrust/util.py # def get_picrust_project_dir(): # """ Returns the top-level PICRUST directory # """ # # Get the full path of util.py # current_file_path = abspath(__file__) # # Get the directory containing util.py # current_dir_path = dirname(current_file_path) # # Return the directory containing the directory containing util.py # return dirname(current_dir_path) # # def system_call(cmd, shell=True): # """Call cmd and return (stdout, stderr, return_value). # # cmd can be either a string containing the command to be run, or a sequence # of strings that are the tokens of the command. # # Please see Python's subprocess.Popen for a description of the shell # parameter and how cmd is interpreted differently based on its value. # # This code was copied from QIIME's qiime_system_call() (util.py) function on June 3rd, 2013. # """ # proc = Popen(cmd, shell=shell, universal_newlines=True, stdout=PIPE, # stderr=PIPE) # # communicate pulls all stdout/stderr from the PIPEs to # # avoid blocking -- don't remove this line! # stdout, stderr = proc.communicate() # return_value = proc.returncode # return stdout, stderr, return_value . Output only the next line.
if not opts.suppress_unit_tests:
Here is a snippet: <|code_start|>script_info = {} script_info['brief_description'] = "" script_info['script_description'] = "" script_info['script_usage'] = [("","","")] script_info['output_description']= "" script_info['required_options'] = [] script_info['optional_options'] = [ make_option('--suppress_unit_tests', action='store_true', help='suppress unit tests [default: %default]', default=False), make_option('--suppress_script_usage_tests', action='store_true', help='suppress script usage tests [default: %default]', default=False), make_option('--unittest_glob', help='wildcard pattern to match tests to run [default: run all]', default=None), make_option('--script_usage_tests', help='comma-separated list of tests to run [default: run all]', default=None), ] script_info['version'] = __version__ script_info['help_on_no_arguments'] = False def main(): option_parser, opts, args =\ parse_command_line_parameters(**script_info) if (opts.suppress_unit_tests and opts.suppress_script_usage_tests): <|code_end|> . Write the next line using the current file imports: from os import walk, environ from sys import exit from os.path import join, abspath, dirname, exists, split from glob import glob from picrust.util import get_picrust_project_dir, system_call from cogent.util.option_parsing import parse_command_line_parameters, make_option from qiime.test import run_script_usage_tests import re import cogent.util.unit_test as unittest and context from other files: # Path: picrust/util.py # def get_picrust_project_dir(): # """ Returns the top-level PICRUST directory # """ # # Get the full path of util.py # current_file_path = abspath(__file__) # # Get the directory containing util.py # current_dir_path = dirname(current_file_path) # # Return the directory containing the directory containing util.py # return dirname(current_dir_path) # # def system_call(cmd, shell=True): # """Call cmd and return (stdout, stderr, return_value). # # cmd can be either a string containing the command to be run, or a sequence # of strings that are the tokens of the command. # # Please see Python's subprocess.Popen for a description of the shell # parameter and how cmd is interpreted differently based on its value. # # This code was copied from QIIME's qiime_system_call() (util.py) function on June 3rd, 2013. # """ # proc = Popen(cmd, shell=shell, universal_newlines=True, stdout=PIPE, # stderr=PIPE) # # communicate pulls all stdout/stderr from the PIPEs to # # avoid blocking -- don't remove this line! # stdout, stderr = proc.communicate() # return_value = proc.returncode # return stdout, stderr, return_value , which may include functions, classes, or code. Output only the next line.
option_parser.error("You're suppressing both test types. Nothing to run.")
Given snippet: <|code_start|>#!/usr/bin/env python # File created on 22 Feb 2012 from __future__ import division __author__ = "Jesse Zaneveld" __copyright__ = "Copyright 2015, The PICRUST project" __credits__ = ["Jesse Zaneveld"] __license__ = "GPL" __version__ = "1.1.4" __maintainer__ = "Jesse Zaneveld" __email__ = "zaneveld@gmail.com" __status__ = "Development" def make_pathway_filter_fn(ok_values,metadata_key='KEGG_Pathways',\ <|code_end|> , continue by predicting the next line. Consider current file imports: from numpy import dot, array, around from biom.table import Table from picrust.predict_metagenomes import get_overlapping_ids,extract_otu_and_genome_data and context: # Path: picrust/predict_metagenomes.py # def get_overlapping_ids(otu_table,genome_table,genome_table_ids="sample",\ # otu_table_ids="observation"): # """Get the ids that overlap between the OTU and genome tables # otu_table - a BIOM Table object representing the OTU table # genome_table - a BIOM Table object for the genomes # genome_table_ids - specifies whether the ids of interest are sample or observation # in the genome table. Useful because metagenome tables are often represented with genes # as observations. # """ # for id_type in [genome_table_ids,otu_table_ids]: # if id_type not in ["sample", "observation"]: # raise ValueError(\ # "%s is not a valid id type. Choices are 'sample' or 'observation'" % id_type) # overlapping_otus = list(set(otu_table.ids(axis=otu_table_ids)) & # set(genome_table.ids(axis=genome_table_ids))) # # if len(overlapping_otus) < 1: # raise ValueError,\ # "No common OTUs between the otu table and the genome table, so can't predict metagenome." # return overlapping_otus # # def extract_otu_and_genome_data(otu_table, genome_table, # genome_table_ids="sample", # otu_table_ids="observation"): # """Return lists of otu,genome data, and overlapping genome/otu ids # # otu_table -- biom Table object for the OTUs # genome_table -- biom Table object for the genomes # """ # overlapping_otus = get_overlapping_ids(otu_table, genome_table, # genome_table_ids=genome_table_ids,otu_table_ids=otu_table_ids) # # create lists to contain filtered data - we're going to need the data in # # numpy arrays, so it makes sense to compute this way rather than filtering # # the tables # otu_data = [] # genome_data = [] # # # build lists of filtered data # for obs_id in overlapping_otus: # if otu_data == "sample": # otu_data.append(otu_table.data(obs_id)) # else: # otu_data.append(otu_table.data(obs_id, axis='observation')) # if genome_table_ids == "observation": # genome_data.append(genome_table.data(obs_id, axis='observation')) # else: # genome_data.append(genome_table.data(obs_id)) # return otu_data, genome_data, overlapping_otus which might include code, classes, or functions. Output only the next line.
search_only_pathway_level=None):
Continue the code snippet: <|code_start|> return hasattr(t, '__thunk__') def _make_thunk(t): setattr(t, '__thunk__', True) class _ThunkBuilder: """This is used to create a thunk from a linq-style method. """ def __init__(self, func): self.func = func self.__name__ = func.__name__ def __call__(self, *args, **kwargs): if len(args)==0 and len(kwargs)==0: _make_thunk(self.func) return self.func def apply(this): return self.func(this, *args, **kwargs) apply.__name__ = self.__name__ _make_thunk(apply) return apply def __repr__(self): return "_ThunkBuilder(%s)" % self.__name__ def _connect_thunk(prev, thunk): """Connect the thunk to the previous in the chain. Handles all the cases where we might be given a filter, a thunk, a thunk builder (unevaluated linq function), or a bare callable.""" if callable(thunk): <|code_end|> . Use current file imports: from collections import namedtuple from thingflow.internal import noop import threading import time import queue import traceback as tb import logging and context (classes, functions, or code) from other files: # Path: thingflow/internal/basic.py # def noop(*args, **kw): # """No operation. Returns nothing""" # pass . Output only the next line.
if _is_thunk(thunk):
Using the snippet: <|code_start|> class Id(Base): def __init__(self, id_replacements, markdown_preview, lowercase): super().__init__() self.id_replacements = id_replacements self.markdown_preview = markdown_preview self.lowercase = lowercase def heading_to_id(self, heading): if heading is None: return "" if self.markdown_preview == "github": _h1 = self.postprocess_inject_header_id("<h1>%s</h1>" % heading) pattern = r'<h1 id="(.*)">.*</h1>' matches = re.finditer(pattern, _h1) for match in matches: return match.groups()[0] elif self.markdown_preview == "markdown": return self.slugify(heading, "-") else: if self.lowercase == "false": _id = heading elif self.lowercase == "only_ascii": <|code_end|> , determine the next line of code. You have imports: import re import unicodedata from urllib.parse import quote from .base import Base and context (class names, function names, or code) available: # Path: markdowntoc/base.py # class Base(object): # def settings(self, attr): # DEFAULT = "Packages/MarkdownTOC/MarkdownTOC.sublime-settings" # files = sublime.find_resources("MarkdownTOC.sublime-settings") # files.remove(DEFAULT) # # settings = self.decode_value(DEFAULT) # for f in files: # user_settings = self.decode_value(f) # if user_settings != None: # Util.dict_merge(settings, user_settings) # return settings[attr] # # def defaults(self): # return self.settings("defaults") # # def decode_value(self, file): # # Check json syntax # try: # return sublime.decode_value(sublime.load_resource(file)) # except ValueError as e: # self.error("Invalid json in %s: %s" % (file, e)) # # def log(self, arg): # if self.settings("logging") is True: # arg = str(arg) # sublime.status_message(arg) # pp.pprint(arg) # # def error(self, arg): # arg = "MarkdownTOC Error: " + arg # arg = str(arg) # sublime.status_message(arg) # pp.pprint(arg) . Output only the next line.
_id = "".join(chr(ord(x) + ("A" <= x <= "Z") * 32) for x in heading)
Here is a snippet: <|code_start|> files = sublime.find_resources("MarkdownTOC.sublime-settings") files.remove(DEFAULT) settings = self.decode_value(DEFAULT) for f in files: user_settings = self.decode_value(f) if user_settings != None: Util.dict_merge(settings, user_settings) return settings[attr] def defaults(self): return self.settings("defaults") def decode_value(self, file): # Check json syntax try: return sublime.decode_value(sublime.load_resource(file)) except ValueError as e: self.error("Invalid json in %s: %s" % (file, e)) def log(self, arg): if self.settings("logging") is True: arg = str(arg) sublime.status_message(arg) pp.pprint(arg) def error(self, arg): arg = "MarkdownTOC Error: " + arg arg = str(arg) sublime.status_message(arg) <|code_end|> . Write the next line using the current file imports: import pprint import sublime from .util import Util and context from other files: # Path: markdowntoc/util.py # class Util: # def is_out_of_areas(num, areas): # for area in areas: # if area[0] < num and num < area[1]: # return False # return True # # def format(items): # levels = [] # for item in items: # levels.append(item[0]) # # -------------------------- # # # minimize diff between levels ----- # _depths = list(set(levels)) # sort and unique # # replace with depth rank # for i, item in enumerate(levels): # levels[i] = _depths.index(levels[i]) + 1 # # # Force set level of first item to 1 ----- # # (first item must be list root) # if len(levels): # diff_to_root = levels[0] - 1 # if 0 < diff_to_root: # # def pad(level): # return level - diff_to_root # # levels = list(map(pad, levels)) # # # -------------------------- # for i, item in enumerate(items): # item[0] = levels[i] # return items # # def strtobool(val): # """pick out from 'distutils.util' module""" # if isinstance(val, str): # val = val.lower() # if val in ("y", "yes", "t", "true", "on", "1"): # return 1 # elif val in ("n", "no", "f", "false", "off", "0"): # return 0 # else: # raise ValueError("invalid truth value %r" % (val,)) # else: # return bool(val) # # def within_ranges(target, ranges): # tb = target[0] # te = target[1] # for _range in ranges: # rb = _range[0] # re = _range[1] # if (rb <= tb and tb <= re) and (rb <= tb and tb <= re): # return True # return False # # # This method is from https://gist.github.com/angstwad/bf22d1822c38a92ec0a9 # def dict_merge(dct, merge_dct): # """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of # updating only top-level keys, dict_merge recurses down into dicts nested # to an arbitrary depth, updating keys. The ``merge_dct`` is merged into # ``dct``. # :param dct: dict onto which the merge is executed # :param merge_dct: dct merged into dct # :return: None # """ # for k, v in merge_dct.items(): # if ( # k in dct # and isinstance(dct[k], dict) # and isinstance(merge_dct[k], collections.Mapping) # ): # Util.dict_merge(dct[k], merge_dct[k]) # else: # dct[k] = merge_dct[k] , which may include functions, classes, or code. Output only the next line.
pp.pprint(arg)
Using the snippet: <|code_start|> for field in model_fields: for method_name in methods_that_should_raise: with self.assertRaises(NotImplementedError): getattr(field, method_name)() def test_get_pk_value_on_save_returns_true_if_field_has_default(self): field_with_default = self.family_member._meta.get_field("id") self.assertTrue( field_with_default.get_pk_value_on_save(instance=self.family_member), self.family_member.id, ) def test_get_pk_value_on_save_returns_none_if_field_no_default(self): field_without_default = self.family_member._meta.get_field("last_name") self.assertIsNone( field_without_default.get_pk_value_on_save(instance=self.family_member), ) def test_formfield_uses_specified_form_class(self): text_field = self.family_member._meta.get_field("last_name") form_field = text_field.formfield(form_class=fields.BooleanField) self.assertTrue(isinstance(form_field, fields.BooleanField)) def test_field_check_returns_error_when_name_is_pk(self): text_field = copy.deepcopy(self.family_member._meta.get_field("last_name")) text_field.name = "pk" check_errors = text_field.check() self.assertEqual(len(check_errors), 1) <|code_end|> , determine the next line of code. You have imports: from datetime import datetime from unittest import skipIf from cassandra.cqlengine import ValidationError as CQLValidationError from django.core import validators from django.forms import fields from common.models import CassandraFamilyMember from django_cassandra_engine.test import TestCase as CassandraTestCase import copy import uuid and context (class names, function names, or code) available: # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) . Output only the next line.
def test_field_check_returns_error_when_name_ends_underscore(self):
Given snippet: <|code_start|> class DjangoCassandraModelSerializer(serializers.ModelSerializer): serializer_field_mapping = { columns.Text: serializers.CharField, columns.UUID: serializers.CharField, columns.Integer: serializers.IntegerField, columns.TinyInt: serializers.IntegerField, columns.SmallInt: serializers.IntegerField, columns.BigInt: serializers.IntegerField, columns.VarInt: serializers.IntegerField, columns.Counter: serializers.IntegerField, columns.DateTime: serializers.DateTimeField, columns.Date: serializers.DateField, columns.Float: serializers.FloatField, columns.Double: serializers.FloatField, columns.Decimal: serializers.DecimalField, columns.Boolean: serializers.BooleanField, columns.DateTime: serializers.DateTimeField, columns.List: serializers.ListField, } <|code_end|> , continue by predicting the next line. Consider current file imports: import warnings from django.core.validators import DecimalValidator from django.utils.text import capfirst from rest_framework import serializers from rest_framework.serializers import ( CharField, ChoiceField, ModelField, models, postgres_fields, ) from rest_framework.utils.field_mapping import ( NUMERIC_FIELD_TYPES, ClassLookupDict, needs_label, validators, ) from ..compat import columns and context: # Path: django_cassandra_engine/compat.py which might include code, classes, or functions. Output only the next line.
def get_field_kwargs(self, field_name, model_field):
Here is a snippet: <|code_start|> class Command(FlushCommand): def handle_noargs(self, **options): engine = get_engine_from_db_alias(options["database"]) if engine == "django_cassandra_engine": options.update({"interactive": False, "inhibit_post_migrate": True}) return super(Command, self).handle_noargs(**options) def handle(self, **options): engine = get_engine_from_db_alias(options["database"]) if engine == "django_cassandra_engine": options.update({"interactive": False, "inhibit_post_migrate": True}) return super(Command, self).handle(**options) @staticmethod <|code_end|> . Write the next line using the current file imports: from django.core.management.commands.flush import Command as FlushCommand from django_cassandra_engine.utils import get_engine_from_db_alias and context from other files: # Path: django_cassandra_engine/utils.py # def get_engine_from_db_alias(db_alias): # """ # :param db_alias: database alias # :return: database engine from DATABASES dict corresponding to db_alias # or None if db_alias was not found # """ # return settings.DATABASES.get(db_alias, {}).get("ENGINE", None) , which may include functions, classes, or code. Output only the next line.
def emit_post_syncdb(verbosity, interactive, database):
Predict the next line for this snippet: <|code_start|> connection.register_connection( self.alias, default=self.default, session=session ) else: connection.register_connection( self.alias, hosts=self.hosts, default=self.default, cluster_options=self.cluster_options, **self.connection_options ) @property def cluster(self): return connection.get_cluster(connection=self.alias) @property def session(self): return connection.get_session(connection=self.alias) def commit(self): pass def rollback(self): pass def cursor(self): return Cursor(self) def execute(self, qs, *args, **kwargs): <|code_end|> with the help of current file imports: from django_cassandra_engine.utils import get_cassandra_connections from .compat import ( Cluster, CQLEngineException, PlainTextAuthProvider, Session, connection, ) from cassandra.cqlengine import models and context from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # Path: django_cassandra_engine/compat.py , which may contain function names, class names, or code. Output only the next line.
self.session.set_keyspace(self.keyspace)
Based on the snippet: <|code_start|> self.alias = alias self.hosts = options.get("HOST").split(",") self.keyspace = options.get("NAME") self.user = options.get("USER") self.password = options.get("PASSWORD") self.options = options.get("OPTIONS", {}) self.cluster_options = self.options.get("connection", {}) self.session_options = self.options.get("session", {}) self.connection_options = { "lazy_connect": self.cluster_options.pop("lazy_connect", False), "retry_connect": self.cluster_options.pop("retry_connect", False), "consistency": self.cluster_options.pop("consistency", None), } if self.user and self.password and "auth_provider" not in self.cluster_options: self.cluster_options["auth_provider"] = PlainTextAuthProvider( username=self.user, password=self.password ) self.default = ( alias == "default" or len(list(get_cassandra_connections())) == 1 or self.cluster_options.pop("default", False) ) self.register() def register(self): try: connection.get_connection(name=self.alias) except CQLEngineException: <|code_end|> , predict the immediate next line with the help of imports: from django_cassandra_engine.utils import get_cassandra_connections from .compat import ( Cluster, CQLEngineException, PlainTextAuthProvider, Session, connection, ) from cassandra.cqlengine import models and context (classes, functions, sometimes code) from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # Path: django_cassandra_engine/compat.py . Output only the next line.
if self.default:
Predict the next line after this snippet: <|code_start|> self.alias = alias self.hosts = options.get("HOST").split(",") self.keyspace = options.get("NAME") self.user = options.get("USER") self.password = options.get("PASSWORD") self.options = options.get("OPTIONS", {}) self.cluster_options = self.options.get("connection", {}) self.session_options = self.options.get("session", {}) self.connection_options = { "lazy_connect": self.cluster_options.pop("lazy_connect", False), "retry_connect": self.cluster_options.pop("retry_connect", False), "consistency": self.cluster_options.pop("consistency", None), } if self.user and self.password and "auth_provider" not in self.cluster_options: self.cluster_options["auth_provider"] = PlainTextAuthProvider( username=self.user, password=self.password ) self.default = ( alias == "default" or len(list(get_cassandra_connections())) == 1 or self.cluster_options.pop("default", False) ) self.register() def register(self): try: connection.get_connection(name=self.alias) except CQLEngineException: <|code_end|> using the current file's imports: from django_cassandra_engine.utils import get_cassandra_connections from .compat import ( Cluster, CQLEngineException, PlainTextAuthProvider, Session, connection, ) from cassandra.cqlengine import models and any relevant context from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # Path: django_cassandra_engine/compat.py . Output only the next line.
if self.default:
Here is a snippet: <|code_start|> self.alias, default=self.default, session=session ) else: connection.register_connection( self.alias, hosts=self.hosts, default=self.default, cluster_options=self.cluster_options, **self.connection_options ) @property def cluster(self): return connection.get_cluster(connection=self.alias) @property def session(self): return connection.get_session(connection=self.alias) def commit(self): pass def rollback(self): pass def cursor(self): return Cursor(self) def execute(self, qs, *args, **kwargs): self.session.set_keyspace(self.keyspace) <|code_end|> . Write the next line using the current file imports: from django_cassandra_engine.utils import get_cassandra_connections from .compat import ( Cluster, CQLEngineException, PlainTextAuthProvider, Session, connection, ) from cassandra.cqlengine import models and context from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # Path: django_cassandra_engine/compat.py , which may include functions, classes, or code. Output only the next line.
return self.session.execute(qs, *args, **kwargs)
Here is a snippet: <|code_start|> self.close() class FakeConnection(object): def commit(self): pass def rollback(self): pass def cursor(self): return Cursor(None) def close(self): pass class CassandraConnection(object): def __init__(self, alias, **options): self.alias = alias self.hosts = options.get("HOST").split(",") self.keyspace = options.get("NAME") self.user = options.get("USER") self.password = options.get("PASSWORD") self.options = options.get("OPTIONS", {}) self.cluster_options = self.options.get("connection", {}) self.session_options = self.options.get("session", {}) self.connection_options = { "lazy_connect": self.cluster_options.pop("lazy_connect", False), "retry_connect": self.cluster_options.pop("retry_connect", False), <|code_end|> . Write the next line using the current file imports: from django_cassandra_engine.utils import get_cassandra_connections from .compat import ( Cluster, CQLEngineException, PlainTextAuthProvider, Session, connection, ) from cassandra.cqlengine import models and context from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # Path: django_cassandra_engine/compat.py , which may include functions, classes, or code. Output only the next line.
"consistency": self.cluster_options.pop("consistency", None),
Next line prediction: <|code_start|> class Cursor(object): def __init__(self, connection): self.connection = connection def execute(self, *args, **kwargs): return self.connection.execute(*args, **kwargs) def close(self): pass def fetchmany(self, _): return [] <|code_end|> . Use current file imports: (from django_cassandra_engine.utils import get_cassandra_connections from .compat import ( Cluster, CQLEngineException, PlainTextAuthProvider, Session, connection, ) from cassandra.cqlengine import models) and context including class names, function names, or small code snippets from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # Path: django_cassandra_engine/compat.py . Output only the next line.
def __enter__(self):
Using the snippet: <|code_start|> router = routers.DefaultRouter() router.register(r"thing-modelviewset", ThingModelViewSet) urlpatterns = [ re_path( r"^thing-viewset/$", ThingMultiplePKViewSet.as_view({"get": "list"}), name="thing_viewset_api", ), re_path( r"^thing-listcreate/$", ThingMultiplePKListCreateAPIView.as_view(), name="thing_listcreate_api", <|code_end|> , determine the next line of code. You have imports: from django.urls import include, re_path from rest_framework import routers from .views import ( ThingModelViewSet, ThingMultiplePKListAPIView, ThingMultiplePKListCreateAPIView, ThingMultiplePKViewSet, ) and context (class names, function names, or code) available: # Path: testproject/common/views.py # class ThingModelViewSet(ModelViewSet): # serializer_class = ThingSerializer # queryset = CassandraThing.objects.all() # permission_classes = () # # class ThingMultiplePKListAPIView(ListAPIView): # queryset = CassandraThingMultiplePK.objects.all() # serializer_class = ThingMultiplePKSerializer # permission_classes = () # # class ThingMultiplePKListCreateAPIView(ListCreateAPIView): # queryset = CassandraThingMultiplePK.objects.all() # serializer_class = ThingMultiplePKSerializer # permission_classes = () # # class ThingMultiplePKViewSet(ViewSet): # def list(self, request): # queryset = CassandraThingMultiplePK.objects.all() # serializer = ThingMultiplePKSerializer(queryset, many=True) # return Response(serializer.data) . Output only the next line.
),
Given the code snippet: <|code_start|> router = routers.DefaultRouter() router.register(r"thing-modelviewset", ThingModelViewSet) urlpatterns = [ re_path( r"^thing-viewset/$", ThingMultiplePKViewSet.as_view({"get": "list"}), name="thing_viewset_api", ), re_path( r"^thing-listcreate/$", ThingMultiplePKListCreateAPIView.as_view(), name="thing_listcreate_api", ), re_path( r"^thing-listview/$", ThingMultiplePKListAPIView.as_view(), <|code_end|> , generate the next line using the imports in this file: from django.urls import include, re_path from rest_framework import routers from .views import ( ThingModelViewSet, ThingMultiplePKListAPIView, ThingMultiplePKListCreateAPIView, ThingMultiplePKViewSet, ) and context (functions, classes, or occasionally code) from other files: # Path: testproject/common/views.py # class ThingModelViewSet(ModelViewSet): # serializer_class = ThingSerializer # queryset = CassandraThing.objects.all() # permission_classes = () # # class ThingMultiplePKListAPIView(ListAPIView): # queryset = CassandraThingMultiplePK.objects.all() # serializer_class = ThingMultiplePKSerializer # permission_classes = () # # class ThingMultiplePKListCreateAPIView(ListCreateAPIView): # queryset = CassandraThingMultiplePK.objects.all() # serializer_class = ThingMultiplePKSerializer # permission_classes = () # # class ThingMultiplePKViewSet(ViewSet): # def list(self, request): # queryset = CassandraThingMultiplePK.objects.all() # serializer = ThingMultiplePKSerializer(queryset, many=True) # return Response(serializer.data) . Output only the next line.
name="thing_listview_api",
Given snippet: <|code_start|> router = routers.DefaultRouter() router.register(r"thing-modelviewset", ThingModelViewSet) urlpatterns = [ re_path( r"^thing-viewset/$", ThingMultiplePKViewSet.as_view({"get": "list"}), name="thing_viewset_api", ), <|code_end|> , continue by predicting the next line. Consider current file imports: from django.urls import include, re_path from rest_framework import routers from .views import ( ThingModelViewSet, ThingMultiplePKListAPIView, ThingMultiplePKListCreateAPIView, ThingMultiplePKViewSet, ) and context: # Path: testproject/common/views.py # class ThingModelViewSet(ModelViewSet): # serializer_class = ThingSerializer # queryset = CassandraThing.objects.all() # permission_classes = () # # class ThingMultiplePKListAPIView(ListAPIView): # queryset = CassandraThingMultiplePK.objects.all() # serializer_class = ThingMultiplePKSerializer # permission_classes = () # # class ThingMultiplePKListCreateAPIView(ListCreateAPIView): # queryset = CassandraThingMultiplePK.objects.all() # serializer_class = ThingMultiplePKSerializer # permission_classes = () # # class ThingMultiplePKViewSet(ViewSet): # def list(self, request): # queryset = CassandraThingMultiplePK.objects.all() # serializer = ThingMultiplePKSerializer(queryset, many=True) # return Response(serializer.data) which might include code, classes, or functions. Output only the next line.
re_path(
Here is a snippet: <|code_start|> self.assertDictEqual(response.json(), expected_json) model = CassandraThingMultiplePK.objects.get(id=self.data["id"]) self.assertEqual(str(model.id), self.data["id"]) self.assertEqual(str(model.another_id), self.data["another_id"]) self.assertEqual(model.data_abstract, self.data["data_abstract"]) class TestSerializer(APITestCase, CassandraTestCase): def test_serialize_creates(self): now = datetime.now() data = { "id": str(uuid.uuid4()), "first_name": "Homer", "last_name": "Simpson", "is_real": True, "favourite_number": 10, "favourite_float_number": float(10.10), "created_on": now, } serializer = CassandraFamilyMemberSerializer(data=data) serializer.is_valid() self.assertEqual(serializer.errors, {}) self.assertEqual(serializer.is_valid(), True) serializer.save() self.assertEqual(CassandraFamilyMember.objects.all().count(), 1) model = CassandraFamilyMember.objects.all()[0] self.assertEqual(model.first_name, "Homer") <|code_end|> . Write the next line using the current file imports: from datetime import datetime from http import client from unittest import skipIf from django.urls import reverse from rest_framework.test import APITestCase from common.models import ( CassandraFamilyMember, CassandraThing, CassandraThingMultiplePK, ) from common.serializers import CassandraFamilyMemberSerializer from django_cassandra_engine.test import TestCase as CassandraTestCase import uuid and context from other files: # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) , which may include functions, classes, or code. Output only the next line.
self.assertEqual(model.last_name, "Simpson")
Predict the next line for this snippet: <|code_start|> class AbstractBaseSession(Model): __abstract__ = True session_key = columns.Text(primary_key=True, max_length=40) expire_date = columns.DateTime() session_data = columns.Text() def __str__(self): return self.session_key @classmethod def get_session_store_class(cls): raise NotImplementedError def get_decoded(self): <|code_end|> with the help of current file imports: from ..compat import Model, columns from django_cassandra_engine.sessions.backends.db import SessionStore and context from other files: # Path: django_cassandra_engine/compat.py , which may contain function names, class names, or code. Output only the next line.
session_store_class = self.get_session_store_class()
Here is a snippet: <|code_start|> class Command(MakeMigrationsCommand): @staticmethod def _change_cassandra_engine_name(name): for alias, _ in get_cassandra_connections(): connections[alias].settings_dict["ENGINE"] = name <|code_end|> . Write the next line using the current file imports: from django.core.management.commands.makemigrations import ( Command as MakeMigrationsCommand, ) from django.db import connections from django_cassandra_engine.utils import get_cassandra_connections and context from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] , which may include functions, classes, or code. Output only the next line.
def handle(self, *args, **options):
Next line prediction: <|code_start|> class TestModelForm(CassandraTestCase): def setUp(self): self.some_uuid = uuid.uuid4() self.family_member = CassandraFamilyMember.objects.create( id=self.some_uuid, first_name="Homer", last_name="Simpson", is_real=False, favourite_number=666, favourite_float_number=43.4, ) def test_form_save(self): form = CassandraFamilyMemberForm( data=dict( id=self.some_uuid, first_name="Homer", last_name="Simpson", is_real=False, <|code_end|> . Use current file imports: (import uuid import django from common.forms import CassandraFamilyMemberForm from common.models import CassandraFamilyMember from django_cassandra_engine.test import TestCase as CassandraTestCase) and context including class names, function names, or small code snippets from other files: # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) . Output only the next line.
favourite_number=666,
Given the code snippet: <|code_start|> class Command(MigrateCommand): def handle(self, *args, **options): engine = get_engine_from_db_alias(options["database"]) # Call regular migrate if engine is different from ours if engine != "django_cassandra_engine": <|code_end|> , generate the next line using the imports in this file: from django.core.management import call_command from django.core.management.commands.migrate import Command as MigrateCommand from django_cassandra_engine.utils import get_engine_from_db_alias and context (functions, classes, or occasionally code) from other files: # Path: django_cassandra_engine/utils.py # def get_engine_from_db_alias(db_alias): # """ # :param db_alias: database alias # :return: database engine from DATABASES dict corresponding to db_alias # or None if db_alias was not found # """ # return settings.DATABASES.get(db_alias, {}).get("ENGINE", None) . Output only the next line.
return super(Command, self).handle(*args, **options)
Given the following code snippet before the placeholder: <|code_start|> def test_cluster_property(self): self.assertEqual( self.connection.cluster, cql_connection._connections[self.connection.alias].cluster, ) def test_connection_options(self): connection_options = self.cassandra_connection.settings_dict["OPTIONS"][ "connection" ] opts = { "lazy_connect": connection_options.pop("lazy_connect", False), "retry_connect": connection_options.pop("retry_connect", False), "consistency": connection_options.pop("consistency", None), } self.assertEqual(self.connection.connection_options, opts) @patch("django_cassandra_engine.connection.connection") def test_register_connection_called_first_time_with_proper_options( self, connection_mock ): settings = self.cassandra_connection.settings_dict connection = CassandraConnection("default", **settings) connection_mock.get_connection.side_effect = CQLEngineException() connection.register() connection_mock.register_connection.assert_called_once_with( <|code_end|> , predict the next line using imports from the current file: from copy import copy from unittest import TestCase from cassandra import ConsistencyLevel from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster from cassandra.cqlengine import CQLEngineException from mock import Mock, patch from django_cassandra_engine.connection import CassandraConnection, Cursor from django_cassandra_engine.utils import get_cassandra_connection from cassandra.cqlengine import connection as cql_connection from cassandra.cqlengine import connection as cql_connection from cassandra.cqlengine import connection as cql_connection import mock and context including class names, function names, and sometimes code from other files: # Path: django_cassandra_engine/connection.py # class CassandraConnection(object): # def __init__(self, alias, **options): # self.alias = alias # self.hosts = options.get("HOST").split(",") # self.keyspace = options.get("NAME") # self.user = options.get("USER") # self.password = options.get("PASSWORD") # self.options = options.get("OPTIONS", {}) # self.cluster_options = self.options.get("connection", {}) # self.session_options = self.options.get("session", {}) # self.connection_options = { # "lazy_connect": self.cluster_options.pop("lazy_connect", False), # "retry_connect": self.cluster_options.pop("retry_connect", False), # "consistency": self.cluster_options.pop("consistency", None), # } # if self.user and self.password and "auth_provider" not in self.cluster_options: # self.cluster_options["auth_provider"] = PlainTextAuthProvider( # username=self.user, password=self.password # ) # # self.default = ( # alias == "default" # or len(list(get_cassandra_connections())) == 1 # or self.cluster_options.pop("default", False) # ) # # self.register() # # def register(self): # try: # connection.get_connection(name=self.alias) # except CQLEngineException: # if self.default: # from cassandra.cqlengine import models # # models.DEFAULT_KEYSPACE = self.keyspace # # for option, value in self.session_options.items(): # setattr(Session, option, value) # if "cloud" in self.cluster_options: # cluster = Cluster(**self.cluster_options) # session = cluster.connect() # connection.register_connection( # self.alias, default=self.default, session=session # ) # else: # connection.register_connection( # self.alias, # hosts=self.hosts, # default=self.default, # cluster_options=self.cluster_options, # **self.connection_options # ) # # @property # def cluster(self): # return connection.get_cluster(connection=self.alias) # # @property # def session(self): # return connection.get_session(connection=self.alias) # # def commit(self): # pass # # def rollback(self): # pass # # def cursor(self): # return Cursor(self) # # def execute(self, qs, *args, **kwargs): # self.session.set_keyspace(self.keyspace) # return self.session.execute(qs, *args, **kwargs) # # def close(self): # """We would like to keep connection always open by default""" # # def unregister(self): # """Unregister this connection""" # connection.unregister_connection(self.alias) # # class Cursor(object): # def __init__(self, connection): # self.connection = connection # # def execute(self, *args, **kwargs): # return self.connection.execute(*args, **kwargs) # # def close(self): # pass # # def fetchmany(self, _): # return [] # # def __enter__(self): # return self # # def __exit__(self, type, value, traceback): # self.close() # # Path: django_cassandra_engine/utils.py # def get_cassandra_connection(alias=None, name=None): # """:return: cassandra connection matching alias or name or just first found.""" # for _alias, connection in get_cassandra_connections(): # if alias is not None: # if alias == _alias: # return connection # elif name is not None: # if name == connection.settings_dict["NAME"]: # return connection # else: # return connection . Output only the next line.
"default",
Predict the next line for this snippet: <|code_start|> connection = CassandraConnection("default", **settings) connection_mock.get_connection.side_effect = CQLEngineException() connection.register() connection_mock.register_connection.assert_called_once_with( "default", hosts=connection.hosts, default=mock.ANY, cluster_options=connection.cluster_options, **connection.connection_options ) @patch("django_cassandra_engine.connection.connection") def test_connection_register_called_second_time(self, connection_mock): settings = self.cassandra_connection.settings_dict CassandraConnection("default", **settings) connection_mock.get_connection.side_effect = CQLEngineException() self.assertFalse(connection_mock.register_connection.called) def test_connection_auth_provider_added_to_connection_options(self): settings = self.cassandra_connection.settings_dict settings["USER"] = "user" settings["PASSWORD"] = "pass" connection = CassandraConnection("default", **settings) self.assertIsInstance( connection.cluster_options["auth_provider"], PlainTextAuthProvider ) <|code_end|> with the help of current file imports: from copy import copy from unittest import TestCase from cassandra import ConsistencyLevel from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster from cassandra.cqlengine import CQLEngineException from mock import Mock, patch from django_cassandra_engine.connection import CassandraConnection, Cursor from django_cassandra_engine.utils import get_cassandra_connection from cassandra.cqlengine import connection as cql_connection from cassandra.cqlengine import connection as cql_connection from cassandra.cqlengine import connection as cql_connection import mock and context from other files: # Path: django_cassandra_engine/connection.py # class CassandraConnection(object): # def __init__(self, alias, **options): # self.alias = alias # self.hosts = options.get("HOST").split(",") # self.keyspace = options.get("NAME") # self.user = options.get("USER") # self.password = options.get("PASSWORD") # self.options = options.get("OPTIONS", {}) # self.cluster_options = self.options.get("connection", {}) # self.session_options = self.options.get("session", {}) # self.connection_options = { # "lazy_connect": self.cluster_options.pop("lazy_connect", False), # "retry_connect": self.cluster_options.pop("retry_connect", False), # "consistency": self.cluster_options.pop("consistency", None), # } # if self.user and self.password and "auth_provider" not in self.cluster_options: # self.cluster_options["auth_provider"] = PlainTextAuthProvider( # username=self.user, password=self.password # ) # # self.default = ( # alias == "default" # or len(list(get_cassandra_connections())) == 1 # or self.cluster_options.pop("default", False) # ) # # self.register() # # def register(self): # try: # connection.get_connection(name=self.alias) # except CQLEngineException: # if self.default: # from cassandra.cqlengine import models # # models.DEFAULT_KEYSPACE = self.keyspace # # for option, value in self.session_options.items(): # setattr(Session, option, value) # if "cloud" in self.cluster_options: # cluster = Cluster(**self.cluster_options) # session = cluster.connect() # connection.register_connection( # self.alias, default=self.default, session=session # ) # else: # connection.register_connection( # self.alias, # hosts=self.hosts, # default=self.default, # cluster_options=self.cluster_options, # **self.connection_options # ) # # @property # def cluster(self): # return connection.get_cluster(connection=self.alias) # # @property # def session(self): # return connection.get_session(connection=self.alias) # # def commit(self): # pass # # def rollback(self): # pass # # def cursor(self): # return Cursor(self) # # def execute(self, qs, *args, **kwargs): # self.session.set_keyspace(self.keyspace) # return self.session.execute(qs, *args, **kwargs) # # def close(self): # """We would like to keep connection always open by default""" # # def unregister(self): # """Unregister this connection""" # connection.unregister_connection(self.alias) # # class Cursor(object): # def __init__(self, connection): # self.connection = connection # # def execute(self, *args, **kwargs): # return self.connection.execute(*args, **kwargs) # # def close(self): # pass # # def fetchmany(self, _): # return [] # # def __enter__(self): # return self # # def __exit__(self, type, value, traceback): # self.close() # # Path: django_cassandra_engine/utils.py # def get_cassandra_connection(alias=None, name=None): # """:return: cassandra connection matching alias or name or just first found.""" # for _alias, connection in get_cassandra_connections(): # if alias is not None: # if alias == _alias: # return connection # elif name is not None: # if name == connection.settings_dict["NAME"]: # return connection # else: # return connection , which may contain function names, class names, or code. Output only the next line.
@patch("django_cassandra_engine.connection.CassandraConnection.register")
Here is a snippet: <|code_start|> self.connection = self.cassandra_connection.connection self.cassandra_connection.connect() def test_cursor(self): self.assertIsInstance(self.connection.cursor(), Cursor) self.assertEqual(self.connection.cursor().connection, self.connection) def test_connected_to_db(self): self.assertIsInstance(cql_connection.cluster, Cluster) self.assertIsNotNone(cql_connection.session) def test_session_property(self): self.assertEqual( self.connection.session, cql_connection._connections[self.connection.alias].session, ) def test_cluster_property(self): self.assertEqual( self.connection.cluster, cql_connection._connections[self.connection.alias].cluster, ) <|code_end|> . Write the next line using the current file imports: from copy import copy from unittest import TestCase from cassandra import ConsistencyLevel from cassandra.auth import PlainTextAuthProvider from cassandra.cluster import Cluster from cassandra.cqlengine import CQLEngineException from mock import Mock, patch from django_cassandra_engine.connection import CassandraConnection, Cursor from django_cassandra_engine.utils import get_cassandra_connection from cassandra.cqlengine import connection as cql_connection from cassandra.cqlengine import connection as cql_connection from cassandra.cqlengine import connection as cql_connection import mock and context from other files: # Path: django_cassandra_engine/connection.py # class CassandraConnection(object): # def __init__(self, alias, **options): # self.alias = alias # self.hosts = options.get("HOST").split(",") # self.keyspace = options.get("NAME") # self.user = options.get("USER") # self.password = options.get("PASSWORD") # self.options = options.get("OPTIONS", {}) # self.cluster_options = self.options.get("connection", {}) # self.session_options = self.options.get("session", {}) # self.connection_options = { # "lazy_connect": self.cluster_options.pop("lazy_connect", False), # "retry_connect": self.cluster_options.pop("retry_connect", False), # "consistency": self.cluster_options.pop("consistency", None), # } # if self.user and self.password and "auth_provider" not in self.cluster_options: # self.cluster_options["auth_provider"] = PlainTextAuthProvider( # username=self.user, password=self.password # ) # # self.default = ( # alias == "default" # or len(list(get_cassandra_connections())) == 1 # or self.cluster_options.pop("default", False) # ) # # self.register() # # def register(self): # try: # connection.get_connection(name=self.alias) # except CQLEngineException: # if self.default: # from cassandra.cqlengine import models # # models.DEFAULT_KEYSPACE = self.keyspace # # for option, value in self.session_options.items(): # setattr(Session, option, value) # if "cloud" in self.cluster_options: # cluster = Cluster(**self.cluster_options) # session = cluster.connect() # connection.register_connection( # self.alias, default=self.default, session=session # ) # else: # connection.register_connection( # self.alias, # hosts=self.hosts, # default=self.default, # cluster_options=self.cluster_options, # **self.connection_options # ) # # @property # def cluster(self): # return connection.get_cluster(connection=self.alias) # # @property # def session(self): # return connection.get_session(connection=self.alias) # # def commit(self): # pass # # def rollback(self): # pass # # def cursor(self): # return Cursor(self) # # def execute(self, qs, *args, **kwargs): # self.session.set_keyspace(self.keyspace) # return self.session.execute(qs, *args, **kwargs) # # def close(self): # """We would like to keep connection always open by default""" # # def unregister(self): # """Unregister this connection""" # connection.unregister_connection(self.alias) # # class Cursor(object): # def __init__(self, connection): # self.connection = connection # # def execute(self, *args, **kwargs): # return self.connection.execute(*args, **kwargs) # # def close(self): # pass # # def fetchmany(self, _): # return [] # # def __enter__(self): # return self # # def __exit__(self, type, value, traceback): # self.close() # # Path: django_cassandra_engine/utils.py # def get_cassandra_connection(alias=None, name=None): # """:return: cassandra connection matching alias or name or just first found.""" # for _alias, connection in get_cassandra_connections(): # if alias is not None: # if alias == _alias: # return connection # elif name is not None: # if name == connection.settings_dict["NAME"]: # return connection # else: # return connection , which may include functions, classes, or code. Output only the next line.
def test_connection_options(self):
Given the following code snippet before the placeholder: <|code_start|> class ModelsTestCase(TestCase): def test_check_if_test_model_synced(self): now = datetime(2010, 1, 1, 1, 1) TestModel.objects.create(id=1, created_at=now) self.assertEqual(TestModel.objects.count(), 1) obj = TestModel.objects.all()[0] self.assertEqual(obj.id, 1) <|code_end|> , predict the next line using imports from the current file: from datetime import datetime from django.db import connections from django_cassandra_engine.test import TestCase from multiapp.models import ( TestModel, TestModel2, TestModel3, ) and context including class names, function names, and sometimes code from other files: # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) . Output only the next line.
self.assertEqual(obj.created_at, now)
Here is a snippet: <|code_start|> self.session.modified = False self.session.accessed = False self.assertIn("some key", self.session) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_values(self): self.assertEqual(list(self.session.values()), []) self.assertTrue(self.session.accessed) self.session["some key"] = 1 self.assertEqual(list(self.session.values()), [1]) def test_iterkeys(self): self.session["x"] = 1 self.session.modified = False self.session.accessed = False i = self.session.keys() self.assertTrue(hasattr(i, "__iter__")) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) self.assertEqual(list(i), ["x"]) def test_itervalues(self): self.session["x"] = 1 self.session.modified = False self.session.accessed = False i = self.session.values() self.assertTrue(hasattr(i, "__iter__")) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) <|code_end|> . Write the next line using the current file imports: from datetime import timedelta from django.conf import settings from django.core.cache import InvalidCacheBackendError from django.test.utils import override_settings from django.utils import timezone from django.utils.encoding import force_str from mock import Mock from django_cassandra_engine.sessions.backends.cached_db import ( SessionStore as CachedDatabaseSession, ) from django_cassandra_engine.sessions.backends.db import ( SessionStore as DatabaseSession, ) from django_cassandra_engine.test import TestCase from django.test.utils import ignore_warnings import string import unittest and context from other files: # Path: django_cassandra_engine/sessions/backends/cached_db.py # class SessionStore(DBStore, CachedStore): # """Implements cached, cassandra backed sessions.""" # # cache_key_prefix = KEY_PREFIX # # Path: django_cassandra_engine/sessions/backends/db.py # class SessionStore(DjangoSessionStore): # @classmethod # def get_model_class(cls): # """Avoid circular import""" # from django_cassandra_engine.sessions.models import Session # # return Session # # @cached_property # def model(self): # return self.get_model_class() # # def create_model_instance(self, data): # """ # Return a new instance of the session model object, which represents the # current session state. Intended to be used for saving the session data # to the database. # :param data: # """ # return self.model( # session_key=self._get_or_create_session_key(), # session_data=self.encode(data), # expire_date=self.get_expiry_date(), # ) # # def load(self): # try: # s = self.model.objects.get(session_key=self.session_key) # if s.expire_date <= datetime.now(): # s.delete() # raise SuspiciousOperation("old session detected") # return self.decode(s.session_data) # except (self.model.DoesNotExist, SuspiciousOperation) as e: # if isinstance(e, SuspiciousOperation): # logger = logging.getLogger("django.security.%s" % e.__class__.__name__) # logger.warning(force_str(e)) # self.create() # return {} # # def exists(self, session_key): # try: # self.model.objects.get(session_key=session_key) # return True # except self.model.DoesNotExist: # return False # # def save(self, must_create=False): # """ # Saves the current session data to the database. If 'must_create' is # True, a database error will be raised if the saving operation doesn't # create a *new* entry (as opposed to possibly updating an existing # entry). # # :param must_create: # """ # if self.session_key is None: # return self.create() # data = self._get_session(no_load=must_create) # obj = self.create_model_instance(data) # obj.save() # # def delete(self, session_key=None): # if session_key is None: # if not self.session_key: # return # session_key = self.session_key # # self.model.objects.filter(session_key=session_key).delete() # # @classmethod # def clear_expired(cls): # """TODO: implement this""" # # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) , which may include functions, classes, or code. Output only the next line.
self.assertEqual(list(i), [1])
Given the following code snippet before the placeholder: <|code_start|> def test_store(self): self.session["cat"] = "dog" self.assertTrue(self.session.modified) self.assertEqual(self.session.pop("cat"), "dog") def test_pop(self): self.session["some key"] = "exists" # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop("some key"), "exists") self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get("some key"), None) def test_pop_default(self): self.assertEqual( self.session.pop("some key", "does not exist"), "does not exist" ) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_setdefault(self): self.assertEqual(self.session.setdefault("foo", "bar"), "bar") self.assertEqual(self.session.setdefault("foo", "baz"), "bar") self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_update(self): <|code_end|> , predict the next line using imports from the current file: from datetime import timedelta from django.conf import settings from django.core.cache import InvalidCacheBackendError from django.test.utils import override_settings from django.utils import timezone from django.utils.encoding import force_str from mock import Mock from django_cassandra_engine.sessions.backends.cached_db import ( SessionStore as CachedDatabaseSession, ) from django_cassandra_engine.sessions.backends.db import ( SessionStore as DatabaseSession, ) from django_cassandra_engine.test import TestCase from django.test.utils import ignore_warnings import string import unittest and context including class names, function names, and sometimes code from other files: # Path: django_cassandra_engine/sessions/backends/cached_db.py # class SessionStore(DBStore, CachedStore): # """Implements cached, cassandra backed sessions.""" # # cache_key_prefix = KEY_PREFIX # # Path: django_cassandra_engine/sessions/backends/db.py # class SessionStore(DjangoSessionStore): # @classmethod # def get_model_class(cls): # """Avoid circular import""" # from django_cassandra_engine.sessions.models import Session # # return Session # # @cached_property # def model(self): # return self.get_model_class() # # def create_model_instance(self, data): # """ # Return a new instance of the session model object, which represents the # current session state. Intended to be used for saving the session data # to the database. # :param data: # """ # return self.model( # session_key=self._get_or_create_session_key(), # session_data=self.encode(data), # expire_date=self.get_expiry_date(), # ) # # def load(self): # try: # s = self.model.objects.get(session_key=self.session_key) # if s.expire_date <= datetime.now(): # s.delete() # raise SuspiciousOperation("old session detected") # return self.decode(s.session_data) # except (self.model.DoesNotExist, SuspiciousOperation) as e: # if isinstance(e, SuspiciousOperation): # logger = logging.getLogger("django.security.%s" % e.__class__.__name__) # logger.warning(force_str(e)) # self.create() # return {} # # def exists(self, session_key): # try: # self.model.objects.get(session_key=session_key) # return True # except self.model.DoesNotExist: # return False # # def save(self, must_create=False): # """ # Saves the current session data to the database. If 'must_create' is # True, a database error will be raised if the saving operation doesn't # create a *new* entry (as opposed to possibly updating an existing # entry). # # :param must_create: # """ # if self.session_key is None: # return self.create() # data = self._get_session(no_load=must_create) # obj = self.create_model_instance(data) # obj.save() # # def delete(self, session_key=None): # if session_key is None: # if not self.session_key: # return # session_key = self.session_key # # self.model.objects.filter(session_key=session_key).delete() # # @classmethod # def clear_expired(cls): # """TODO: implement this""" # # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) . Output only the next line.
self.session.update({"update key": 1})
Continue the code snippet: <|code_start|> self.assertEqual(self.session.get("some key"), None) def test_pop_default(self): self.assertEqual( self.session.pop("some key", "does not exist"), "does not exist" ) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_setdefault(self): self.assertEqual(self.session.setdefault("foo", "bar"), "bar") self.assertEqual(self.session.setdefault("foo", "baz"), "bar") self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) def test_update(self): self.session.update({"update key": 1}) self.assertTrue(self.session.accessed) self.assertTrue(self.session.modified) self.assertEqual(self.session.get("update key", None), 1) def test_has_key(self): self.session["some key"] = 1 self.session.modified = False self.session.accessed = False self.assertIn("some key", self.session) self.assertTrue(self.session.accessed) self.assertFalse(self.session.modified) def test_values(self): <|code_end|> . Use current file imports: from datetime import timedelta from django.conf import settings from django.core.cache import InvalidCacheBackendError from django.test.utils import override_settings from django.utils import timezone from django.utils.encoding import force_str from mock import Mock from django_cassandra_engine.sessions.backends.cached_db import ( SessionStore as CachedDatabaseSession, ) from django_cassandra_engine.sessions.backends.db import ( SessionStore as DatabaseSession, ) from django_cassandra_engine.test import TestCase from django.test.utils import ignore_warnings import string import unittest and context (classes, functions, or code) from other files: # Path: django_cassandra_engine/sessions/backends/cached_db.py # class SessionStore(DBStore, CachedStore): # """Implements cached, cassandra backed sessions.""" # # cache_key_prefix = KEY_PREFIX # # Path: django_cassandra_engine/sessions/backends/db.py # class SessionStore(DjangoSessionStore): # @classmethod # def get_model_class(cls): # """Avoid circular import""" # from django_cassandra_engine.sessions.models import Session # # return Session # # @cached_property # def model(self): # return self.get_model_class() # # def create_model_instance(self, data): # """ # Return a new instance of the session model object, which represents the # current session state. Intended to be used for saving the session data # to the database. # :param data: # """ # return self.model( # session_key=self._get_or_create_session_key(), # session_data=self.encode(data), # expire_date=self.get_expiry_date(), # ) # # def load(self): # try: # s = self.model.objects.get(session_key=self.session_key) # if s.expire_date <= datetime.now(): # s.delete() # raise SuspiciousOperation("old session detected") # return self.decode(s.session_data) # except (self.model.DoesNotExist, SuspiciousOperation) as e: # if isinstance(e, SuspiciousOperation): # logger = logging.getLogger("django.security.%s" % e.__class__.__name__) # logger.warning(force_str(e)) # self.create() # return {} # # def exists(self, session_key): # try: # self.model.objects.get(session_key=session_key) # return True # except self.model.DoesNotExist: # return False # # def save(self, must_create=False): # """ # Saves the current session data to the database. If 'must_create' is # True, a database error will be raised if the saving operation doesn't # create a *new* entry (as opposed to possibly updating an existing # entry). # # :param must_create: # """ # if self.session_key is None: # return self.create() # data = self._get_session(no_load=must_create) # obj = self.create_model_instance(data) # obj.save() # # def delete(self, session_key=None): # if session_key is None: # if not self.session_key: # return # session_key = self.session_key # # self.model.objects.filter(session_key=session_key).delete() # # @classmethod # def clear_expired(cls): # """TODO: implement this""" # # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) . Output only the next line.
self.assertEqual(list(self.session.values()), [])
Predict the next line for this snippet: <|code_start|> class ModelsTestCase(TestCase): def test_check_if_model_synced(self): now = datetime(2010, 1, 1, 1, 1) ExampleModel.objects.create(id=1, created_at=now) self.assertEqual(ExampleModel.objects.count(), 1) obj = ExampleModel.objects.all()[0] self.assertEqual(obj.id, 1) self.assertEqual(obj.created_at, now) def test_check_if_model_saved_to_test_keyspace(self): now = datetime(2010, 1, 1, 1, 1) obj_id = 123456 obj = ExampleModel.objects.create(id=obj_id, created_at=now) self.assertEqual(obj.__keyspace__, "test_db") session = get_session() session.set_keyspace("test_db") self.assertEqual( session.execute("SELECT id FROM example_model")[0]["id"], obj_id ) def test_truncate_models_before_running_tests_works(self): self.assertEqual(ExampleModel.objects.count(), 0) <|code_end|> with the help of current file imports: from datetime import datetime from app.models import ExampleModel, ExampleModel2 from django_cassandra_engine.test import TestCase from cassandra.cqlengine.connection import get_session and context from other files: # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) , which may contain function names, class names, or code. Output only the next line.
self.assertEqual(ExampleModel2.objects.count(), 0)
Based on the snippet: <|code_start|> class TestCase(DjangoTestCase): databases = list(get_cassandra_db_aliases()) def _should_reload_connections(self): <|code_end|> , predict the immediate next line with the help of imports: from django.core.management import call_command from django.test import TestCase as DjangoTestCase from django_cassandra_engine.utils import ( get_cassandra_connections, get_cassandra_db_aliases, ) and context (classes, functions, sometimes code) from other files: # Path: django_cassandra_engine/utils.py # def get_cassandra_connections(): # """ # :return: List of tuples (db_alias, connection) for all cassandra # connections in DATABASES dict. # """ # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias, connections[alias] # # def get_cassandra_db_aliases(): # from django.db import connections # # for alias in connections: # engine = connections[alias].settings_dict.get("ENGINE", "") # if engine == "django_cassandra_engine": # yield alias . Output only the next line.
return False
Given the following code snippet before the placeholder: <|code_start|> class CassandraDatabaseIntrospection(BaseDatabaseIntrospection): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cql_models = {} self._models_discovered = False <|code_end|> , predict the next line using imports from the current file: from itertools import chain from django.db.backends.base.introspection import BaseDatabaseIntrospection from django_cassandra_engine.utils import get_cql_models, get_installed_apps and context including class names, function names, and sometimes code from other files: # Path: django_cassandra_engine/utils.py # def get_cql_models(app, connection=None, keyspace=None): # """ # :param app: django models module # :param connection: connection name # :param keyspace: keyspace # :return: list of all cassandra.cqlengine.Model within app that should be # synced to keyspace. # """ # from .models import DjangoCassandraModel # # models = [] # single_cassandra_connection = len(list(get_cassandra_connections())) == 1 # is_default_connection = ( # connection == DEFAULT_DB_ALIAS or single_cassandra_connection # ) # # for name, obj in inspect.getmembers(app): # cql_model_types = (cqlengine.models.Model, DjangoCassandraModel) # if ( # inspect.isclass(obj) # and issubclass(obj, cql_model_types) # and not obj.__abstract__ # ): # if ( # obj.__connection__ == connection # or (obj.__connection__ is None and is_default_connection) # or obj.__connection__ is None # and obj.__keyspace__ is not None # and obj.__keyspace__ == keyspace # ): # models.append(obj) # # return models # # def get_installed_apps(): # """Return list of all installed apps""" # from django.apps import apps # # return [ # a.models_module for a in apps.get_app_configs() if a.models_module is not None # ] . Output only the next line.
def _discover_models(self):
Given the code snippet: <|code_start|> class CassandraDatabaseIntrospection(BaseDatabaseIntrospection): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._cql_models = {} self._models_discovered = False <|code_end|> , generate the next line using the imports in this file: from itertools import chain from django.db.backends.base.introspection import BaseDatabaseIntrospection from django_cassandra_engine.utils import get_cql_models, get_installed_apps and context (functions, classes, or occasionally code) from other files: # Path: django_cassandra_engine/utils.py # def get_cql_models(app, connection=None, keyspace=None): # """ # :param app: django models module # :param connection: connection name # :param keyspace: keyspace # :return: list of all cassandra.cqlengine.Model within app that should be # synced to keyspace. # """ # from .models import DjangoCassandraModel # # models = [] # single_cassandra_connection = len(list(get_cassandra_connections())) == 1 # is_default_connection = ( # connection == DEFAULT_DB_ALIAS or single_cassandra_connection # ) # # for name, obj in inspect.getmembers(app): # cql_model_types = (cqlengine.models.Model, DjangoCassandraModel) # if ( # inspect.isclass(obj) # and issubclass(obj, cql_model_types) # and not obj.__abstract__ # ): # if ( # obj.__connection__ == connection # or (obj.__connection__ is None and is_default_connection) # or obj.__connection__ is None # and obj.__keyspace__ is not None # and obj.__keyspace__ == keyspace # ): # models.append(obj) # # return models # # def get_installed_apps(): # """Return list of all installed apps""" # from django.apps import apps # # return [ # a.models_module for a in apps.get_app_configs() if a.models_module is not None # ] . Output only the next line.
def _discover_models(self):
Given the code snippet: <|code_start|> class Command(SyncCommand): def handle_noargs(self, **options): engine = get_engine_from_db_alias(options["database"]) # Call regular syncdb if engine is different from ours if engine != "django_cassandra_engine": return super(Command, self).handle_noargs(**options) else: return sync_cassandra.Command().execute(**options) def handle(self, **options): engine = get_engine_from_db_alias(options["database"]) # Call regular syncdb if engine is different from ours if engine != "django_cassandra_engine": return super(Command, self).handle(**options) <|code_end|> , generate the next line using the imports in this file: from django_cassandra_engine.management.commands import sync_cassandra from django_cassandra_engine.management.commands.sync_cassandra import ( Command as SyncCommand, ) from django_cassandra_engine.utils import get_engine_from_db_alias and context (functions, classes, or occasionally code) from other files: # Path: django_cassandra_engine/management/commands/sync_cassandra.py # class Command(BaseCommand): # def add_arguments(self, parser): # def _import_management(): # def sync(self, alias): # def handle(self, **options): # # Path: django_cassandra_engine/management/commands/sync_cassandra.py # class Command(BaseCommand): # help = "Sync Cassandra database(s)" # # def add_arguments(self, parser): # parser.add_argument( # "--database", # action="store", # dest="database", # default=None, # help="Nominates a database to synchronize.", # ) # # @staticmethod # def _import_management(): # """ # Import the 'management' module within each installed app, to register # dispatcher events. # """ # from importlib import import_module # # for app_config in apps.get_app_configs(): # try: # import_module(".management", app_config.name) # except SystemError: # # We get SystemError if INSTALLED_APPS contains the # # name of a class rather than a module # pass # except ImportError as exc: # # This is slightly hackish. We want to ignore ImportErrors # # if the "management" module itself is missing -- but we don't # # want to ignore the exception if the management module exists # # but raises an ImportError for some reason. The only way we # # can do this is to check the text of the exception. Note that # # we're a bit broad in how we check the text, because different # # Python implementations may not use the same text. # # CPython uses the text "No module named management" # # PyPy uses "No module named myproject.myapp.management" # msg = exc.args[0] # if not msg.startswith("No module named") or "management" not in msg: # raise # # def sync(self, alias): # engine = get_engine_from_db_alias(alias) # # if engine != "django_cassandra_engine": # raise CommandError("Database {} is not cassandra!".format(alias)) # # connection = connections[alias] # connection.connect() # options = connection.settings_dict.get("OPTIONS", {}) # keyspace = connection.settings_dict["NAME"] # replication_opts = options.get("replication", {}) # strategy_class = replication_opts.pop("strategy_class", "SimpleStrategy") # replication_factor = replication_opts.pop("replication_factor", 1) # # self.stdout.write( # "Creating keyspace {} [CONNECTION {}] ..".format(keyspace, alias) # ) # # if strategy_class == "SimpleStrategy": # management.create_keyspace_simple( # keyspace, replication_factor, connections=[alias] # ) # else: # management.create_keyspace_network_topology( # keyspace, replication_opts, connections=[alias] # ) # # connection.connection.cluster.refresh_schema_metadata() # connection.connection.cluster.schema_metadata_enabled = True # # for app_name, app_models in connection.introspection.cql_models.items(): # for model in app_models: # self.stdout.write("Syncing %s.%s" % (app_name, model.__name__)) # # patch this object used for type check in management.sync_table() # management.Model = (Model, DjangoCassandraModel) # management.sync_table(model, keyspaces=[keyspace], connections=[alias]) # # def handle(self, **options): # # self._import_management() # # database = options.get("database") # if database is not None: # return self.sync(database) # # cassandra_alias = None # for alias in connections: # engine = get_engine_from_db_alias(alias) # if engine == "django_cassandra_engine": # self.sync(alias) # cassandra_alias = alias # # if cassandra_alias is None: # raise CommandError( # "Please add django_cassandra_engine backend to DATABASES!" # ) # # Path: django_cassandra_engine/utils.py # def get_engine_from_db_alias(db_alias): # """ # :param db_alias: database alias # :return: database engine from DATABASES dict corresponding to db_alias # or None if db_alias was not found # """ # return settings.DATABASES.get(db_alias, {}).get("ENGINE", None) . Output only the next line.
else:
Using the snippet: <|code_start|> @freeze_time("14-06-15 15:44:25") class TestListCreateAPIView(CassandraTestCase): def test_get_when_no_records_exist(self): response = self.client.get(reverse("thing_listcreate_api")) self.assertEqual(response.status_code, client.OK) self.assertEqual(response.json(), []) def test_post(self): response = self.client.post( reverse("thing_listcreate_api"), {"created_on": "2015-06-14T15:44:25Z"}, ) self.assertEqual(response.status_code, client.CREATED) assert CassandraThingMultiplePK.objects.all().count() == 1 @freeze_time("14-06-15 15:44:25") class TestListAPIView(CassandraTestCase): def test_get(self): thing = create_thing() response = self.client.get(reverse("thing_listview_api")) self.assertEqual(response.status_code, client.OK) expected_response = [ { "created_on": "2015-06-14T15:44:25Z", "data_abstract": None, "another_id": str(thing.another_id), "id": str(thing.id), <|code_end|> , determine the next line of code. You have imports: from datetime import datetime from http import client from django.urls import reverse from common.models import CassandraThingMultiplePK from django_cassandra_engine.test import TestCase as CassandraTestCase from freezegun import freeze_time and context (class names, function names, or code) available: # Path: django_cassandra_engine/test.py # class TestCase(DjangoTestCase): # databases = list(get_cassandra_db_aliases()) # # def _should_reload_connections(self): # return False # # def _fixture_teardown(self): # """ # Allow normal django TestCase fixture teardown, but also flush the test # database for each cassandra alias. # """ # super(TestCase, self)._fixture_teardown() # # for alias, _ in get_cassandra_connections(): # # Flush the database # call_command( # "flush", # verbosity=1, # interactive=False, # database=alias, # skip_checks=True, # reset_sequences=False, # allow_cascade=False, # inhibit_post_migrate=True, # ) . Output only the next line.
}
Based on the snippet: <|code_start|> class ThingMultiplePKViewSet(ViewSet): def list(self, request): queryset = CassandraThingMultiplePK.objects.all() serializer = ThingMultiplePKSerializer(queryset, many=True) return Response(serializer.data) <|code_end|> , predict the immediate next line with the help of imports: from rest_framework.generics import ListAPIView, ListCreateAPIView from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet, ViewSet from .models import CassandraThing, CassandraThingMultiplePK from .serializers import ThingMultiplePKSerializer, ThingSerializer and context (classes, functions, sometimes code) from other files: # Path: testproject/common/models.py # class CassandraThing(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # # class Meta: # get_pk_field = "id" # # class CassandraThingMultiplePK(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # another_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # created_on = cassandra_columns.DateTime() # # class Meta: # get_pk_field = "id" # # Path: testproject/common/serializers.py # class ThingMultiplePKSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThingMultiplePK # fields = "__all__" # # class ThingSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThing # fields = "__all__" . Output only the next line.
class ThingMultiplePKListCreateAPIView(ListCreateAPIView):
Based on the snippet: <|code_start|> class ThingMultiplePKViewSet(ViewSet): def list(self, request): queryset = CassandraThingMultiplePK.objects.all() serializer = ThingMultiplePKSerializer(queryset, many=True) return Response(serializer.data) class ThingMultiplePKListCreateAPIView(ListCreateAPIView): queryset = CassandraThingMultiplePK.objects.all() serializer_class = ThingMultiplePKSerializer <|code_end|> , predict the immediate next line with the help of imports: from rest_framework.generics import ListAPIView, ListCreateAPIView from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet, ViewSet from .models import CassandraThing, CassandraThingMultiplePK from .serializers import ThingMultiplePKSerializer, ThingSerializer and context (classes, functions, sometimes code) from other files: # Path: testproject/common/models.py # class CassandraThing(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # # class Meta: # get_pk_field = "id" # # class CassandraThingMultiplePK(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # another_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # created_on = cassandra_columns.DateTime() # # class Meta: # get_pk_field = "id" # # Path: testproject/common/serializers.py # class ThingMultiplePKSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThingMultiplePK # fields = "__all__" # # class ThingSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThing # fields = "__all__" . Output only the next line.
permission_classes = ()
Predict the next line after this snippet: <|code_start|> class ThingMultiplePKViewSet(ViewSet): def list(self, request): queryset = CassandraThingMultiplePK.objects.all() serializer = ThingMultiplePKSerializer(queryset, many=True) return Response(serializer.data) class ThingMultiplePKListCreateAPIView(ListCreateAPIView): queryset = CassandraThingMultiplePK.objects.all() serializer_class = ThingMultiplePKSerializer permission_classes = () class ThingMultiplePKListAPIView(ListAPIView): queryset = CassandraThingMultiplePK.objects.all() serializer_class = ThingMultiplePKSerializer <|code_end|> using the current file's imports: from rest_framework.generics import ListAPIView, ListCreateAPIView from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet, ViewSet from .models import CassandraThing, CassandraThingMultiplePK from .serializers import ThingMultiplePKSerializer, ThingSerializer and any relevant context from other files: # Path: testproject/common/models.py # class CassandraThing(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # # class Meta: # get_pk_field = "id" # # class CassandraThingMultiplePK(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # another_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # created_on = cassandra_columns.DateTime() # # class Meta: # get_pk_field = "id" # # Path: testproject/common/serializers.py # class ThingMultiplePKSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThingMultiplePK # fields = "__all__" # # class ThingSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThing # fields = "__all__" . Output only the next line.
permission_classes = ()
Next line prediction: <|code_start|> class ThingMultiplePKViewSet(ViewSet): def list(self, request): queryset = CassandraThingMultiplePK.objects.all() serializer = ThingMultiplePKSerializer(queryset, many=True) return Response(serializer.data) class ThingMultiplePKListCreateAPIView(ListCreateAPIView): queryset = CassandraThingMultiplePK.objects.all() serializer_class = ThingMultiplePKSerializer permission_classes = () class ThingMultiplePKListAPIView(ListAPIView): queryset = CassandraThingMultiplePK.objects.all() serializer_class = ThingMultiplePKSerializer permission_classes = () class ThingModelViewSet(ModelViewSet): serializer_class = ThingSerializer queryset = CassandraThing.objects.all() <|code_end|> . Use current file imports: (from rest_framework.generics import ListAPIView, ListCreateAPIView from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet, ViewSet from .models import CassandraThing, CassandraThingMultiplePK from .serializers import ThingMultiplePKSerializer, ThingSerializer) and context including class names, function names, or small code snippets from other files: # Path: testproject/common/models.py # class CassandraThing(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # # class Meta: # get_pk_field = "id" # # class CassandraThingMultiplePK(DjangoCassandraModel): # __keyspace__ = "db" # id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # another_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4) # data_abstract = cassandra_columns.Text(max_length=10) # created_on = cassandra_columns.DateTime() # # class Meta: # get_pk_field = "id" # # Path: testproject/common/serializers.py # class ThingMultiplePKSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThingMultiplePK # fields = "__all__" # # class ThingSerializer(DjangoCassandraModelSerializer): # class Meta: # model = CassandraThing # fields = "__all__" . Output only the next line.
permission_classes = ()
Given snippet: <|code_start|> class TextSendInline(admin.TabularInline): editable = False model = TextSend @admin.register(ShowerThought) class ShowerThoughtAdmin(admin.ModelAdmin): list_display = ('date', 'thought_text', 'post_id', 'active') @admin.register(Subscriber) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from texts.models import Subscriber, TextSend, ShowerThought and context: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # class TextSend(models.Model): # subscriber = models.ForeignKey(Subscriber) # date_sent = models.DateTimeField(auto_now_add=True) # post_id = models.CharField(max_length=20) # message_text = models.CharField(max_length=500) # result_message = models.CharField(max_length=500, null=True, blank=True) # sucess = models.BooleanField(default=True) # # def __unicode__(self): # return self.subscriber.sms_number + ": " + self.post_id + ' - ' + self.message_text # # class ShowerThought(models.Model): # date = models.DateField(auto_now_add=True) # post_id = models.CharField(max_length=20) # thought_text = models.CharField(max_length=500) # url = models.URLField(max_length=300, null=True, blank=True) # active = models.BooleanField(default=True) # bot_notified = models.BooleanField(default=False) # # def __unicode__(self): # return str(self.date) + ' ' + self.thought_text which might include code, classes, or functions. Output only the next line.
class SubscriberAdmin(admin.ModelAdmin):
Based on the snippet: <|code_start|> class TextSendInline(admin.TabularInline): editable = False model = TextSend @admin.register(ShowerThought) class ShowerThoughtAdmin(admin.ModelAdmin): list_display = ('date', 'thought_text', 'post_id', 'active') @admin.register(Subscriber) class SubscriberAdmin(admin.ModelAdmin): readonly_fields = ('date_created',) list_display = ('sms_number', 'date_created', 'date_renewed', 'active', 'expired', 'lifetime') inlines = [ TextSendInline, <|code_end|> , predict the immediate next line with the help of imports: from django.contrib import admin from texts.models import Subscriber, TextSend, ShowerThought and context (classes, functions, sometimes code) from other files: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # class TextSend(models.Model): # subscriber = models.ForeignKey(Subscriber) # date_sent = models.DateTimeField(auto_now_add=True) # post_id = models.CharField(max_length=20) # message_text = models.CharField(max_length=500) # result_message = models.CharField(max_length=500, null=True, blank=True) # sucess = models.BooleanField(default=True) # # def __unicode__(self): # return self.subscriber.sms_number + ": " + self.post_id + ' - ' + self.message_text # # class ShowerThought(models.Model): # date = models.DateField(auto_now_add=True) # post_id = models.CharField(max_length=20) # thought_text = models.CharField(max_length=500) # url = models.URLField(max_length=300, null=True, blank=True) # active = models.BooleanField(default=True) # bot_notified = models.BooleanField(default=False) # # def __unicode__(self): # return str(self.date) + ' ' + self.thought_text . Output only the next line.
]
Given the following code snippet before the placeholder: <|code_start|> class TextSendInline(admin.TabularInline): editable = False model = TextSend @admin.register(ShowerThought) class ShowerThoughtAdmin(admin.ModelAdmin): list_display = ('date', 'thought_text', 'post_id', 'active') @admin.register(Subscriber) class SubscriberAdmin(admin.ModelAdmin): readonly_fields = ('date_created',) list_display = ('sms_number', 'date_created', 'date_renewed', 'active', 'expired', 'lifetime') inlines = [ TextSendInline, <|code_end|> , predict the next line using imports from the current file: from django.contrib import admin from texts.models import Subscriber, TextSend, ShowerThought and context including class names, function names, and sometimes code from other files: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # class TextSend(models.Model): # subscriber = models.ForeignKey(Subscriber) # date_sent = models.DateTimeField(auto_now_add=True) # post_id = models.CharField(max_length=20) # message_text = models.CharField(max_length=500) # result_message = models.CharField(max_length=500, null=True, blank=True) # sucess = models.BooleanField(default=True) # # def __unicode__(self): # return self.subscriber.sms_number + ": " + self.post_id + ' - ' + self.message_text # # class ShowerThought(models.Model): # date = models.DateField(auto_now_add=True) # post_id = models.CharField(max_length=20) # thought_text = models.CharField(max_length=500) # url = models.URLField(max_length=300, null=True, blank=True) # active = models.BooleanField(default=True) # bot_notified = models.BooleanField(default=False) # # def __unicode__(self): # return str(self.date) + ' ' + self.thought_text . Output only the next line.
]
Given the following code snippet before the placeholder: <|code_start|> class Texter(object): def __init__(self): self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) def send_text(self, subscriber, message, post_id): if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): logging.warning('Attempted to send a duplicate text. Won\'t do it.') raise DuplicateTextException() <|code_end|> , predict the next line using imports from the current file: import logging import datetime from django.conf import settings from twilio import TwilioRestException from twilio.rest import TwilioRestClient from texts.models import TextSend, Subscriber from util.showerthoughts import get_todays_thought and context including class names, function names, and sometimes code from other files: # Path: texts/models.py # class TextSend(models.Model): # subscriber = models.ForeignKey(Subscriber) # date_sent = models.DateTimeField(auto_now_add=True) # post_id = models.CharField(max_length=20) # message_text = models.CharField(max_length=500) # result_message = models.CharField(max_length=500, null=True, blank=True) # sucess = models.BooleanField(default=True) # # def __unicode__(self): # return self.subscriber.sms_number + ": " + self.post_id + ' - ' + self.message_text # # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought . Output only the next line.
try:
Here is a snippet: <|code_start|> class Texter(object): def __init__(self): self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) def send_text(self, subscriber, message, post_id): if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): logging.warning('Attempted to send a duplicate text. Won\'t do it.') raise DuplicateTextException() try: self.client.messages.create( to=subscriber.sms_number, from_=settings.TWILIO_NUMBER, body=message, ) <|code_end|> . Write the next line using the current file imports: import logging import datetime from django.conf import settings from twilio import TwilioRestException from twilio.rest import TwilioRestClient from texts.models import TextSend, Subscriber from util.showerthoughts import get_todays_thought and context from other files: # Path: texts/models.py # class TextSend(models.Model): # subscriber = models.ForeignKey(Subscriber) # date_sent = models.DateTimeField(auto_now_add=True) # post_id = models.CharField(max_length=20) # message_text = models.CharField(max_length=500) # result_message = models.CharField(max_length=500, null=True, blank=True) # sucess = models.BooleanField(default=True) # # def __unicode__(self): # return self.subscriber.sms_number + ": " + self.post_id + ' - ' + self.message_text # # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought , which may include functions, classes, or code. Output only the next line.
except TwilioRestException as e:
Using the snippet: <|code_start|> self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) def send_text(self, subscriber, message, post_id): if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): logging.warning('Attempted to send a duplicate text. Won\'t do it.') raise DuplicateTextException() try: self.client.messages.create( to=subscriber.sms_number, from_=settings.TWILIO_NUMBER, body=message, ) except TwilioRestException as e: logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) TextSend.objects.create( subscriber=subscriber, post_id=post_id, message_text=message, sucess=False, result_message=str(e), ) #TODO: refactor into a configurable list if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e): subscriber.active = False subscriber.save() raise e TextSend.objects.create( subscriber=subscriber, post_id=post_id, message_text=message, <|code_end|> , determine the next line of code. You have imports: import logging import datetime from django.conf import settings from twilio import TwilioRestException from twilio.rest import TwilioRestClient from texts.models import TextSend, Subscriber from util.showerthoughts import get_todays_thought and context (class names, function names, or code) available: # Path: texts/models.py # class TextSend(models.Model): # subscriber = models.ForeignKey(Subscriber) # date_sent = models.DateTimeField(auto_now_add=True) # post_id = models.CharField(max_length=20) # message_text = models.CharField(max_length=500) # result_message = models.CharField(max_length=500, null=True, blank=True) # sucess = models.BooleanField(default=True) # # def __unicode__(self): # return self.subscriber.sms_number + ": " + self.post_id + ' - ' + self.message_text # # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought . Output only the next line.
)
Predict the next line for this snippet: <|code_start|> subscriber.active = False subscriber.save() logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) return 'I couldn\'t send a text to that number! (' + str(e.msg) + ')' except DuplicateTextException: # no prob, they already got todays message pass return 'Welcome back! Check your phone!' elif not subscriber.active: # technically they could be blacklisted, but i can't do anything about that return 'Did you reply STOP? Reply START and try again.' else: return 'You\'re already subscribed, yo.' try: message = "Cool! Welcome to ShowerTexts.com! You'll start receiving Shower Texts daily. " \ "Reply STOP at any time if you get sick of them. " \ "Your first one will follow..." texter.send_text(subscriber, message, 'initial') except TwilioRestException as e: logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) return 'I couldn\'t send a text to that number! (' + str(e.msg) + ')' except DuplicateTextException: logging.warning('Duplicate welcome text.') thought = get_todays_thought() try: texter.send_text(subscriber, thought.thought_text, thought.post_id) except TwilioRestException as e: logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) return 'I couldn\'t send a text to that number! (' + str(e.msg) + ')' except DuplicateTextException: <|code_end|> with the help of current file imports: import logging from texts.models import Subscriber from twilio import TwilioRestException from util.showerthoughts import get_todays_thought from util.texter import DuplicateTextException, Texter and context from other files: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought # # Path: util/texter.py # class DuplicateTextException(Exception): # pass # # class Texter(object): # def __init__(self): # self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) # # def send_text(self, subscriber, message, post_id): # if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): # logging.warning('Attempted to send a duplicate text. Won\'t do it.') # raise DuplicateTextException() # try: # self.client.messages.create( # to=subscriber.sms_number, # from_=settings.TWILIO_NUMBER, # body=message, # ) # except TwilioRestException as e: # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # sucess=False, # result_message=str(e), # ) # #TODO: refactor into a configurable list # if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e): # subscriber.active = False # subscriber.save() # raise e # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # ) # # def send_todays_texts(self): # ret = [] # thought = get_todays_thought() # for subscriber in Subscriber.objects.filter(active=True): # row = {'to': subscriber, 'action': 'showertext'} # message = thought.thought_text # post_id = thought.post_id # if subscriber.expired: # row['action'] = 'expiration' # subscriber.active = False # subscriber.save() # message = 'HOUSE KEEPING! I\'m clearing out old numbers to make room for more. If you like these, ' \ # 'please resubscribe for free! http://www.showertexts.com' # post_id = 'EXP-' + str(datetime.date.today()) # try: # self.send_text(subscriber, message, post_id) # row['result'] = 'Success' # except DuplicateTextException: # row['result'] = 'Duplicate' # except TwilioRestException as ex: # row['result'] = 'Exception: ' + str(ex) # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(ex)) # ret.append(row) # return ret , which may contain function names, class names, or code. Output only the next line.
logging.error('Duplicate initial thought. Shouldn\'t happen - odd.')
Predict the next line after this snippet: <|code_start|> def subscribe(sms_number): if not sms_number: return 'You sent nothing yo.' sms_number = filter(str.isdigit, str(sms_number)) subscriber, created = Subscriber.objects.get_or_create(sms_number=sms_number) texter = Texter() if not created: <|code_end|> using the current file's imports: import logging from texts.models import Subscriber from twilio import TwilioRestException from util.showerthoughts import get_todays_thought from util.texter import DuplicateTextException, Texter and any relevant context from other files: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought # # Path: util/texter.py # class DuplicateTextException(Exception): # pass # # class Texter(object): # def __init__(self): # self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) # # def send_text(self, subscriber, message, post_id): # if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): # logging.warning('Attempted to send a duplicate text. Won\'t do it.') # raise DuplicateTextException() # try: # self.client.messages.create( # to=subscriber.sms_number, # from_=settings.TWILIO_NUMBER, # body=message, # ) # except TwilioRestException as e: # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # sucess=False, # result_message=str(e), # ) # #TODO: refactor into a configurable list # if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e): # subscriber.active = False # subscriber.save() # raise e # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # ) # # def send_todays_texts(self): # ret = [] # thought = get_todays_thought() # for subscriber in Subscriber.objects.filter(active=True): # row = {'to': subscriber, 'action': 'showertext'} # message = thought.thought_text # post_id = thought.post_id # if subscriber.expired: # row['action'] = 'expiration' # subscriber.active = False # subscriber.save() # message = 'HOUSE KEEPING! I\'m clearing out old numbers to make room for more. If you like these, ' \ # 'please resubscribe for free! http://www.showertexts.com' # post_id = 'EXP-' + str(datetime.date.today()) # try: # self.send_text(subscriber, message, post_id) # row['result'] = 'Success' # except DuplicateTextException: # row['result'] = 'Duplicate' # except TwilioRestException as ex: # row['result'] = 'Exception: ' + str(ex) # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(ex)) # ret.append(row) # return ret . Output only the next line.
if subscriber.expired:
Here is a snippet: <|code_start|> def subscribe(sms_number): if not sms_number: return 'You sent nothing yo.' sms_number = filter(str.isdigit, str(sms_number)) subscriber, created = Subscriber.objects.get_or_create(sms_number=sms_number) texter = Texter() if not created: if subscriber.expired: # yay! a renewal subscriber.renew() <|code_end|> . Write the next line using the current file imports: import logging from texts.models import Subscriber from twilio import TwilioRestException from util.showerthoughts import get_todays_thought from util.texter import DuplicateTextException, Texter and context from other files: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought # # Path: util/texter.py # class DuplicateTextException(Exception): # pass # # class Texter(object): # def __init__(self): # self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) # # def send_text(self, subscriber, message, post_id): # if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): # logging.warning('Attempted to send a duplicate text. Won\'t do it.') # raise DuplicateTextException() # try: # self.client.messages.create( # to=subscriber.sms_number, # from_=settings.TWILIO_NUMBER, # body=message, # ) # except TwilioRestException as e: # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # sucess=False, # result_message=str(e), # ) # #TODO: refactor into a configurable list # if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e): # subscriber.active = False # subscriber.save() # raise e # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # ) # # def send_todays_texts(self): # ret = [] # thought = get_todays_thought() # for subscriber in Subscriber.objects.filter(active=True): # row = {'to': subscriber, 'action': 'showertext'} # message = thought.thought_text # post_id = thought.post_id # if subscriber.expired: # row['action'] = 'expiration' # subscriber.active = False # subscriber.save() # message = 'HOUSE KEEPING! I\'m clearing out old numbers to make room for more. If you like these, ' \ # 'please resubscribe for free! http://www.showertexts.com' # post_id = 'EXP-' + str(datetime.date.today()) # try: # self.send_text(subscriber, message, post_id) # row['result'] = 'Success' # except DuplicateTextException: # row['result'] = 'Duplicate' # except TwilioRestException as ex: # row['result'] = 'Exception: ' + str(ex) # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(ex)) # ret.append(row) # return ret , which may include functions, classes, or code. Output only the next line.
subscriber.save()
Given the following code snippet before the placeholder: <|code_start|> def subscribe(sms_number): if not sms_number: return 'You sent nothing yo.' sms_number = filter(str.isdigit, str(sms_number)) subscriber, created = Subscriber.objects.get_or_create(sms_number=sms_number) texter = Texter() if not created: if subscriber.expired: # yay! a renewal <|code_end|> , predict the next line using imports from the current file: import logging from texts.models import Subscriber from twilio import TwilioRestException from util.showerthoughts import get_todays_thought from util.texter import DuplicateTextException, Texter and context including class names, function names, and sometimes code from other files: # Path: texts/models.py # class Subscriber(models.Model): # sms_number = models.CharField(max_length=20, unique=True) # date_created = models.DateTimeField(auto_now_add=True) # active = models.BooleanField(default=True) # date_renewed = models.DateTimeField(null=True, blank=True) # lifetime = models.BooleanField(default=False) # note = models.CharField(max_length=100, null=True, blank=True) # # @property # def expired(self): # if self.lifetime: # return False # date_renewed = self.date_renewed or self.date_created # # is their renewal date before expiration_days ago? # return date_renewed < timezone.now() - datetime.timedelta(days=settings.EXPIRATION_DAYS) # # def renew(self): # self.date_renewed = timezone.now() # self.active = True # # def __unicode__(self): # return self.sms_number # # Path: util/showerthoughts.py # def get_todays_thought(): # thought = ShowerThought.objects.filter(date=datetime.datetime.today(), active=True).first() # if thought: # return thought # new_thought = get_thought() # showerthought = ShowerThought.objects.create(thought_text=new_thought.title, # post_id=new_thought.id, # url=new_thought.url, # date=datetime.datetime.today(), # active=True) # cache.set('todays_thought_text', new_thought.title) # # post a notification comment on the thread for this showerthought # bot = ShowerBot() # bot.login() # bot.post_notification(showerthought) # return showerthought # # Path: util/texter.py # class DuplicateTextException(Exception): # pass # # class Texter(object): # def __init__(self): # self.client = TwilioRestClient(settings.TWILIO_SID, settings.TWILIO_TOKEN) # # def send_text(self, subscriber, message, post_id): # if TextSend.objects.filter(subscriber=subscriber, post_id=post_id).exists(): # logging.warning('Attempted to send a duplicate text. Won\'t do it.') # raise DuplicateTextException() # try: # self.client.messages.create( # to=subscriber.sms_number, # from_=settings.TWILIO_NUMBER, # body=message, # ) # except TwilioRestException as e: # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(e)) # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # sucess=False, # result_message=str(e), # ) # #TODO: refactor into a configurable list # if 'not a valid phone number' in str(e) or 'violates a blacklist rule' in str(e) or 'not a mobile number' in str(e): # subscriber.active = False # subscriber.save() # raise e # TextSend.objects.create( # subscriber=subscriber, # post_id=post_id, # message_text=message, # ) # # def send_todays_texts(self): # ret = [] # thought = get_todays_thought() # for subscriber in Subscriber.objects.filter(active=True): # row = {'to': subscriber, 'action': 'showertext'} # message = thought.thought_text # post_id = thought.post_id # if subscriber.expired: # row['action'] = 'expiration' # subscriber.active = False # subscriber.save() # message = 'HOUSE KEEPING! I\'m clearing out old numbers to make room for more. If you like these, ' \ # 'please resubscribe for free! http://www.showertexts.com' # post_id = 'EXP-' + str(datetime.date.today()) # try: # self.send_text(subscriber, message, post_id) # row['result'] = 'Success' # except DuplicateTextException: # row['result'] = 'Duplicate' # except TwilioRestException as ex: # row['result'] = 'Exception: ' + str(ex) # logging.error('Exception sending number to: ' + subscriber.sms_number + ' - ' + str(ex)) # ret.append(row) # return ret . Output only the next line.
subscriber.renew()
Given the following code snippet before the placeholder: <|code_start|> class TestFetch(unittest.TestCase): def test_fetch(self): thought = util.showerthoughts.get_todays_thought() print thought print ShowerThought.objects.all() assert ShowerThought.objects.count() == 1 def test_no_duplicate(self): todays_thought = util.showerthoughts.get_todays_thought() <|code_end|> , predict the next line using imports from the current file: import unittest import util.showerthoughts from texts.models import ShowerThought and context including class names, function names, and sometimes code from other files: # Path: texts/models.py # class ShowerThought(models.Model): # date = models.DateField(auto_now_add=True) # post_id = models.CharField(max_length=20) # thought_text = models.CharField(max_length=500) # url = models.URLField(max_length=300, null=True, blank=True) # active = models.BooleanField(default=True) # bot_notified = models.BooleanField(default=False) # # def __unicode__(self): # return str(self.date) + ' ' + self.thought_text . Output only the next line.
submission = util.showerthoughts.get_thought()
Using the snippet: <|code_start|> if not hasattr(w, 'testcounter'): w.testcounter = 0 w.testcounter += 1 if w.testcounter % 2: raise Exception("failed task!") if w.testcounter > 10: #TODO: Look up condition variables in python and asyncio. Could # be handy for doing automatic wakeup of threads. asyncio.Future # works, but is it the best option? def success(w): w.wait_fut.set_result(None) w.submit_work(0, success) for i in range(12): w.submit_work(1, count_except) w.wait_fut = asyncio.Future() await w.wait_fut cluster(2, f) @mpi_procs(2) def test_remote_work(): async def f(w): if w.addr != 0: return async def g(w): assert(w.addr == 1) def h(w): assert(w.addr == 0) taskloaf.worker.shutdown(w) w.submit_work(0, h) taskloaf.worker.shutdown(w) <|code_end|> , determine the next line of code. You have imports: import os import pytest import asyncio import taskloaf.worker import gc; gc.collect() from taskloaf.cluster import cluster from taskloaf.mpi import mpiexisting, MPIComm, rank from taskloaf.test_decorators import mpi_procs from taskloaf.run import run from fixtures import w and context (class names, function names, or code) available: # Path: taskloaf/mpi.py # def mpiexisting(n_workers, f, cfg, die_on_exception=True): # orig_sys_except = sys.excepthook # if die_on_exception: # # def die(*args, **kwargs): # orig_sys_except(*args, **kwargs) # sys.stderr.flush() # MPI.COMM_WORLD.Abort() # # sys.excepthook = die # # n_mpi_procs = MPI.COMM_WORLD.Get_size() # if n_workers > n_mpi_procs: # raise Exception( # "There are only %s MPI processes but %s were requested" # % (n_mpi_procs, n_workers) # ) # c = MPIComm() # out = f(c) if c.addr < n_workers else None # sys.excepthook = orig_sys_except # return out # # class MPIComm: # default_comm = MPI.COMM_WORLD # # # TODO: multi part messages can be done with tags. # def __init__(self, comm=None): # if comm is None: # comm = MPIComm.default_comm # self.comm = comm # self.addr = rank(self.comm) # # def send(self, to_addr, data): # self.comm.Isend(data, dest=to_addr) # # def recv(self): # s = MPI.Status() # msg_exists = self.comm.iprobe(status=s) # if not msg_exists: # return None # out = memoryview(bytearray(s.count)) # self.comm.Recv(out, source=s.source) # return out # # def barrier(self): # self.comm.Barrier() # # def rank(comm=MPI.COMM_WORLD): # return comm.Get_rank() # # Path: taskloaf/test_decorators.py # def mpi_procs(n): # n_procs_available = MPI.COMM_WORLD.Get_size() # # def decorator(test_fnc): # test_fnc.n_procs = n # return test_fnc # # return decorator . Output only the next line.
w.submit_work(1, g)
Predict the next line after this snippet: <|code_start|> if __name__ == "__main__": test_log() def test_shutdown(w): async def f(w): taskloaf.worker.shutdown(w) w.start(f) def test_run_work(): <|code_end|> using the current file's imports: import os import pytest import asyncio import taskloaf.worker import gc; gc.collect() from taskloaf.cluster import cluster from taskloaf.mpi import mpiexisting, MPIComm, rank from taskloaf.test_decorators import mpi_procs from taskloaf.run import run from fixtures import w and any relevant context from other files: # Path: taskloaf/mpi.py # def mpiexisting(n_workers, f, cfg, die_on_exception=True): # orig_sys_except = sys.excepthook # if die_on_exception: # # def die(*args, **kwargs): # orig_sys_except(*args, **kwargs) # sys.stderr.flush() # MPI.COMM_WORLD.Abort() # # sys.excepthook = die # # n_mpi_procs = MPI.COMM_WORLD.Get_size() # if n_workers > n_mpi_procs: # raise Exception( # "There are only %s MPI processes but %s were requested" # % (n_mpi_procs, n_workers) # ) # c = MPIComm() # out = f(c) if c.addr < n_workers else None # sys.excepthook = orig_sys_except # return out # # class MPIComm: # default_comm = MPI.COMM_WORLD # # # TODO: multi part messages can be done with tags. # def __init__(self, comm=None): # if comm is None: # comm = MPIComm.default_comm # self.comm = comm # self.addr = rank(self.comm) # # def send(self, to_addr, data): # self.comm.Isend(data, dest=to_addr) # # def recv(self): # s = MPI.Status() # msg_exists = self.comm.iprobe(status=s) # if not msg_exists: # return None # out = memoryview(bytearray(s.count)) # self.comm.Recv(out, source=s.source) # return out # # def barrier(self): # self.comm.Barrier() # # def rank(comm=MPI.COMM_WORLD): # return comm.Get_rank() # # Path: taskloaf/test_decorators.py # def mpi_procs(n): # n_procs_available = MPI.COMM_WORLD.Get_size() # # def decorator(test_fnc): # test_fnc.n_procs = n # return test_fnc # # return decorator . Output only the next line.
val = [0, 1]
Predict the next line for this snippet: <|code_start|> def test_await_work(): val = [0] async def f(w): def h(w, x): val[0] = x S = 'dang' await w.wait_for_work(h, S) assert(val[0] == S) run(f) def test_run_output(): async def f(w): return 1 assert(run(f) == 1) def test_exception(): async def f(w): def count_except(w): if not hasattr(w, 'testcounter'): w.testcounter = 0 w.testcounter += 1 if w.testcounter % 2: raise Exception("failed task!") if w.testcounter > 10: #TODO: Look up condition variables in python and asyncio. Could # be handy for doing automatic wakeup of threads. asyncio.Future # works, but is it the best option? def success(w): w.wait_fut.set_result(None) <|code_end|> with the help of current file imports: import os import pytest import asyncio import taskloaf.worker import gc; gc.collect() from taskloaf.cluster import cluster from taskloaf.mpi import mpiexisting, MPIComm, rank from taskloaf.test_decorators import mpi_procs from taskloaf.run import run from fixtures import w and context from other files: # Path: taskloaf/mpi.py # def mpiexisting(n_workers, f, cfg, die_on_exception=True): # orig_sys_except = sys.excepthook # if die_on_exception: # # def die(*args, **kwargs): # orig_sys_except(*args, **kwargs) # sys.stderr.flush() # MPI.COMM_WORLD.Abort() # # sys.excepthook = die # # n_mpi_procs = MPI.COMM_WORLD.Get_size() # if n_workers > n_mpi_procs: # raise Exception( # "There are only %s MPI processes but %s were requested" # % (n_mpi_procs, n_workers) # ) # c = MPIComm() # out = f(c) if c.addr < n_workers else None # sys.excepthook = orig_sys_except # return out # # class MPIComm: # default_comm = MPI.COMM_WORLD # # # TODO: multi part messages can be done with tags. # def __init__(self, comm=None): # if comm is None: # comm = MPIComm.default_comm # self.comm = comm # self.addr = rank(self.comm) # # def send(self, to_addr, data): # self.comm.Isend(data, dest=to_addr) # # def recv(self): # s = MPI.Status() # msg_exists = self.comm.iprobe(status=s) # if not msg_exists: # return None # out = memoryview(bytearray(s.count)) # self.comm.Recv(out, source=s.source) # return out # # def barrier(self): # self.comm.Barrier() # # def rank(comm=MPI.COMM_WORLD): # return comm.Get_rank() # # Path: taskloaf/test_decorators.py # def mpi_procs(n): # n_procs_available = MPI.COMM_WORLD.Get_size() # # def decorator(test_fnc): # test_fnc.n_procs = n # return test_fnc # # return decorator , which may contain function names, class names, or code. Output only the next line.
w.submit_work(0, success)
Next line prediction: <|code_start|> def random_test_matrix(nrows, nnz): rows = np.random.randint(0, nrows, nnz).astype(np.int) cols = np.random.randint(0, nrows, nnz).astype(np.int) data = np.random.rand(nnz) A = scipy.sparse.coo_matrix( (data, (rows, cols)), shape=(nrows, nrows) ).tocsr() return A def setup_worker(name, cfg): tsk.cfg.stdout_logging(name, logger_name="taskloaf.profile") def main(): cfg = tsk.Cfg( n_workers=2, log_level=logging.WARN, initializer=setup_worker ) async def f(): nrows = int(1e7) nnz = nrows * 10 n_repeats = 1 mat = random_test_matrix(nrows, nnz) vec = np.random.rand(nrows) - 0.5 t = tsk.Timer() <|code_end|> . Use current file imports: (import logging import numpy as np import scipy.sparse import taskloaf as tsk from taskloaf.csr import distribute, TskArray) and context including class names, function names, or small code snippets from other files: # Path: taskloaf/csr.py # def distribute(mat, gang): # n_chunks = len(gang) # nrows = mat.shape[0] # ncols = mat.shape[1] # print(n_chunks, nrows, ncols) # # # TODO: optimal chunking? # row_chunk_bounds = np.linspace(0, nrows, n_chunks + 1).astype(np.int) # dist_chunks = [] # for i in range(n_chunks): # start_row = row_chunk_bounds[i] # end_row = row_chunk_bounds[i + 1] # chunk_mat = mat[start_row:end_row] # dist_chunks.append(TskCSRChunk(chunk_mat, start_row)) # # return TskCSR(mat.shape, dist_chunks, gang) # # class TskArray: # def __init__(self, vals=None, size=None): # if vals is not None: # assert len(vals.shape) == 1 # self.dtype = vals.dtype # self.ref = tsk.alloc(vals.shape[0] * self.dtype.itemsize) # self._array(self.ref.get_local())[:] = vals # else: # self.dtype = np.float64() # self.ref = tsk.alloc(size * self.dtype.itemsize) # # def _array(self, buf): # return np.frombuffer(buf, dtype=self.dtype) # # async def array(self): # return self._array(await self.ref.get()) . Output only the next line.
for i in range(n_repeats):
Next line prediction: <|code_start|> mat = random_test_matrix(nrows, nnz) vec = np.random.rand(nrows) - 0.5 t = tsk.Timer() for i in range(n_repeats): correct = mat.dot(vec) t.report("simple dot") gang = await tsk.ctx().wait_for_workers(cfg.n_workers) t.report("wait for workers") t.report("launch profiler") tsk_vec = TskArray(vals=vec) t.report("shmem v") tsk_mat = distribute(mat, gang) t.report("distribute mat") result = await tsk_mat.dot(tsk_vec) t.report("first dot") async with tsk.Profiler(gang): t.restart() for i in range(n_repeats): result = await tsk_mat.dot(tsk_vec) t.report("parallel dot") print(np.sum(correct)) print(np.sum(result)) assert np.sum(result) == np.sum(correct) <|code_end|> . Use current file imports: (import logging import numpy as np import scipy.sparse import taskloaf as tsk from taskloaf.csr import distribute, TskArray) and context including class names, function names, or small code snippets from other files: # Path: taskloaf/csr.py # def distribute(mat, gang): # n_chunks = len(gang) # nrows = mat.shape[0] # ncols = mat.shape[1] # print(n_chunks, nrows, ncols) # # # TODO: optimal chunking? # row_chunk_bounds = np.linspace(0, nrows, n_chunks + 1).astype(np.int) # dist_chunks = [] # for i in range(n_chunks): # start_row = row_chunk_bounds[i] # end_row = row_chunk_bounds[i + 1] # chunk_mat = mat[start_row:end_row] # dist_chunks.append(TskCSRChunk(chunk_mat, start_row)) # # return TskCSR(mat.shape, dist_chunks, gang) # # class TskArray: # def __init__(self, vals=None, size=None): # if vals is not None: # assert len(vals.shape) == 1 # self.dtype = vals.dtype # self.ref = tsk.alloc(vals.shape[0] * self.dtype.itemsize) # self._array(self.ref.get_local())[:] = vals # else: # self.dtype = np.float64() # self.ref = tsk.alloc(size * self.dtype.itemsize) # # def _array(self, buf): # return np.frombuffer(buf, dtype=self.dtype) # # async def array(self): # return self._array(await self.ref.get()) . Output only the next line.
tsk.zmq_run(cfg=cfg, f=f)
Given the code snippet: <|code_start|> test_cfg = dict() def queue_test_helper(q): q.put(123) def test_queue(): <|code_end|> , generate the next line using the imports in this file: import cloudpickle from multiprocessing import Process, Queue from mpi4py import MPI from taskloaf.local import LocalComm from taskloaf.mpi import MPIComm from taskloaf.zmq import ZMQComm, zmqrun from taskloaf.test_decorators import mpi_procs and context (functions, classes, or occasionally code) from other files: # Path: taskloaf/mpi.py # class MPIComm: # default_comm = MPI.COMM_WORLD # # # TODO: multi part messages can be done with tags. # def __init__(self, comm=None): # if comm is None: # comm = MPIComm.default_comm # self.comm = comm # self.addr = rank(self.comm) # # def send(self, to_addr, data): # self.comm.Isend(data, dest=to_addr) # # def recv(self): # s = MPI.Status() # msg_exists = self.comm.iprobe(status=s) # if not msg_exists: # return None # out = memoryview(bytearray(s.count)) # self.comm.Recv(out, source=s.source) # return out # # def barrier(self): # self.comm.Barrier() # # Path: taskloaf/test_decorators.py # def mpi_procs(n): # n_procs_available = MPI.COMM_WORLD.Get_size() # # def decorator(test_fnc): # test_fnc.n_procs = n # return test_fnc # # return decorator . Output only the next line.
q = Queue()
Continue the code snippet: <|code_start|> test_cfg = dict() def queue_test_helper(q): q.put(123) def test_queue(): q = Queue() p = Process(target = queue_test_helper, args = (q, )) p.start() <|code_end|> . Use current file imports: import cloudpickle from multiprocessing import Process, Queue from mpi4py import MPI from taskloaf.local import LocalComm from taskloaf.mpi import MPIComm from taskloaf.zmq import ZMQComm, zmqrun from taskloaf.test_decorators import mpi_procs and context (classes, functions, or code) from other files: # Path: taskloaf/mpi.py # class MPIComm: # default_comm = MPI.COMM_WORLD # # # TODO: multi part messages can be done with tags. # def __init__(self, comm=None): # if comm is None: # comm = MPIComm.default_comm # self.comm = comm # self.addr = rank(self.comm) # # def send(self, to_addr, data): # self.comm.Isend(data, dest=to_addr) # # def recv(self): # s = MPI.Status() # msg_exists = self.comm.iprobe(status=s) # if not msg_exists: # return None # out = memoryview(bytearray(s.count)) # self.comm.Recv(out, source=s.source) # return out # # def barrier(self): # self.comm.Barrier() # # Path: taskloaf/test_decorators.py # def mpi_procs(n): # n_procs_available = MPI.COMM_WORLD.Get_size() # # def decorator(test_fnc): # test_fnc.n_procs = n # return test_fnc # # return decorator . Output only the next line.
assert(q.get() == 123)
Given snippet: <|code_start|> def sum_shmem(filepath): with Shmem(filepath) as sm: return np.sum(np.frombuffer(sm.mem)) def test_shmem(): A = np.random.rand(100) with alloc_shmem(A.nbytes, 'test') as filepath: with Shmem(filepath) as sm: <|code_end|> , continue by predicting the next line. Consider current file imports: import os import time import numpy as np import multiprocessing from taskloaf.shmem import alloc_shmem, Shmem from taskloaf.timer import Timer and context: # Path: taskloaf/shmem.py # @contextlib.contextmanager # def alloc_shmem(size, filepath): # assert not os.path.exists(filepath) # try: # init_shmem_file(filepath, size) # logger.info(f"creating shm {filepath}") # yield filepath # finally: # try: # logger.info(f"deleting shm {filepath}") # os.remove(filepath) # except FileNotFoundError: # logger.info( # f"failed to delete shm {filepath} because it no longer exists" # ) # pass # # class Shmem: # def __init__(self, filepath, track_refs=False): # self.filepath = filepath # self.track_refs = track_refs # # def __enter__(self): # self.file = open(self.filepath, "r+b") # self.size = get_size_from_fd(self.file.fileno()) # self.mmap = mmap_full_file(self.file.fileno()) # # if not self.track_refs: # # mmap tracks references internally. This is annoying when trying # # to delete the mmap. This code is some crooked trickery using # # ctypes and grabbing the pointer from a numpy buffer to create a # # memoryview from the mmap without mmap knowing about it so that # # the mmap can be closed without tracking its references (this WILL # # cause seg faults if there are existing references to the mmap # # segment when it's deleted) # # When using Shmem blocks through the allocator system, this is # # fine since then taskloaf performs its own memory tracking # temp_np = np.frombuffer(self.mmap, dtype=np.uint8) # ptr = temp_np.ctypes.data # del temp_np # ptrc = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_byte)) # new_array = np.ctypeslib.as_array(ptrc, shape=(self.size,)) # self.mem = memoryview(new_array.data.cast("B")) # else: # self.mem = memoryview(self.mmap) # # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.file.close() # self.mmap.close() # # Path: taskloaf/timer.py # class Timer(object): # def __init__(self, output_fnc=print): # if output_fnc is None: # output_fnc = ignore_args # self.output_fnc = output_fnc # self.restart() # # def restart(self): # self.start = get_time() # # def report(self, name, should_restart=True): # text = name + " took " + str(get_time() - self.start) # self.output_fnc(text) # if should_restart: # self.restart() which might include code, classes, or functions. Output only the next line.
sm.mem[:] = A.data.cast('B')
Using the snippet: <|code_start|> def sum_shmem(filepath): with Shmem(filepath) as sm: return np.sum(np.frombuffer(sm.mem)) def test_shmem(): A = np.random.rand(100) with alloc_shmem(A.nbytes, 'test') as filepath: with Shmem(filepath) as sm: sm.mem[:] = A.data.cast('B') out = multiprocessing.Pool(1).map(sum_shmem, [sm.filepath])[0] assert(out == sum_shmem(sm.filepath)) def shmem_zeros(filepath): with Shmem(filepath) as sm: np.frombuffer(sm.mem)[:] = 0 <|code_end|> , determine the next line of code. You have imports: import os import time import numpy as np import multiprocessing from taskloaf.shmem import alloc_shmem, Shmem from taskloaf.timer import Timer and context (class names, function names, or code) available: # Path: taskloaf/shmem.py # @contextlib.contextmanager # def alloc_shmem(size, filepath): # assert not os.path.exists(filepath) # try: # init_shmem_file(filepath, size) # logger.info(f"creating shm {filepath}") # yield filepath # finally: # try: # logger.info(f"deleting shm {filepath}") # os.remove(filepath) # except FileNotFoundError: # logger.info( # f"failed to delete shm {filepath} because it no longer exists" # ) # pass # # class Shmem: # def __init__(self, filepath, track_refs=False): # self.filepath = filepath # self.track_refs = track_refs # # def __enter__(self): # self.file = open(self.filepath, "r+b") # self.size = get_size_from_fd(self.file.fileno()) # self.mmap = mmap_full_file(self.file.fileno()) # # if not self.track_refs: # # mmap tracks references internally. This is annoying when trying # # to delete the mmap. This code is some crooked trickery using # # ctypes and grabbing the pointer from a numpy buffer to create a # # memoryview from the mmap without mmap knowing about it so that # # the mmap can be closed without tracking its references (this WILL # # cause seg faults if there are existing references to the mmap # # segment when it's deleted) # # When using Shmem blocks through the allocator system, this is # # fine since then taskloaf performs its own memory tracking # temp_np = np.frombuffer(self.mmap, dtype=np.uint8) # ptr = temp_np.ctypes.data # del temp_np # ptrc = ctypes.cast(ptr, ctypes.POINTER(ctypes.c_byte)) # new_array = np.ctypeslib.as_array(ptrc, shape=(self.size,)) # self.mem = memoryview(new_array.data.cast("B")) # else: # self.mem = memoryview(self.mmap) # # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.file.close() # self.mmap.close() # # Path: taskloaf/timer.py # class Timer(object): # def __init__(self, output_fnc=print): # if output_fnc is None: # output_fnc = ignore_args # self.output_fnc = output_fnc # self.restart() # # def restart(self): # self.start = get_time() # # def report(self, name, should_restart=True): # text = name + " took " + str(get_time() - self.start) # self.output_fnc(text) # if should_restart: # self.restart() . Output only the next line.
def test_shmem_edit():
Continue the code snippet: <|code_start|> def pytest_runtest_protocol(item, nextitem): n_procs = getattr(item.function, 'n_procs', 1) rank = MPI.COMM_WORLD.Get_rank() size = MPI.COMM_WORLD.Get_size() if n_procs > size: print( 'skipping ' + str(item.name) + ' because it needs ' + str(n_procs) + ' MPI procs' ) return True if rank >= n_procs: new_comm = MPI.COMM_WORLD.Split(color = 0) MPI.COMM_WORLD.Barrier() return True else: new_comm = MPI.COMM_WORLD.Split(color = 1) MPIComm.default_comm = new_comm <|code_end|> . Use current file imports: import sys import logging import _pytest.runner from mpi4py import MPI from taskloaf.mpi import MPIComm and context (classes, functions, or code) from other files: # Path: taskloaf/mpi.py # class MPIComm: # default_comm = MPI.COMM_WORLD # # # TODO: multi part messages can be done with tags. # def __init__(self, comm=None): # if comm is None: # comm = MPIComm.default_comm # self.comm = comm # self.addr = rank(self.comm) # # def send(self, to_addr, data): # self.comm.Isend(data, dest=to_addr) # # def recv(self): # s = MPI.Status() # msg_exists = self.comm.iprobe(status=s) # if not msg_exists: # return None # out = memoryview(bytearray(s.count)) # self.comm.Recv(out, source=s.source) # return out # # def barrier(self): # self.comm.Barrier() . Output only the next line.
res = _pytest.runner.pytest_runtest_protocol(item, nextitem)
Predict the next line after this snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class ThreadSimPipe: __next_petition_id = 0 __THREAD_GROUP_SIZE = 34 __petition_mutex = Lock() @classmethod def get_next_petition(cls): with cls.__petition_mutex: <|code_end|> using the current file's imports: import os import subprocess import shutil from threading import Lock from cirque.connectivity.socatpipepair import SocatPipePair and any relevant context from other files: # Path: cirque/connectivity/socatpipepair.py # class SocatPipePair: # # @staticmethod # def __find_socat_pts(stream, wait_lines=5): # # socat creates pipe file /dev/pts/${NUMBER} # r = re.compile('/dev/pts/.*$') # for _ in range(wait_lines): # line = stream.readline().decode() # match = r.search(line) # if match: # return match.group() # return '' # # def __init__(self): # self.socat = None # self.pipe0 = None # self.pipe1 = None # # def open(self): # self.socat = subprocess.Popen( # ['socat', '-d', '-d', 'pty,raw,echo=0', 'pty,raw,echo=0'], # stderr=subprocess.PIPE) # self.pipe0 = SocatPipePair.__find_socat_pts(self.socat.stderr) # self.pipe1 = SocatPipePair.__find_socat_pts(self.socat.stderr) # # def close(self): # if self.socat is not None: # self.socat.terminate() # self.socat = None # # def __del__(self): # self.close() . Output only the next line.
cls.__next_petition_id += 1
Continue the code snippet: <|code_start|> def __check_docker_run_args(self, docker_run_args, display_id, docker_display_id): self.assertEqual(docker_run_args['environment'], [f'DISPLAY=:{docker_display_id}']) src_path = f'/tmp/.X11-unix/X{display_id}' dest_path = f'/tmp/.X11-unix/X{docker_display_id}' self.assertEqual(docker_run_args['volumes'], [f'{src_path}:{dest_path}']) def test_auto_assigned_display_id(self, popen): xvnccapability = XvncCapability(display_id=0) docker_run_args = xvnccapability.get_docker_run_args(None) display_id = xvnccapability.description['display_id'] self.__check_docker_run_args(docker_run_args, display_id, 0) def test_fixed_display_id(self, popen): xvnccapability = XvncCapability(display_id=2) docker_run_args = xvnccapability.get_docker_run_args(None) self.__check_docker_run_args(docker_run_args, 2, 0) def test_fixed_docker_display_id(self, popen): xvnccapability = XvncCapability(display_id=42, docker_display_id=13) docker_run_args = xvnccapability.get_docker_run_args(None) self.__check_docker_run_args(docker_run_args, 42, 13) if __name__ == '__main__': <|code_end|> . Use current file imports: import unittest from unittest import mock from cirque.capabilities.xvnccapability import XvncCapability and context (classes, functions, or code) from other files: # Path: cirque/capabilities/xvnccapability.py # class XvncCapability(BaseCapability): # X_SOCKET_PATH = '/tmp/.X11-unix' # # def __init__(self, localhost=True, display_id=0, docker_display_id=0): # self.localhost = localhost # self.__display_id = display_id # self.__docker_display_id = docker_display_id # self.__xvnc_process = None # self.__launch_xvnc_server() # # def __launch_xvnc_server(self): # xvnc_args = ['Xvnc', '--SecurityTypes=None'] # if self.__display_id == 0: # self.__display_id = self.__get_next_display_id() # if self.localhost: # xvnc_args.append('-localhost') # xvnc_args.append(':{}'.format(self.__display_id)) # self.xvnc_proces = subprocess.Popen(xvnc_args) # # def __get_next_display_id(self): # if not os.path.exists(self.X_SOCKET_PATH) or \ # len(os.listdir(self.X_SOCKET_PATH)) == 0: # return 0 # x_server_ids = glob.glob(os.path.join(self.X_SOCKET_PATH, 'X*')) # x_server_ids = [int(os.path.basename(f)[1:]) for f in x_server_ids] # return max(x_server_ids) + 1 # # @property # def name(self): # return 'Xvnc' # # @property # def description(self): # return { # 'localhost': self.localhost, # 'display_id': self.__display_id, # } # # def get_docker_run_args(self, dockernode): # return { # 'environment': ['DISPLAY=:{}'.format(self.__docker_display_id)], # 'volumes': [ # '{}/X{}:{}/X{}'.format(self.X_SOCKET_PATH, self.__display_id, # self.X_SOCKET_PATH, self.__docker_display_id) # ] # } # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # if self.__xvnc_process: # self.__xvnc_process.kill() # self.__xvnc_process = None . Output only the next line.
suite = unittest.TestLoader().loadTestsFromTestCase(TestXvncCapability)
Given snippet: <|code_start|># Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class LanAccessCapability(BaseCapability): def __init__(self, home_lan): self.__home_lan = home_lan @property def name(self): return 'LanAccess' <|code_end|> , continue by predicting the next line. Consider current file imports: from cirque.capabilities.basecapability import BaseCapability from cirque.common.utils import manipulate_iptable_src_dst_rule and context: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/utils.py # def manipulate_iptable_src_dst_rule(logger, src, dst, action, add=True): # chain = 'DOCKER-USER' # manipulate_action = '-I' if add else '-D' # ret = host_run(logger, 'iptables -L DOCKER-USER') # if b'No chain/target/match by that name' in ret.stderr: # chain = 'INPUT' # cmd = [ # 'iptables', manipulate_action, chain, '-s', src, '-d', dst, '-j', action # ] # ret = host_run(logger, cmd) # if ret.returncode != 0: # logger.error('Failed to add iptables rule %s', ' '.join(cmd)) which might include code, classes, or functions. Output only the next line.
def enable_capability(self, docker_node):
Given the following code snippet before the placeholder: <|code_start|># # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. CIRQUE_ROOT = dirname(dirname(dirname(abspath(__file__)))) BLUEZ_DIR = os.path.join(CIRQUE_ROOT, "bluez") class BlueToothCapability(BaseCapability): BLE_ADAPTS_LIST = list() def __init__(self, num_btvirts=2): self.num_btvirts = num_btvirts self.logger = CirqueLog.get_cirque_logger(self.__class__.__name__) self.__run_bluetoothd() self.__run_btvirt_infs() self.__get_ble_controller() @property def name(self): return "Bluetooth" def get_docker_run_args(self, docker_node): return { 'environment': { 'BLE_ADAPT': self.ble_adapt, <|code_end|> , predict the next line using imports from the current file: import os import time import cirque.common.utils as utils from os.path import abspath, dirname from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog and context including class names, function names, and sometimes code from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) . Output only the next line.
},
Predict the next line after this snippet: <|code_start|> def name(self): return "Bluetooth" def get_docker_run_args(self, docker_node): return { 'environment': { 'BLE_ADAPT': self.ble_adapt, }, 'volumes': [ '/var/run/dbus:/var/run/dbus' ], 'network_mode': 'host', } def disable_capability(self, docker_node): self.logger.warn("ble_adapt:{}".format(self.ble_adapt)) self.logger.warn("BLE_ADAPTS_LIST: {}".format( BlueToothCapability.BLE_ADAPTS_LIST)) BlueToothCapability.BLE_ADAPTS_LIST.remove(self.ble_adapt) if len(BlueToothCapability.BLE_ADAPTS_LIST): return utils.host_run(self.logger, "killall btvirt") utils.host_run(self.logger, "killall bluetoothd") def __get_ble_controller(self): self.logger.info("start getting ble adapters...") command = os.path.join( BLUEZ_DIR, "tools/hciconfig | awk '/Bus: Virtual/ {print $1}' | sort") <|code_end|> using the current file's imports: import os import time import cirque.common.utils as utils from os.path import abspath, dirname from cirque.capabilities.basecapability import BaseCapability from cirque.common.cirquelog import CirqueLog and any relevant context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) . Output only the next line.
ret = utils.host_run(self.logger, command)
Predict the next line after this snippet: <|code_start|># limitations under the License. class ThreadCapability(BaseCapability): def __init__(self, node_id, petition_id, daemons=['wpantund', 'otbr-agent'], rcp=False): self.thread_endpoint = ThreadSimPipe(node_id, petition_id, rcp) self.thread_endpoint.open() self.logger = CirqueLog.get_cirque_logger(self.__class__.__name__) self.daemons = daemons for daemon in daemons: if daemon not in {'wpantund', 'otbr-agent'}: self.logger.warning( 'using unkown thread daemon mode: {}'.format(daemon)) @property def name(self): return 'Thread' def get_docker_run_args(self, dockernode): return { 'devices': [ '{}:/dev/ttyUSB0'.format(self.thread_endpoint.pipe_path_for_user) ], 'volumes': [ <|code_end|> using the current file's imports: from cirque.capabilities.basecapability import BaseCapability from cirque.connectivity.threadsimpipe import ThreadSimPipe from cirque.common.cirquelog import CirqueLog and any relevant context from other files: # Path: cirque/capabilities/basecapability.py # class BaseCapability: # # @property # def name(self): # return '' # # def get_docker_run_args(self, docker_node): # return {} # # def enable_capability(self, docker_node): # pass # # def disable_capability(self, docker_node): # pass # # @property # def description(self): # return {} # # Path: cirque/connectivity/threadsimpipe.py # class ThreadSimPipe: # __next_petition_id = 0 # __THREAD_GROUP_SIZE = 34 # __petition_mutex = Lock() # # @classmethod # def get_next_petition(cls): # with cls.__petition_mutex: # cls.__next_petition_id += 1 # return cls.__next_petition_id # # def __init__(self, node_id, petition_id=0, rcp=False): # self._socat_pipe = SocatPipePair() # self.pipe_path_for_user = None # self.pipe_path_for_ncp = None # self.node_id = node_id # self.radio_fd = None # self.radio_process = None # self.petition_id = petition_id # if rcp: # self.radio_command = 'ot-rcp' # else: # self.radio_command = 'ot-ncp-ftd' # # def open(self): # self._socat_pipe.open() # self.pipe_path_for_user = self._socat_pipe.pipe0 # self.pipe_path_for_ncp = self._socat_pipe.pipe1 # self.radio_fd = os.open(self.pipe_path_for_ncp, os.O_RDWR) # env = os.environ # env['PORT_OFFSET'] = str(self.petition_id * self.__THREAD_GROUP_SIZE) # self.radio_process = subprocess.Popen( # [self.radio_command, '{}'.format(self.node_id)], # env=env, # stdout=self.radio_fd, # stdin=self.radio_fd) # # def close(self): # if self.radio_fd is not None: # os.close(self.radio_fd) # self.radio_fd = None # if self.radio_process is not None: # self.radio_process.terminate() # self.radio_process = None # if self._socat_pipe is not None: # self._socat_pipe.close() # self._socat_pipe = None # if os.path.exists('./tmp'): # shutil.rmtree('./tmp') # # def __del__(self): # self.close() # # Path: cirque/common/cirquelog.py # class CirqueLog: # # logger = None # # @classmethod # def setup_cirque_logger(cls, level=logging.INFO): # if cls.logger: # return # cls.logger = logging.getLogger('cirque') # cls.logger.setLevel(level) # sh = logging.StreamHandler() # sh.setFormatter( # logging.Formatter('%(asctime)s [%(name)s] %(levelname)s %(message)s')) # cls.logger.addHandler(sh) # # @classmethod # def get_cirque_logger(cls, name=None): # name = 'cirque' if not name else 'cirque.{}'.format(name) # return logging.getLogger(name) . Output only the next line.
'{}:/dev/ttyUSB0'.format(self.thread_endpoint.pipe_path_for_user)