Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Continue the code snippet: <|code_start|>
card_list = soup.cockatrice_carddatabase.cards.find_all('card')
cnt = 0
fout = open("data/all_set_cards.py", "w")
fout.write("from MTG import card\n"
"from MTG import gameobject\n"
"from MTG import cardtype\n"
"from MTG import static_abilities\n"
"from MTG import mana\n\n")
id_to_name = {}
name_to_id = {}
for card in card_list:
supertype = []
types = []
try:
ID = 'c' + re.search('(?<=multiverseid=)[0-9]+', card.set['picURL']).group(0)
name = card.find('name').text
characteristics = {'name': name}
characteristics['text'] = card.find('text').text
characteristics['color'] = [c.text for c in card.find_all('color')]
characteristics['mana_cost'] = card.find('manacost').text
# types
_type = card.find('type').text.split(' - ')
if len(_type) > 1:
characteristics['subtype'] = _type[1].split(' ')
_type = _type[0].split(' ')
<|code_end|>
. Use current file imports:
import re, sys, traceback
import pickle
from bs4 import BeautifulSoup
from MTG import cardtype
from MTG import static_abilities
and context (classes, functions, or code) from other files:
# Path: MTG/cardtype.py
# class SuperType(Enum):
# class CardType(Enum):
# class LandType(Enum):
# BASIC = 0
# LEGENDARY = 1
# SNOW = 2
# WORLD = 3
# ARTIFACT = 0
# CREATURE = 1
# ENCHANTMENT = 2
# INSTANT = 3
# LAND = 4
# PLANESWALKER = 5
# SORCERY = 6
# TRIBAL = 7
# PLAINS = 0
# ISLAND = 1
# SWAMP = 2
# MOUNTAIN = 3
# FOREST = 4
#
# Path: MTG/static_abilities.py
# class StaticAbilities(Enum):
. Output only the next line. | if len(_type) > 1 and _type[0].upper() in cardtype.SuperType._member_names_: |
Given snippet: <|code_start|> types = []
try:
ID = 'c' + re.search('(?<=multiverseid=)[0-9]+', card.set['picURL']).group(0)
name = card.find('name').text
characteristics = {'name': name}
characteristics['text'] = card.find('text').text
characteristics['color'] = [c.text for c in card.find_all('color')]
characteristics['mana_cost'] = card.find('manacost').text
# types
_type = card.find('type').text.split(' - ')
if len(_type) > 1:
characteristics['subtype'] = _type[1].split(' ')
_type = _type[0].split(' ')
if len(_type) > 1 and _type[0].upper() in cardtype.SuperType._member_names_:
supertype = '[cardtype.SuperType[%r]]' % _type[0].upper()
_type.pop(0)
types = '[' + ', '.join(['cardtype.CardType[%r]' % i.upper() for i in _type]) + ']'
if 'Creature' in _type:
try:
characteristics['power'], characteristics['toughness'] = map(int, card.find('pt').text.split('/'))
except ValueError:
pass
# static abilities
_abilities = []
texts = characteristics['text'].replace(' ', '_')
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re, sys, traceback
import pickle
from bs4 import BeautifulSoup
from MTG import cardtype
from MTG import static_abilities
and context:
# Path: MTG/cardtype.py
# class SuperType(Enum):
# class CardType(Enum):
# class LandType(Enum):
# BASIC = 0
# LEGENDARY = 1
# SNOW = 2
# WORLD = 3
# ARTIFACT = 0
# CREATURE = 1
# ENCHANTMENT = 2
# INSTANT = 3
# LAND = 4
# PLANESWALKER = 5
# SORCERY = 6
# TRIBAL = 7
# PLAINS = 0
# ISLAND = 1
# SWAMP = 2
# MOUNTAIN = 3
# FOREST = 4
#
# Path: MTG/static_abilities.py
# class StaticAbilities(Enum):
which might include code, classes, or functions. Output only the next line. | for ability in static_abilities.StaticAbilities._member_names_: |
Here is a snippet: <|code_start|>"""
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
"""
"""
WSGI config for udon project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
<|code_end|>
. Write the next line using the current file imports:
from udon.boot import fix_path
from django.core.wsgi import get_wsgi_application
from djangae.wsgi import DjangaeApplication
from djangae.utils import on_production
import os
and context from other files:
# Path: udon/boot.py
# def fix_path():
# if exists(APPENGINE_DIR) and APPENGINE_DIR not in sys.path:
# sys.path.insert(1, APPENGINE_DIR)
#
# if SITEPACKAGES_DIR not in sys.path:
# sys.path.insert(1, SITEPACKAGES_DIR)
, which may include functions, classes, or code. Output only the next line. | fix_path() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
"""
* Copyright 2016 Google Inc. All Rights Reserved.
*
* 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.
"""
<|code_end|>
, generate the next line using the imports in this file:
import os
import sys
from udon.boot import fix_path
from djangae.core.management import execute_from_command_line
and context (functions, classes, or occasionally code) from other files:
# Path: udon/boot.py
# def fix_path():
# if exists(APPENGINE_DIR) and APPENGINE_DIR not in sys.path:
# sys.path.insert(1, APPENGINE_DIR)
#
# if SITEPACKAGES_DIR not in sys.path:
# sys.path.insert(1, SITEPACKAGES_DIR)
. Output only the next line. | fix_path() |
Continue the code snippet: <|code_start|> *
* 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.
"""
"""
Django settings for udon project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
PROJECT_DIR = find_project_root()
SITE_URL = "https://virtualart.chromeexperiments.com"
SHORT_URL = "g.co/VirtualArtSessions"
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
<|code_end|>
. Use current file imports:
from djangae.settings_base import * # set up some AppEngine specific stuff
from djangae.utils import find_project_root
from django.core.urlresolvers import reverse_lazy
from google.appengine.api.app_identity.app_identity import get_default_gcs_bucket_name
from ..boot import get_app_config
import os
and context (classes, functions, or code) from other files:
# Path: udon/boot.py
# def get_app_config():
# """Returns the application configuration, creating it if necessary."""
# from django.utils.crypto import get_random_string
# from google.appengine.ext import ndb
#
# class Config(ndb.Model):
# """A simple key-value store for application configuration settings."""
# secret_key = ndb.StringProperty()
#
# # Create a random SECRET_KEY hash
# chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
# secret_key = get_random_string(50, chars)
#
# key = ndb.Key(Config, 'config')
# entity = key.get()
# if not entity:
# entity = Config(key=key)
# entity.secret_key = str(secret_key)
# entity.put()
# return entity
. Output only the next line. | SECRET_KEY = get_app_config().secret_key |
Based on the snippet: <|code_start|>
class TestSeasonRange(TestCase):
def test_instantiation(self):
start_season = Season.season_2015
end_season = Season.season_2016
<|code_end|>
, predict the immediate next line with the help of imports:
from unittest import TestCase
from nba_data.data.season import Season
from nba_data.data.season_range import SeasonRange
and context (classes, functions, sometimes code) from other files:
# Path: nba_data/data/season.py
# class Season(BaseQueryParameter, Enum):
# season_2016 = "2016-17"
# season_2015 = "2015-16"
# season_2014 = "2014-15"
# season_2013 = "2013-14"
# season_2012 = "2012-13"
# season_2011 = "2011-12"
# season_2010 = "2010-11"
# season_2009 = "2009-10"
# season_2008 = "2008-09"
# season_2007 = "2007-08"
# season_2006 = "2006-07"
# season_2005 = "2005-06"
# season_2004 = "2004-05"
# season_2003 = "2003-04"
# season_2002 = "2002-03"
# season_2001 = "2001-02"
# season_2000 = "2000-01"
# season_1999 = "1999-00"
# season_1998 = "1998-99"
# season_1997 = "1997-98"
# season_1996 = "1996-97"
# season_1995 = "1995-96"
# season_1994 = "1994-95"
# season_1993 = "1993-94"
# season_1992 = "1992-93"
# season_1991 = "1991-92"
# season_1990 = "1990-91"
#
# @staticmethod
# def get_query_parameter_name():
# return "Season"
#
# @staticmethod
# def get_season_by_name(name):
# season = season_name_map.get(name)
#
# if season is None:
# raise ValueError("Unknown season name: %s", name)
#
# return season
#
# @staticmethod
# def get_season_by_start_year(year):
# season = start_year_to_season_map.get(year)
#
# if season is None:
# raise ValueError("Unknown season start year: %s", year)
#
# return season
#
# @staticmethod
# def get_season_by_end_year(year):
# season = season_end_year_map.get(year)
#
# if season is None:
# raise ValueError("Unknown season end year: %s", year)
#
# return season
#
# @staticmethod
# def get_season_by_start_and_end_year(start_year, end_year):
# start_year_season = Season.get_season_by_start_year(year=start_year)
# end_year_season = Season.get_season_by_end_year(year=end_year)
#
# if start_year_season is not end_year_season:
# raise ValueError("Cannot find season with start year: %s and end year: %s", start_year, end_year)
#
# return start_year_season
#
# @staticmethod
# def get_start_year_by_season(season):
# assert isinstance(season, Season)
#
# start_year = season_to_start_year_map.get(season)
#
# if start_year is None:
# raise ValueError("Cannot find start year for season: %s", season)
#
# return start_year
#
# Path: nba_data/data/season_range.py
# class SeasonRange:
# def __init__(self, start, end):
# self.start = start
# self.end = end
. Output only the next line. | self.assertIsNotNone(SeasonRange(start=start_season, end=end_season)) |
Continue the code snippet: <|code_start|>
class TestAdvancedBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(AdvancedGameBoxScoreDeserializer())
def test_deserialize_advanced_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoreadvanced.json')) as data_file:
data = json.load(data_file)
advanced_box_score = AdvancedGameBoxScoreDeserializer().deserialize(data)
self.assertEqual(advanced_box_score.game_id, "0021501205")
self.assertEqual(len(advanced_box_score.player_box_scores), 26)
nicolas_batum_box_score = advanced_box_score.player_box_scores[0]
self.assertEqual(nicolas_batum_box_score.player.id, 201587)
self.assertEqual(nicolas_batum_box_score.player.name, "Nicolas Batum")
self.assertEqual(nicolas_batum_box_score.player.team, Team.charlotte_hornets)
<|code_end|>
. Use current file imports:
import json
import os
from decimal import Decimal
from unittest import TestCase
from nba_data.data.player_status import PlayerStatusType
from nba_data.data.team import Team
from nba_data.deserializers.box_scores.game import AdvancedGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and context (classes, functions, or code) from other files:
# Path: nba_data/data/player_status.py
# class PlayerStatusType(Enum):
# active = 'active'
# did_not_play = 'did not play'
# did_not_dress = 'did not dress'
# not_with_team = 'not with team'
#
# @staticmethod
# def from_abbreviation(abbreviation):
# player_status_type = player_status_type_abbreviation_map.get(abbreviation)
#
# if player_status_type is None:
# raise ValueError('Unknown player status abbreviation: %s', abbreviation)
#
# return player_status_type
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
#
# Path: nba_data/deserializers/box_scores/game.py
# class AdvancedGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def player_box_scores_deserializer(self, data):
# return AdvancedPlayerBoxScoresDeserializer.deserialize(data=data)
#
# def team_box_scores_deserializer(self, data):
# return AdvancedTeamBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | self.assertEqual(nicolas_batum_box_score.player.status.type, PlayerStatusType.active) |
Predict the next line after this snippet: <|code_start|>
class TestAdvancedBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(AdvancedGameBoxScoreDeserializer())
def test_deserialize_advanced_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoreadvanced.json')) as data_file:
data = json.load(data_file)
advanced_box_score = AdvancedGameBoxScoreDeserializer().deserialize(data)
self.assertEqual(advanced_box_score.game_id, "0021501205")
self.assertEqual(len(advanced_box_score.player_box_scores), 26)
nicolas_batum_box_score = advanced_box_score.player_box_scores[0]
self.assertEqual(nicolas_batum_box_score.player.id, 201587)
self.assertEqual(nicolas_batum_box_score.player.name, "Nicolas Batum")
<|code_end|>
using the current file's imports:
import json
import os
from decimal import Decimal
from unittest import TestCase
from nba_data.data.player_status import PlayerStatusType
from nba_data.data.team import Team
from nba_data.deserializers.box_scores.game import AdvancedGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and any relevant context from other files:
# Path: nba_data/data/player_status.py
# class PlayerStatusType(Enum):
# active = 'active'
# did_not_play = 'did not play'
# did_not_dress = 'did not dress'
# not_with_team = 'not with team'
#
# @staticmethod
# def from_abbreviation(abbreviation):
# player_status_type = player_status_type_abbreviation_map.get(abbreviation)
#
# if player_status_type is None:
# raise ValueError('Unknown player status abbreviation: %s', abbreviation)
#
# return player_status_type
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
#
# Path: nba_data/deserializers/box_scores/game.py
# class AdvancedGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def player_box_scores_deserializer(self, data):
# return AdvancedPlayerBoxScoresDeserializer.deserialize(data=data)
#
# def team_box_scores_deserializer(self, data):
# return AdvancedTeamBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | self.assertEqual(nicolas_batum_box_score.player.team, Team.charlotte_hornets) |
Here is a snippet: <|code_start|>
class TestAdvancedBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(AdvancedGameBoxScoreDeserializer())
def test_deserialize_advanced_box_score(self):
<|code_end|>
. Write the next line using the current file imports:
import json
import os
from decimal import Decimal
from unittest import TestCase
from nba_data.data.player_status import PlayerStatusType
from nba_data.data.team import Team
from nba_data.deserializers.box_scores.game import AdvancedGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and context from other files:
# Path: nba_data/data/player_status.py
# class PlayerStatusType(Enum):
# active = 'active'
# did_not_play = 'did not play'
# did_not_dress = 'did not dress'
# not_with_team = 'not with team'
#
# @staticmethod
# def from_abbreviation(abbreviation):
# player_status_type = player_status_type_abbreviation_map.get(abbreviation)
#
# if player_status_type is None:
# raise ValueError('Unknown player status abbreviation: %s', abbreviation)
#
# return player_status_type
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
#
# Path: nba_data/deserializers/box_scores/game.py
# class AdvancedGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def player_box_scores_deserializer(self, data):
# return AdvancedPlayerBoxScoresDeserializer.deserialize(data=data)
#
# def team_box_scores_deserializer(self, data):
# return AdvancedTeamBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
, which may include functions, classes, or code. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoreadvanced.json')) as data_file: |
Using the snippet: <|code_start|>
class TestSeasonPlayersDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(SeasonPlayersDeserializer())
def test_deserialize(self):
<|code_end|>
, determine the next line of code. You have imports:
import json
import os
from unittest import TestCase
from nba_data.deserializers.season_players import SeasonPlayersDeserializer
from tests.config import ROOT_DIRECTORY
and context (class names, function names, or code) available:
# Path: nba_data/deserializers/season_players.py
# class SeasonPlayersDeserializer:
# # I don't know if there's a non-standard league
# league_field_name = 'league'
# standard_field_name = 'standard'
# first_name_field_name = 'firstName'
# last_name_field_name = 'lastName'
# player_id_field_name = 'personId'
# team_id_field_name = 'teamId'
# jersey_field_name = 'jersey'
# team_seasons_field_name = 'teams'
# team_seasons_team_id_field_name = 'teamId'
# team_season_season_start_year_field_name = 'seasonStart'
# team_season_season_end_year_field_name = 'seasonEnd'
#
# def __init__(self):
# pass
#
# @staticmethod
# def deserialize(data):
# if SeasonPlayersDeserializer.league_field_name not in data:
# raise ValueError('Unable to deserialize league field for %s', data)
#
# league = data[SeasonPlayersDeserializer.league_field_name]
#
# if SeasonPlayersDeserializer.standard_field_name not in league:
# raise ValueError('Unable to deserialize standard field for %s', data)
#
# players = league[SeasonPlayersDeserializer.standard_field_name]
#
# return [SeasonPlayersDeserializer.parse_player(data=player)
# for player in players]
#
# @staticmethod
# def parse_player(data):
# if SeasonPlayersDeserializer.player_id_field_name not in data:
# raise ValueError('Unable to parse id field for %s', data)
#
# if SeasonPlayersDeserializer.first_name_field_name not in data:
# raise ValueError('Unable to parse first name field for %s', data)
#
# if SeasonPlayersDeserializer.last_name_field_name not in data:
# raise ValueError('Unable to parse last name field for %s', data)
#
# if SeasonPlayersDeserializer.jersey_field_name not in data:
# raise ValueError('Unable to parse jersey value field for %s', data)
#
# player_id = data[SeasonPlayersDeserializer.player_id_field_name]
# first_name = data[SeasonPlayersDeserializer.first_name_field_name]
# last_name = data[SeasonPlayersDeserializer.last_name_field_name]
# jersey_value = data[SeasonPlayersDeserializer.jersey_field_name]
# jersey = int(jersey_value) if jersey_value.isdigit() else None
# name = '{0} {1}'.format(first_name, last_name)
# team_seasons = SeasonPlayersDeserializer.parse_team_seasons(data=data)
#
# return SeasonPlayer(id=player_id, name=name, jersey=jersey, team_seasons=team_seasons)
#
# @staticmethod
# def parse_team_seasons(data):
# if SeasonPlayersDeserializer.team_seasons_field_name not in data:
# raise ValueError('Unable to parse team seasons field for %s', data)
#
# team_seasons = data[SeasonPlayersDeserializer.team_seasons_field_name]
#
# return [SeasonPlayersDeserializer.parse_team_season(data=team_season)
# for team_season in team_seasons]
#
# @staticmethod
# def parse_team_season(data):
# return TeamSeasonRange(team=SeasonPlayersDeserializer.parse_team(data=data),
# season_range=SeasonPlayersDeserializer.parse_season_range(data=data))
#
# @staticmethod
# def parse_team(data):
# if SeasonPlayersDeserializer.team_seasons_team_id_field_name not in data:
# raise ValueError('Unable to parse team id for %s', data)
#
# team_id = int(data[SeasonPlayersDeserializer.team_seasons_team_id_field_name])
# return Team.get_team_by_id(team_id=team_id)
#
# @staticmethod
# def parse_season_range(data):
# if SeasonPlayersDeserializer.team_season_season_start_year_field_name not in data:
# raise ValueError('Unable to parse season start for %s', data)
#
# if SeasonPlayersDeserializer.team_season_season_end_year_field_name not in data:
# raise ValueError('Unable to parse season end for %s', data)
#
# season_range_start_year = int(data[SeasonPlayersDeserializer.team_season_season_start_year_field_name])
# season_range_end_year = int(data[SeasonPlayersDeserializer.team_season_season_end_year_field_name])
#
# # NBA API returns start year for last year in range
# return SeasonRange(start=Season.get_season_by_start_year(year=season_range_start_year),
# end=Season.get_season_by_start_year(year=season_range_end_year))
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/players.json')) as data_file: |
Here is a snippet: <|code_start|>
if len(row_set) < 1:
raise ValueError('Unable to parse row set from %s', data)
return row_set[CommonPlayerInfoDeserializer.row_set_index]
@staticmethod
def deserialize(data):
result = CommonPlayerInfoDeserializer.parse_result(data=data)
weight = result[CommonPlayerInfoDeserializer.weight_index]
if weight is not None:
weight = int(weight)
height_value = result[CommonPlayerInfoDeserializer.height_index]
if height_value is not None:
height = CommonPlayerInfoDeserializer.parse_height(height_value=height_value)
else:
height = None
jersey_number = result[CommonPlayerInfoDeserializer.jersey_number_index]
if jersey_number is not None:
jersey_number = int(jersey_number)
id = int(result[CommonPlayerInfoDeserializer.nba_id_index])
name = result[CommonPlayerInfoDeserializer.name_index]
team = Team.get_team_by_id(team_id=int(result[CommonPlayerInfoDeserializer.team_id_index]))
birth_date = CommonPlayerInfoDeserializer.parse_date(result[CommonPlayerInfoDeserializer.birth_date_index])
position = Position.get_position_from_name(name=str(result[CommonPlayerInfoDeserializer.position_name_index]))
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from nba_data.data.players import DetailedPlayer
from nba_data.data.position import Position
from nba_data.data.team import Team
and context from other files:
# Path: nba_data/data/players.py
# class DetailedPlayer(TeamPlayer):
#
# def __init__(self, name, team, id, birth_date, height, weight, jersey, position):
# self.birth_date = birth_date
# self.height = height
# self.weight = weight
# self.jersey = jersey
# self.position = position
# self.jersey = jersey
# TeamPlayer.__init__(self, name=name, id=id, team=team)
#
# def get_additional_unicode(self):
# return 'birth date: {birth_date} | height: {height} | weight: {weight} | ' 'jersey: {jersey} | ' \
# 'position: {position}'.format(birth_data=self.birth_date, height=self.height, weight=self.weight,
# jersey=self.jersey, position=self.position)
#
# Path: nba_data/data/position.py
# class Position(Enum):
# guard = "GUARD"
# guard_forward = "GUARD-FORWARD"
# forward_guard = "FORWARD-GUARD"
# forward = "FORWARD"
# center = "CENTER"
# forward_center = "FORWARD-CENTER"
#
# @staticmethod
# def get_position_from_abbreviation(abbreviation):
# return abbreviation_to_position_map.get(abbreviation.upper())
#
# @staticmethod
# def get_position_from_name(name):
# return name_to_position_map.get(name.upper())
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
, which may include functions, classes, or code. Output only the next line. | return DetailedPlayer(id=id, name=name, team=team, birth_date=birth_date, height=height, weight=weight, |
Based on the snippet: <|code_start|>
row_set = result_set[CommonPlayerInfoDeserializer.row_set_field_name]
if len(row_set) < 1:
raise ValueError('Unable to parse row set from %s', data)
return row_set[CommonPlayerInfoDeserializer.row_set_index]
@staticmethod
def deserialize(data):
result = CommonPlayerInfoDeserializer.parse_result(data=data)
weight = result[CommonPlayerInfoDeserializer.weight_index]
if weight is not None:
weight = int(weight)
height_value = result[CommonPlayerInfoDeserializer.height_index]
if height_value is not None:
height = CommonPlayerInfoDeserializer.parse_height(height_value=height_value)
else:
height = None
jersey_number = result[CommonPlayerInfoDeserializer.jersey_number_index]
if jersey_number is not None:
jersey_number = int(jersey_number)
id = int(result[CommonPlayerInfoDeserializer.nba_id_index])
name = result[CommonPlayerInfoDeserializer.name_index]
team = Team.get_team_by_id(team_id=int(result[CommonPlayerInfoDeserializer.team_id_index]))
birth_date = CommonPlayerInfoDeserializer.parse_date(result[CommonPlayerInfoDeserializer.birth_date_index])
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime
from nba_data.data.players import DetailedPlayer
from nba_data.data.position import Position
from nba_data.data.team import Team
and context (classes, functions, sometimes code) from other files:
# Path: nba_data/data/players.py
# class DetailedPlayer(TeamPlayer):
#
# def __init__(self, name, team, id, birth_date, height, weight, jersey, position):
# self.birth_date = birth_date
# self.height = height
# self.weight = weight
# self.jersey = jersey
# self.position = position
# self.jersey = jersey
# TeamPlayer.__init__(self, name=name, id=id, team=team)
#
# def get_additional_unicode(self):
# return 'birth date: {birth_date} | height: {height} | weight: {weight} | ' 'jersey: {jersey} | ' \
# 'position: {position}'.format(birth_data=self.birth_date, height=self.height, weight=self.weight,
# jersey=self.jersey, position=self.position)
#
# Path: nba_data/data/position.py
# class Position(Enum):
# guard = "GUARD"
# guard_forward = "GUARD-FORWARD"
# forward_guard = "FORWARD-GUARD"
# forward = "FORWARD"
# center = "CENTER"
# forward_center = "FORWARD-CENTER"
#
# @staticmethod
# def get_position_from_abbreviation(abbreviation):
# return abbreviation_to_position_map.get(abbreviation.upper())
#
# @staticmethod
# def get_position_from_name(name):
# return name_to_position_map.get(name.upper())
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
. Output only the next line. | position = Position.get_position_from_name(name=str(result[CommonPlayerInfoDeserializer.position_name_index])) |
Predict the next line for this snippet: <|code_start|> if CommonPlayerInfoDeserializer.row_set_field_name not in result_set:
raise ValueError('Unable to parse results from %s', data)
row_set = result_set[CommonPlayerInfoDeserializer.row_set_field_name]
if len(row_set) < 1:
raise ValueError('Unable to parse row set from %s', data)
return row_set[CommonPlayerInfoDeserializer.row_set_index]
@staticmethod
def deserialize(data):
result = CommonPlayerInfoDeserializer.parse_result(data=data)
weight = result[CommonPlayerInfoDeserializer.weight_index]
if weight is not None:
weight = int(weight)
height_value = result[CommonPlayerInfoDeserializer.height_index]
if height_value is not None:
height = CommonPlayerInfoDeserializer.parse_height(height_value=height_value)
else:
height = None
jersey_number = result[CommonPlayerInfoDeserializer.jersey_number_index]
if jersey_number is not None:
jersey_number = int(jersey_number)
id = int(result[CommonPlayerInfoDeserializer.nba_id_index])
name = result[CommonPlayerInfoDeserializer.name_index]
<|code_end|>
with the help of current file imports:
from datetime import datetime
from nba_data.data.players import DetailedPlayer
from nba_data.data.position import Position
from nba_data.data.team import Team
and context from other files:
# Path: nba_data/data/players.py
# class DetailedPlayer(TeamPlayer):
#
# def __init__(self, name, team, id, birth_date, height, weight, jersey, position):
# self.birth_date = birth_date
# self.height = height
# self.weight = weight
# self.jersey = jersey
# self.position = position
# self.jersey = jersey
# TeamPlayer.__init__(self, name=name, id=id, team=team)
#
# def get_additional_unicode(self):
# return 'birth date: {birth_date} | height: {height} | weight: {weight} | ' 'jersey: {jersey} | ' \
# 'position: {position}'.format(birth_data=self.birth_date, height=self.height, weight=self.weight,
# jersey=self.jersey, position=self.position)
#
# Path: nba_data/data/position.py
# class Position(Enum):
# guard = "GUARD"
# guard_forward = "GUARD-FORWARD"
# forward_guard = "FORWARD-GUARD"
# forward = "FORWARD"
# center = "CENTER"
# forward_center = "FORWARD-CENTER"
#
# @staticmethod
# def get_position_from_abbreviation(abbreviation):
# return abbreviation_to_position_map.get(abbreviation.upper())
#
# @staticmethod
# def get_position_from_name(name):
# return name_to_position_map.get(name.upper())
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
, which may contain function names, class names, or code. Output only the next line. | team = Team.get_team_by_id(team_id=int(result[CommonPlayerInfoDeserializer.team_id_index])) |
Here is a snippet: <|code_start|>
class CalendarDeserializer:
internal_field_name = "_internal"
start_date_field_name = "startDate"
end_date_field_name = "endDate"
start_date_current_season_field_name = "startDateCurrentSeason"
fields_to_ignore = { internal_field_name, start_date_field_name, end_date_field_name, start_date_current_season_field_name }
date_format = "%Y%m%d"
def __init__(self):
pass
# TODO: @jbradley add pub date time to returned object
@staticmethod
<|code_end|>
. Write the next line using the current file imports:
from datetime import datetime
from nba_data.data.date_range import DateRange
and context from other files:
# Path: nba_data/data/date_range.py
# class DateRange:
# def __init__(self, start=date.today(), end=date.today()):
# assert start <= end
#
# self.start = start
# self.end = end
#
# def is_date_in_range(self, value):
# assert isinstance(value, date)
#
# return self.start <= value <= self.end
, which may include functions, classes, or code. Output only the next line. | def deserialize(calendar_json, date_range=DateRange(), ignore_dates_without_games=True): |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
class TestRotoWirePlayerNewsItemsDeserializer(TestCase):
def test_instantiation(self):
deserializer = RotoWirePlayerNewsItemsDeserializer()
self.assertTrue(deserializer.__dict__ == {})
def test_deserialize_common_all_players(self):
<|code_end|>
. Use current file imports:
(import json
import os
from unittest import TestCase
from nba_data.deserializers.roto_wire.player_news_items import RotoWirePlayerNewsItemsDeserializer
from tests.config import ROOT_DIRECTORY)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/deserializers/roto_wire/player_news_items.py
# class RotoWirePlayerNewsItemsDeserializer:
# def __init__(self):
# pass
#
# list_items_field_name = 'ListItems'
#
# @staticmethod
# def deserialize(data):
# return [
# RotoWirePlayerNewsItemDeserializer.deserialize(data=player_news_item)
# for player_news_item in data[RotoWirePlayerNewsItemsDeserializer.list_items_field_name]
# ]
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/rotowire_player_news.json')) as data_file: |
Next line prediction: <|code_start|>
@staticmethod
def generate_common_player_info_uri():
return UriGenerator.stats_base_uri + UriGenerator.common_player_info_path
@staticmethod
def generate_advanced_box_score_uri():
return UriGenerator.stats_base_uri + UriGenerator.advanced_box_score_path
@staticmethod
def generate_traditional_box_score_uri():
return UriGenerator.stats_base_uri + UriGenerator.traditional_box_score_path
@staticmethod
def generate_data_uri(path):
return UriGenerator.data_base_uri + 'data/10s/prod/v1/' + path + '.json'
@staticmethod
def generate_calendar_data_uri():
return UriGenerator.generate_data_uri(path=UriGenerator.calendar_path)
@staticmethod
def generate_scoreboard_data_uri(date_value):
assert isinstance(date_value, date)
path = date_value.strftime(UriGenerator.date_format) + '/' + UriGenerator.scoreboard_path
return UriGenerator.generate_data_uri(path=path)
@staticmethod
def generate_players_data_uri(season):
<|code_end|>
. Use current file imports:
(from datetime import date
from nba_data.data.season import Season)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/data/season.py
# class Season(BaseQueryParameter, Enum):
# season_2016 = "2016-17"
# season_2015 = "2015-16"
# season_2014 = "2014-15"
# season_2013 = "2013-14"
# season_2012 = "2012-13"
# season_2011 = "2011-12"
# season_2010 = "2010-11"
# season_2009 = "2009-10"
# season_2008 = "2008-09"
# season_2007 = "2007-08"
# season_2006 = "2006-07"
# season_2005 = "2005-06"
# season_2004 = "2004-05"
# season_2003 = "2003-04"
# season_2002 = "2002-03"
# season_2001 = "2001-02"
# season_2000 = "2000-01"
# season_1999 = "1999-00"
# season_1998 = "1998-99"
# season_1997 = "1997-98"
# season_1996 = "1996-97"
# season_1995 = "1995-96"
# season_1994 = "1994-95"
# season_1993 = "1993-94"
# season_1992 = "1992-93"
# season_1991 = "1991-92"
# season_1990 = "1990-91"
#
# @staticmethod
# def get_query_parameter_name():
# return "Season"
#
# @staticmethod
# def get_season_by_name(name):
# season = season_name_map.get(name)
#
# if season is None:
# raise ValueError("Unknown season name: %s", name)
#
# return season
#
# @staticmethod
# def get_season_by_start_year(year):
# season = start_year_to_season_map.get(year)
#
# if season is None:
# raise ValueError("Unknown season start year: %s", year)
#
# return season
#
# @staticmethod
# def get_season_by_end_year(year):
# season = season_end_year_map.get(year)
#
# if season is None:
# raise ValueError("Unknown season end year: %s", year)
#
# return season
#
# @staticmethod
# def get_season_by_start_and_end_year(start_year, end_year):
# start_year_season = Season.get_season_by_start_year(year=start_year)
# end_year_season = Season.get_season_by_end_year(year=end_year)
#
# if start_year_season is not end_year_season:
# raise ValueError("Cannot find season with start year: %s and end year: %s", start_year, end_year)
#
# return start_year_season
#
# @staticmethod
# def get_start_year_by_season(season):
# assert isinstance(season, Season)
#
# start_year = season_to_start_year_map.get(season)
#
# if start_year is None:
# raise ValueError("Cannot find start year for season: %s", season)
#
# return start_year
. Output only the next line. | assert isinstance(season, Season) |
Predict the next line after this snippet: <|code_start|>
class TestDateRange(TestCase):
start = date(year=2015, month=1, day=1)
end = date(year=2015, month=1, day=2)
def test_instantiation(self):
<|code_end|>
using the current file's imports:
from datetime import date, timedelta
from unittest import TestCase
from nba_data.data.date_range import DateRange
and any relevant context from other files:
# Path: nba_data/data/date_range.py
# class DateRange:
# def __init__(self, start=date.today(), end=date.today()):
# assert start <= end
#
# self.start = start
# self.end = end
#
# def is_date_in_range(self, value):
# assert isinstance(value, date)
#
# return self.start <= value <= self.end
. Output only the next line. | self.assertIsNotNone(DateRange(start=TestDateRange.start, end=TestDateRange.end)) |
Given snippet: <|code_start|>
# TODO: @jbradley in future make test more robust
class TestScoreboardDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(ScoreboardDeserializer())
def test_deserialize(self):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
from unittest import TestCase
from nba_data.deserializers.scoreboard import ScoreboardDeserializer
from tests.config import ROOT_DIRECTORY
and context:
# Path: nba_data/deserializers/scoreboard.py
# class ScoreboardDeserializer:
#
# datetime_format = '%Y-%m-%dT%H:%M:%S.%fZ'
# date_format = '%Y-%m-%d'
# start_time_time_zone = pytz.utc
#
# games_field_name = 'games'
# season_year_field_name = 'seasonYear'
# game_id_field_name = 'gameId'
# start_time_field_name = 'startTimeUTC'
# visiting_team_field_name = 'vTeam'
# home_team_field_name = 'hTeam'
# team_id_field_name = 'teamId'
#
# def __init__(self):
# pass
#
# @staticmethod
# def deserialize(data):
# if ScoreboardDeserializer.games_field_name not in data:
# raise ValueError('Unable to parse games field for %s', data)
#
# return [ScoreboardDeserializer.parse_game(data=game)
# for game in data[ScoreboardDeserializer.games_field_name]]
#
# @staticmethod
# def parse_game(data):
# if ScoreboardDeserializer.game_id_field_name not in data:
# raise ValueError('Unable to parse game id field for %s', data)
#
# if ScoreboardDeserializer.season_year_field_name not in data:
# raise ValueError('Unable to parse season year field for %s', data)
#
# if ScoreboardDeserializer.start_time_field_name not in data:
# raise ValueError('Unable to parse start time field for %s', data)
#
# game_id = data[ScoreboardDeserializer.game_id_field_name]
# season = Season.get_season_by_start_year(year=int(data[ScoreboardDeserializer.season_year_field_name]))
# start_time_value = data[ScoreboardDeserializer.start_time_field_name]
#
# # If start time is not a datetime then use date formatting
# try:
# start_time = datetime.strptime(start_time_value, ScoreboardDeserializer.datetime_format)
# except ValueError:
# start_time = datetime.strptime(start_time_value, ScoreboardDeserializer.date_format)
#
# start_time = start_time.replace(tzinfo=ScoreboardDeserializer.start_time_time_zone)
#
# match_up = ScoreboardDeserializer.parse_match_up(data=data)
#
# return ScoreboardGame(id=game_id, season=season, start_time=start_time, match_up=match_up)
#
# @staticmethod
# def parse_match_up(data):
# if ScoreboardDeserializer.home_team_field_name not in data:
# raise ValueError('Unable to parse home team field for %s', data)
#
# if ScoreboardDeserializer.visiting_team_field_name not in data:
# raise ValueError('Unable to parse visiting team field for %s', data)
#
# home_team = ScoreboardDeserializer.parse_team(data=data[ScoreboardDeserializer.home_team_field_name])
# away_team = ScoreboardDeserializer.parse_team(data=data[ScoreboardDeserializer.visiting_team_field_name])
#
# return MatchUp(home_team=home_team, away_team=away_team)
#
# @staticmethod
# def parse_team(data):
# if ScoreboardDeserializer.team_id_field_name not in data:
# raise ValueError('Unable to parse team id for %s', data)
#
# return Team.get_team_by_id(team_id=int(data[ScoreboardDeserializer.team_id_field_name]))
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
which might include code, classes, or functions. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/scoreboard.json')) as data_file: |
Continue the code snippet: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoretraditional.json')) as data_file:
data = json.load(data_file)
box_score = TraditionalGameBoxScoreDeserializer().deserialize(data=data)
self.assertIsNotNone(box_score)
<|code_end|>
. Use current file imports:
import json
import os
from unittest import TestCase
from nba_data.data.box_scores import GameBoxScore, TraditionalPlayerBoxScore, TraditionalTeamBoxScore
from nba_data.deserializers.box_scores.game import TraditionalGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and context (classes, functions, or code) from other files:
# Path: nba_data/data/box_scores.py
# class GameBoxScore:
# def __init__(self, game_id, player_box_scores, team_box_scores):
# self.game_id = game_id
# self.player_box_scores = player_box_scores
# self.team_box_scores = team_box_scores
#
# class TraditionalPlayerBoxScore(TraditionalBoxScore):
# def __init__(self, player, seconds_played, field_goals_made, field_goals_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls, plus_minus):
# self.player = player
# self.plus_minus = plus_minus
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'player: {player} | plus minus: {plus_minus}'.format(player=self.player, plus_minus=self.plus_minus)
#
# class TraditionalTeamBoxScore(TraditionalBoxScore):
# def __init__(self, team, seconds_played, field_goals_made, field_goals_attempted, free_throws_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls):
# self.team = team
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'team: {team}'.format(self.team)
#
# Path: nba_data/deserializers/box_scores/game.py
# class TraditionalGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def team_box_scores_deserializer(self, data):
# return TraditionalTeamBoxScoresDeserializer.deserialize(data=data)
#
# def player_box_scores_deserializer(self, data):
# return TraditionalPlayerBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | self.assertIsInstance(box_score, GameBoxScore) |
Given the following code snippet before the placeholder: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoretraditional.json')) as data_file:
data = json.load(data_file)
box_score = TraditionalGameBoxScoreDeserializer().deserialize(data=data)
self.assertIsNotNone(box_score)
self.assertIsInstance(box_score, GameBoxScore)
self.assertEqual(box_score.game_id, "0021500945")
self.assertEqual(len(box_score.player_box_scores), 25)
self.assertEqual(len(box_score.team_box_scores), 2)
<|code_end|>
, predict the next line using imports from the current file:
import json
import os
from unittest import TestCase
from nba_data.data.box_scores import GameBoxScore, TraditionalPlayerBoxScore, TraditionalTeamBoxScore
from nba_data.deserializers.box_scores.game import TraditionalGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and context including class names, function names, and sometimes code from other files:
# Path: nba_data/data/box_scores.py
# class GameBoxScore:
# def __init__(self, game_id, player_box_scores, team_box_scores):
# self.game_id = game_id
# self.player_box_scores = player_box_scores
# self.team_box_scores = team_box_scores
#
# class TraditionalPlayerBoxScore(TraditionalBoxScore):
# def __init__(self, player, seconds_played, field_goals_made, field_goals_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls, plus_minus):
# self.player = player
# self.plus_minus = plus_minus
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'player: {player} | plus minus: {plus_minus}'.format(player=self.player, plus_minus=self.plus_minus)
#
# class TraditionalTeamBoxScore(TraditionalBoxScore):
# def __init__(self, team, seconds_played, field_goals_made, field_goals_attempted, free_throws_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls):
# self.team = team
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'team: {team}'.format(self.team)
#
# Path: nba_data/deserializers/box_scores/game.py
# class TraditionalGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def team_box_scores_deserializer(self, data):
# return TraditionalTeamBoxScoresDeserializer.deserialize(data=data)
#
# def player_box_scores_deserializer(self, data):
# return TraditionalPlayerBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | self.assertIsInstance(box_score.player_box_scores[0], TraditionalPlayerBoxScore) |
Predict the next line after this snippet: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoretraditional.json')) as data_file:
data = json.load(data_file)
box_score = TraditionalGameBoxScoreDeserializer().deserialize(data=data)
self.assertIsNotNone(box_score)
self.assertIsInstance(box_score, GameBoxScore)
self.assertEqual(box_score.game_id, "0021500945")
self.assertEqual(len(box_score.player_box_scores), 25)
self.assertEqual(len(box_score.team_box_scores), 2)
self.assertIsInstance(box_score.player_box_scores[0], TraditionalPlayerBoxScore)
<|code_end|>
using the current file's imports:
import json
import os
from unittest import TestCase
from nba_data.data.box_scores import GameBoxScore, TraditionalPlayerBoxScore, TraditionalTeamBoxScore
from nba_data.deserializers.box_scores.game import TraditionalGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and any relevant context from other files:
# Path: nba_data/data/box_scores.py
# class GameBoxScore:
# def __init__(self, game_id, player_box_scores, team_box_scores):
# self.game_id = game_id
# self.player_box_scores = player_box_scores
# self.team_box_scores = team_box_scores
#
# class TraditionalPlayerBoxScore(TraditionalBoxScore):
# def __init__(self, player, seconds_played, field_goals_made, field_goals_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls, plus_minus):
# self.player = player
# self.plus_minus = plus_minus
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'player: {player} | plus minus: {plus_minus}'.format(player=self.player, plus_minus=self.plus_minus)
#
# class TraditionalTeamBoxScore(TraditionalBoxScore):
# def __init__(self, team, seconds_played, field_goals_made, field_goals_attempted, free_throws_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls):
# self.team = team
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'team: {team}'.format(self.team)
#
# Path: nba_data/deserializers/box_scores/game.py
# class TraditionalGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def team_box_scores_deserializer(self, data):
# return TraditionalTeamBoxScoresDeserializer.deserialize(data=data)
#
# def player_box_scores_deserializer(self, data):
# return TraditionalPlayerBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | self.assertIsInstance(box_score.team_box_scores[0], TraditionalTeamBoxScore) |
Based on the snippet: <|code_start|>
class TestTraditionalBoxScoreDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(TraditionalGameBoxScoreDeserializer())
def test_deserialize_traditional_box_score(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import json
import os
from unittest import TestCase
from nba_data.data.box_scores import GameBoxScore, TraditionalPlayerBoxScore, TraditionalTeamBoxScore
from nba_data.deserializers.box_scores.game import TraditionalGameBoxScoreDeserializer
from tests.config import ROOT_DIRECTORY
and context (classes, functions, sometimes code) from other files:
# Path: nba_data/data/box_scores.py
# class GameBoxScore:
# def __init__(self, game_id, player_box_scores, team_box_scores):
# self.game_id = game_id
# self.player_box_scores = player_box_scores
# self.team_box_scores = team_box_scores
#
# class TraditionalPlayerBoxScore(TraditionalBoxScore):
# def __init__(self, player, seconds_played, field_goals_made, field_goals_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, free_throws_attempted, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls, plus_minus):
# self.player = player
# self.plus_minus = plus_minus
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'player: {player} | plus minus: {plus_minus}'.format(player=self.player, plus_minus=self.plus_minus)
#
# class TraditionalTeamBoxScore(TraditionalBoxScore):
# def __init__(self, team, seconds_played, field_goals_made, field_goals_attempted, free_throws_attempted,
# three_point_field_goals_made, three_point_field_goals_attempted,
# free_throws_made, offensive_rebounds, defensive_rebounds, assists,
# steals, blocks, turnovers, personal_fouls):
# self.team = team
# TraditionalBoxScore.__init__(self, seconds_played=seconds_played, field_goals_made=field_goals_made,
# field_goals_attempted=field_goals_attempted,
# three_point_field_goals_made=three_point_field_goals_made,
# three_point_field_goals_attempted=three_point_field_goals_attempted,
# free_throws_made=free_throws_made, free_throws_attempted=free_throws_attempted,
# offensive_rebounds=offensive_rebounds, defensive_rebounds=defensive_rebounds,
# assists=assists, steals=steals, blocks=blocks, turnovers=turnovers,
# personal_fouls=personal_fouls)
#
# def get_additional_unicode(self):
# return 'team: {team}'.format(self.team)
#
# Path: nba_data/deserializers/box_scores/game.py
# class TraditionalGameBoxScoreDeserializer(BoxScoreDeserializer):
#
# def team_box_scores_deserializer(self, data):
# return TraditionalTeamBoxScoresDeserializer.deserialize(data=data)
#
# def player_box_scores_deserializer(self, data):
# return TraditionalPlayerBoxScoresDeserializer.deserialize(data=data)
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/boxscoretraditional.json')) as data_file: |
Next line prediction: <|code_start|>
class TestSeasonType(TestCase):
def test_get_query_parameter_name(self):
self.assertEqual(SeasonType.get_query_parameter_name(), "SeasonType")
def test_get_season_typea(self):
self.assertEqual(SeasonType.get_season_type("Regular Season"), SeasonType.regular_season)
self.assertRaises(ValueError, SeasonType.get_season_type, "regular season")
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from nba_data.data.season_type import SeasonType, season_type_name_map)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/data/season_type.py
# class SeasonType(BaseQueryParameter, Enum):
# def get_query_parameter_name():
# def get_season_type(season_type_name):
. Output only the next line. | self.assertEqual(season_type_name_map, |
Given the code snippet: <|code_start|>
class TestOutcome(TestCase):
def test_get_outcome_from_abbreviation(self):
self.assertEqual(Outcome.get_outcome_from_abbreviation("w"), Outcome.win)
self.assertEqual(Outcome.get_outcome_from_abbreviation("W"), Outcome.win)
self.assertRaises(ValueError, Outcome.get_outcome_from_abbreviation, "jae")
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from nba_data.data.outcome import Outcome, outcome_abbreviation_to_outcome_map
and context (functions, classes, or occasionally code) from other files:
# Path: nba_data/data/outcome.py
# class Outcome(Enum):
# def get_outcome_from_abbreviation(abbreviation):
. Output only the next line. | self.assertEqual(outcome_abbreviation_to_outcome_map, |
Next line prediction: <|code_start|>
class CommonAllPlayersDeserializer:
name_index = 2
team_id_index = 7
id_index = 0
result_sets_field_name = 'resultSets'
row_set_field_name = 'rowSet'
results_index = 0
def __init__(self):
pass
@staticmethod
def deserialize(data):
return [CommonAllPlayersDeserializer.deserialize_result(result=result)
for result in CommonAllPlayersDeserializer.parse_results(data=data)]
@staticmethod
def deserialize_result(result):
<|code_end|>
. Use current file imports:
(from nba_data.data.players import CommonAllPlayer
from nba_data.data.team import Team)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/data/players.py
# class CommonAllPlayer(TeamPlayer):
# def __init__(self, name, id, team):
# TeamPlayer.__init__(self, name, id, team)
#
# def get_additional_unicode(self):
# return ''
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
. Output only the next line. | return CommonAllPlayer(name=result[CommonAllPlayersDeserializer.name_index], |
Predict the next line after this snippet: <|code_start|>
class CommonAllPlayersDeserializer:
name_index = 2
team_id_index = 7
id_index = 0
result_sets_field_name = 'resultSets'
row_set_field_name = 'rowSet'
results_index = 0
def __init__(self):
pass
@staticmethod
def deserialize(data):
return [CommonAllPlayersDeserializer.deserialize_result(result=result)
for result in CommonAllPlayersDeserializer.parse_results(data=data)]
@staticmethod
def deserialize_result(result):
return CommonAllPlayer(name=result[CommonAllPlayersDeserializer.name_index],
<|code_end|>
using the current file's imports:
from nba_data.data.players import CommonAllPlayer
from nba_data.data.team import Team
and any relevant context from other files:
# Path: nba_data/data/players.py
# class CommonAllPlayer(TeamPlayer):
# def __init__(self, name, id, team):
# TeamPlayer.__init__(self, name, id, team)
#
# def get_additional_unicode(self):
# return ''
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
. Output only the next line. | team=Team.get_team_by_id(team_id=result[CommonAllPlayersDeserializer.team_id_index]), |
Next line prediction: <|code_start|>
class TestPosition(TestCase):
def test_get_position_from_abbreviation(self):
guard = Position.get_position_from_abbreviation("g")
self.assertEqual(guard, Position.guard)
another_guard = Position.get_position_from_abbreviation("G")
self.assertEqual(another_guard, Position.guard)
self.assertIsNone(Position.get_position_from_abbreviation("jae"))
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from nba_data.data.position import Position, abbreviation_to_position_map, name_to_position_map)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/data/position.py
# class Position(Enum):
# def get_position_from_abbreviation(abbreviation):
# def get_position_from_name(name):
. Output only the next line. | self.assertEqual(abbreviation_to_position_map, |
Given the code snippet: <|code_start|>
class TestPosition(TestCase):
def test_get_position_from_abbreviation(self):
guard = Position.get_position_from_abbreviation("g")
self.assertEqual(guard, Position.guard)
another_guard = Position.get_position_from_abbreviation("G")
self.assertEqual(another_guard, Position.guard)
self.assertIsNone(Position.get_position_from_abbreviation("jae"))
self.assertEqual(abbreviation_to_position_map,
{
"G": Position.guard,
"G-F": Position.guard_forward,
"F-G": Position.forward_guard,
"F": Position.forward,
"C": Position.center,
"F-C": Position.forward_center,
})
def test_get_position_from_name(self):
guard = Position.get_position_from_name("GUARD")
self.assertEqual(guard, Position.guard)
another_guard = Position.get_position_from_name("guard")
self.assertEqual(another_guard, Position.guard)
self.assertIsNone(Position.get_position_from_name("jae"))
<|code_end|>
, generate the next line using the imports in this file:
from unittest import TestCase
from nba_data.data.position import Position, abbreviation_to_position_map, name_to_position_map
and context (functions, classes, or occasionally code) from other files:
# Path: nba_data/data/position.py
# class Position(Enum):
# def get_position_from_abbreviation(abbreviation):
# def get_position_from_name(name):
. Output only the next line. | self.assertEqual(name_to_position_map, |
Here is a snippet: <|code_start|>
class TestCalendarDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(CalendarDeserializer())
def test_deserialize(self):
start = date(year=2016, month=12, day=1)
end = date(year=2017, month=2, day=15)
<|code_end|>
. Write the next line using the current file imports:
import json
import os
from datetime import date
from unittest import TestCase
from nba_data.data.date_range import DateRange
from nba_data.deserializers.calendar import CalendarDeserializer
from tests.config import ROOT_DIRECTORY
and context from other files:
# Path: nba_data/data/date_range.py
# class DateRange:
# def __init__(self, start=date.today(), end=date.today()):
# assert start <= end
#
# self.start = start
# self.end = end
#
# def is_date_in_range(self, value):
# assert isinstance(value, date)
#
# return self.start <= value <= self.end
#
# Path: nba_data/deserializers/calendar.py
# class CalendarDeserializer:
# internal_field_name = "_internal"
# start_date_field_name = "startDate"
# end_date_field_name = "endDate"
# start_date_current_season_field_name = "startDateCurrentSeason"
# fields_to_ignore = { internal_field_name, start_date_field_name, end_date_field_name, start_date_current_season_field_name }
# date_format = "%Y%m%d"
#
# def __init__(self):
# pass
#
# # TODO: @jbradley add pub date time to returned object
# @staticmethod
# def deserialize(calendar_json, date_range=DateRange(), ignore_dates_without_games=True):
# calendar_values = {}
# for key, value in calendar_json.items():
# if ((value != 0 and ignore_dates_without_games is True) or ignore_dates_without_games is False) \
# and key not in CalendarDeserializer.fields_to_ignore:
# date_value = datetime.strptime(key, CalendarDeserializer.date_format).date()
# if date_range.is_date_in_range(value=date_value):
# calendar_values[date_value] = value
# return calendar_values
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
, which may include functions, classes, or code. Output only the next line. | date_range = DateRange(start=start, end=end) |
Predict the next line for this snippet: <|code_start|>
class TestCalendarDeserializer(TestCase):
def test_instantiation(self):
self.assertIsNotNone(CalendarDeserializer())
def test_deserialize(self):
start = date(year=2016, month=12, day=1)
end = date(year=2017, month=2, day=15)
date_range = DateRange(start=start, end=end)
very_beginning = date(year=2015, month=10, day=2)
very_end = date(year=2017, month=4, day=12)
complete_date_range = DateRange(start=very_beginning, end=very_end)
# TODO: @jbradley make this piss-poor test slightly more robust in the future
<|code_end|>
with the help of current file imports:
import json
import os
from datetime import date
from unittest import TestCase
from nba_data.data.date_range import DateRange
from nba_data.deserializers.calendar import CalendarDeserializer
from tests.config import ROOT_DIRECTORY
and context from other files:
# Path: nba_data/data/date_range.py
# class DateRange:
# def __init__(self, start=date.today(), end=date.today()):
# assert start <= end
#
# self.start = start
# self.end = end
#
# def is_date_in_range(self, value):
# assert isinstance(value, date)
#
# return self.start <= value <= self.end
#
# Path: nba_data/deserializers/calendar.py
# class CalendarDeserializer:
# internal_field_name = "_internal"
# start_date_field_name = "startDate"
# end_date_field_name = "endDate"
# start_date_current_season_field_name = "startDateCurrentSeason"
# fields_to_ignore = { internal_field_name, start_date_field_name, end_date_field_name, start_date_current_season_field_name }
# date_format = "%Y%m%d"
#
# def __init__(self):
# pass
#
# # TODO: @jbradley add pub date time to returned object
# @staticmethod
# def deserialize(calendar_json, date_range=DateRange(), ignore_dates_without_games=True):
# calendar_values = {}
# for key, value in calendar_json.items():
# if ((value != 0 and ignore_dates_without_games is True) or ignore_dates_without_games is False) \
# and key not in CalendarDeserializer.fields_to_ignore:
# date_value = datetime.strptime(key, CalendarDeserializer.date_format).date()
# if date_range.is_date_in_range(value=date_value):
# calendar_values[date_value] = value
# return calendar_values
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
, which may contain function names, class names, or code. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/calendar.json')) as data_file: |
Next line prediction: <|code_start|>
class TestCommonAllPlayersDeserializer(TestCase):
def test_instantiation(self):
deserializer = CommonAllPlayersDeserializer()
self.assertTrue(deserializer.__dict__ == {})
def test_deserialize_common_all_players(self):
with open(os.path.join(ROOT_DIRECTORY, 'tests/files/commonallplayers.json')) as data_file:
data = json.load(data_file)
deserialized_players = CommonAllPlayersDeserializer.deserialize(data)
quincy_acy = deserialized_players[0]
self.assertEqual(quincy_acy.name, "Quincy Acy")
self.assertEqual(quincy_acy.id, 203112)
<|code_end|>
. Use current file imports:
(import json
import os
from unittest import TestCase
from nba_data.data.team import Team
from nba_data.deserializers.common_all_players import CommonAllPlayersDeserializer
from tests.config import ROOT_DIRECTORY)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
#
# Path: nba_data/deserializers/common_all_players.py
# class CommonAllPlayersDeserializer:
# name_index = 2
# team_id_index = 7
# id_index = 0
# result_sets_field_name = 'resultSets'
# row_set_field_name = 'rowSet'
# results_index = 0
#
# def __init__(self):
# pass
#
# @staticmethod
# def deserialize(data):
# return [CommonAllPlayersDeserializer.deserialize_result(result=result)
# for result in CommonAllPlayersDeserializer.parse_results(data=data)]
#
# @staticmethod
# def deserialize_result(result):
# return CommonAllPlayer(name=result[CommonAllPlayersDeserializer.name_index],
# team=Team.get_team_by_id(team_id=result[CommonAllPlayersDeserializer.team_id_index]),
# id=result[CommonAllPlayersDeserializer.id_index])
#
# @staticmethod
# def parse_results(data):
# if CommonAllPlayersDeserializer.result_sets_field_name not in data:
# raise ValueError('Unable to identify results for %s', data)
#
# result_sets = data[CommonAllPlayersDeserializer.result_sets_field_name]
#
# if len(result_sets) < 1:
# raise ValueError('Unable to identify results for %s', data)
#
# if CommonAllPlayersDeserializer.row_set_field_name not in result_sets[CommonAllPlayersDeserializer.results_index]:
# raise ValueError('Unable to identify results for %s', data)
#
# return result_sets[CommonAllPlayersDeserializer.results_index][CommonAllPlayersDeserializer.row_set_field_name]
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
. Output only the next line. | self.assertEqual(quincy_acy.team, Team.sacramento_kings) |
Here is a snippet: <|code_start|>
class TestCommonAllPlayersDeserializer(TestCase):
def test_instantiation(self):
deserializer = CommonAllPlayersDeserializer()
self.assertTrue(deserializer.__dict__ == {})
def test_deserialize_common_all_players(self):
<|code_end|>
. Write the next line using the current file imports:
import json
import os
from unittest import TestCase
from nba_data.data.team import Team
from nba_data.deserializers.common_all_players import CommonAllPlayersDeserializer
from tests.config import ROOT_DIRECTORY
and context from other files:
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
#
# Path: nba_data/deserializers/common_all_players.py
# class CommonAllPlayersDeserializer:
# name_index = 2
# team_id_index = 7
# id_index = 0
# result_sets_field_name = 'resultSets'
# row_set_field_name = 'rowSet'
# results_index = 0
#
# def __init__(self):
# pass
#
# @staticmethod
# def deserialize(data):
# return [CommonAllPlayersDeserializer.deserialize_result(result=result)
# for result in CommonAllPlayersDeserializer.parse_results(data=data)]
#
# @staticmethod
# def deserialize_result(result):
# return CommonAllPlayer(name=result[CommonAllPlayersDeserializer.name_index],
# team=Team.get_team_by_id(team_id=result[CommonAllPlayersDeserializer.team_id_index]),
# id=result[CommonAllPlayersDeserializer.id_index])
#
# @staticmethod
# def parse_results(data):
# if CommonAllPlayersDeserializer.result_sets_field_name not in data:
# raise ValueError('Unable to identify results for %s', data)
#
# result_sets = data[CommonAllPlayersDeserializer.result_sets_field_name]
#
# if len(result_sets) < 1:
# raise ValueError('Unable to identify results for %s', data)
#
# if CommonAllPlayersDeserializer.row_set_field_name not in result_sets[CommonAllPlayersDeserializer.results_index]:
# raise ValueError('Unable to identify results for %s', data)
#
# return result_sets[CommonAllPlayersDeserializer.results_index][CommonAllPlayersDeserializer.row_set_field_name]
#
# Path: tests/config.py
# ROOT_DIRECTORY = root_path = os.path.dirname(os.path.dirname(__file__))
, which may include functions, classes, or code. Output only the next line. | with open(os.path.join(ROOT_DIRECTORY, 'tests/files/commonallplayers.json')) as data_file: |
Given the code snippet: <|code_start|>
class RotoWirePlayerNewsItemsDeserializer:
def __init__(self):
pass
list_items_field_name = 'ListItems'
@staticmethod
def deserialize(data):
return [
<|code_end|>
, generate the next line using the imports in this file:
from nba_data.deserializers.roto_wire.player_news_item import RotoWirePlayerNewsItemDeserializer
and context (functions, classes, or occasionally code) from other files:
# Path: nba_data/deserializers/roto_wire/player_news_item.py
# class RotoWirePlayerNewsItemDeserializer:
#
# def __init__(self):
# pass
#
# caption_field_name = 'ListItemCaption'
# description_field_name = 'ListItemDescription'
# list_item_publish_date_field_name = 'ListItemPubDate'
# last_updated_field_name = 'lastUpdate'
# update_id_field_name = 'UpdateId'
# roto_id_field_name = 'RotoId'
# player_id_field_name = 'PlayerID'
# first_name_field_name = 'FirstName'
# last_name_field_name = 'LastName'
# position_abbreviation_field_name = 'Position'
# team_abbreviation_field_name = 'Team'
# team_code_field_name = 'TeamCode'
# date_field_name = 'Date'
# priority_field_name = 'Priority'
# player_code_field_name = 'player_code'
# headline_field_name = 'Headline'
# injured_field_name = 'Injured'
# injured_status_field_name = 'Injured_Status'
# injury_location_field_name = 'Injury_Location'
# injury_type_field_name = 'Injury_Type'
# injury_detail_field_name = 'Injury_Detail'
# injury_side_field_name = 'Injury_Side'
# date_time_format = '%m/%d/%Y %H:%M:%S %p'
# timezone = timezone('US/Central')
#
# @staticmethod
# def deserialize(data):
# position_abbreviation = data[RotoWirePlayerNewsItemDeserializer.position_abbreviation_field_name]
# caption = unicode(data[RotoWirePlayerNewsItemDeserializer.caption_field_name])
# date = data[RotoWirePlayerNewsItemDeserializer.date_field_name]
# description = unicode(data[RotoWirePlayerNewsItemDeserializer.description_field_name])
#
# is_injured = False
# if data[RotoWirePlayerNewsItemDeserializer.injured_field_name] == 'YES':
# is_injured = True
#
# team_abbreviation = data[RotoWirePlayerNewsItemDeserializer.team_abbreviation_field_name]
# team = Team.get_team_by_abbreviation(abbreviation=team_abbreviation)
# player_news_item_date = datetime.datetime.fromtimestamp(int(date), utc)
# source_update_id = int(data[RotoWirePlayerNewsItemDeserializer.update_id_field_name])
# source_id = int(data[RotoWirePlayerNewsItemDeserializer.roto_id_field_name])
# source_player_id = data[RotoWirePlayerNewsItemDeserializer.player_id_field_name]
# first_name = unicode(data[RotoWirePlayerNewsItemDeserializer.first_name_field_name])
# last_name = unicode(data[RotoWirePlayerNewsItemDeserializer.last_name_field_name])
# priority = int(data[RotoWirePlayerNewsItemDeserializer.priority_field_name])
# headline = unicode(data[RotoWirePlayerNewsItemDeserializer.headline_field_name])
#
# status = Status.from_value(data[RotoWirePlayerNewsItemDeserializer.injured_status_field_name])
# affected_area = unicode(data[RotoWirePlayerNewsItemDeserializer.injury_type_field_name])
# detail = unicode(data[RotoWirePlayerNewsItemDeserializer.injury_detail_field_name])
# side = unicode(data[RotoWirePlayerNewsItemDeserializer.injury_side_field_name])
# position = Position.get_position_from_abbreviation(abbreviation=position_abbreviation)
#
# injury_details = InjuryDetails(is_injured=is_injured, status=status, affected_area=affected_area,
# detail=detail, side=side)
#
# return PlayerNewsItem(caption=caption, description=description, source_update_id=source_update_id,
# source_id=source_id, source_player_id=source_player_id, first_name=first_name,
# last_name=last_name, position=position, team=team, published_at=player_news_item_date,
# priority=priority, headline=headline, injury=injury_details)
. Output only the next line. | RotoWirePlayerNewsItemDeserializer.deserialize(data=player_news_item) |
Next line prediction: <|code_start|>
class TestTeamSeasonRange(TestCase):
def test_instantiation(self):
team = Team.atlanta_hawks
<|code_end|>
. Use current file imports:
(from unittest import TestCase
from nba_data.data.season import Season
from nba_data.data.season_range import SeasonRange
from nba_data.data.team import Team
from nba_data.data.team_season_range import TeamSeasonRange)
and context including class names, function names, or small code snippets from other files:
# Path: nba_data/data/season.py
# class Season(BaseQueryParameter, Enum):
# season_2016 = "2016-17"
# season_2015 = "2015-16"
# season_2014 = "2014-15"
# season_2013 = "2013-14"
# season_2012 = "2012-13"
# season_2011 = "2011-12"
# season_2010 = "2010-11"
# season_2009 = "2009-10"
# season_2008 = "2008-09"
# season_2007 = "2007-08"
# season_2006 = "2006-07"
# season_2005 = "2005-06"
# season_2004 = "2004-05"
# season_2003 = "2003-04"
# season_2002 = "2002-03"
# season_2001 = "2001-02"
# season_2000 = "2000-01"
# season_1999 = "1999-00"
# season_1998 = "1998-99"
# season_1997 = "1997-98"
# season_1996 = "1996-97"
# season_1995 = "1995-96"
# season_1994 = "1994-95"
# season_1993 = "1993-94"
# season_1992 = "1992-93"
# season_1991 = "1991-92"
# season_1990 = "1990-91"
#
# @staticmethod
# def get_query_parameter_name():
# return "Season"
#
# @staticmethod
# def get_season_by_name(name):
# season = season_name_map.get(name)
#
# if season is None:
# raise ValueError("Unknown season name: %s", name)
#
# return season
#
# @staticmethod
# def get_season_by_start_year(year):
# season = start_year_to_season_map.get(year)
#
# if season is None:
# raise ValueError("Unknown season start year: %s", year)
#
# return season
#
# @staticmethod
# def get_season_by_end_year(year):
# season = season_end_year_map.get(year)
#
# if season is None:
# raise ValueError("Unknown season end year: %s", year)
#
# return season
#
# @staticmethod
# def get_season_by_start_and_end_year(start_year, end_year):
# start_year_season = Season.get_season_by_start_year(year=start_year)
# end_year_season = Season.get_season_by_end_year(year=end_year)
#
# if start_year_season is not end_year_season:
# raise ValueError("Cannot find season with start year: %s and end year: %s", start_year, end_year)
#
# return start_year_season
#
# @staticmethod
# def get_start_year_by_season(season):
# assert isinstance(season, Season)
#
# start_year = season_to_start_year_map.get(season)
#
# if start_year is None:
# raise ValueError("Cannot find start year for season: %s", season)
#
# return start_year
#
# Path: nba_data/data/season_range.py
# class SeasonRange:
# def __init__(self, start, end):
# self.start = start
# self.end = end
#
# Path: nba_data/data/team.py
# class Team(BaseQueryParameter, Enum):
# atlanta_hawks = "Atlanta Hawks"
# boston_celtics = "Boston Celtics"
# brooklyn_nets = "Brooklyn Nets"
# charlotte_hornets = "Charlotte Hornets"
# chicago_bulls = "Chicago Bulls"
# cleveland_cavaliers = "Cleveland Cavaliers"
# dallas_mavericks = "Dallas Mavericks"
# denver_nuggets = "Denver Nuggets"
# detroit_pistons = "Detroit Pistons"
# golden_state_warriors = "Golden State Warriors"
# houston_rockets = "Houston Rockets"
# indiana_pacers = "Indiana Pacers"
# los_angeles_clippers = "Los Angeles Clippers"
# los_angeles_lakers = "Los Angeles Lakers"
# memphis_grizzlies = "Memphis Grizzlies"
# miami_heat = "Miami Heat"
# milwaukee_bucks = "Milwaukee Bucks"
# minnesota_timberwolves = "Minnesota Timberwolves"
# new_orleans_pelicans = "New Orleans Pelicans"
# new_york_knicks = "New York Knicks"
# oklahoma_city_thunder = "Oklahoma City Thunder"
# orlando_magic = "Orlando Magic"
# philadelphia_76ers = "Philadelphia 76ers"
# phoenix_suns = "Phoenix Suns"
# portland_trail_blazers = "Portland Trail Blazers"
# sacramento_kings = "Sacramento Kings"
# san_antonio_spurs = "San Antonio Spurs"
# toronto_raptors = "Toronto Raptors"
# utah_jazz = "Utah Jazz"
# washington_wizards = "Washington Wizards"
#
# @staticmethod
# def get_query_parameter_name():
# return "TeamId"
#
# @staticmethod
# def get_team_by_id(team_id):
# assert isinstance(team_id, int)
#
# return team_id_map.get(team_id)
#
# @staticmethod
# def get_id(team):
# assert isinstance(team, Team)
#
# return team_to_id_map.get(team)
#
# @staticmethod
# def get_team_by_abbreviation(abbreviation):
# assert isinstance(abbreviation, basestring)
#
# team = team_abbreviation_map.get(abbreviation.upper())
#
# if team is None:
# raise ValueError('Unknown team abbreviation: %s', abbreviation)
#
# return team_abbreviation_map.get(abbreviation.upper())
#
# @staticmethod
# def get_team_by_name(name):
# assert isinstance(name, basestring)
#
# team = team_name_map.get(name)
#
# if team is None:
# raise ValueError('Unknown team name: %s', name)
#
# return team
#
# Path: nba_data/data/team_season_range.py
# class TeamSeasonRange:
# def __init__(self, team, season_range):
# self.team = team
# self.season_range = season_range
. Output only the next line. | start_season = Season.season_2015 |
Here is a snippet: <|code_start|>
class CourseModelTest(TestCase):
def test_course_can_be_created_with_only_no(self):
Course.objects.create(no='12345QAQ 010101')
self.assertEqual(1, Course.objects.count())
class FlatPrerequisiteModelTest(TestCase):
def test_update_html_creates_object(self):
<|code_end|>
. Write the next line using the current file imports:
from django.test import TestCase
from data_center.models import Course, FlatPrerequisite
and context from other files:
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class FlatPrerequisite(models.Model):
# '''
# store rendered prerequisite in the database
# alternative: django.contrib.flatpage
# '''
# updated_at = models.DateTimeField(auto_now=True)
# html = models.TextField()
#
# @classmethod
# def update_html(cls, html):
# if cls.objects.exists():
# ins = cls.objects.get()
# ins.html = html
# ins.save()
# return ins
# else:
# return cls.objects.create(html=html)
, which may include functions, classes, or code. Output only the next line. | FlatPrerequisite.update_html('<3') |
Here is a snippet: <|code_start|>
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print('Automated decaptcha failed.')
else:
print('crawler.decaptcha not available (requires tesseract >= 3.03).')
print('Please provide valid ACIXSTORE and auth_num from')
print(url)
ACIXSTORE = input('ACIXSTORE: ')
auth_num = input('auth_num: ')
return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
for ys in [get_config('crawler', 'semester')]:
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.9/JH629001.php'
)
print('Crawling course for ' + ys)
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
from crawler.course import get_cou_codes
from crawler.decaptcha import Entrance, DecaptchaFailure
from data_center.models import Course, Department
from utils.config import get_config
import time
and context from other files:
# Path: crawler/crawler.py
# def crawl_course(acixstore, auth_num, cou_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# curriculum_futures = [
# cou_code_2_future(session, cou_code, acixstore, auth_num, ys)
# for cou_code in cou_codes
# ]
#
# progress = progressbar.ProgressBar(maxval=len(cou_codes))
# with transaction.atomic():
# for future, cou_code in progress(zip(curriculum_futures,
# cou_codes)):
# response = future.result()
# response.encoding = 'cp950'
# handle_curriculum_html(response.text, cou_code)
#
# print('Crawling syllabus...')
# course_list = list(Course.objects.all())
#
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# course_futures = [
# session.get(
# syllabus_url,
# params={
# 'c_key': course.no,
# 'ACIXSTORE': acixstore,
# }
# )
# for course in course_list
# ]
#
# progress = progressbar.ProgressBar(maxval=len(course_list))
# for future, course in progress(zip_longest(course_futures,
# course_list)):
# response = future.result()
# response.encoding = 'cp950'
# save_syllabus(response.text, course, ys)
#
# print('Total course information: %d' % Course.objects.filter(ys=ys).count()) # noqa
#
# def crawl_dept(acixstore, auth_num, dept_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# future_depts = [
# dept_2_future(session, dept_code, acixstore, auth_num, ys)
# for dept_code in dept_codes
# ]
#
# progress = progressbar.ProgressBar()
# with transaction.atomic():
# for future in progress(future_depts):
# response = future.result()
# response.encoding = encoding
# handle_dept_html(response.text, ys)
#
# print('Total department information: %d' % Department.objects.filter(ys=ys).count()) # noqa
#
# Path: crawler/course.py
# def get_cou_codes():
# html = get(form_url).text
# document = lxml.html.fromstring(html)
# return document.xpath('//select[@name="cou_code"]/option/@value')
#
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class Department(models.Model):
# dept_name = models.CharField(max_length=20, blank=True)
# required_course = models.ManyToManyField(Course, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# def __str__(self):
# return self.dept_name
#
# Path: utils/config.py
# def get_config(section, option, filename='nthu_course.cfg'):
# '''Return a config in that section'''
# try:
# config = configparser.ConfigParser()
# config.optionxform = str
# config.read(settings.BASE_DIR + '/NTHU_Course/config/' + filename)
# return config.get(section, option)
# except Exception as ex:
# # no config found
# return None
, which may include functions, classes, or code. Output only the next line. | crawl_course(ACIXSTORE, auth_num, cou_codes, ys) |
Given snippet: <|code_start|> else:
print('crawler.decaptcha not available (requires tesseract >= 3.03).')
print('Please provide valid ACIXSTORE and auth_num from')
print(url)
ACIXSTORE = input('ACIXSTORE: ')
auth_num = input('auth_num: ')
return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
for ys in [get_config('crawler', 'semester')]:
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.9/JH629001.php'
)
print('Crawling course for ' + ys)
crawl_course(ACIXSTORE, auth_num, cou_codes, ys)
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.3/JH623001.php'
)
print('Crawling dept for ' + ys)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
from crawler.course import get_cou_codes
from crawler.decaptcha import Entrance, DecaptchaFailure
from data_center.models import Course, Department
from utils.config import get_config
import time
and context:
# Path: crawler/crawler.py
# def crawl_course(acixstore, auth_num, cou_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# curriculum_futures = [
# cou_code_2_future(session, cou_code, acixstore, auth_num, ys)
# for cou_code in cou_codes
# ]
#
# progress = progressbar.ProgressBar(maxval=len(cou_codes))
# with transaction.atomic():
# for future, cou_code in progress(zip(curriculum_futures,
# cou_codes)):
# response = future.result()
# response.encoding = 'cp950'
# handle_curriculum_html(response.text, cou_code)
#
# print('Crawling syllabus...')
# course_list = list(Course.objects.all())
#
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# course_futures = [
# session.get(
# syllabus_url,
# params={
# 'c_key': course.no,
# 'ACIXSTORE': acixstore,
# }
# )
# for course in course_list
# ]
#
# progress = progressbar.ProgressBar(maxval=len(course_list))
# for future, course in progress(zip_longest(course_futures,
# course_list)):
# response = future.result()
# response.encoding = 'cp950'
# save_syllabus(response.text, course, ys)
#
# print('Total course information: %d' % Course.objects.filter(ys=ys).count()) # noqa
#
# def crawl_dept(acixstore, auth_num, dept_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# future_depts = [
# dept_2_future(session, dept_code, acixstore, auth_num, ys)
# for dept_code in dept_codes
# ]
#
# progress = progressbar.ProgressBar()
# with transaction.atomic():
# for future in progress(future_depts):
# response = future.result()
# response.encoding = encoding
# handle_dept_html(response.text, ys)
#
# print('Total department information: %d' % Department.objects.filter(ys=ys).count()) # noqa
#
# Path: crawler/course.py
# def get_cou_codes():
# html = get(form_url).text
# document = lxml.html.fromstring(html)
# return document.xpath('//select[@name="cou_code"]/option/@value')
#
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class Department(models.Model):
# dept_name = models.CharField(max_length=20, blank=True)
# required_course = models.ManyToManyField(Course, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# def __str__(self):
# return self.dept_name
#
# Path: utils/config.py
# def get_config(section, option, filename='nthu_course.cfg'):
# '''Return a config in that section'''
# try:
# config = configparser.ConfigParser()
# config.optionxform = str
# config.read(settings.BASE_DIR + '/NTHU_Course/config/' + filename)
# return config.get(section, option)
# except Exception as ex:
# # no config found
# return None
which might include code, classes, or functions. Output only the next line. | crawl_dept(ACIXSTORE, auth_num, cou_codes, ys) |
Here is a snippet: <|code_start|>
try:
except ImportError:
Entrance = None
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print('Automated decaptcha failed.')
else:
print('crawler.decaptcha not available (requires tesseract >= 3.03).')
print('Please provide valid ACIXSTORE and auth_num from')
print(url)
ACIXSTORE = input('ACIXSTORE: ')
auth_num = input('auth_num: ')
return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
from crawler.course import get_cou_codes
from crawler.decaptcha import Entrance, DecaptchaFailure
from data_center.models import Course, Department
from utils.config import get_config
import time
and context from other files:
# Path: crawler/crawler.py
# def crawl_course(acixstore, auth_num, cou_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# curriculum_futures = [
# cou_code_2_future(session, cou_code, acixstore, auth_num, ys)
# for cou_code in cou_codes
# ]
#
# progress = progressbar.ProgressBar(maxval=len(cou_codes))
# with transaction.atomic():
# for future, cou_code in progress(zip(curriculum_futures,
# cou_codes)):
# response = future.result()
# response.encoding = 'cp950'
# handle_curriculum_html(response.text, cou_code)
#
# print('Crawling syllabus...')
# course_list = list(Course.objects.all())
#
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# course_futures = [
# session.get(
# syllabus_url,
# params={
# 'c_key': course.no,
# 'ACIXSTORE': acixstore,
# }
# )
# for course in course_list
# ]
#
# progress = progressbar.ProgressBar(maxval=len(course_list))
# for future, course in progress(zip_longest(course_futures,
# course_list)):
# response = future.result()
# response.encoding = 'cp950'
# save_syllabus(response.text, course, ys)
#
# print('Total course information: %d' % Course.objects.filter(ys=ys).count()) # noqa
#
# def crawl_dept(acixstore, auth_num, dept_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# future_depts = [
# dept_2_future(session, dept_code, acixstore, auth_num, ys)
# for dept_code in dept_codes
# ]
#
# progress = progressbar.ProgressBar()
# with transaction.atomic():
# for future in progress(future_depts):
# response = future.result()
# response.encoding = encoding
# handle_dept_html(response.text, ys)
#
# print('Total department information: %d' % Department.objects.filter(ys=ys).count()) # noqa
#
# Path: crawler/course.py
# def get_cou_codes():
# html = get(form_url).text
# document = lxml.html.fromstring(html)
# return document.xpath('//select[@name="cou_code"]/option/@value')
#
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class Department(models.Model):
# dept_name = models.CharField(max_length=20, blank=True)
# required_course = models.ManyToManyField(Course, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# def __str__(self):
# return self.dept_name
#
# Path: utils/config.py
# def get_config(section, option, filename='nthu_course.cfg'):
# '''Return a config in that section'''
# try:
# config = configparser.ConfigParser()
# config.optionxform = str
# config.read(settings.BASE_DIR + '/NTHU_Course/config/' + filename)
# return config.get(section, option)
# except Exception as ex:
# # no config found
# return None
, which may include functions, classes, or code. Output only the next line. | cou_codes = get_cou_codes() |
Given snippet: <|code_start|> return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
for ys in [get_config('crawler', 'semester')]:
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.9/JH629001.php'
)
print('Crawling course for ' + ys)
crawl_course(ACIXSTORE, auth_num, cou_codes, ys)
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.3/JH623001.php'
)
print('Crawling dept for ' + ys)
crawl_dept(ACIXSTORE, auth_num, cou_codes, ys)
print('===============================\n')
elapsed_time = time.time() - start_time
print('Total %.3f second used.' % elapsed_time)
if len(args) == 1:
if args[0] == 'clear':
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
from crawler.course import get_cou_codes
from crawler.decaptcha import Entrance, DecaptchaFailure
from data_center.models import Course, Department
from utils.config import get_config
import time
and context:
# Path: crawler/crawler.py
# def crawl_course(acixstore, auth_num, cou_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# curriculum_futures = [
# cou_code_2_future(session, cou_code, acixstore, auth_num, ys)
# for cou_code in cou_codes
# ]
#
# progress = progressbar.ProgressBar(maxval=len(cou_codes))
# with transaction.atomic():
# for future, cou_code in progress(zip(curriculum_futures,
# cou_codes)):
# response = future.result()
# response.encoding = 'cp950'
# handle_curriculum_html(response.text, cou_code)
#
# print('Crawling syllabus...')
# course_list = list(Course.objects.all())
#
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# course_futures = [
# session.get(
# syllabus_url,
# params={
# 'c_key': course.no,
# 'ACIXSTORE': acixstore,
# }
# )
# for course in course_list
# ]
#
# progress = progressbar.ProgressBar(maxval=len(course_list))
# for future, course in progress(zip_longest(course_futures,
# course_list)):
# response = future.result()
# response.encoding = 'cp950'
# save_syllabus(response.text, course, ys)
#
# print('Total course information: %d' % Course.objects.filter(ys=ys).count()) # noqa
#
# def crawl_dept(acixstore, auth_num, dept_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# future_depts = [
# dept_2_future(session, dept_code, acixstore, auth_num, ys)
# for dept_code in dept_codes
# ]
#
# progress = progressbar.ProgressBar()
# with transaction.atomic():
# for future in progress(future_depts):
# response = future.result()
# response.encoding = encoding
# handle_dept_html(response.text, ys)
#
# print('Total department information: %d' % Department.objects.filter(ys=ys).count()) # noqa
#
# Path: crawler/course.py
# def get_cou_codes():
# html = get(form_url).text
# document = lxml.html.fromstring(html)
# return document.xpath('//select[@name="cou_code"]/option/@value')
#
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class Department(models.Model):
# dept_name = models.CharField(max_length=20, blank=True)
# required_course = models.ManyToManyField(Course, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# def __str__(self):
# return self.dept_name
#
# Path: utils/config.py
# def get_config(section, option, filename='nthu_course.cfg'):
# '''Return a config in that section'''
# try:
# config = configparser.ConfigParser()
# config.optionxform = str
# config.read(settings.BASE_DIR + '/NTHU_Course/config/' + filename)
# return config.get(section, option)
# except Exception as ex:
# # no config found
# return None
which might include code, classes, or functions. Output only the next line. | Course.objects.all().delete() |
Here is a snippet: <|code_start|>
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
for ys in [get_config('crawler', 'semester')]:
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.9/JH629001.php'
)
print('Crawling course for ' + ys)
crawl_course(ACIXSTORE, auth_num, cou_codes, ys)
ACIXSTORE, auth_num = get_auth_pair(
'https://www.ccxp.nthu.edu.tw/ccxp/INQUIRE'
'/JH/6/6.2/6.2.3/JH623001.php'
)
print('Crawling dept for ' + ys)
crawl_dept(ACIXSTORE, auth_num, cou_codes, ys)
print('===============================\n')
elapsed_time = time.time() - start_time
print('Total %.3f second used.' % elapsed_time)
if len(args) == 1:
if args[0] == 'clear':
Course.objects.all().delete()
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
from crawler.course import get_cou_codes
from crawler.decaptcha import Entrance, DecaptchaFailure
from data_center.models import Course, Department
from utils.config import get_config
import time
and context from other files:
# Path: crawler/crawler.py
# def crawl_course(acixstore, auth_num, cou_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# curriculum_futures = [
# cou_code_2_future(session, cou_code, acixstore, auth_num, ys)
# for cou_code in cou_codes
# ]
#
# progress = progressbar.ProgressBar(maxval=len(cou_codes))
# with transaction.atomic():
# for future, cou_code in progress(zip(curriculum_futures,
# cou_codes)):
# response = future.result()
# response.encoding = 'cp950'
# handle_curriculum_html(response.text, cou_code)
#
# print('Crawling syllabus...')
# course_list = list(Course.objects.all())
#
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# course_futures = [
# session.get(
# syllabus_url,
# params={
# 'c_key': course.no,
# 'ACIXSTORE': acixstore,
# }
# )
# for course in course_list
# ]
#
# progress = progressbar.ProgressBar(maxval=len(course_list))
# for future, course in progress(zip_longest(course_futures,
# course_list)):
# response = future.result()
# response.encoding = 'cp950'
# save_syllabus(response.text, course, ys)
#
# print('Total course information: %d' % Course.objects.filter(ys=ys).count()) # noqa
#
# def crawl_dept(acixstore, auth_num, dept_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# future_depts = [
# dept_2_future(session, dept_code, acixstore, auth_num, ys)
# for dept_code in dept_codes
# ]
#
# progress = progressbar.ProgressBar()
# with transaction.atomic():
# for future in progress(future_depts):
# response = future.result()
# response.encoding = encoding
# handle_dept_html(response.text, ys)
#
# print('Total department information: %d' % Department.objects.filter(ys=ys).count()) # noqa
#
# Path: crawler/course.py
# def get_cou_codes():
# html = get(form_url).text
# document = lxml.html.fromstring(html)
# return document.xpath('//select[@name="cou_code"]/option/@value')
#
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class Department(models.Model):
# dept_name = models.CharField(max_length=20, blank=True)
# required_course = models.ManyToManyField(Course, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# def __str__(self):
# return self.dept_name
#
# Path: utils/config.py
# def get_config(section, option, filename='nthu_course.cfg'):
# '''Return a config in that section'''
# try:
# config = configparser.ConfigParser()
# config.optionxform = str
# config.read(settings.BASE_DIR + '/NTHU_Course/config/' + filename)
# return config.get(section, option)
# except Exception as ex:
# # no config found
# return None
, which may include functions, classes, or code. Output only the next line. | Department.objects.all().delete() |
Here is a snippet: <|code_start|>
try:
except ImportError:
Entrance = None
def get_auth_pair(url):
if Entrance is not None:
try:
return Entrance(url).get_ticket()
except DecaptchaFailure:
print('Automated decaptcha failed.')
else:
print('crawler.decaptcha not available (requires tesseract >= 3.03).')
print('Please provide valid ACIXSTORE and auth_num from')
print(url)
ACIXSTORE = input('ACIXSTORE: ')
auth_num = input('auth_num: ')
return ACIXSTORE, auth_num
class Command(BaseCommand):
args = ''
help = 'Help crawl the course data from NTHU.'
def handle(self, *args, **kwargs):
if len(args) == 0:
start_time = time.time()
cou_codes = get_cou_codes()
<|code_end|>
. Write the next line using the current file imports:
from django.core.management.base import BaseCommand
from crawler.crawler import crawl_course, crawl_dept
from crawler.course import get_cou_codes
from crawler.decaptcha import Entrance, DecaptchaFailure
from data_center.models import Course, Department
from utils.config import get_config
import time
and context from other files:
# Path: crawler/crawler.py
# def crawl_course(acixstore, auth_num, cou_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# curriculum_futures = [
# cou_code_2_future(session, cou_code, acixstore, auth_num, ys)
# for cou_code in cou_codes
# ]
#
# progress = progressbar.ProgressBar(maxval=len(cou_codes))
# with transaction.atomic():
# for future, cou_code in progress(zip(curriculum_futures,
# cou_codes)):
# response = future.result()
# response.encoding = 'cp950'
# handle_curriculum_html(response.text, cou_code)
#
# print('Crawling syllabus...')
# course_list = list(Course.objects.all())
#
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# course_futures = [
# session.get(
# syllabus_url,
# params={
# 'c_key': course.no,
# 'ACIXSTORE': acixstore,
# }
# )
# for course in course_list
# ]
#
# progress = progressbar.ProgressBar(maxval=len(course_list))
# for future, course in progress(zip_longest(course_futures,
# course_list)):
# response = future.result()
# response.encoding = 'cp950'
# save_syllabus(response.text, course, ys)
#
# print('Total course information: %d' % Course.objects.filter(ys=ys).count()) # noqa
#
# def crawl_dept(acixstore, auth_num, dept_codes, ys):
# with FuturesSession(max_workers=MAX_WORKERS) as session:
# future_depts = [
# dept_2_future(session, dept_code, acixstore, auth_num, ys)
# for dept_code in dept_codes
# ]
#
# progress = progressbar.ProgressBar()
# with transaction.atomic():
# for future in progress(future_depts):
# response = future.result()
# response.encoding = encoding
# handle_dept_html(response.text, ys)
#
# print('Total department information: %d' % Department.objects.filter(ys=ys).count()) # noqa
#
# Path: crawler/course.py
# def get_cou_codes():
# html = get(form_url).text
# document = lxml.html.fromstring(html)
# return document.xpath('//select[@name="cou_code"]/option/@value')
#
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
#
# class Department(models.Model):
# dept_name = models.CharField(max_length=20, blank=True)
# required_course = models.ManyToManyField(Course, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# def __str__(self):
# return self.dept_name
#
# Path: utils/config.py
# def get_config(section, option, filename='nthu_course.cfg'):
# '''Return a config in that section'''
# try:
# config = configparser.ConfigParser()
# config.optionxform = str
# config.read(settings.BASE_DIR + '/NTHU_Course/config/' + filename)
# return config.get(section, option)
# except Exception as ex:
# # no config found
# return None
, which may include functions, classes, or code. Output only the next line. | for ys in [get_config('crawler', 'semester')]: |
Based on the snippet: <|code_start|>
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^search/', include('search.urls')),
url(r'^', include('index.urls')),
url(r'^', include('table.urls')),
]
<|code_end|>
, predict the immediate next line with the help of imports:
from django.conf.urls import include, url
from django.contrib import admin
from utils.error_handler import error404
and context (classes, functions, sometimes code) from other files:
# Path: utils/error_handler.py
# def error404(request):
# return render(request, template_name='index/404.html')
. Output only the next line. | handler404 = error404 |
Predict the next line for this snippet: <|code_start|>
def prerequisite(request):
return render(
request,
'table/prerequisites.html',
<|code_end|>
with the help of current file imports:
from django.shortcuts import render
from data_center.models import FlatPrerequisite
and context from other files:
# Path: data_center/models.py
# class FlatPrerequisite(models.Model):
# '''
# store rendered prerequisite in the database
# alternative: django.contrib.flatpage
# '''
# updated_at = models.DateTimeField(auto_now=True)
# html = models.TextField()
#
# @classmethod
# def update_html(cls, html):
# if cls.objects.exists():
# ins = cls.objects.get()
# ins.html = html
# ins.save()
# return ins
# else:
# return cls.objects.create(html=html)
, which may contain function names, class names, or code. Output only the next line. | {'data': FlatPrerequisite.objects.get()} |
Continue the code snippet: <|code_start|>
urlpatterns = [
url(r'^$', search),
url(r'^syllabus/(?P<no>.+)/$',
<|code_end|>
. Use current file imports:
from django.conf.urls import url
from .views import search, syllabus, hit, autocomplete
and context (classes, functions, or code) from other files:
# Path: search/views.py
# def search(request):
# result = {}
# q = request.GET.get('q', '')
# q = ' '.join(group_words(q))
# page = request.GET.get('page', '')
# size = request.GET.get('size', '')
# code = request.GET.get('code', '')
# dept_required = request.GET.get('dept_required', '')
# sortby_param = request.GET.get('sort', '')
# reverse_param = request.GET.get('reverse', '')
# ys = request.GET.get('ys', SEMESTER)
#
# page_size = size or 10
# sortby = sortby_param or 'time_token'
# reverse = True if reverse_param == 'true' else False
# rev_sortby = '-' + sortby if reverse else sortby
#
# courses = SearchQuerySet().filter()
#
# if dept_required:
# try:
# courses = Department.objects.get(
# ys=ys, dept_name=dept_required).required_course.all()
# except:
# pass
# if courses:
# result['type'] = 'required'
# page_size = courses.count()
# else:
# courses = courses.filter(content=AutoQuery(q))
# if code:
# courses = courses.filter(code__contains=code)
#
# if code in ['GE', 'GEC']:
# core = request.GET.get(code.lower(), '')
# if core:
# courses = courses.filter(ge__contains=core)
# courses = courses.order_by(rev_sortby)
# paginator = Paginator(courses, page_size)
#
# try:
# courses_page = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# courses_page = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# courses_page = paginator.page(paginator.num_pages)
#
# course_list = [
# {k: v for (k, v) in x.__dict__.items() if not k.startswith('_')}
# for x in [
# x if dept_required else x.object for x in courses_page.object_list]
# ]
#
# result['total'] = courses.count()
# result['page'] = courses_page.number
# result['courses'] = course_list
# result['page_size'] = page_size
#
# return JsonResponse(result)
#
# @cache_page(60 * 60)
# def syllabus(request, no):
# course = get_object_or_404(Course, no=no)
# return render(request, 'search/syllabus.html',
# {'course': course, 'syllabus_path': request.path})
#
# def hit(request, no):
# course = get_object_or_404(Course, no=no)
# course.hit += 1
# course.save()
# return HttpResponse('')
#
# def autocomplete(request):
# q = request.GET.get('term', '')
# q = ' '.join(group_words(q))
# code = request.GET.get('code', '')
# result = []
# courses = SearchQuerySet().filter(content=AutoQuery(q))
#
# if code:
# courses = courses.filter(code__contains=code)
# if code in ['GE', 'GEC']:
# core = request.GET.get(code.lower(), '')
# if core:
# courses = courses.filter(ge__contains=core)
# if courses.count() < 100:
# course_list = [x.chi_title for x in courses]
# result = [{'value': c} for c in set(course_list)]
#
# return JsonResponse(result, safe=False)
. Output only the next line. | syllabus, name='syllabus'), |
Given snippet: <|code_start|>
urlpatterns = [
url(r'^$', search),
url(r'^syllabus/(?P<no>.+)/$',
syllabus, name='syllabus'),
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from django.conf.urls import url
from .views import search, syllabus, hit, autocomplete
and context:
# Path: search/views.py
# def search(request):
# result = {}
# q = request.GET.get('q', '')
# q = ' '.join(group_words(q))
# page = request.GET.get('page', '')
# size = request.GET.get('size', '')
# code = request.GET.get('code', '')
# dept_required = request.GET.get('dept_required', '')
# sortby_param = request.GET.get('sort', '')
# reverse_param = request.GET.get('reverse', '')
# ys = request.GET.get('ys', SEMESTER)
#
# page_size = size or 10
# sortby = sortby_param or 'time_token'
# reverse = True if reverse_param == 'true' else False
# rev_sortby = '-' + sortby if reverse else sortby
#
# courses = SearchQuerySet().filter()
#
# if dept_required:
# try:
# courses = Department.objects.get(
# ys=ys, dept_name=dept_required).required_course.all()
# except:
# pass
# if courses:
# result['type'] = 'required'
# page_size = courses.count()
# else:
# courses = courses.filter(content=AutoQuery(q))
# if code:
# courses = courses.filter(code__contains=code)
#
# if code in ['GE', 'GEC']:
# core = request.GET.get(code.lower(), '')
# if core:
# courses = courses.filter(ge__contains=core)
# courses = courses.order_by(rev_sortby)
# paginator = Paginator(courses, page_size)
#
# try:
# courses_page = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# courses_page = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# courses_page = paginator.page(paginator.num_pages)
#
# course_list = [
# {k: v for (k, v) in x.__dict__.items() if not k.startswith('_')}
# for x in [
# x if dept_required else x.object for x in courses_page.object_list]
# ]
#
# result['total'] = courses.count()
# result['page'] = courses_page.number
# result['courses'] = course_list
# result['page_size'] = page_size
#
# return JsonResponse(result)
#
# @cache_page(60 * 60)
# def syllabus(request, no):
# course = get_object_or_404(Course, no=no)
# return render(request, 'search/syllabus.html',
# {'course': course, 'syllabus_path': request.path})
#
# def hit(request, no):
# course = get_object_or_404(Course, no=no)
# course.hit += 1
# course.save()
# return HttpResponse('')
#
# def autocomplete(request):
# q = request.GET.get('term', '')
# q = ' '.join(group_words(q))
# code = request.GET.get('code', '')
# result = []
# courses = SearchQuerySet().filter(content=AutoQuery(q))
#
# if code:
# courses = courses.filter(code__contains=code)
# if code in ['GE', 'GEC']:
# core = request.GET.get(code.lower(), '')
# if core:
# courses = courses.filter(ge__contains=core)
# if courses.count() < 100:
# course_list = [x.chi_title for x in courses]
# result = [{'value': c} for c in set(course_list)]
#
# return JsonResponse(result, safe=False)
which might include code, classes, or functions. Output only the next line. | url(r'^hit/(?P<no>.+)/$', hit, name='hit'), |
Given the following code snippet before the placeholder: <|code_start|>
urlpatterns = [
url(r'^$', search),
url(r'^syllabus/(?P<no>.+)/$',
syllabus, name='syllabus'),
url(r'^hit/(?P<no>.+)/$', hit, name='hit'),
<|code_end|>
, predict the next line using imports from the current file:
from django.conf.urls import url
from .views import search, syllabus, hit, autocomplete
and context including class names, function names, and sometimes code from other files:
# Path: search/views.py
# def search(request):
# result = {}
# q = request.GET.get('q', '')
# q = ' '.join(group_words(q))
# page = request.GET.get('page', '')
# size = request.GET.get('size', '')
# code = request.GET.get('code', '')
# dept_required = request.GET.get('dept_required', '')
# sortby_param = request.GET.get('sort', '')
# reverse_param = request.GET.get('reverse', '')
# ys = request.GET.get('ys', SEMESTER)
#
# page_size = size or 10
# sortby = sortby_param or 'time_token'
# reverse = True if reverse_param == 'true' else False
# rev_sortby = '-' + sortby if reverse else sortby
#
# courses = SearchQuerySet().filter()
#
# if dept_required:
# try:
# courses = Department.objects.get(
# ys=ys, dept_name=dept_required).required_course.all()
# except:
# pass
# if courses:
# result['type'] = 'required'
# page_size = courses.count()
# else:
# courses = courses.filter(content=AutoQuery(q))
# if code:
# courses = courses.filter(code__contains=code)
#
# if code in ['GE', 'GEC']:
# core = request.GET.get(code.lower(), '')
# if core:
# courses = courses.filter(ge__contains=core)
# courses = courses.order_by(rev_sortby)
# paginator = Paginator(courses, page_size)
#
# try:
# courses_page = paginator.page(page)
# except PageNotAnInteger:
# # If page is not an integer, deliver first page.
# courses_page = paginator.page(1)
# except EmptyPage:
# # If page is out of range (e.g. 9999), deliver last page of results.
# courses_page = paginator.page(paginator.num_pages)
#
# course_list = [
# {k: v for (k, v) in x.__dict__.items() if not k.startswith('_')}
# for x in [
# x if dept_required else x.object for x in courses_page.object_list]
# ]
#
# result['total'] = courses.count()
# result['page'] = courses_page.number
# result['courses'] = course_list
# result['page_size'] = page_size
#
# return JsonResponse(result)
#
# @cache_page(60 * 60)
# def syllabus(request, no):
# course = get_object_or_404(Course, no=no)
# return render(request, 'search/syllabus.html',
# {'course': course, 'syllabus_path': request.path})
#
# def hit(request, no):
# course = get_object_or_404(Course, no=no)
# course.hit += 1
# course.save()
# return HttpResponse('')
#
# def autocomplete(request):
# q = request.GET.get('term', '')
# q = ' '.join(group_words(q))
# code = request.GET.get('code', '')
# result = []
# courses = SearchQuerySet().filter(content=AutoQuery(q))
#
# if code:
# courses = courses.filter(code__contains=code)
# if code in ['GE', 'GEC']:
# core = request.GET.get(code.lower(), '')
# if core:
# courses = courses.filter(ge__contains=core)
# if courses.count() < 100:
# course_list = [x.chi_title for x in courses]
# result = [{'value': c} for c in set(course_list)]
#
# return JsonResponse(result, safe=False)
. Output only the next line. | url(r'^autocomplete/$', autocomplete, name='autocomplete'), |
Continue the code snippet: <|code_start|>
class CourseIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.NgramField(document=True, use_template=True)
no = indexes.CharField(model_attr='no')
code = indexes.CharField(model_attr='code')
eng_title = indexes.CharField(model_attr='eng_title')
chi_title = indexes.CharField(model_attr='chi_title')
note = indexes.CharField(model_attr='note')
objective = indexes.CharField(model_attr='objective')
time = indexes.CharField(model_attr='time')
time_token = indexes.CharField(model_attr='time_token')
teacher = indexes.CharField(model_attr='teacher')
room = indexes.CharField(model_attr='room')
ge = indexes.CharField(model_attr='ge')
credit = indexes.IntegerField(model_attr='credit')
limit = indexes.IntegerField(model_attr='limit')
prerequisite = indexes.BooleanField(model_attr='prerequisite')
ys = indexes.CharField(model_attr='ys')
hit = indexes.IntegerField(model_attr='hit')
syllabus = indexes.CharField(model_attr='syllabus')
def get_model(self):
<|code_end|>
. Use current file imports:
from data_center.models import Course
from haystack import indexes
and context (classes, functions, or code) from other files:
# Path: data_center/models.py
# class Course(models.Model):
# """Course database schema"""
# no = models.CharField(max_length=20, unique=True, db_index=True)
# code = models.CharField(max_length=20, blank=True)
# eng_title = models.CharField(max_length=200, blank=True)
# chi_title = models.CharField(max_length=200, blank=True)
# note = models.TextField(blank=True)
# objective = models.CharField(max_length=80, blank=True)
# time = models.CharField(max_length=20, blank=True)
# time_token = models.CharField(max_length=20, blank=True)
# teacher = models.CharField(max_length=40, blank=True) # Only save Chinese
# room = models.CharField(max_length=80, blank=True)
# credit = models.IntegerField(default=0)
# limit = models.IntegerField(default=0)
# prerequisite = models.BooleanField(default=False, blank=True)
# ys = models.CharField(max_length=10, blank=True)
#
# ge = models.CharField(max_length=80, blank=True)
#
# hit = models.IntegerField(default=0)
#
# syllabus = models.TextField(blank=True) # pure text
# has_attachment = models.BooleanField(default=False) # has pdf
#
# def __str__(self):
# return self.no
#
# @property
# def attachment_url(self):
# return attachment_url_format % urlquote(self.no)
. Output only the next line. | return Course |
Next line prediction: <|code_start|># Name: mapper_occci_online.py
# Purpose: Nansat mapping for OC CCI data, stored online in THREDDS
# Author: Anton Korosov
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# http://www.gnu.org/licenses/gpl-3.0.html
#http://thredds.met.no/thredds/dodsC/myocean/siw-tac/sst-metno-arc-sst03/20121001000000-METNO-L4_GHRSST-SSTfnd-METNO_OI-ARC-v02.0-fv01.0.nc
#http://thredds.met.no/thredds/dodsC/myocean/siw-tac/sst-metno-arc-sst03_V1/20120808-METNO-L4UHfnd-ARC-v01-fv01-METNO_OI.nc
#http://thredds.met.no/thredds/dodsC/sea_ice/SST-METNO-ARC-SST_L4-OBS-V2-V1/sst_arctic_aggregated
class Mapper(Opendap):
"""VRT with mapping of WKV for NCEP GFS"""
baseURLs = ['http://thredds.met.no/thredds/dodsC/myocean/siw-tac/sst-metno-arc-sst03/',
'http://thredds.met.no/thredds/dodsC/myocean/siw-tac/sst-metno-arc-sst03_V1/',
'http://thredds.met.no/thredds/dodsC/sea_ice/SST-METNO-ARC-SST_L4-OBS-V2-V1/']
timeVarName = 'time'
xName = 'lon'
yName = 'lat'
t0 = dt.datetime(1981, 1, 1)
<|code_end|>
. Use current file imports:
(import os
import json
import datetime as dt
import numpy as np
import pythesint as pti
from nansat.nsr import NSR
from nansat.mappers.opendap import Dataset, Opendap)
and context including class names, function names, or small code snippets from other files:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/mappers/opendap.py
# class Opendap(VRT):
# P2S = {
# 'H': 60*60,
# 'D': 86400,
# 'M': 30*24*60*60,
# 'Y': 31536000,
# }
# def test_mapper(self, filename):
# def get_dataset(self, ds):
# def get_geospatial_variable_names(self):
# def get_dataset_time(self):
# def get_layer_datetime(date, datetimes):
# def get_metaitem(self, url, var_name, var_dimensions):
# def _fix_encoding(var):
# def create_vrt(self, filename, gdalDataset, gdalMetadata, date, ds, bands, cachedir):
# def _filter_dimensions(self, dim_name):
# def create_metadict(self, filename, var_names, time_id):
# def get_time_coverage_resolution(self):
# def get_shape(self):
# def get_geotransform(self):
. Output only the next line. | srcDSProjection = NSR().wkt |
Using the snippet: <|code_start|> 'sourceBand': 1,
'ScaleRatio': subScaleRatio,
'ScaleOffset': subScaleOffset},
'dst': {'wkv': subWKV}}
# append band metadata to metaDict
metaDict.append(metaEntry)
# create empty VRT dataset with geolocation only
self._init_from_gdal_dataset(subGDALDataset)
# add mask
if qualName != '':
qualDataset = vrt.gdal.Open(qualName)
qualArray = qualDataset.ReadAsArray()
qualArray[qualArray < minQual] = 1
qualArray[qualArray >= minQual] = 128
self.band_vrts = {'maskVRT': vrt.VRT(array=qualArray.astype('int8'))}
metaDict.append({'src': {'SourceFilename': (self.
band_vrts['maskVRT'].
filename),
'SourceBand': 1,
'SourceType': 'SimpleSource',
'DataType': 1},
'dst': {'name': 'mask'}})
# add bands with metadata and corresponding values to the empty VRT
self.create_bands(metaDict)
# append fixed projection and geotransform
<|code_end|>
, determine the next line of code. You have imports:
from dateutil.parser import parse
from nansat.nsr import NSR
from nansat.exceptions import WrongMapperError
import numpy as np
import nansat.vrt as vrt
and context (class names, function names, or code) available:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/exceptions.py
# class WrongMapperError(Exception):
# """ Error for handling data that does not fit a given mapper """
# pass
. Output only the next line. | self.dataset.SetProjection(NSR().wkt) |
Here is a snippet: <|code_start|># Name: mapper_pathfinder52
# Purpose: Mapping for NOAA AVHRR PATHFINDER52 DATA
# Authors: Anton Korosov, Dmitry Petrenko
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# http://www.gnu.org/licenses/gpl-3.0.html
class Mapper(vrt.VRT):
''' Mapper PATHFINDER (local files)
TODO:
* remote files
'''
def __init__(self, filename, gdalDataset, gdalMetadata, minQual=4,
**kwargs):
''' Create VRT '''
if not 'AVHRR_Pathfinder-PFV5.2' in filename:
<|code_end|>
. Write the next line using the current file imports:
from dateutil.parser import parse
from nansat.nsr import NSR
from nansat.exceptions import WrongMapperError
import numpy as np
import nansat.vrt as vrt
and context from other files:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/exceptions.py
# class WrongMapperError(Exception):
# """ Error for handling data that does not fit a given mapper """
# pass
, which may include functions, classes, or code. Output only the next line. | raise WrongMapperError(filename) |
Based on the snippet: <|code_start|># ------------------------------------------------------------------------------
# Name: nansat_test_base.py
# Purpose: Basic class for Nansat tests
#
# Author: Anton Korosov
#
# Created: 20.03.2018
# Copyright: (c) NERSC
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# http://www.gnu.org/licenses/gpl-3.0.html
# ------------------------------------------------------------------------------
from __future__ import print_function, absolute_import, division
class NansatTestBase(unittest.TestCase):
def setUp(self):
<|code_end|>
, predict the immediate next line with the help of imports:
import os
import sys
import unittest
import tempfile
import pythesint
from mock import patch, PropertyMock, Mock, MagicMock, DEFAULT
from nansat.tests import nansat_test_data as ntd
and context (classes, functions, sometimes code) from other files:
# Path: nansat/tests/nansat_test_data.py
. Output only the next line. | self.test_file_gcps = os.path.join(ntd.test_data_path, 'gcps.tif') |
Here is a snippet: <|code_start|># Name: mapper_occci_online.py
# Purpose: Nansat mapping for OC CCI data, stored online in THREDDS
# Author: Anton Korosov
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# http://www.gnu.org/licenses/gpl-3.0.html
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/conc/2016/04/ice_conc_sh_polstere-100_multi_201604261200.nc ice_conc
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/drift_lr/merged/2016/04/ice_drift_nh_polstere-625_multi-oi_201604151200-201604171200.nc dX dY
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/type/2016/04/ice_type_nh_polstere-100_multi_201604151200.nc ice_type
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/edge/2016/04/ice_edge_nh_polstere-100_multi_201604241200.nc ice_edge
# http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/drift_lr/merged/2013/09/ice_drift_nh_polstere-625_multi-oi_201309171200-201309191200.nc dX dY
class Mapper(Opendap):
''' VRT with mapping of WKV for NCEP GFS '''
baseURLs = ['http://thredds.met.no/thredds/dodsC/cryoclim/met.no/osisaf-nh',
'http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/',
'http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/']
timeVarName = 'time'
xName = 'xc'
yName = 'yc'
t0 = dt.datetime(1978, 1, 1)
<|code_end|>
. Write the next line using the current file imports:
import os
import json
import numpy as np
import datetime as dt
import pythesint as pti
from nansat.nsr import NSR
from nansat.mappers.opendap import Dataset, Opendap
and context from other files:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/mappers/opendap.py
# class Opendap(VRT):
# P2S = {
# 'H': 60*60,
# 'D': 86400,
# 'M': 30*24*60*60,
# 'Y': 31536000,
# }
# def test_mapper(self, filename):
# def get_dataset(self, ds):
# def get_geospatial_variable_names(self):
# def get_dataset_time(self):
# def get_layer_datetime(date, datetimes):
# def get_metaitem(self, url, var_name, var_dimensions):
# def _fix_encoding(var):
# def create_vrt(self, filename, gdalDataset, gdalMetadata, date, ds, bands, cachedir):
# def _filter_dimensions(self, dim_name):
# def create_metadict(self, filename, var_names, time_id):
# def get_time_coverage_resolution(self):
# def get_shape(self):
# def get_geotransform(self):
, which may include functions, classes, or code. Output only the next line. | srcDSProjection = NSR().wkt |
Here is a snippet: <|code_start|># http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/conc/2016/04/ice_conc_sh_polstere-100_multi_201604261200.nc ice_conc
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/drift_lr/merged/2016/04/ice_drift_nh_polstere-625_multi-oi_201604151200-201604171200.nc dX dY
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/type/2016/04/ice_type_nh_polstere-100_multi_201604151200.nc ice_type
# http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/edge/2016/04/ice_edge_nh_polstere-100_multi_201604241200.nc ice_edge
# http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/drift_lr/merged/2013/09/ice_drift_nh_polstere-625_multi-oi_201309171200-201309191200.nc dX dY
class Mapper(Opendap):
''' VRT with mapping of WKV for NCEP GFS '''
baseURLs = ['http://thredds.met.no/thredds/dodsC/cryoclim/met.no/osisaf-nh',
'http://thredds.met.no/thredds/dodsC/osisaf_test/met.no/ice/',
'http://thredds.met.no/thredds/dodsC/osisaf/met.no/ice/']
timeVarName = 'time'
xName = 'xc'
yName = 'yc'
t0 = dt.datetime(1978, 1, 1)
srcDSProjection = NSR().wkt
def __init__(self, filename, gdalDataset, gdalMetadata, date=None, ds=None, bands=None,
cachedir=None, **kwargs):
''' Create NCEP VRT
Parameters:
filename : URL
date : str
2010-05-01
ds : netCDF.Dataset
previously opened dataset
'''
self.test_mapper(filename)
<|code_end|>
. Write the next line using the current file imports:
import os
import json
import numpy as np
import datetime as dt
import pythesint as pti
from nansat.nsr import NSR
from nansat.mappers.opendap import Dataset, Opendap
and context from other files:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/mappers/opendap.py
# class Opendap(VRT):
# P2S = {
# 'H': 60*60,
# 'D': 86400,
# 'M': 30*24*60*60,
# 'Y': 31536000,
# }
# def test_mapper(self, filename):
# def get_dataset(self, ds):
# def get_geospatial_variable_names(self):
# def get_dataset_time(self):
# def get_layer_datetime(date, datetimes):
# def get_metaitem(self, url, var_name, var_dimensions):
# def _fix_encoding(var):
# def create_vrt(self, filename, gdalDataset, gdalMetadata, date, ds, bands, cachedir):
# def _filter_dimensions(self, dim_name):
# def create_metadict(self, filename, var_names, time_id):
# def get_time_coverage_resolution(self):
# def get_shape(self):
# def get_geotransform(self):
, which may include functions, classes, or code. Output only the next line. | ds = Dataset(filename) |
Here is a snippet: <|code_start|> AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
AUTHORITY["EPSG","8901"]],
UNIT["degree",0.0174532925199433,
AUTHORITY["EPSG","9108"]],
AUTHORITY["EPSG","4326"]]'
"""
def __init__(self, srs=0):
"""Create Spatial Reference System from input parameter"""
if sys.version_info.major == 2:
str_types = (str, unicode)
else:
str_types = str
# create SRS
osr.SpatialReference.__init__(self)
# parse input parameters
status = 1
if srs is 0:
# generate default WGS84 SRS
status = self.ImportFromEPSG(4326)
elif isinstance(srs, str_types):
# parse as proj4 string
status = self.ImportFromProj4(str(srs))
if status > 0:
# parse as WKT string
status = self.ImportFromWkt(str(srs))
if status > 0:
<|code_end|>
. Write the next line using the current file imports:
import sys
from nansat.utils import osr
from nansat.exceptions import NansatProjectionError
and context from other files:
# Path: nansat/utils.py
# MATPLOTLIB_IS_INSTALLED = False
# MATPLOTLIB_IS_INSTALLED = True
# NUMPY_TO_GDAL_TYPE_MAP = {
# 'uint8': 1,
# 'int8': 1,
# 'uint16': 2,
# 'int16': 3,
# 'uint32': 4,
# 'int32': 5,
# 'float32': 6,
# 'float64': 7,
# 'complex64': 10,
# 'complex128': 11
# }
# def remove_keys(dict, keys):
# def register_colormaps():
# def initial_bearing(lon1, lat1, lon2, lat2):
# def haversine(lon1, lat1, lon2, lat2):
# def add_logger(logName='', logLevel=None):
# def get_random_color(c0=None, minDist=100, low=0, high=255):
# def parse_time(time_string):
#
# Path: nansat/exceptions.py
# class NansatProjectionError(Exception):
# """ Cannot get the projection """
# pass
, which may include functions, classes, or code. Output only the next line. | raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs) |
Given snippet: <|code_start|> palette = None
pilImg = None
pilImgLegend = None
extensionList = ['png', 'PNG', 'tif', 'TIF', 'bmp',
'BMP', 'jpg', 'JPG', 'jpeg', 'JPEG']
_cmapName = 'jet'
# instance attributes
array = None
def __init__(self, nparray, **kwargs):
""" Set attributes
See class Figure(object) for information about:
Modifies
--------
Parameters
----------
Advanced parameters
--------------------
"""
# make a copy of nparray (otherwise a new reference to the same data is
# created and the original input data is destroyed at process())
array = np.array(nparray)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import os
import numpy as np
import matplotlib; matplotlib.use('Agg')
import Image
import ImageDraw
import ImageFont
from math import floor, log10
from matplotlib import cm
from PIL import Image, ImageDraw, ImageFont
from nansat.utils import add_logger
and context:
# Path: nansat/utils.py
# def add_logger(logName='', logLevel=None):
# """ Creates and returns logger with default formatting for Nansat
#
# Parameters
# -----------
# logName : string, optional
# Name of the logger
#
# Returns
# --------
# logging.logger
#
# See also
# --------
# `<http://docs.python.org/howto/logging.html>`_
#
# """
# if logLevel is not None:
# os.environ['LOG_LEVEL'] = str(logLevel)
# # create (or take already existing) logger
# # with default logging level WARNING
# logger = logging.getLogger(logName)
# logger.setLevel(int(os.environ['LOG_LEVEL']))
#
# # if logger already exits, default stream handler has been already added
# # otherwise create and add a new handler
# if len(logger.handlers) == 0:
# # create console handler and set level to debug
# ch = logging.StreamHandler()
# # create formatter
# formatter = logging.Formatter('%(asctime)s|%(levelno)s|%(module)s|'
# '%(funcName)s|%(message)s',
# datefmt='%I:%M:%S')
# # add formatter to ch
# ch.setFormatter(formatter)
# # add ch to logger
# logger.addHandler(ch)
#
# logger.handlers[0].setLevel(int(os.environ['LOG_LEVEL']))
#
# return logger
which might include code, classes, or functions. Output only the next line. | self.logger = add_logger('Nansat') |
Predict the next line for this snippet: <|code_start|> dataset : gdal.Dataset
input dataset to copy Geolocation metadata from
"""
self = cls.__new__(cls) # empty object
self.x_vrt = None
self.y_vrt = None
self.data = dataset.GetMetadata('GEOLOCATION')
return self
@classmethod
def from_filenames(cls, x_filename, y_filename, **kwargs):
"""Create geolocation from names of files with geolocation
Parameters
----------
x_filename : str
name of file for X-dataset
y_filename : str
name of file for Y-dataset
**kwargs : dict
parameters for self._init_data()
"""
self = cls.__new__(cls) # empty object
self.x_vrt = None
self.y_vrt = None
self.data = {}
self._init_data(x_filename, y_filename, **kwargs)
return self
def get_geolocation_grids(self):
"""Read values of geolocation grids"""
<|code_end|>
with the help of current file imports:
from nansat.utils import gdal, osr
from nansat.nsr import NSR
and context from other files:
# Path: nansat/utils.py
# MATPLOTLIB_IS_INSTALLED = False
# MATPLOTLIB_IS_INSTALLED = True
# NUMPY_TO_GDAL_TYPE_MAP = {
# 'uint8': 1,
# 'int8': 1,
# 'uint16': 2,
# 'int16': 3,
# 'uint32': 4,
# 'int32': 5,
# 'float32': 6,
# 'float64': 7,
# 'complex64': 10,
# 'complex128': 11
# }
# def remove_keys(dict, keys):
# def register_colormaps():
# def initial_bearing(lon1, lat1, lon2, lat2):
# def haversine(lon1, lat1, lon2, lat2):
# def add_logger(logName='', logLevel=None):
# def get_random_color(c0=None, minDist=100, low=0, high=255):
# def parse_time(time_string):
#
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
, which may contain function names, class names, or code. Output only the next line. | lon_dataset = gdal.Open(self.data['X_DATASET']) |
Here is a snippet: <|code_start|> line_offset=0, line_step=1,
pixel_offset=0, pixel_step=1):
"""Init data of Geolocation object from input parameters
Parameters
-----------
x_filename : str
name of file for X-dataset
y_filename : str
name of file for Y-dataset
x_band : int
number of the band in the X-dataset
y_band : int
number of the band in the Y-dataset
srs : str
WKT
line_offset : int
offset of first line
line_step : int
step of lines
pixel_offset : int
offset of first pixel
pixel_step : int
step of pixels
Notes
-----
Saves everything in self.data dict
"""
if srs is None:
<|code_end|>
. Write the next line using the current file imports:
from nansat.utils import gdal, osr
from nansat.nsr import NSR
and context from other files:
# Path: nansat/utils.py
# MATPLOTLIB_IS_INSTALLED = False
# MATPLOTLIB_IS_INSTALLED = True
# NUMPY_TO_GDAL_TYPE_MAP = {
# 'uint8': 1,
# 'int8': 1,
# 'uint16': 2,
# 'int16': 3,
# 'uint32': 4,
# 'int32': 5,
# 'float32': 6,
# 'float64': 7,
# 'complex64': 10,
# 'complex128': 11
# }
# def remove_keys(dict, keys):
# def register_colormaps():
# def initial_bearing(lon1, lat1, lon2, lat2):
# def haversine(lon1, lat1, lon2, lat2):
# def add_logger(logName='', logLevel=None):
# def get_random_color(c0=None, minDist=100, low=0, high=255):
# def parse_time(time_string):
#
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
, which may include functions, classes, or code. Output only the next line. | srs = NSR().wkt |
Predict the next line after this snippet: <|code_start|>
class MyWaveOpenDAPTests(unittest.TestCase):
def setUp(self):
self.src = 'http://thredds.met.no/thredds/dodsC/fou-hi/mywavewam4archive' \
'/2017/10/29/MyWave_wam4_WAVE_20171029T18Z.nc'
def test_get_date(self):
<|code_end|>
using the current file's imports:
import unittest
from nansat.mappers.mapper_opendap_mywave import Mapper
and any relevant context from other files:
# Path: nansat/mappers/mapper_opendap_mywave.py
# class Mapper(Opendap):
#
# baseURLs = ['http://thredds.met.no/thredds/dodsC/fou-hi/mywavewam4archive',
# 'https://thredds.met.no/thredds/dodsC/sea/mywavewam4/mywavewam4_be']
#
# timeVarName = 'time'
# xName = 'rlon'
# yName = 'rlat'
# timeCalendarStart = '1970-01-01'
#
# def __init__(self, filename, gdal_dataset, gdal_metadata, date=None,
# ds=None, bands=None, cachedir=None, *args, **kwargs):
#
# self.test_mapper(filename)
# timestamp = date if date else self.get_date(filename)
# ds = Dataset(filename)
# try:
# self.srcDSProjection = NSR(ds.variables['projection_3'].proj4 +
# ' +to_meter=0.0174532925199 +wktext')
# except KeyError:
# raise WrongMapperError
#
# self.create_vrt(filename, gdal_dataset, gdal_metadata, timestamp, ds, bands, cachedir)
#
# self.dataset.SetMetadataItem('instrument', json.dumps(pti.get_gcmd_instrument('Computer')))
# self.dataset.SetMetadataItem('platform', json.dumps(pti.get_gcmd_platform('MODELS')))
# self.dataset.SetMetadataItem('Data Center', json.dumps(pti.get_gcmd_provider('NO/MET')))
# self.dataset.SetMetadataItem('Entry Title', str(ds.getncattr('title')))
# self.dataset.SetMetadataItem('Entry Title',
# json.dumps(pti.get_iso19115_topic_category('Oceans')))
# self.dataset.SetMetadataItem('gcmd_location',
# json.dumps(pti.get_gcmd_location('sea surface')))
#
# @staticmethod
# def get_date(filename):
# """Extract date and time parameters from filename and return
# it as a formatted (isoformat) string
#
# Parameters
# ----------
#
# filename: str
#
# Returns
# -------
# str, YYYY-mm-ddThh:MM:00Z
#
# Examples
# --------
# >>> Mapper.get_date('/path/to/MyWave_wam4_WAVE_20171029T18Z.nc')
# '2017-10-29T18:00:00Z'
# """
# _, filename = os.path.split(filename)
# t = datetime.strptime(filename.split('_')[-1], '%Y%m%dT%HZ.nc')
# return datetime.strftime(t, '%Y-%m-%dT%H:%M:00Z')
#
# def convert_dstime_datetimes(self, ds_time):
# """Convert time variable to np.datetime64"""
# ds_datetimes = np.array(
# [(np.datetime64(self.timeCalendarStart).astype('M8[s]')
# + np.timedelta64(int(sec), 's').astype('m8[s]')) for sec in ds_time]).astype('M8[s]')
# return ds_datetimes
. Output only the next line. | res = Mapper.get_date(self.src) |
Based on the snippet: <|code_start|> self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_proj4_unicode(self):
nsr = NSR(u'+proj=longlat')
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_wkt(self):
nsr = NSR(
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,'\
'AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,'\
'AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],'\
'AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]')
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_NSR(self):
nsr = NSR(NSR(4326))
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_dont_init_from_invalid(self):
self.assertRaises(NansatProjectionError, NSR, -10)
self.assertRaises(NansatProjectionError, NSR, 'some crap')
<|code_end|>
, predict the immediate next line with the help of imports:
import unittest
from nansat import NSR
from nansat.utils import osr
from nansat.exceptions import NansatProjectionError
and context (classes, functions, sometimes code) from other files:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/utils.py
# MATPLOTLIB_IS_INSTALLED = False
# MATPLOTLIB_IS_INSTALLED = True
# NUMPY_TO_GDAL_TYPE_MAP = {
# 'uint8': 1,
# 'int8': 1,
# 'uint16': 2,
# 'int16': 3,
# 'uint32': 4,
# 'int32': 5,
# 'float32': 6,
# 'float64': 7,
# 'complex64': 10,
# 'complex128': 11
# }
# def remove_keys(dict, keys):
# def register_colormaps():
# def initial_bearing(lon1, lat1, lon2, lat2):
# def haversine(lon1, lat1, lon2, lat2):
# def add_logger(logName='', logLevel=None):
# def get_random_color(c0=None, minDist=100, low=0, high=255):
# def parse_time(time_string):
#
# Path: nansat/exceptions.py
# class NansatProjectionError(Exception):
# """ Cannot get the projection """
# pass
. Output only the next line. | ss = osr.SpatialReference() |
Predict the next line for this snippet: <|code_start|> self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_proj4_unicode(self):
nsr = NSR(u'+proj=longlat')
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_wkt(self):
nsr = NSR(
'GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,'\
'AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,'\
'AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],'\
'AXIS["Latitude",NORTH],AXIS["Longitude",EAST],AUTHORITY["EPSG","4326"]]')
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_init_from_NSR(self):
nsr = NSR(NSR(4326))
self.assertEqual(type(nsr), NSR)
self.assertEqual(nsr.Validate(), 0)
self.assertTrue('longlat' in nsr.ExportToProj4())
def test_dont_init_from_invalid(self):
<|code_end|>
with the help of current file imports:
import unittest
from nansat import NSR
from nansat.utils import osr
from nansat.exceptions import NansatProjectionError
and context from other files:
# Path: nansat/nsr.py
# class NSR(osr.SpatialReference, object):
# """Nansat Spatial Reference. Overrides constructor of osr.SpatialReference.
#
# Parameters
# ----------
# srs : 0, PROJ4 or EPSG or WKT or osr.SpatialReference, NSR
# Specifies spatial reference system (SRS)
# PROJ4:
# string with proj4 options [http://trac.osgeo.org/proj/] e.g.:
# '+proj=latlong +datum=WGS84 +ellps=WGS84 +no_defs'
# '+proj=stere +datum=WGS84 +ellps=WGS84 +lat_0=75 +lon_0=0 +no_defs'
# EPSG:
# integer with EPSG number, [http://spatialreference.org/],
# e.g. 4326
# WKT:
# string with Well Know Text of SRS. E.g.:
# 'GEOGCS["WGS 84",
# DATUM["WGS_1984",
# SPHEROID["WGS 84",6378137,298.257223563,
# AUTHORITY["EPSG","7030"]],
# TOWGS84[0,0,0,0,0,0,0],
# AUTHORITY["EPSG","6326"]],
# PRIMEM["Greenwich",0,
# AUTHORITY["EPSG","8901"]],
# UNIT["degree",0.0174532925199433,
# AUTHORITY["EPSG","9108"]],
# AUTHORITY["EPSG","4326"]]'
#
# """
#
# def __init__(self, srs=0):
# """Create Spatial Reference System from input parameter"""
# if sys.version_info.major == 2:
# str_types = (str, unicode)
# else:
# str_types = str
# # create SRS
# osr.SpatialReference.__init__(self)
#
# # parse input parameters
# status = 1
# if srs is 0:
# # generate default WGS84 SRS
# status = self.ImportFromEPSG(4326)
# elif isinstance(srs, str_types):
# # parse as proj4 string
# status = self.ImportFromProj4(str(srs))
# if status > 0:
# # parse as WKT string
# status = self.ImportFromWkt(str(srs))
# if status > 0:
# raise NansatProjectionError('Proj4 or WKT (%s) is wrong' % srs)
# elif isinstance(srs, int):
# # parse as EPSG code
# status = self.ImportFromEPSG(srs)
# if status > 0:
# raise NansatProjectionError('EPSG %d is wrong' % srs)
# elif type(srs) in [osr.SpatialReference, NSR]:
# # parse from input Spatial Reference
# status = self.ImportFromWkt(srs.ExportToWkt())
# if status > 0:
# raise NansatProjectionError('NSR %s is wrong' % srs)
#
# @property
# def wkt(self):
# """Well Known Text representation of SRS"""
# return self.ExportToWkt()
#
# Path: nansat/utils.py
# MATPLOTLIB_IS_INSTALLED = False
# MATPLOTLIB_IS_INSTALLED = True
# NUMPY_TO_GDAL_TYPE_MAP = {
# 'uint8': 1,
# 'int8': 1,
# 'uint16': 2,
# 'int16': 3,
# 'uint32': 4,
# 'int32': 5,
# 'float32': 6,
# 'float64': 7,
# 'complex64': 10,
# 'complex128': 11
# }
# def remove_keys(dict, keys):
# def register_colormaps():
# def initial_bearing(lon1, lat1, lon2, lat2):
# def haversine(lon1, lat1, lon2, lat2):
# def add_logger(logName='', logLevel=None):
# def get_random_color(c0=None, minDist=100, low=0, high=255):
# def parse_time(time_string):
#
# Path: nansat/exceptions.py
# class NansatProjectionError(Exception):
# """ Cannot get the projection """
# pass
, which may contain function names, class names, or code. Output only the next line. | self.assertRaises(NansatProjectionError, NSR, -10) |
Using the snippet: <|code_start|> assert isinstance(num_workers, int), \
'num workers must be an int: %r' % (num_workers)
# check existing workers and issue a warning if it exceeds max
num_existing = len(self._workers) if self._workers else 0
num_expected = num_workers + num_existing
if num_expected > self._max_workers:
logger.warning(
'starting %d workers when %d already exist, '
'total workers will exceed max workers: %d / %d',
num_workers, num_existing, num_expected, self._max_workers,
)
# but fall through and start the new workers anyway
created_workers = set(
spawn_worker(self, name=generate_id(self._thread_name_prefix))
for _ in range(num_workers)
)
logger.debug('created workers: %r', created_workers)
if self._workers is None:
self._workers = set()
self._workers.update(created_workers)
def submit(self, fn, *args, **kwargs):
with self._lock:
if not self._running:
raise RuntimeError('task pool is not running')
future = futurebase.Future()
<|code_end|>
, determine the next line of code. You have imports:
from concurrent.futures import _base as futurebase
from ..task.task import Task
from ..task.worker import spawn_worker
from ..util.id import generate_id
from ..util.sys import get_cpu_count
import logging
import queue
import threading
and context (class names, function names, or code) available:
# Path: lib/task/task.py
# class Task(object):
#
# def __init__(self, future, fn, args, kwargs):
# self._future = future # type: concurrent.futures.Future
# self._fn = fn # type: callable
# self._args = args
# self._kwargs = kwargs
#
# def run(self):
# if not self._future.set_running_or_notify_cancel():
# # cancelled, skip it
# return
#
# logger.debug('starting task: %r', self)
#
# try:
# result = self._fn(*self._args, **self._kwargs)
# except Exception as exception:
# self._future.set_exception(exception)
# except: # noqa: E722
# # failure - old style exceptions
# exception = sys.exc_info()[1]
# self._future.set_exception(exception)
# else:
# # success - set result
# self._future.set_result(result)
#
# logger.debug('finished task: %r', self)
#
# def __repr__(self):
# return '%s(%r)' % ('Task', {
# 'future': self._future,
# 'fn': self._fn,
# 'args': self._args,
# 'kwargs': self._kwargs,
# })
#
# Path: lib/task/worker.py
# def spawn_worker(pool, name=None):
# if name is not None and not isinstance(name, str):
# raise TypeError('name must be a str: %r' % (name))
#
# worker_instance = Worker(pool)
#
# def run_worker():
# try:
# worker_instance.run()
# except Exception as e:
# logger.error(
# 'unhandled exception during worker thread loop: %r', e,
# )
#
# # explicitly delete references since worker is about to exit:
# worker_instance.clear()
#
# worker_thread = threading.Thread(target=run_worker, name=name)
# worker_thread.daemon = True
#
# worker_instance.handle = worker_thread
# logger.debug('created worker: %r', worker_instance)
#
# worker_thread.start()
# return worker_instance
#
# Path: lib/util/id.py
# def generate_id(prefix=None):
# '''
# Generates and returns a `str` id.
#
# The id is generated by appending the `prefix` to a globally unique integer
# counter. The counter is not specific to the prefix.
# '''
# if not isinstance(prefix, str):
# raise TypeError('prefix must be a str: %r' % (prefix))
#
# if prefix is None:
# prefix = ''
#
# current_count = _get_counter()
# _increment_counter()
#
# return '%s%d' % (prefix, current_count)
#
# Path: lib/util/sys.py
# def get_cpu_count():
# ''' Returns the core count of the current system. '''
# try:
# return multiprocessing.cpu_count()
# except (AttributeError, NotImplementedError):
# return 1
. Output only the next line. | task = Task(future, fn, args, kwargs) |
Given the code snippet: <|code_start|> self._name = None
self.name = thread_name_prefix
self.start()
def start(self):
with self._lock:
self._running = True
# NOTE : This unconditionally adds more workers (can go over max).
self._create_workers()
def _create_workers(self, num_workers=None):
if num_workers is None:
num_workers = self._max_workers
assert isinstance(num_workers, int), \
'num workers must be an int: %r' % (num_workers)
# check existing workers and issue a warning if it exceeds max
num_existing = len(self._workers) if self._workers else 0
num_expected = num_workers + num_existing
if num_expected > self._max_workers:
logger.warning(
'starting %d workers when %d already exist, '
'total workers will exceed max workers: %d / %d',
num_workers, num_existing, num_expected, self._max_workers,
)
# but fall through and start the new workers anyway
created_workers = set(
<|code_end|>
, generate the next line using the imports in this file:
from concurrent.futures import _base as futurebase
from ..task.task import Task
from ..task.worker import spawn_worker
from ..util.id import generate_id
from ..util.sys import get_cpu_count
import logging
import queue
import threading
and context (functions, classes, or occasionally code) from other files:
# Path: lib/task/task.py
# class Task(object):
#
# def __init__(self, future, fn, args, kwargs):
# self._future = future # type: concurrent.futures.Future
# self._fn = fn # type: callable
# self._args = args
# self._kwargs = kwargs
#
# def run(self):
# if not self._future.set_running_or_notify_cancel():
# # cancelled, skip it
# return
#
# logger.debug('starting task: %r', self)
#
# try:
# result = self._fn(*self._args, **self._kwargs)
# except Exception as exception:
# self._future.set_exception(exception)
# except: # noqa: E722
# # failure - old style exceptions
# exception = sys.exc_info()[1]
# self._future.set_exception(exception)
# else:
# # success - set result
# self._future.set_result(result)
#
# logger.debug('finished task: %r', self)
#
# def __repr__(self):
# return '%s(%r)' % ('Task', {
# 'future': self._future,
# 'fn': self._fn,
# 'args': self._args,
# 'kwargs': self._kwargs,
# })
#
# Path: lib/task/worker.py
# def spawn_worker(pool, name=None):
# if name is not None and not isinstance(name, str):
# raise TypeError('name must be a str: %r' % (name))
#
# worker_instance = Worker(pool)
#
# def run_worker():
# try:
# worker_instance.run()
# except Exception as e:
# logger.error(
# 'unhandled exception during worker thread loop: %r', e,
# )
#
# # explicitly delete references since worker is about to exit:
# worker_instance.clear()
#
# worker_thread = threading.Thread(target=run_worker, name=name)
# worker_thread.daemon = True
#
# worker_instance.handle = worker_thread
# logger.debug('created worker: %r', worker_instance)
#
# worker_thread.start()
# return worker_instance
#
# Path: lib/util/id.py
# def generate_id(prefix=None):
# '''
# Generates and returns a `str` id.
#
# The id is generated by appending the `prefix` to a globally unique integer
# counter. The counter is not specific to the prefix.
# '''
# if not isinstance(prefix, str):
# raise TypeError('prefix must be a str: %r' % (prefix))
#
# if prefix is None:
# prefix = ''
#
# current_count = _get_counter()
# _increment_counter()
#
# return '%s%d' % (prefix, current_count)
#
# Path: lib/util/sys.py
# def get_cpu_count():
# ''' Returns the core count of the current system. '''
# try:
# return multiprocessing.cpu_count()
# except (AttributeError, NotImplementedError):
# return 1
. Output only the next line. | spawn_worker(self, name=generate_id(self._thread_name_prefix)) |
Using the snippet: <|code_start|> self._name = None
self.name = thread_name_prefix
self.start()
def start(self):
with self._lock:
self._running = True
# NOTE : This unconditionally adds more workers (can go over max).
self._create_workers()
def _create_workers(self, num_workers=None):
if num_workers is None:
num_workers = self._max_workers
assert isinstance(num_workers, int), \
'num workers must be an int: %r' % (num_workers)
# check existing workers and issue a warning if it exceeds max
num_existing = len(self._workers) if self._workers else 0
num_expected = num_workers + num_existing
if num_expected > self._max_workers:
logger.warning(
'starting %d workers when %d already exist, '
'total workers will exceed max workers: %d / %d',
num_workers, num_existing, num_expected, self._max_workers,
)
# but fall through and start the new workers anyway
created_workers = set(
<|code_end|>
, determine the next line of code. You have imports:
from concurrent.futures import _base as futurebase
from ..task.task import Task
from ..task.worker import spawn_worker
from ..util.id import generate_id
from ..util.sys import get_cpu_count
import logging
import queue
import threading
and context (class names, function names, or code) available:
# Path: lib/task/task.py
# class Task(object):
#
# def __init__(self, future, fn, args, kwargs):
# self._future = future # type: concurrent.futures.Future
# self._fn = fn # type: callable
# self._args = args
# self._kwargs = kwargs
#
# def run(self):
# if not self._future.set_running_or_notify_cancel():
# # cancelled, skip it
# return
#
# logger.debug('starting task: %r', self)
#
# try:
# result = self._fn(*self._args, **self._kwargs)
# except Exception as exception:
# self._future.set_exception(exception)
# except: # noqa: E722
# # failure - old style exceptions
# exception = sys.exc_info()[1]
# self._future.set_exception(exception)
# else:
# # success - set result
# self._future.set_result(result)
#
# logger.debug('finished task: %r', self)
#
# def __repr__(self):
# return '%s(%r)' % ('Task', {
# 'future': self._future,
# 'fn': self._fn,
# 'args': self._args,
# 'kwargs': self._kwargs,
# })
#
# Path: lib/task/worker.py
# def spawn_worker(pool, name=None):
# if name is not None and not isinstance(name, str):
# raise TypeError('name must be a str: %r' % (name))
#
# worker_instance = Worker(pool)
#
# def run_worker():
# try:
# worker_instance.run()
# except Exception as e:
# logger.error(
# 'unhandled exception during worker thread loop: %r', e,
# )
#
# # explicitly delete references since worker is about to exit:
# worker_instance.clear()
#
# worker_thread = threading.Thread(target=run_worker, name=name)
# worker_thread.daemon = True
#
# worker_instance.handle = worker_thread
# logger.debug('created worker: %r', worker_instance)
#
# worker_thread.start()
# return worker_instance
#
# Path: lib/util/id.py
# def generate_id(prefix=None):
# '''
# Generates and returns a `str` id.
#
# The id is generated by appending the `prefix` to a globally unique integer
# counter. The counter is not specific to the prefix.
# '''
# if not isinstance(prefix, str):
# raise TypeError('prefix must be a str: %r' % (prefix))
#
# if prefix is None:
# prefix = ''
#
# current_count = _get_counter()
# _increment_counter()
#
# return '%s%d' % (prefix, current_count)
#
# Path: lib/util/sys.py
# def get_cpu_count():
# ''' Returns the core count of the current system. '''
# try:
# return multiprocessing.cpu_count()
# except (AttributeError, NotImplementedError):
# return 1
. Output only the next line. | spawn_worker(self, name=generate_id(self._thread_name_prefix)) |
Using the snippet: <|code_start|>#!/usr/bin/env python3
'''
lib/task/pool.py
Task pool abstraction. Replacement for `concurrent.futures`.
Defines a task pool class that can be used to run tasks asynchronously.
Most of this logic was taken from pythonfutures:
https://github.com/agronholm/pythonfutures
https://git.io/vdCQ2
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
class Pool(object):
'''
Task pool. Schedules work to run in a thread pool.
This class conforms to `concurrent.futures.Executor`. It does not use
weak references, however, so it is expected that the application shuts down
the pool properly. Worker threads are created as daemons, so they won't
stop the program from shutting down.
'''
def __init__(self, max_workers=None, thread_name_prefix=''):
if max_workers is None:
<|code_end|>
, determine the next line of code. You have imports:
from concurrent.futures import _base as futurebase
from ..task.task import Task
from ..task.worker import spawn_worker
from ..util.id import generate_id
from ..util.sys import get_cpu_count
import logging
import queue
import threading
and context (class names, function names, or code) available:
# Path: lib/task/task.py
# class Task(object):
#
# def __init__(self, future, fn, args, kwargs):
# self._future = future # type: concurrent.futures.Future
# self._fn = fn # type: callable
# self._args = args
# self._kwargs = kwargs
#
# def run(self):
# if not self._future.set_running_or_notify_cancel():
# # cancelled, skip it
# return
#
# logger.debug('starting task: %r', self)
#
# try:
# result = self._fn(*self._args, **self._kwargs)
# except Exception as exception:
# self._future.set_exception(exception)
# except: # noqa: E722
# # failure - old style exceptions
# exception = sys.exc_info()[1]
# self._future.set_exception(exception)
# else:
# # success - set result
# self._future.set_result(result)
#
# logger.debug('finished task: %r', self)
#
# def __repr__(self):
# return '%s(%r)' % ('Task', {
# 'future': self._future,
# 'fn': self._fn,
# 'args': self._args,
# 'kwargs': self._kwargs,
# })
#
# Path: lib/task/worker.py
# def spawn_worker(pool, name=None):
# if name is not None and not isinstance(name, str):
# raise TypeError('name must be a str: %r' % (name))
#
# worker_instance = Worker(pool)
#
# def run_worker():
# try:
# worker_instance.run()
# except Exception as e:
# logger.error(
# 'unhandled exception during worker thread loop: %r', e,
# )
#
# # explicitly delete references since worker is about to exit:
# worker_instance.clear()
#
# worker_thread = threading.Thread(target=run_worker, name=name)
# worker_thread.daemon = True
#
# worker_instance.handle = worker_thread
# logger.debug('created worker: %r', worker_instance)
#
# worker_thread.start()
# return worker_instance
#
# Path: lib/util/id.py
# def generate_id(prefix=None):
# '''
# Generates and returns a `str` id.
#
# The id is generated by appending the `prefix` to a globally unique integer
# counter. The counter is not specific to the prefix.
# '''
# if not isinstance(prefix, str):
# raise TypeError('prefix must be a str: %r' % (prefix))
#
# if prefix is None:
# prefix = ''
#
# current_count = _get_counter()
# _increment_counter()
#
# return '%s%d' % (prefix, current_count)
#
# Path: lib/util/sys.py
# def get_cpu_count():
# ''' Returns the core count of the current system. '''
# try:
# return multiprocessing.cpu_count()
# except (AttributeError, NotImplementedError):
# return 1
. Output only the next line. | max_workers = (get_cpu_count() or 1) * 5 |
Predict the next line for this snippet: <|code_start|>
class TestMergeDictionaries(unittest.TestCase):
'''
Unit tests for the dictionary merge algorithm. This should recursively
merge the structure of dictionaries, overwriting leaf nodes instead of
branches whenever possible.
'''
@log_function('[merge : shallow]')
def test_md_shallow(self):
''' Tests dictionary merges with max depth 1. '''
shallow_dictionary_cases = [(
({'a': 1}, {'b': 2}),
{'expected': {'a': 1, 'b': 2}},
), (
({'a': 1}, {'b': 2}, {'a': 3}),
{'expected': {'a': 3, 'b': 2}},
), (
({'a': 1}, {'b': 2}, {'c': 3}, {'a': 4, 'b': 5, 'c': 6}),
{'expected': {'a': 4, 'b': 5, 'c': 6}},
), (
({'a': 1}, {'b': 2}, {'a': 3, 'b': 4}, {'a': 1, 'c': 5}),
{'expected': {'a': 1, 'b': 4, 'c': 5}},
), (
({'a': 1}, {'b': 2}, {}, {'a': []}, {}, {'b': {}}),
{'expected': {'a': [], 'b': {}}},
)]
def test_md_shallow_one(base, *rest, expected=''):
<|code_end|>
with the help of current file imports:
import logging
import unittest
from lib.util.dict import merge_dicts
from tests.lib.decorator import log_function
from tests.lib.subtest import map_test_function
and context from other files:
# Path: lib/util/dict.py
# def merge_dicts(base, *rest):
# '''
# Recursively merges `base`, which should be a `dict`, with `rest`.
#
# The result first starts out being equal to `base` (a deep copy). Then for
# each item in `rest`, the keys are merged into the result. If the mapped
# value is not a collection, it overwrites the key in the result. If the
# mapped value is a collection, it is recursed into to overwrite the result.
#
# Examples:
# merge_dicts({
# 'foo': 'bar',
# }, {
# 'foo': 'baz',
# })
# # --> { 'foo': 'baz' }
#
# NOTE : This method creates deep copies of input data. Do not supply objects
# that contain cyclic references. Do not supply large objects.
# '''
#
# result = copy.deepcopy(base)
# for src in rest:
# _merge_recursively(result, src)
#
# return result
#
# Path: tests/lib/decorator.py
# def log_function(desc=None, logger=None,
# include_args=False, include_kwargs=False,
# include_return=False):
# '''
# Decorator for a function call.
# Generates log messages when executing the underlying function. Attaches a
# specialized filter to the logger to prepend the description to all log
# messages while executing the function.
# If `desc` is provided, it is used in the log message prefix. If omitted,
# the function name will be used.
# If `logger` is provided, a handler is attached to it during the execution
# of the test function, and restored afterwards. Log statements will then
# include a prefix of `desc` in the messages. If `logger` is omitted, the
# root logger is used.
# If `include_args` is true, then positional arguments are logged prior to
# running the function.
# If `include_kwargs` is true, then keyword-arguments are logged prior to
# running the function.
# If `include_return` is true, then the return value is logged after running
# the function.
# '''
#
# # pylint: disable=redefined-outer-name
# if desc:
# def get_desc(fn):
# # pylint: disable=unused-argument
# return desc
# else:
# def get_desc(fn):
# if hasattr(fn, '__name__'):
# return getattr(fn, '__name__')
# return '?'
#
# if logger is None:
# logger = logging.getLogger('sublime-ycmd')
#
# def log_function_runner(fn):
# ''' Base decorator. Decorates the underlying function. '''
#
# desc = get_desc(fn)
#
# @functools.wraps(fn)
# def log_function_run(*args, **kwargs):
# with LoggingContext(logger=logger, desc=desc):
# if include_args and include_kwargs:
# logger.debug('args, kwargs: %r, %r', args, kwargs)
# elif include_args:
# logger.debug('args: %r', args)
# elif include_kwargs:
# logger.debug('kwargs: %r', kwargs)
#
# result = fn(*args, **kwargs)
#
# if include_return:
# logger.debug('return: %r', result)
#
# return result
#
# return log_function_run
#
# return log_function_runner
#
# Path: tests/lib/subtest.py
# def map_test_function(test_instance, test_function, test_cases):
# assert isinstance(test_instance, unittest.TestCase), \
# 'test instance must be a unittest.TestCase: %r' % (test_instance)
# assert callable(test_function), \
# 'test function must be callable: %r' % (test_function)
# assert hasattr(test_cases, '__iter__'), \
# 'test cases must be iterable: %r' % (test_cases)
#
# for test_index, test_case in enumerate(test_cases, start=1):
# is_args_kwargs = _is_args_kwargs(test_case)
# is_kwargs = isinstance(test_case, dict)
# is_args = not (is_args_kwargs or is_kwargs)
#
# if is_args_kwargs:
# test_args, test_kwargs = test_case
# elif is_kwargs:
# test_args = tuple()
# test_kwargs = test_case
# elif is_args:
# test_args = test_case
# test_kwargs = dict()
#
# log_args = is_args_kwargs or is_args
# log_kwargs = is_args_kwargs or is_kwargs
#
# wrapped_test_function = log_function(
# desc='[%d]' % (test_index),
# include_args=log_args, include_kwargs=log_kwargs,
# )(test_function)
#
# with test_instance.subTest(num=test_index,
# args=test_args, kwargs=test_kwargs):
# wrapped_test_function(*test_args, **test_kwargs)
, which may contain function names, class names, or code. Output only the next line. | result = merge_dicts(base, *rest) |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
'''
tests/util/dict.py
Tests for dictionary utility functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
class TestMergeDictionaries(unittest.TestCase):
'''
Unit tests for the dictionary merge algorithm. This should recursively
merge the structure of dictionaries, overwriting leaf nodes instead of
branches whenever possible.
'''
<|code_end|>
. Write the next line using the current file imports:
import logging
import unittest
from lib.util.dict import merge_dicts
from tests.lib.decorator import log_function
from tests.lib.subtest import map_test_function
and context from other files:
# Path: lib/util/dict.py
# def merge_dicts(base, *rest):
# '''
# Recursively merges `base`, which should be a `dict`, with `rest`.
#
# The result first starts out being equal to `base` (a deep copy). Then for
# each item in `rest`, the keys are merged into the result. If the mapped
# value is not a collection, it overwrites the key in the result. If the
# mapped value is a collection, it is recursed into to overwrite the result.
#
# Examples:
# merge_dicts({
# 'foo': 'bar',
# }, {
# 'foo': 'baz',
# })
# # --> { 'foo': 'baz' }
#
# NOTE : This method creates deep copies of input data. Do not supply objects
# that contain cyclic references. Do not supply large objects.
# '''
#
# result = copy.deepcopy(base)
# for src in rest:
# _merge_recursively(result, src)
#
# return result
#
# Path: tests/lib/decorator.py
# def log_function(desc=None, logger=None,
# include_args=False, include_kwargs=False,
# include_return=False):
# '''
# Decorator for a function call.
# Generates log messages when executing the underlying function. Attaches a
# specialized filter to the logger to prepend the description to all log
# messages while executing the function.
# If `desc` is provided, it is used in the log message prefix. If omitted,
# the function name will be used.
# If `logger` is provided, a handler is attached to it during the execution
# of the test function, and restored afterwards. Log statements will then
# include a prefix of `desc` in the messages. If `logger` is omitted, the
# root logger is used.
# If `include_args` is true, then positional arguments are logged prior to
# running the function.
# If `include_kwargs` is true, then keyword-arguments are logged prior to
# running the function.
# If `include_return` is true, then the return value is logged after running
# the function.
# '''
#
# # pylint: disable=redefined-outer-name
# if desc:
# def get_desc(fn):
# # pylint: disable=unused-argument
# return desc
# else:
# def get_desc(fn):
# if hasattr(fn, '__name__'):
# return getattr(fn, '__name__')
# return '?'
#
# if logger is None:
# logger = logging.getLogger('sublime-ycmd')
#
# def log_function_runner(fn):
# ''' Base decorator. Decorates the underlying function. '''
#
# desc = get_desc(fn)
#
# @functools.wraps(fn)
# def log_function_run(*args, **kwargs):
# with LoggingContext(logger=logger, desc=desc):
# if include_args and include_kwargs:
# logger.debug('args, kwargs: %r, %r', args, kwargs)
# elif include_args:
# logger.debug('args: %r', args)
# elif include_kwargs:
# logger.debug('kwargs: %r', kwargs)
#
# result = fn(*args, **kwargs)
#
# if include_return:
# logger.debug('return: %r', result)
#
# return result
#
# return log_function_run
#
# return log_function_runner
#
# Path: tests/lib/subtest.py
# def map_test_function(test_instance, test_function, test_cases):
# assert isinstance(test_instance, unittest.TestCase), \
# 'test instance must be a unittest.TestCase: %r' % (test_instance)
# assert callable(test_function), \
# 'test function must be callable: %r' % (test_function)
# assert hasattr(test_cases, '__iter__'), \
# 'test cases must be iterable: %r' % (test_cases)
#
# for test_index, test_case in enumerate(test_cases, start=1):
# is_args_kwargs = _is_args_kwargs(test_case)
# is_kwargs = isinstance(test_case, dict)
# is_args = not (is_args_kwargs or is_kwargs)
#
# if is_args_kwargs:
# test_args, test_kwargs = test_case
# elif is_kwargs:
# test_args = tuple()
# test_kwargs = test_case
# elif is_args:
# test_args = test_case
# test_kwargs = dict()
#
# log_args = is_args_kwargs or is_args
# log_kwargs = is_args_kwargs or is_kwargs
#
# wrapped_test_function = log_function(
# desc='[%d]' % (test_index),
# include_args=log_args, include_kwargs=log_kwargs,
# )(test_function)
#
# with test_instance.subTest(num=test_index,
# args=test_args, kwargs=test_kwargs):
# wrapped_test_function(*test_args, **test_kwargs)
, which may include functions, classes, or code. Output only the next line. | @log_function('[merge : shallow]') |
Based on the snippet: <|code_start|> return False
return True
def map_test_function(test_instance, test_function, test_cases):
assert isinstance(test_instance, unittest.TestCase), \
'test instance must be a unittest.TestCase: %r' % (test_instance)
assert callable(test_function), \
'test function must be callable: %r' % (test_function)
assert hasattr(test_cases, '__iter__'), \
'test cases must be iterable: %r' % (test_cases)
for test_index, test_case in enumerate(test_cases, start=1):
is_args_kwargs = _is_args_kwargs(test_case)
is_kwargs = isinstance(test_case, dict)
is_args = not (is_args_kwargs or is_kwargs)
if is_args_kwargs:
test_args, test_kwargs = test_case
elif is_kwargs:
test_args = tuple()
test_kwargs = test_case
elif is_args:
test_args = test_case
test_kwargs = dict()
log_args = is_args_kwargs or is_args
log_kwargs = is_args_kwargs or is_kwargs
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import unittest
from tests.lib.decorator import log_function
and context (classes, functions, sometimes code) from other files:
# Path: tests/lib/decorator.py
# def log_function(desc=None, logger=None,
# include_args=False, include_kwargs=False,
# include_return=False):
# '''
# Decorator for a function call.
# Generates log messages when executing the underlying function. Attaches a
# specialized filter to the logger to prepend the description to all log
# messages while executing the function.
# If `desc` is provided, it is used in the log message prefix. If omitted,
# the function name will be used.
# If `logger` is provided, a handler is attached to it during the execution
# of the test function, and restored afterwards. Log statements will then
# include a prefix of `desc` in the messages. If `logger` is omitted, the
# root logger is used.
# If `include_args` is true, then positional arguments are logged prior to
# running the function.
# If `include_kwargs` is true, then keyword-arguments are logged prior to
# running the function.
# If `include_return` is true, then the return value is logged after running
# the function.
# '''
#
# # pylint: disable=redefined-outer-name
# if desc:
# def get_desc(fn):
# # pylint: disable=unused-argument
# return desc
# else:
# def get_desc(fn):
# if hasattr(fn, '__name__'):
# return getattr(fn, '__name__')
# return '?'
#
# if logger is None:
# logger = logging.getLogger('sublime-ycmd')
#
# def log_function_runner(fn):
# ''' Base decorator. Decorates the underlying function. '''
#
# desc = get_desc(fn)
#
# @functools.wraps(fn)
# def log_function_run(*args, **kwargs):
# with LoggingContext(logger=logger, desc=desc):
# if include_args and include_kwargs:
# logger.debug('args, kwargs: %r, %r', args, kwargs)
# elif include_args:
# logger.debug('args: %r', args)
# elif include_kwargs:
# logger.debug('kwargs: %r', kwargs)
#
# result = fn(*args, **kwargs)
#
# if include_return:
# logger.debug('return: %r', result)
#
# return result
#
# return log_function_run
#
# return log_function_runner
. Output only the next line. | wrapped_test_function = log_function( |
Here is a snippet: <|code_start|>#!/usr/bin/env python3
'''
tests/util/fs.py
Tests for file-system utility functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
if os.name == 'posix':
FS_ROOT = '/'
elif os.name == 'nt':
FS_ROOT = 'C:\\'
else:
logger.error('unknown os type, test data might be invalid')
FS_ROOT = ''
class TestGetCommonAncestor(unittest.TestCase):
'''
Unit tests for calculating the common ancestor between paths. The common
ancestor should represent the path to a common file node between all the
input paths.
'''
@log_function('[ancestor : empty]')
def test_gca_empty(self):
''' Ensures that `None` is returned for an empty path list. '''
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
import unittest
from lib.util.fs import get_common_ancestor
from tests.lib.decorator import log_function
from tests.lib.subtest import map_test_function
and context from other files:
# Path: lib/util/fs.py
# def get_common_ancestor(paths, default=None):
# common_path = default
# try:
# # common_path = os.path.commonpath(paths)
# common_path = _commonpath_polyfill(paths)
# except ValueError as e:
# logger.debug(
# 'invalid paths, cannot get common ancenstor: %s, %r',
# paths, e,
# )
#
# return common_path
#
# Path: tests/lib/decorator.py
# def log_function(desc=None, logger=None,
# include_args=False, include_kwargs=False,
# include_return=False):
# '''
# Decorator for a function call.
# Generates log messages when executing the underlying function. Attaches a
# specialized filter to the logger to prepend the description to all log
# messages while executing the function.
# If `desc` is provided, it is used in the log message prefix. If omitted,
# the function name will be used.
# If `logger` is provided, a handler is attached to it during the execution
# of the test function, and restored afterwards. Log statements will then
# include a prefix of `desc` in the messages. If `logger` is omitted, the
# root logger is used.
# If `include_args` is true, then positional arguments are logged prior to
# running the function.
# If `include_kwargs` is true, then keyword-arguments are logged prior to
# running the function.
# If `include_return` is true, then the return value is logged after running
# the function.
# '''
#
# # pylint: disable=redefined-outer-name
# if desc:
# def get_desc(fn):
# # pylint: disable=unused-argument
# return desc
# else:
# def get_desc(fn):
# if hasattr(fn, '__name__'):
# return getattr(fn, '__name__')
# return '?'
#
# if logger is None:
# logger = logging.getLogger('sublime-ycmd')
#
# def log_function_runner(fn):
# ''' Base decorator. Decorates the underlying function. '''
#
# desc = get_desc(fn)
#
# @functools.wraps(fn)
# def log_function_run(*args, **kwargs):
# with LoggingContext(logger=logger, desc=desc):
# if include_args and include_kwargs:
# logger.debug('args, kwargs: %r, %r', args, kwargs)
# elif include_args:
# logger.debug('args: %r', args)
# elif include_kwargs:
# logger.debug('kwargs: %r', kwargs)
#
# result = fn(*args, **kwargs)
#
# if include_return:
# logger.debug('return: %r', result)
#
# return result
#
# return log_function_run
#
# return log_function_runner
#
# Path: tests/lib/subtest.py
# def map_test_function(test_instance, test_function, test_cases):
# assert isinstance(test_instance, unittest.TestCase), \
# 'test instance must be a unittest.TestCase: %r' % (test_instance)
# assert callable(test_function), \
# 'test function must be callable: %r' % (test_function)
# assert hasattr(test_cases, '__iter__'), \
# 'test cases must be iterable: %r' % (test_cases)
#
# for test_index, test_case in enumerate(test_cases, start=1):
# is_args_kwargs = _is_args_kwargs(test_case)
# is_kwargs = isinstance(test_case, dict)
# is_args = not (is_args_kwargs or is_kwargs)
#
# if is_args_kwargs:
# test_args, test_kwargs = test_case
# elif is_kwargs:
# test_args = tuple()
# test_kwargs = test_case
# elif is_args:
# test_args = test_case
# test_kwargs = dict()
#
# log_args = is_args_kwargs or is_args
# log_kwargs = is_args_kwargs or is_kwargs
#
# wrapped_test_function = log_function(
# desc='[%d]' % (test_index),
# include_args=log_args, include_kwargs=log_kwargs,
# )(test_function)
#
# with test_instance.subTest(num=test_index,
# args=test_args, kwargs=test_kwargs):
# wrapped_test_function(*test_args, **test_kwargs)
, which may include functions, classes, or code. Output only the next line. | result = get_common_ancestor([]) |
Given snippet: <|code_start|>#!/usr/bin/env python3
'''
tests/util/fs.py
Tests for file-system utility functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
if os.name == 'posix':
FS_ROOT = '/'
elif os.name == 'nt':
FS_ROOT = 'C:\\'
else:
logger.error('unknown os type, test data might be invalid')
FS_ROOT = ''
class TestGetCommonAncestor(unittest.TestCase):
'''
Unit tests for calculating the common ancestor between paths. The common
ancestor should represent the path to a common file node between all the
input paths.
'''
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import logging
import os
import unittest
from lib.util.fs import get_common_ancestor
from tests.lib.decorator import log_function
from tests.lib.subtest import map_test_function
and context:
# Path: lib/util/fs.py
# def get_common_ancestor(paths, default=None):
# common_path = default
# try:
# # common_path = os.path.commonpath(paths)
# common_path = _commonpath_polyfill(paths)
# except ValueError as e:
# logger.debug(
# 'invalid paths, cannot get common ancenstor: %s, %r',
# paths, e,
# )
#
# return common_path
#
# Path: tests/lib/decorator.py
# def log_function(desc=None, logger=None,
# include_args=False, include_kwargs=False,
# include_return=False):
# '''
# Decorator for a function call.
# Generates log messages when executing the underlying function. Attaches a
# specialized filter to the logger to prepend the description to all log
# messages while executing the function.
# If `desc` is provided, it is used in the log message prefix. If omitted,
# the function name will be used.
# If `logger` is provided, a handler is attached to it during the execution
# of the test function, and restored afterwards. Log statements will then
# include a prefix of `desc` in the messages. If `logger` is omitted, the
# root logger is used.
# If `include_args` is true, then positional arguments are logged prior to
# running the function.
# If `include_kwargs` is true, then keyword-arguments are logged prior to
# running the function.
# If `include_return` is true, then the return value is logged after running
# the function.
# '''
#
# # pylint: disable=redefined-outer-name
# if desc:
# def get_desc(fn):
# # pylint: disable=unused-argument
# return desc
# else:
# def get_desc(fn):
# if hasattr(fn, '__name__'):
# return getattr(fn, '__name__')
# return '?'
#
# if logger is None:
# logger = logging.getLogger('sublime-ycmd')
#
# def log_function_runner(fn):
# ''' Base decorator. Decorates the underlying function. '''
#
# desc = get_desc(fn)
#
# @functools.wraps(fn)
# def log_function_run(*args, **kwargs):
# with LoggingContext(logger=logger, desc=desc):
# if include_args and include_kwargs:
# logger.debug('args, kwargs: %r, %r', args, kwargs)
# elif include_args:
# logger.debug('args: %r', args)
# elif include_kwargs:
# logger.debug('kwargs: %r', kwargs)
#
# result = fn(*args, **kwargs)
#
# if include_return:
# logger.debug('return: %r', result)
#
# return result
#
# return log_function_run
#
# return log_function_runner
#
# Path: tests/lib/subtest.py
# def map_test_function(test_instance, test_function, test_cases):
# assert isinstance(test_instance, unittest.TestCase), \
# 'test instance must be a unittest.TestCase: %r' % (test_instance)
# assert callable(test_function), \
# 'test function must be callable: %r' % (test_function)
# assert hasattr(test_cases, '__iter__'), \
# 'test cases must be iterable: %r' % (test_cases)
#
# for test_index, test_case in enumerate(test_cases, start=1):
# is_args_kwargs = _is_args_kwargs(test_case)
# is_kwargs = isinstance(test_case, dict)
# is_args = not (is_args_kwargs or is_kwargs)
#
# if is_args_kwargs:
# test_args, test_kwargs = test_case
# elif is_kwargs:
# test_args = tuple()
# test_kwargs = test_case
# elif is_args:
# test_args = test_case
# test_kwargs = dict()
#
# log_args = is_args_kwargs or is_args
# log_kwargs = is_args_kwargs or is_kwargs
#
# wrapped_test_function = log_function(
# desc='[%d]' % (test_index),
# include_args=log_args, include_kwargs=log_kwargs,
# )(test_function)
#
# with test_instance.subTest(num=test_index,
# args=test_args, kwargs=test_kwargs):
# wrapped_test_function(*test_args, **test_kwargs)
which might include code, classes, or functions. Output only the next line. | @log_function('[ancestor : empty]') |
Predict the next line for this snippet: <|code_start|> '''
@log_function('[ancestor : empty]')
def test_gca_empty(self):
''' Ensures that `None` is returned for an empty path list. '''
result = get_common_ancestor([])
self.assertEqual(None, result,
'common ancestor of empty paths should be None')
@log_function('[ancestor : single]')
def test_gca_single(self):
''' Ensures that a single path always results in that same path. '''
single_paths = [
'/',
'/usr',
'/usr/local/bin',
'/var/log/foo\\bar.log',
'C:\\',
'D:\\',
'C:\\Users',
'C:\\Program Files',
'C:\\Program Files/Sublime Text 3',
]
single_path_args = [
([p], {}) for p in single_paths
]
def test_gca_single_one(path):
result = get_common_ancestor([path])
self.assertEqual(path, result)
<|code_end|>
with the help of current file imports:
import logging
import os
import unittest
from lib.util.fs import get_common_ancestor
from tests.lib.decorator import log_function
from tests.lib.subtest import map_test_function
and context from other files:
# Path: lib/util/fs.py
# def get_common_ancestor(paths, default=None):
# common_path = default
# try:
# # common_path = os.path.commonpath(paths)
# common_path = _commonpath_polyfill(paths)
# except ValueError as e:
# logger.debug(
# 'invalid paths, cannot get common ancenstor: %s, %r',
# paths, e,
# )
#
# return common_path
#
# Path: tests/lib/decorator.py
# def log_function(desc=None, logger=None,
# include_args=False, include_kwargs=False,
# include_return=False):
# '''
# Decorator for a function call.
# Generates log messages when executing the underlying function. Attaches a
# specialized filter to the logger to prepend the description to all log
# messages while executing the function.
# If `desc` is provided, it is used in the log message prefix. If omitted,
# the function name will be used.
# If `logger` is provided, a handler is attached to it during the execution
# of the test function, and restored afterwards. Log statements will then
# include a prefix of `desc` in the messages. If `logger` is omitted, the
# root logger is used.
# If `include_args` is true, then positional arguments are logged prior to
# running the function.
# If `include_kwargs` is true, then keyword-arguments are logged prior to
# running the function.
# If `include_return` is true, then the return value is logged after running
# the function.
# '''
#
# # pylint: disable=redefined-outer-name
# if desc:
# def get_desc(fn):
# # pylint: disable=unused-argument
# return desc
# else:
# def get_desc(fn):
# if hasattr(fn, '__name__'):
# return getattr(fn, '__name__')
# return '?'
#
# if logger is None:
# logger = logging.getLogger('sublime-ycmd')
#
# def log_function_runner(fn):
# ''' Base decorator. Decorates the underlying function. '''
#
# desc = get_desc(fn)
#
# @functools.wraps(fn)
# def log_function_run(*args, **kwargs):
# with LoggingContext(logger=logger, desc=desc):
# if include_args and include_kwargs:
# logger.debug('args, kwargs: %r, %r', args, kwargs)
# elif include_args:
# logger.debug('args: %r', args)
# elif include_kwargs:
# logger.debug('kwargs: %r', kwargs)
#
# result = fn(*args, **kwargs)
#
# if include_return:
# logger.debug('return: %r', result)
#
# return result
#
# return log_function_run
#
# return log_function_runner
#
# Path: tests/lib/subtest.py
# def map_test_function(test_instance, test_function, test_cases):
# assert isinstance(test_instance, unittest.TestCase), \
# 'test instance must be a unittest.TestCase: %r' % (test_instance)
# assert callable(test_function), \
# 'test function must be callable: %r' % (test_function)
# assert hasattr(test_cases, '__iter__'), \
# 'test cases must be iterable: %r' % (test_cases)
#
# for test_index, test_case in enumerate(test_cases, start=1):
# is_args_kwargs = _is_args_kwargs(test_case)
# is_kwargs = isinstance(test_case, dict)
# is_args = not (is_args_kwargs or is_kwargs)
#
# if is_args_kwargs:
# test_args, test_kwargs = test_case
# elif is_kwargs:
# test_args = tuple()
# test_kwargs = test_case
# elif is_args:
# test_args = test_case
# test_kwargs = dict()
#
# log_args = is_args_kwargs or is_args
# log_kwargs = is_args_kwargs or is_kwargs
#
# wrapped_test_function = log_function(
# desc='[%d]' % (test_index),
# include_args=log_args, include_kwargs=log_kwargs,
# )(test_function)
#
# with test_instance.subTest(num=test_index,
# args=test_args, kwargs=test_kwargs):
# wrapped_test_function(*test_args, **test_kwargs)
, which may contain function names, class names, or code. Output only the next line. | map_test_function( |
Given the following code snippet before the placeholder: <|code_start|> This is calculated by first generating the HMAC for each item in
`content` separately, then concatenating them, and finally running another
HMAC on the concatenated intermediate result. Finally, the result of that
is base-64 encoded, so it is suitable for use in headers.
'''
assert isinstance(hmac_secret, (str, bytes)), \
'hmac secret must be str or bytes: %r' % (hmac_secret)
if len(content) == 0:
raise ValueError('no data supplied')
hmac_secret = str_to_bytes(hmac_secret)
content_hmac_digests = map(
lambda data: _calculate_hmac(
hmac_secret, data=data, digestmod=digestmod,
), content,
)
if len(content) > 1:
# compose individual hmac fragments into one and then hash it again
concatenated_hmac_digests = b''.join(content_hmac_digests)
hmac_digest_binary = _calculate_hmac(
hmac_secret, data=concatenated_hmac_digests, digestmod=digestmod,
)
else:
assert len(content) == 1, \
'[internal] number of arguments is not 1: %r' % (content)
hmac_digest_binary = next(content_hmac_digests)
hmac_digest_bytes = base64_encode(hmac_digest_binary)
<|code_end|>
, predict the next line using imports from the current file:
import hashlib
import hmac
import logging
import os
from ..util.str import (
bytes_to_str,
str_to_bytes,
)
from ..util.format import (
base64_encode,
)
and context including class names, function names, and sometimes code from other files:
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
#
# def str_to_bytes(data):
# '''
# Converts `data` to `bytes`.
#
# If data is a `str`, it is encoded into `bytes`.
# If data is `bytes`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, bytes):
# # already bytes, yay
# return data
# return data.encode()
#
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
. Output only the next line. | hmac_digest_str = bytes_to_str(hmac_digest_bytes) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
'''
lib/util/hmac.py
Contains HMAC utility functions. The ycmd server expects an HMAC header with
all requests to verify the client's identity. The ycmd server also includes an
HMAC header in all responses to allow the client to verify the responses.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def new_hmac_secret(num_bytes=32):
''' Generates and returns an HMAC secret in binary encoding. '''
hmac_secret_binary = os.urandom(num_bytes)
return hmac_secret_binary
def _calculate_hmac(hmac_secret, data, digestmod=hashlib.sha256):
assert isinstance(hmac_secret, (str, bytes)), \
'hmac secret must be str or bytes: %r' % (hmac_secret)
assert isinstance(data, (str, bytes)), \
'data must be str or bytes: %r' % (data)
<|code_end|>
, predict the next line using imports from the current file:
import hashlib
import hmac
import logging
import os
from ..util.str import (
bytes_to_str,
str_to_bytes,
)
from ..util.format import (
base64_encode,
)
and context including class names, function names, and sometimes code from other files:
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
#
# def str_to_bytes(data):
# '''
# Converts `data` to `bytes`.
#
# If data is a `str`, it is encoded into `bytes`.
# If data is `bytes`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, bytes):
# # already bytes, yay
# return data
# return data.encode()
#
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
. Output only the next line. | hmac_secret = str_to_bytes(hmac_secret) |
Given the code snippet: <|code_start|> Calculates the HMAC for the given `content` using the `hmac_secret`.
This is calculated by first generating the HMAC for each item in
`content` separately, then concatenating them, and finally running another
HMAC on the concatenated intermediate result. Finally, the result of that
is base-64 encoded, so it is suitable for use in headers.
'''
assert isinstance(hmac_secret, (str, bytes)), \
'hmac secret must be str or bytes: %r' % (hmac_secret)
if len(content) == 0:
raise ValueError('no data supplied')
hmac_secret = str_to_bytes(hmac_secret)
content_hmac_digests = map(
lambda data: _calculate_hmac(
hmac_secret, data=data, digestmod=digestmod,
), content,
)
if len(content) > 1:
# compose individual hmac fragments into one and then hash it again
concatenated_hmac_digests = b''.join(content_hmac_digests)
hmac_digest_binary = _calculate_hmac(
hmac_secret, data=concatenated_hmac_digests, digestmod=digestmod,
)
else:
assert len(content) == 1, \
'[internal] number of arguments is not 1: %r' % (content)
hmac_digest_binary = next(content_hmac_digests)
<|code_end|>
, generate the next line using the imports in this file:
import hashlib
import hmac
import logging
import os
from ..util.str import (
bytes_to_str,
str_to_bytes,
)
from ..util.format import (
base64_encode,
)
and context (functions, classes, or occasionally code) from other files:
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
#
# def str_to_bytes(data):
# '''
# Converts `data` to `bytes`.
#
# If data is a `str`, it is encoded into `bytes`.
# If data is `bytes`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, bytes):
# # already bytes, yay
# return data
# return data.encode()
#
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
. Output only the next line. | hmac_digest_bytes = base64_encode(hmac_digest_binary) |
Continue the code snippet: <|code_start|>#!/usr/bin/env python3
'''
lib/util/format.py
Data formatting functions. Includes base64 encode/decode functions as well as
json parse/serialize functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def base64_encode(data):
'''
Encodes the given `data` in base-64. The result will either be a `str`,
or `bytes`, depending on the input type (same as input type).
'''
assert isinstance(data, (str, bytes)), \
'data must be str or bytes: %r' % (data)
is_str = isinstance(data, str)
if is_str:
data = str_to_bytes(data)
encoded = base64.b64encode(data)
if is_str:
<|code_end|>
. Use current file imports:
import base64
import json
import logging
from ..util.str import (
bytes_to_str,
str_to_bytes,
)
and context (classes, functions, or code) from other files:
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
#
# def str_to_bytes(data):
# '''
# Converts `data` to `bytes`.
#
# If data is a `str`, it is encoded into `bytes`.
# If data is `bytes`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, bytes):
# # already bytes, yay
# return data
# return data.encode()
. Output only the next line. | encoded = bytes_to_str(encoded) |
Given the following code snippet before the placeholder: <|code_start|>#!/usr/bin/env python3
'''
lib/util/format.py
Data formatting functions. Includes base64 encode/decode functions as well as
json parse/serialize functions.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def base64_encode(data):
'''
Encodes the given `data` in base-64. The result will either be a `str`,
or `bytes`, depending on the input type (same as input type).
'''
assert isinstance(data, (str, bytes)), \
'data must be str or bytes: %r' % (data)
is_str = isinstance(data, str)
if is_str:
<|code_end|>
, predict the next line using imports from the current file:
import base64
import json
import logging
from ..util.str import (
bytes_to_str,
str_to_bytes,
)
and context including class names, function names, and sometimes code from other files:
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
#
# def str_to_bytes(data):
# '''
# Converts `data` to `bytes`.
#
# If data is a `str`, it is encoded into `bytes`.
# If data is `bytes`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, bytes):
# # already bytes, yay
# return data
# return data.encode()
. Output only the next line. | data = str_to_bytes(data) |
Based on the snippet: <|code_start|> logger.warning(
'ycmd settings template is missing the '
'filetype_whitelist placeholder'
)
ycmd_settings['filetype_whitelist'] = {}
ycmd_settings['filetype_whitelist']['*'] = 1
# BLACKLIST
# Disable for nothing. This plugin will decide what to ignore.
if 'filetype_blacklist' not in ycmd_settings:
logger.warning(
'ycmd settings template is missing the '
'filetype_blacklist placeholder'
)
ycmd_settings['filetype_blacklist'] = {}
# HMAC
# Pass in the hmac parameter. It needs to be base-64 encoded first.
if 'hmac_secret' not in ycmd_settings:
logger.warning(
'ycmd settings template is missing the hmac_secret placeholder'
)
if not isinstance(hmac_secret, bytes):
logger.warning(
'hmac secret was not passed in as binary, it might be incorrect'
)
else:
logger.debug('converting hmac secret to base64')
hmac_secret_binary = hmac_secret
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import os
from ..util.format import base64_encode
from ..util.fs import (
is_directory,
is_file,
load_json_file,
)
from ..util.str import bytes_to_str
and context (classes, functions, sometimes code) from other files:
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
#
# Path: lib/util/fs.py
# def is_directory(path):
# '''
# Returns true if the supplied `path` refers to a valid directory, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isdir(path)
#
# def is_file(path):
# '''
# Returns true if the supplied `path` refers to a valid plain file, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isfile(path)
#
# def load_json_file(path, encoding='utf-8'):
# '''
# Returns a `dict` generated by reading the file at `path`, and then parsing
# it as JSON. This will throw if the file does not exist, cannot be read, or
# cannot be parsed as JSON.
# The `encoding` parameter is used when initially reading the file.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# if not isinstance(encoding, str):
# raise TypeError('encoding must be a str: %r' % (encoding))
#
# path = resolve_env(path)
# if not is_file(path):
# logger.warning('path does not seem to refer to a valid file: %s', path)
# # but fall through and try anyway
#
# logger.debug(
# 'attempting to parse file with path, encoding: %s, %s', path, encoding,
# )
# with open(path, encoding=encoding) as file_handle:
# file_data = json.load(file_handle)
#
# logger.debug('successfully parsed json file')
# return file_data
#
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
. Output only the next line. | hmac_secret_encoded = base64_encode(hmac_secret_binary) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
'''
lib/ycmd/settings.py
Utility functions for ycmd settings.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def get_default_settings_path(ycmd_root_directory):
'''
Generates the path to the default settings json file from the ycmd module.
The `ycmd_root_directory` should refer to the path to the repository.
'''
<|code_end|>
with the help of current file imports:
import logging
import os
from ..util.format import base64_encode
from ..util.fs import (
is_directory,
is_file,
load_json_file,
)
from ..util.str import bytes_to_str
and context from other files:
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
#
# Path: lib/util/fs.py
# def is_directory(path):
# '''
# Returns true if the supplied `path` refers to a valid directory, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isdir(path)
#
# def is_file(path):
# '''
# Returns true if the supplied `path` refers to a valid plain file, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isfile(path)
#
# def load_json_file(path, encoding='utf-8'):
# '''
# Returns a `dict` generated by reading the file at `path`, and then parsing
# it as JSON. This will throw if the file does not exist, cannot be read, or
# cannot be parsed as JSON.
# The `encoding` parameter is used when initially reading the file.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# if not isinstance(encoding, str):
# raise TypeError('encoding must be a str: %r' % (encoding))
#
# path = resolve_env(path)
# if not is_file(path):
# logger.warning('path does not seem to refer to a valid file: %s', path)
# # but fall through and try anyway
#
# logger.debug(
# 'attempting to parse file with path, encoding: %s, %s', path, encoding,
# )
# with open(path, encoding=encoding) as file_handle:
# file_data = json.load(file_handle)
#
# logger.debug('successfully parsed json file')
# return file_data
#
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
, which may contain function names, class names, or code. Output only the next line. | if not is_directory(ycmd_root_directory): |
Given the following code snippet before the placeholder: <|code_start|>Utility functions for ycmd settings.
'''
logger = logging.getLogger('sublime-ycmd.' + __name__)
def get_default_settings_path(ycmd_root_directory):
'''
Generates the path to the default settings json file from the ycmd module.
The `ycmd_root_directory` should refer to the path to the repository.
'''
if not is_directory(ycmd_root_directory):
logger.warning('invalid ycmd root directory: %s', ycmd_root_directory)
# but whatever, fall through and provide the expected path anyway
return os.path.join(ycmd_root_directory, 'ycmd', 'default_settings.json')
def generate_settings_data(ycmd_settings_path, hmac_secret):
'''
Generates and returns a settings `dict` containing the options for
starting a ycmd server. This settings object should be written to a json
file and supplied as a command-line argument to the ycmd module.
The `hmac_secret` argument should be the binary-encoded HMAC secret. It
will be base64-encoded before adding it to the settings object.
'''
assert isinstance(ycmd_settings_path, str), \
'ycmd settings path must be a str: %r' % (ycmd_settings_path)
<|code_end|>
, predict the next line using imports from the current file:
import logging
import os
from ..util.format import base64_encode
from ..util.fs import (
is_directory,
is_file,
load_json_file,
)
from ..util.str import bytes_to_str
and context including class names, function names, and sometimes code from other files:
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
#
# Path: lib/util/fs.py
# def is_directory(path):
# '''
# Returns true if the supplied `path` refers to a valid directory, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isdir(path)
#
# def is_file(path):
# '''
# Returns true if the supplied `path` refers to a valid plain file, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isfile(path)
#
# def load_json_file(path, encoding='utf-8'):
# '''
# Returns a `dict` generated by reading the file at `path`, and then parsing
# it as JSON. This will throw if the file does not exist, cannot be read, or
# cannot be parsed as JSON.
# The `encoding` parameter is used when initially reading the file.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# if not isinstance(encoding, str):
# raise TypeError('encoding must be a str: %r' % (encoding))
#
# path = resolve_env(path)
# if not is_file(path):
# logger.warning('path does not seem to refer to a valid file: %s', path)
# # but fall through and try anyway
#
# logger.debug(
# 'attempting to parse file with path, encoding: %s, %s', path, encoding,
# )
# with open(path, encoding=encoding) as file_handle:
# file_data = json.load(file_handle)
#
# logger.debug('successfully parsed json file')
# return file_data
#
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
. Output only the next line. | if not is_file(ycmd_settings_path): |
Next line prediction: <|code_start|>logger = logging.getLogger('sublime-ycmd.' + __name__)
def get_default_settings_path(ycmd_root_directory):
'''
Generates the path to the default settings json file from the ycmd module.
The `ycmd_root_directory` should refer to the path to the repository.
'''
if not is_directory(ycmd_root_directory):
logger.warning('invalid ycmd root directory: %s', ycmd_root_directory)
# but whatever, fall through and provide the expected path anyway
return os.path.join(ycmd_root_directory, 'ycmd', 'default_settings.json')
def generate_settings_data(ycmd_settings_path, hmac_secret):
'''
Generates and returns a settings `dict` containing the options for
starting a ycmd server. This settings object should be written to a json
file and supplied as a command-line argument to the ycmd module.
The `hmac_secret` argument should be the binary-encoded HMAC secret. It
will be base64-encoded before adding it to the settings object.
'''
assert isinstance(ycmd_settings_path, str), \
'ycmd settings path must be a str: %r' % (ycmd_settings_path)
if not is_file(ycmd_settings_path):
logger.warning(
'ycmd settings path appears to be invalid: %r', ycmd_settings_path
)
<|code_end|>
. Use current file imports:
(import logging
import os
from ..util.format import base64_encode
from ..util.fs import (
is_directory,
is_file,
load_json_file,
)
from ..util.str import bytes_to_str)
and context including class names, function names, or small code snippets from other files:
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
#
# Path: lib/util/fs.py
# def is_directory(path):
# '''
# Returns true if the supplied `path` refers to a valid directory, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isdir(path)
#
# def is_file(path):
# '''
# Returns true if the supplied `path` refers to a valid plain file, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isfile(path)
#
# def load_json_file(path, encoding='utf-8'):
# '''
# Returns a `dict` generated by reading the file at `path`, and then parsing
# it as JSON. This will throw if the file does not exist, cannot be read, or
# cannot be parsed as JSON.
# The `encoding` parameter is used when initially reading the file.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# if not isinstance(encoding, str):
# raise TypeError('encoding must be a str: %r' % (encoding))
#
# path = resolve_env(path)
# if not is_file(path):
# logger.warning('path does not seem to refer to a valid file: %s', path)
# # but fall through and try anyway
#
# logger.debug(
# 'attempting to parse file with path, encoding: %s, %s', path, encoding,
# )
# with open(path, encoding=encoding) as file_handle:
# file_data = json.load(file_handle)
#
# logger.debug('successfully parsed json file')
# return file_data
#
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
. Output only the next line. | ycmd_settings = load_json_file(ycmd_settings_path) |
Next line prediction: <|code_start|> 'ycmd settings template is missing the '
'filetype_whitelist placeholder'
)
ycmd_settings['filetype_whitelist'] = {}
ycmd_settings['filetype_whitelist']['*'] = 1
# BLACKLIST
# Disable for nothing. This plugin will decide what to ignore.
if 'filetype_blacklist' not in ycmd_settings:
logger.warning(
'ycmd settings template is missing the '
'filetype_blacklist placeholder'
)
ycmd_settings['filetype_blacklist'] = {}
# HMAC
# Pass in the hmac parameter. It needs to be base-64 encoded first.
if 'hmac_secret' not in ycmd_settings:
logger.warning(
'ycmd settings template is missing the hmac_secret placeholder'
)
if not isinstance(hmac_secret, bytes):
logger.warning(
'hmac secret was not passed in as binary, it might be incorrect'
)
else:
logger.debug('converting hmac secret to base64')
hmac_secret_binary = hmac_secret
hmac_secret_encoded = base64_encode(hmac_secret_binary)
<|code_end|>
. Use current file imports:
(import logging
import os
from ..util.format import base64_encode
from ..util.fs import (
is_directory,
is_file,
load_json_file,
)
from ..util.str import bytes_to_str)
and context including class names, function names, or small code snippets from other files:
# Path: lib/util/format.py
# def base64_encode(data):
# '''
# Encodes the given `data` in base-64. The result will either be a `str`,
# or `bytes`, depending on the input type (same as input type).
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
#
# is_str = isinstance(data, str)
# if is_str:
# data = str_to_bytes(data)
#
# encoded = base64.b64encode(data)
#
# if is_str:
# encoded = bytes_to_str(encoded)
#
# return encoded
#
# Path: lib/util/fs.py
# def is_directory(path):
# '''
# Returns true if the supplied `path` refers to a valid directory, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isdir(path)
#
# def is_file(path):
# '''
# Returns true if the supplied `path` refers to a valid plain file, and
# false otherwise.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# return os.path.exists(path) and os.path.isfile(path)
#
# def load_json_file(path, encoding='utf-8'):
# '''
# Returns a `dict` generated by reading the file at `path`, and then parsing
# it as JSON. This will throw if the file does not exist, cannot be read, or
# cannot be parsed as JSON.
# The `encoding` parameter is used when initially reading the file.
# '''
# if not isinstance(path, str):
# raise TypeError('path must be a str: %r' % (path))
# if not isinstance(encoding, str):
# raise TypeError('encoding must be a str: %r' % (encoding))
#
# path = resolve_env(path)
# if not is_file(path):
# logger.warning('path does not seem to refer to a valid file: %s', path)
# # but fall through and try anyway
#
# logger.debug(
# 'attempting to parse file with path, encoding: %s, %s', path, encoding,
# )
# with open(path, encoding=encoding) as file_handle:
# file_data = json.load(file_handle)
#
# logger.debug('successfully parsed json file')
# return file_data
#
# Path: lib/util/str.py
# def bytes_to_str(data):
# '''
# Converts `data` to `str`.
#
# If data is a `bytes`, it is decoded into `str`.
# If data is `str`, it is returned as-is.
# '''
# assert isinstance(data, (str, bytes)), \
# 'data must be str or bytes: %r' % (data)
# if isinstance(data, str):
# # already str, yay
# return data
# return data.decode()
. Output only the next line. | hmac_secret_str = bytes_to_str(hmac_secret_encoded) |
Given the following code snippet before the placeholder: <|code_start|>"""plot_expressions.py - make cluster gene expression plots"""
def normalize_js(value):
if math.isnan(value) or math.isinf(value):
return 0.0
else:
return value
def generate_plots(session, result_dir, output_dir):
<|code_end|>
, predict the next line using imports from the current file:
import matplotlib.pyplot as plt
import numpy as np
import os
import math
import cmonkey.database as cm2db
from cmonkey.tools.util import read_ratios
from sqlalchemy import func, and_
and context including class names, function names, and sometimes code from other files:
# Path: cmonkey/tools/util.py
# def read_ratios(result_dir):
# csvpath = os.path.join(result_dir, 'ratios.tsv.gz')
# df = pandas.read_csv(csvpath, index_col=0, sep='\t')
# df.index = map(str, df.index)
# return df
. Output only the next line. | ratios = read_ratios(result_dir) |
Given snippet: <|code_start|> cm_string += '<span class="gaggle-species">' + species + '</span>\n'
cm_string += '<div class="gaggle-namelist"><ol>\n'
cluster_conds = [c.column_name.name for c in session.query(cm2db.ColumnMember).filter(
and_(cm2db.ColumnMember.cluster == cluster, cm2db.ColumnMember.iteration == iteration))]
for col_name in cluster_conds:
cm_string += "<li>" + col_name + "</li>\n"
cm_string += "</ol></div>"
# motifs
m_string = ''
for m in session.query(cm2db.MotifInfo).filter(
and_(cm2db.MotifInfo.cluster == cluster, cm2db.MotifInfo.iteration == iteration)):
m_string += '<div class="gaggle-data motifs">\n'
m_string += '<span class="gaggle-name">%s motif %d (%s)</span>\n' % (runinfo.organism, m.motif_num, m.seqtype)
m_string += '<span class="gaggle-species">' + species + '</span>\n'
m_string += '<div class="gaggle-matrix-tsv">\n'
m_string += "\tPOSITION\tA\tC\tG\tT\n"
for r in m.pssm_rows:
m_string += "%d\t%f\t%f\t%f\t%f\n" % (r.row, r.a, r.c, r.g, r.t)
m_string += "</div></div>\n"
s = templ.substitute(cluster=cluster, row_members=rm_string, column_members=cm_string, motifs=m_string)
with open(os.path.join(output_dir, 'cluster-%03d.html' % cluster), 'w') as outfile:
outfile.write(s)
def cluster_expressions_to_json_file(session, result_dir, output_dir):
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import json
import os
import string
import cmonkey.database as cm2db
from sqlalchemy import func, and_
from cmonkey.tools.util import read_ratios
and context:
# Path: cmonkey/tools/util.py
# def read_ratios(result_dir):
# csvpath = os.path.join(result_dir, 'ratios.tsv.gz')
# df = pandas.read_csv(csvpath, index_col=0, sep='\t')
# df.index = map(str, df.index)
# return df
which might include code, classes, or functions. Output only the next line. | ratios = read_ratios(result_dir) |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/python3
# -*- coding: utf-8 -*-
def model_getter(cls):
def f(x):
if isinstance(x, str) and x.isdigit() or isinstance(x, Number):
return cls.objects.get(pk=x)
<|code_end|>
with the help of current file imports:
from numbers import Number
from floreal import models as m
from django.core.exceptions import PermissionDenied
from typing import Union, Optional
from django.db.models import Q
and context from other files:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
, which may contain function names, class names, or code. Output only the next line. | elif isinstance(cls, m.IdentifiedBySlug): |
Here is a snippet: <|code_start|>sys.path += ["."]
os.environ['DJANGO_SETTINGS_MODULE']='solalim.settings'
django.setup()
months={
"janvier": 1,
"février": 2,
"fevrier": 2,
"mars": 3,
"avril": 4,
"mai": 5,
"juin": 6,
"juillet": 7,
"août": 8,
"aout": 8,
"septembre": 9,
"octobre": 10,
"novembre": 11,
"décembre": 12,
"decembre": 12}
iregex = r"(\d+)\s*("+"|".join(months.keys())+")"
ciregex = re.compile(iregex, re.IGNORECASE)
def sort_deliveries_par_network_and_date():
dsets = {}
<|code_end|>
. Write the next line using the current file imports:
import sys
import os
import django
import re
from floreal import models as m
and context from other files:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
, which may include functions, classes, or code. Output only the next line. | for dv in m.Delivery.objects.filter(name__iregex=iregex): |
Using the snippet: <|code_start|> subkey = x.pk
dump.__dict__.setdefault(key, {})[subkey] = val
return dump
# In [12]: for k, v in dump.__dict__.items():
# ...: first_val = list(v.values())[0]
# ...: subkeys = list(first_val.__dict__.keys())
# ...: print(f"{k}: {', '.join(subkeys)}")
def parse_structure(dump):
# network: name, auto_validate, description, staff
# subgroup: name, network, extra_user, auto_validate, staff, users
# user: password, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined, groups, user_permissions
print(" * filtering and creating users")
USER_FIELDS = "password is_superuser username first_name last_name email is_staff date_joined".split()
purchaser_user_ids = {pc.user for pc in dump.purchase.values()}
staff_user_ids = (
{u for sg in dump.subgroup.values() for u in sg.staff}
| {u for nw in dump.network.values() for u in nw.staff}
| {k for k, v in dump.user.items() if v.is_staff}
)
kept_user_ids = purchaser_user_ids | staff_user_ids
deleted_user_ids = set()
for uid, u in dump.user.items():
if not u.is_active or uid not in kept_user_ids:
deleted_user_ids.add(uid) # Don't bother with people who never bought or left
else:
<|code_end|>
, determine the next line of code. You have imports:
from django.core.management.base import BaseCommand
from types import SimpleNamespace
from floreal import models as m
from markdown import markdown
from django.db import IntegrityError, DataError
import json
import sys
and context (class names, function names, or code) available:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
. Output only the next line. | u_db, _ = m.User.objects.get_or_create( |
Predict the next line for this snippet: <|code_start|> if granted[k] == wishes[k]:
n_unsatisfied -= 1 # He's satisfied now!
# 2nd stage: give the remaining units, one by one, to biggest unsatisfied buyers
got_leftover = sorted(wishes.keys(), key=lambda k: granted[k]-wishes[k])[0:unallocated]
# print ("%i more units to distribute, they will go to %s" % (unallocated, got_leftover))
for k in got_leftover:
granted[k] += 1
unallocated -= 1
# Some invariant checks
if True:
assert unallocated == 0
assert sum(granted.values()) == limit
for k in wishes.keys():
assert granted[k] <= wishes[k]
assert granted[k] <= ceiling+1
return granted
def set_limit(pd, last_pc=None, reallocate=False):
"""
Use `allocate()` to ensure that product `pd` hasn't been granted in amount larger than `limit`.
:param pd: product featuring the quantity limit
"""
# TODO: in case of limitation, first cancel extra users' orders
if pd.quantity_limit is None: # No limit, granted==ordered for everyone
return
<|code_end|>
with the help of current file imports:
from floreal import models as m
and context from other files:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
, which may contain function names, class names, or code. Output only the next line. | purchases = m.Purchase.objects.filter(product=pd)
|
Using the snippet: <|code_start|>def unit_multiple(unit, n=None):
if unit[0].isdigit():
return "×"+unit
else:
return " "+m.plural(unit, n)
@register.filter
def articulate(name, n=None):
return m.articulate(name, n)
@register.filter
def subgroup_state(sg, dv):
x = dv.subgroupstatefordelivery_set.filter(delivery=dv, subgroup=sg)
return x[0].state if x else m.SubgroupStateForDelivery.DEFAULT
@register.filter
def subgroup_has_purchases(sg, dv):
return m.Purchase.objects.filter(product__delivery_id=dv,
user__in=m.Subgroup.objects.get(pk=sg).users.all()).exists()
@register.filter
def is_admin_of(u, nw_or_sg):
return nw_or_sg.staff.filter(id=u.id).exists()
@register.filter
def sort(collection):
return sorted(collection)
@register.filter
def plural(singular):
<|code_end|>
, determine the next line of code. You have imports:
from datetime import datetime, date
from django import template
from django.utils.dateparse import parse_date
from floreal import francais
from floreal import models as m
and context (class names, function names, or code) available:
# Path: floreal/francais.py
# class Plural(models.Model):
# def __str__(self):
# def plural(noun, n=None):
# def articulate(noun, n=1):
#
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
. Output only the next line. | return francais.plural(singular, 2) |
Based on the snippet: <|code_start|>@register.filter
def several(x):
return len(x) > 1
@register.filter
def forced_sign(f):
return "%+g" % f
@register.filter
def price(f):
return "%.02f€" % f
@register.filter
def price_nocurrency(f):
return "%.02f" % f
@register.filter
def weight(w):
if w>=1: return "%.2gkg" % w
else: return "%dg" % (w*1000)
@register.filter
def email(u):
return '"%s %s" <%s>' % (u.first_name, u.last_name, u.email)
@register.filter
def unit_multiple(unit, n=None):
if unit[0].isdigit():
return "×"+unit
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from datetime import datetime, date
from django import template
from django.utils.dateparse import parse_date
from floreal import francais
from floreal import models as m
and context (classes, functions, sometimes code) from other files:
# Path: floreal/francais.py
# class Plural(models.Model):
# def __str__(self):
# def plural(noun, n=None):
# def articulate(noun, n=1):
#
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
. Output only the next line. | return " "+m.plural(unit, n) |
Based on the snippet: <|code_start|> dump.__dict__.setdefault(key, {})[subkey] = val
return dump
# In [12]: for k, v in dump.__dict__.items():
# ...: first_val = list(v.values())[0]
# ...: subkeys = list(first_val.__dict__.keys())
# ...: print(f"{k}: {', '.join(subkeys)}")
def parse_u(dump):
# user: password, last_login, is_superuser, username, first_name, last_name, email, is_staff, is_active, date_joined, groups, user_permissions
print(" * filtering and creating users")
USER_FIELDS = "password is_superuser username first_name last_name email is_staff date_joined".split()
purchaser_user_ids = {pc.user for pc in dump.purchase.values()}
staff_user_ids = (
{u for sg in dump.subgroup.values() for u in sg.staff}
| {u for nw in dump.network.values() for u in nw.staff}
| {k for k, v in dump.user.items() if v.is_staff}
)
candidate_user_ids = {cd.user for cd in dump.candidacy.values()}
kept_user_ids = purchaser_user_ids | staff_user_ids | candidate_user_ids
deleted_user_ids = set()
for uid, u in dump.user.items():
if not u.is_active or uid not in kept_user_ids:
deleted_user_ids.add(
uid
) # Don't bother with people who never bought or left
else:
<|code_end|>
, predict the immediate next line with the help of imports:
from django.core.management.base import BaseCommand
from types import SimpleNamespace
from floreal import models as m
from markdown import markdown
from django.db import IntegrityError, DataError
import json
import sys
and context (classes, functions, sometimes code) from other files:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
. Output only the next line. | u_db, _ = m.User.objects.get_or_create( |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def render_text(template_name, ctx):
t = get_template(template_name)
text_unicode = t.render(ctx)
return text_unicode
def non_html_response(name_bits, name_extension, content):
"""Common helper to serve PDF and Excel content."""
mime_type = "text/plain; charset=utf-8"
response = HttpResponse(content_type=mime_type)
response.write(content)
return response
def invoice_mail_form(request, network):
nw = get_network(network)
if request.method == "POST":
P = request.POST
recipients = {u.strip() for u in P["recipients"].split(",")}
return send_invoice_mail(
request, network, recipients, P["subject"], P["body"]
)
else:
<|code_end|>
. Use current file imports:
(from floreal import models as m
from collections import defaultdict
from django.template.loader import get_template
from django.http import HttpResponse
from django.core.mail import send_mail, send_mass_mail
from django.conf import settings
from django.shortcuts import redirect, render
from .getters import get_network
from django.template.context_processors import csrf
from django.template.base import Template
from django.template.context import Context)
and context including class names, function names, or small code snippets from other files:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
#
# Path: floreal/views/getters.py
# def model_getter(cls):
# def f(x):
# def must_be_prod_or_staff(request, network=None):
# def must_be_staff(request, network: Union[m.Network, int, str, None] = None) -> None:
. Output only the next line. | deliveries = m.Delivery.objects.filter(network_id=network, state=m.Delivery.FROZEN) |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
def render_text(template_name, ctx):
t = get_template(template_name)
text_unicode = t.render(ctx)
return text_unicode
def non_html_response(name_bits, name_extension, content):
"""Common helper to serve PDF and Excel content."""
mime_type = "text/plain; charset=utf-8"
response = HttpResponse(content_type=mime_type)
response.write(content)
return response
def invoice_mail_form(request, network):
<|code_end|>
, determine the next line of code. You have imports:
from floreal import models as m
from collections import defaultdict
from django.template.loader import get_template
from django.http import HttpResponse
from django.core.mail import send_mail, send_mass_mail
from django.conf import settings
from django.shortcuts import redirect, render
from .getters import get_network
from django.template.context_processors import csrf
from django.template.base import Template
from django.template.context import Context
and context (class names, function names, or code) available:
# Path: floreal/models.py
# class IdentifiedBySlug(models.Model):
# class Meta:
# class Mapped(models.Model):
# class Meta:
# class FlorealUser(IdentifiedBySlug, Mapped):
# class NetworkSubgroup(IdentifiedBySlug):
# class Meta:
# class NetworkMembership(models.Model):
# class Meta:
# class Network(IdentifiedBySlug, Mapped):
# class Meta:
# class Delivery(IdentifiedBySlug):
# class Meta:
# class Product(models.Model):
# class Meta:
# class Purchase(models.Model):
# class Meta:
# class Bestof(models.Model):
# class Meta:
# class JournalEntry(models.Model):
# class AdminMessage(models.Model):
# def slug_prefix(self):
# def save(self, **kwargs):
# def __str__(self):
# def slug_prefix(self):
# def display_name(self):
# def display_number(self):
# def uri(self):
# def has_some_admin_rights(self):
# def __str__(self) -> str:
# def __str__(self):
# def __str__(self):
# def description_text(self):
# def grouped(self):
# def save(self, **kwargs):
# def __str__(self):
# def state_name(self):
# def description_text(self):
# def freeze_overdue_deliveries(cls):
# def __str__(self):
# def _normalize_unit(cls, u):
# def save(
# self, force_insert=False, force_update=False, using=None, update_fields=None
# ):
# def left(self):
# def description_text(self):
# def price(self):
# def weight(self):
# def packages(self):
# def out_of_package(self):
# def max_quantity(self):
# def __str__(self, specify_user=False):
# def __str__(self):
# def update(cls):
# def log(cls, u, fmt, *args, **kwargs):
# def __str__(self):
# def __str__(self):
# (PREPARATION, ORDERING_ALL, ORDERING_ADMIN, FROZEN, TERMINATED) = "ABCDE"
# STATE_CHOICES = {
# PREPARATION: "En préparation",
# ORDERING_ALL: "Ouverte",
# ORDERING_ADMIN: "Admins",
# FROZEN: "Gelée",
# TERMINATED: "Terminée",
# }
# UNIT_AUTO_TRANSLATE = {
# "1": "pièce",
# "piece": "pièce",
# "kilo": "kg",
# "gr": "g",
# "unité": "pièce",
# "unite": "pièce",
# }
# UNIT_TRANSLATE_REGEXP = re.compile(r"""
# ^
# ([0-9]+)
# (?: [,.] ([0-9]+) )?
# \s*
# ([A-Za-z]+)
# $""", re.VERBOSE)
#
# Path: floreal/views/getters.py
# def model_getter(cls):
# def f(x):
# def must_be_prod_or_staff(request, network=None):
# def must_be_staff(request, network: Union[m.Network, int, str, None] = None) -> None:
. Output only the next line. | nw = get_network(network) |
Given the code snippet: <|code_start|># Generated by Django 3.2.6 on 2021-08-26 16:32
def load_villes(apps, schema_editor):
fixtures = Path(__file__).parent / 'villes.json.gz'
print(" Populating database...")
<|code_end|>
, generate the next line using the imports in this file:
from pathlib import Path
from django.db import migrations
from django.core.management import call_command
from ..models import Ville
and context (functions, classes, or occasionally code) from other files:
# Path: villes/models.py
# class Ville(models.Model):
# id = models.IntegerField(db_column="ville_id", primary_key=True)
# departement = models.CharField(
# db_column="ville_departement", max_length=3, blank=True, null=True
# )
# slug = models.CharField(
# db_column="ville_slug", max_length=255, blank=True, null=True
# )
# nom = models.CharField(db_column="ville_nom", max_length=45, blank=True, null=True)
# nom_simple = models.CharField(
# db_column="ville_nom_simple", max_length=45, blank=True, null=True
# )
# nom_reel = models.CharField(
# db_column="ville_nom_reel", max_length=45, blank=True, null=True
# )
# nom_soundex = models.CharField(
# db_column="ville_nom_soundex", max_length=20, blank=True, null=True
# )
# nom_metaphone = models.CharField(
# db_column="ville_nom_metaphone", max_length=22, blank=True, null=True
# )
# code_postal = models.CharField(
# db_column="ville_code_postal", max_length=255, blank=True, null=True
# )
# commune = models.CharField(
# db_column="ville_commune", max_length=3, blank=True, null=True
# )
# code_commune = models.CharField(db_column="ville_code_commune", max_length=5)
# arrondissement = models.IntegerField(
# db_column="ville_arrondissement", blank=True, null=True
# )
# canton = models.CharField(
# db_column="ville_canton", max_length=4, blank=True, null=True
# )
# amdi = models.IntegerField(db_column="ville_amdi", blank=True, null=True)
# population_2010 = models.IntegerField(
# db_column="ville_population_2010", blank=True, null=True
# )
# population_1999 = models.IntegerField(
# db_column="ville_population_1999", blank=True, null=True
# )
# population_2012 = models.IntegerField(
# db_column="ville_population_2012", blank=True, null=True
# )
# densite_2010 = models.IntegerField(
# db_column="ville_densite_2010", blank=True, null=True
# )
# surface = models.FloatField(db_column="ville_surface", blank=True, null=True)
# longitude_deg = models.FloatField(
# db_column="ville_longitude_deg", blank=True, null=True
# )
# latitude_deg = models.FloatField(
# db_column="ville_latitude_deg", blank=True, null=True
# )
# longitude_grd = models.CharField(
# db_column="ville_longitude_grd", max_length=9, blank=True, null=True
# )
# latitude_grd = models.CharField(
# db_column="ville_latitude_grd", max_length=8, blank=True, null=True
# )
# longitude_dms = models.CharField(
# db_column="ville_longitude_dms", max_length=9, blank=True, null=True
# )
# latitude_dms = models.CharField(
# db_column="ville_latitude_dms", max_length=8, blank=True, null=True
# )
# zmin = models.IntegerField(db_column="ville_zmin", blank=True, null=True)
# zmax = models.IntegerField(db_column="ville_zmax", blank=True, null=True)
#
# class Meta:
# db_table = "villes_france_free"
# indexes = [
# models.Index(fields=["departement"], name="departement_idx"),
# models.Index(fields=["slug"], name="slug_idx"),
# models.Index(fields=["nom"], name="nom_idx"),
# models.Index(fields=["nom_simple"], name="nom_simple_idx"),
# models.Index(fields=["nom_reel"], name="nom_reel_idx"),
# models.Index(fields=["nom_soundex"], name="nom_soundex_idx"),
# models.Index(fields=["nom_metaphone"], name="nom_metaphone_idx"),
# models.Index(fields=["code_postal"], name="code_postal_idx"),
# models.Index(fields=["commune"], name="commune_idx"),
# models.Index(fields=["code_commune"], name="code_commune_idx"),
# models.Index(fields=["arrondissement"], name="arrondissement_idx"),
# models.Index(fields=["canton"], name="canton_idx"),
# models.Index(fields=["amdi"], name="amdi_idx"),
# # models.Index(fields=['population_2010'], name='population_2010_idx'),
# # models.Index(fields=['population_1999'], name='population_1999_idx'),
# # models.Index(fields=['population_2012'], name='population_2012_idx'),
# # models.Index(fields=['densite_2010'], name='densite_2010_idx'),
# # models.Index(fields=['surface'], name='surface_idx'),
# # models.Index(fields=['longitude_deg'], name='longitude_deg_idx'),
# # models.Index(fields=['latitude_deg'], name='latitude_deg_idx'),
# # models.Index(fields=['longitude_grd'], name='longitude_grd_idx'),
# # models.Index(fields=['latitude_grd'], name='latitude_grd_idx'),
# # models.Index(fields=['longitude_dms'], name='longitude_dms_idx'),
# # models.Index(fields=['latitude_dms'], name='latitude_dms_idx'),
# # models.Index(fields=['zmin'], name='zmin_idx'),
# # models.Index(fields=['zmax'], name='zmax_idx'),
# ]
#
# def __str__(self):
# return self.nom_reel + " " + self.code_postal
. Output only the next line. | Ville.objects.all().delete() # In case of partially loaded or corrupted data |
Using the snippet: <|code_start|># import logging
# logger = logging.getLogger("nextion").getChild(__name__)
class EventType(IntEnum):
TOUCH = 0x65 # Touch event
TOUCH_COORDINATE = 0x67 # Touch coordinate
TOUCH_IN_SLEEP = 0x68 # Touch event in sleep mode
AUTO_SLEEP = 0x86 # Device automatically enters into sleep mode
AUTO_WAKE = 0x87 # Device automatically wake up
STARTUP = 0x88 # System successful start up
SD_CARD_UPGRADE = 0x89 # Start SD card upgrade
class ResponseType(IntEnum):
STRING = 0x70
NUMBER = 0x71
PAGE = 0x66
<|code_end|>
, determine the next line of code. You have imports:
import binascii
import typing
from enum import IntEnum
from .base import BasicProtocol
from main.pi_ager_cl_logger import cl_fact_logger
and context (class names, function names, or code) available:
# Path: opt/pi-ager/pi_ager_nextion/protocol/base.py
# class BasicProtocol(asyncio.Protocol):
# def __init__(self):
# self.transport = None
# self.queue = asyncio.Queue()
# self.connect_future = asyncio.get_event_loop().create_future()
# self.disconnect_future = asyncio.get_event_loop().create_future()
#
# async def close(self):
# if self.transport:
# self.transport.close()
#
# await self.disconnect_future
#
# async def wait_connection(self):
# await self.connect_future
#
# def connection_made(self, transport):
# self.transport = transport
# cl_fact_logger.get_instance().info("Connected to serial")
# self.connect_future.set_result(True)
#
# def data_received(self, data):
# cl_fact_logger.get_instance().debug("received: %s", binascii.hexlify(data))
# self.queue.put_nowait(data)
#
# def read_no_wait(self) -> bytes:
# return self.queue.get_nowait()
#
# async def read(self) -> bytes:
# return await self.queue.get()
#
# def write(self, data: bytes, eol=True):
# assert isinstance(data, bytes)
# self.transport.write(data)
# cl_fact_logger.get_instance().debug("sent: %d bytes", len(data))
#
# def connection_lost(self, exc):
# cl_fact_logger.get_instance().error("Connection lost")
# if not self.connect_future.done():
# self.connect_future.set_result(False)
# # self.connect_future = asyncio.get_event_loop().create_future()
# if not self.disconnect_future.done():
# self.disconnect_future.set_result(True)
. Output only the next line. | class NextionProtocol(BasicProtocol): |
Continue the code snippet: <|code_start|># hash_to_ipv4 - Return IP associated with <Hash> #
# hash_to_score - Return Score to given <Hash> #
#################################################################
class Ibmxforce(object):
def __init__(self):
# lists of values that can be returned
self.ipv4_list = []
self.ipv6_list = []
self.domain_list = []
self.hash_list = []
self.url_list = []
self.score_list = []
self.imphash_list = []
# get helping functions
self.api = helpers.Common()
# static station settings
self.station_name = 'IBM X-Force'
self.endpoint = 'https://xforce-api.mybluemix.net:443'
self.url_path = ''
self.parameters = {}
self.headers = {'Accept': 'application/json'}
self.user_agent = {}
self.response_format = 'json'
<|code_end|>
. Use current file imports:
from lib import config, helpers
and context (classes, functions, or code) from other files:
# Path: lib/config.py
#
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
. Output only the next line. | if config.ibmxforce_token: |
Next line prediction: <|code_start|># Author: 10TOHH #
# #
# Tunes: #
# domain_to_ipv4 - Resolves IP to <Domain> #
# domain_to_hash - Return Hash to <Domain> #
# domain_to_score - Return Score to <Domain> #
# #
# ipv4_to_domain - Resolves Domain to <IP> #
# ipv4_to_score - Return Score to <IP> #
# ipv4_to_hash - Return Hash associated with <IP> #
# #
# hash_to_ipv4 - Return IP associated with <Hash> #
# hash_to_score - Return Score to given <Hash> #
#################################################################
class Ibmxforce(object):
def __init__(self):
# lists of values that can be returned
self.ipv4_list = []
self.ipv6_list = []
self.domain_list = []
self.hash_list = []
self.url_list = []
self.score_list = []
self.imphash_list = []
# get helping functions
<|code_end|>
. Use current file imports:
(from lib import config, helpers)
and context including class names, function names, or small code snippets from other files:
# Path: lib/config.py
#
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
. Output only the next line. | self.api = helpers.Common() |
Predict the next line for this snippet: <|code_start|> self.ma = Mcafee()
# Check IPv4 in blacklist tunes
def ipv4_blacklist_check(self, ip_address):
if self.a.ipv4_to_blacklist(ip_address):
return True
elif self.f.ipv4_to_blacklist(ip_address):
return True
elif self.m.ipv4_to_blacklist(ip_address):
return True
elif self.z.ipv4_to_blacklist(ip_address):
return True
elif self.ma.ipv4_to_blacklist(ip_address):
return True
else:
return False
# Check Domain in blacklist tunes
def domain_blacklist_check(self, domain_name):
if self.ma.domain_to_blacklist(domain_name):
return True
else:
return False
#########################################################
# Station tunes
class Asprox(object):
def __init__(self):
# get helping functions
<|code_end|>
with the help of current file imports:
from lib import helpers
import re
and context from other files:
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
, which may contain function names, class names, or code. Output only the next line. | self.api = helpers.Common() |
Given the following code snippet before the placeholder: <|code_start|># #
# Tunes: #
# domain_to_hash - Return Hash to <Domain> #
# #
# ipv4_to_hash - Return Hash associated with <IP> #
# #
# hash_to_ipv4 - Return IP associated with <Hash> #
# hash_to_domain - Return Domain associated with <Hash> #
# hash_to_url - Return URL to report for given <Hash> #
# hash_to_score - Return Score to given <Hash> #
# #
# imphash_to_hash - Return Hash associated with <Imphash> #
# - Not in QRadio main #
# mutex_to_hash - Return Hash associated with <Mutex> #
# - Not in QRadio main #
#################################################################
class Threatexpert(object):
def __init__(self):
# lists of values that can be returned
self.ip_list = []
self.domain_list = []
self.hash_list = []
self.url_list = []
self.score_list = []
self.imphash_list = []
# get helping functions
<|code_end|>
, predict the next line using imports from the current file:
from lib import helpers
import re
and context including class names, function names, and sometimes code from other files:
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
. Output only the next line. | self.api = helpers.Common() |
Predict the next line after this snippet: <|code_start|># mutex_to_hash - Return Hash associated with <Mutex> #
#################################################################
class Totalhash(object):
def __init__(self):
# lists of values that can be returned
self.ip_list = []
self.domain_list = []
self.hash_list = []
self.url_list = []
self.score_list = []
self.imphash_list = []
# get helping functions
self.api = helpers.Common()
self.error_log = helpers.IO()
# static station settings
self.station_name = 'Totalhash'
self.endpoint = 'https://api.totalhash.com/search/'
self.path = ''
self.parameters = {}
self.headers = {}
self.user_agent = {}
self.response_format = ''
def signature(self, searching_query):
<|code_end|>
using the current file's imports:
import hmac
import hashlib
import xmltodict
import re
from lib import config, helpers
and any relevant context from other files:
# Path: lib/config.py
#
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
. Output only the next line. | if config.totalhash_api_key: |
Continue the code snippet: <|code_start|># Tunes: #
# domain_to_hash - Return Hash to <Domain> #
# domain_to_url - Return URL to report for given <Domain> #
# #
# ipv4_to_hash - Return Hash associated with <IP> #
# ipv4_to_url - Return URL to report for given <IP> #
# #
# hash_to_ipv4 - Return IP associated with <Hash> #
# hash_to_imphash - Return Imphash associated with <Hash> #
# hash_to_url - Return URL to report for given <Hash> #
# hash_to_domain - Return Domain associated with <Hash> #
# #
# imphash_to_hash - Return Hash associated with <Imphash> #
# mutex_to_hash - Return Hash associated with <Mutex> #
#################################################################
class Totalhash(object):
def __init__(self):
# lists of values that can be returned
self.ip_list = []
self.domain_list = []
self.hash_list = []
self.url_list = []
self.score_list = []
self.imphash_list = []
# get helping functions
<|code_end|>
. Use current file imports:
import hmac
import hashlib
import xmltodict
import re
from lib import config, helpers
and context (classes, functions, or code) from other files:
# Path: lib/config.py
#
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
. Output only the next line. | self.api = helpers.Common() |
Given the following code snippet before the placeholder: <|code_start|>#################################################################
class Cymon(object):
def __init__(self):
# lists of values that can be returned
self.ip_list = []
self.domain_list = []
self.hash_list = []
self.url_list = []
self.score_list = []
self.imphash_list = []
# get helping functions
self.api = helpers.Common()
self.error_log = helpers.IO()
# static station settings
self.station_name = 'Cymon'
self.endpoint = 'https://cymon.io/api/nexus/v1/'
self.url_path = ''
self.parameters = {'limit': '1000'}
self.headers = {'content-type': 'application/json',
'accept': 'application/json',
}
self.user_agent = {}
self.return_format = 'json'
# Check for api key
<|code_end|>
, predict the next line using imports from the current file:
from lib import config, helpers
and context including class names, function names, and sometimes code from other files:
# Path: lib/config.py
#
# Path: lib/helpers.py
# class Common(object):
# class IO(object):
# class MaltegoEntity(object):
# class MaltegoTransform(object):
# def session_helper(self, station_name=None, # station_name - REQUIRE - 'Station_name'
# endpoint=None, # 'https://station.com/api/search/index.php'
# method_type=None, # GET/POST
# data_to_send=None, # Data to sent in POST
# url_path=None, # '/api/search/google.com'
# parameters=None, # {'limit': '1000'}
# headers=None, # {'api_key': 'api_key_value'}
# user_agent=None, # {'User-agent': 'VxStream Sandbox'}
# response_format=None, # json or bs(BeautifulSoup)
# go_to_url=None): # https://www.station.com/index.php?a=somethins&d=something
# def verbose_output(self, search_value, search_from, search_to, dictionary):
# def nonverbose_output(self, search_value, search_from, search_to, dictionary):
# def error_log(self, error, station_name=None):
# def process_file(self, file_path):
# def input_validator(self,input_value):
# def __init__(self,eT=None,v=None):
# def setType(self,eT=None):
# def setValue(self,eV=None):
# def setWeight(self,w=None):
# def setDisplayInformation(self,di=None):
# def addAdditionalFields(self,fieldName=None,displayName=None,matchingRule='',value=None):
# def setIconURL(self,iU=None):
# def setLinkColor(self,color):
# def setLinkStyle(self,style):
# def setLinkThickness(self,thick):
# def setLinkLabel(self,label):
# def setBookmark(self,bookmark):
# def setNote(self,note):
# def returnEntity(self):
# def __init__(self):
# def parseArguments(self,argv):
# def getValue(self):
# def getVar(self,varName):
# def addEntity(self,enType,enValue):
# def addEntityToMessage(self,maltegoEntity):
# def addUIMessage(self,message,messageType="Inform"):
# def addException(self,exceptionString):
# def throwExceptions(self):
# def returnOutput(self):
# def writeSTDERR(self,msg):
# def heartbeat(self):
# def progress(self,percent):
# def debug(self,msg):
# def sanitise(self, value):
# BOOKMARK_COLOR_NONE="-1"
# BOOKMARK_COLOR_BLUE="0"
# BOOKMARK_COLOR_GREEN="1"
# BOOKMARK_COLOR_YELLOW="2"
# BOOKMARK_COLOR_ORANGE="3"
# BOOKMARK_COLOR_RED="4"
# LINK_STYLE_NORMAL="0"
# LINK_STYLE_DASHED="1"
# LINK_STYLE_DOTTED="2"
# LINK_STYLE_DASHDOT="3"
# UIM_FATAL='FatalError'
# UIM_PARTIAL='PartialError'
# UIM_INFORM='Inform'
# UIM_DEBUG='Debug'
. Output only the next line. | if config.cymon_api_key: |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.