Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Given the following code snippet before the placeholder: <|code_start|>
def test_create():
db = DB()
user = create_user()
title = random_string(10)
blog_id = BlogAction.create(
db,
owner_id=user.id,
title=title,
)
found_blog = BlogLoader.find_by_id(db, blog_id)
<|code_end|>
, predict the next line using imports from the current file:
import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.loader.user import UserLoader
from hakoblog.action.blog import BlogAction
from hakoblog.loader.blog import BlogLoader
from tests.util import random_string, create_user, global_user
and context including class names, function names, and sometimes code from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/loader/user.py
# class UserLoader:
# @classmethod
# def find_by_name(cls, db, name):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, name
# FROM user
# WHERE name = %s
# LIMIT 1
# """,
# (name,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return User(**row)
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/blog.py
# class BlogLoader:
# @classmethod
# def find_by_id(cls, db, blog_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE id = %s
# LIMIT 1
# """,
# (blog_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# @classmethod
# def find_by_owner_id(cls, db, owner_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE owner_id = %s
# LIMIT 1
# """,
# (owner_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# Path: tests/util.py
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
#
# def create_user():
# db = DB()
# name = random_string(10)
# UserAction.create(db, name)
# return UserLoader.find_by_name(db, name)
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
. Output only the next line. | assert found_blog.id == blog_id |
Based on the snippet: <|code_start|>
def test_create():
db = DB()
user = create_user()
title = random_string(10)
blog_id = BlogAction.create(
db,
owner_id=user.id,
title=title,
<|code_end|>
, predict the immediate next line with the help of imports:
import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.loader.user import UserLoader
from hakoblog.action.blog import BlogAction
from hakoblog.loader.blog import BlogLoader
from tests.util import random_string, create_user, global_user
and context (classes, functions, sometimes code) from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/loader/user.py
# class UserLoader:
# @classmethod
# def find_by_name(cls, db, name):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, name
# FROM user
# WHERE name = %s
# LIMIT 1
# """,
# (name,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return User(**row)
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/blog.py
# class BlogLoader:
# @classmethod
# def find_by_id(cls, db, blog_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE id = %s
# LIMIT 1
# """,
# (blog_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# @classmethod
# def find_by_owner_id(cls, db, owner_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE owner_id = %s
# LIMIT 1
# """,
# (owner_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# Path: tests/util.py
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
#
# def create_user():
# db = DB()
# name = random_string(10)
# UserAction.create(db, name)
# return UserLoader.find_by_name(db, name)
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
. Output only the next line. | ) |
Using the snippet: <|code_start|>
def test_create():
db = DB()
user = create_user()
title = random_string(10)
blog_id = BlogAction.create(
db,
owner_id=user.id,
title=title,
)
found_blog = BlogLoader.find_by_id(db, blog_id)
assert found_blog.id == blog_id
<|code_end|>
, determine the next line of code. You have imports:
import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.loader.user import UserLoader
from hakoblog.action.blog import BlogAction
from hakoblog.loader.blog import BlogLoader
from tests.util import random_string, create_user, global_user
and context (class names, function names, or code) available:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/loader/user.py
# class UserLoader:
# @classmethod
# def find_by_name(cls, db, name):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, name
# FROM user
# WHERE name = %s
# LIMIT 1
# """,
# (name,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return User(**row)
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/blog.py
# class BlogLoader:
# @classmethod
# def find_by_id(cls, db, blog_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE id = %s
# LIMIT 1
# """,
# (blog_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# @classmethod
# def find_by_owner_id(cls, db, owner_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE owner_id = %s
# LIMIT 1
# """,
# (owner_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# Path: tests/util.py
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
#
# def create_user():
# db = DB()
# name = random_string(10)
# UserAction.create(db, name)
# return UserLoader.find_by_name(db, name)
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
. Output only the next line. | assert found_blog.owner_id == user.id |
Given the following code snippet before the placeholder: <|code_start|>
def test_create():
db = DB()
user = create_user()
title = random_string(10)
blog_id = BlogAction.create(
db,
<|code_end|>
, predict the next line using imports from the current file:
import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.loader.user import UserLoader
from hakoblog.action.blog import BlogAction
from hakoblog.loader.blog import BlogLoader
from tests.util import random_string, create_user, global_user
and context including class names, function names, and sometimes code from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/loader/user.py
# class UserLoader:
# @classmethod
# def find_by_name(cls, db, name):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, name
# FROM user
# WHERE name = %s
# LIMIT 1
# """,
# (name,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return User(**row)
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/blog.py
# class BlogLoader:
# @classmethod
# def find_by_id(cls, db, blog_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE id = %s
# LIMIT 1
# """,
# (blog_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# @classmethod
# def find_by_owner_id(cls, db, owner_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE owner_id = %s
# LIMIT 1
# """,
# (owner_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# Path: tests/util.py
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
#
# def create_user():
# db = DB()
# name = random_string(10)
# UserAction.create(db, name)
# return UserLoader.find_by_name(db, name)
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
. Output only the next line. | owner_id=user.id, |
Using the snippet: <|code_start|>
def test_create():
db = DB()
user = create_user()
title = random_string(10)
blog_id = BlogAction.create(
db,
owner_id=user.id,
title=title,
)
found_blog = BlogLoader.find_by_id(db, blog_id)
assert found_blog.id == blog_id
<|code_end|>
, determine the next line of code. You have imports:
import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.loader.user import UserLoader
from hakoblog.action.blog import BlogAction
from hakoblog.loader.blog import BlogLoader
from tests.util import random_string, create_user, global_user
and context (class names, function names, or code) available:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/loader/user.py
# class UserLoader:
# @classmethod
# def find_by_name(cls, db, name):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, name
# FROM user
# WHERE name = %s
# LIMIT 1
# """,
# (name,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return User(**row)
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/blog.py
# class BlogLoader:
# @classmethod
# def find_by_id(cls, db, blog_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE id = %s
# LIMIT 1
# """,
# (blog_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# @classmethod
# def find_by_owner_id(cls, db, owner_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE owner_id = %s
# LIMIT 1
# """,
# (owner_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# Path: tests/util.py
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
#
# def create_user():
# db = DB()
# name = random_string(10)
# UserAction.create(db, name)
# return UserLoader.find_by_name(db, name)
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
. Output only the next line. | assert found_blog.owner_id == user.id |
Predict the next line after this snippet: <|code_start|>
def test_create():
db = DB()
user = create_user()
title = random_string(10)
blog_id = BlogAction.create(
db,
owner_id=user.id,
<|code_end|>
using the current file's imports:
import tests.hakoblog # noqa: F401
from hakoblog.db import DB
from hakoblog.loader.user import UserLoader
from hakoblog.action.blog import BlogAction
from hakoblog.loader.blog import BlogLoader
from tests.util import random_string, create_user, global_user
and any relevant context from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/loader/user.py
# class UserLoader:
# @classmethod
# def find_by_name(cls, db, name):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, name
# FROM user
# WHERE name = %s
# LIMIT 1
# """,
# (name,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return User(**row)
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/blog.py
# class BlogLoader:
# @classmethod
# def find_by_id(cls, db, blog_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE id = %s
# LIMIT 1
# """,
# (blog_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# @classmethod
# def find_by_owner_id(cls, db, owner_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, owner_id, title
# FROM blog
# WHERE owner_id = %s
# LIMIT 1
# """,
# (owner_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Blog(**row)
#
# Path: tests/util.py
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
#
# def create_user():
# db = DB()
# name = random_string(10)
# UserAction.create(db, name)
# return UserLoader.find_by_name(db, name)
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
. Output only the next line. | title=title, |
Predict the next line after this snippet: <|code_start|>
def test_security_header():
with global_user(random_string(5)):
res = web_client().get('/')
assert res.status == '200 OK'
assert res.headers['X-Frame-Options'] == 'DENY'
assert res.headers['X-Content-Type-Options'] == 'nosniff'
assert res.headers['X-XSS-Protection'] == '1;mode=block'
<|code_end|>
using the current file's imports:
import tests.hakoblog # noqa: F401
from tests.util import web_client, global_user, random_string
and any relevant context from other files:
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | assert res.headers['Content-Security-Policy'] == "default-src 'self'" |
Based on the snippet: <|code_start|>
def test_security_header():
with global_user(random_string(5)):
res = web_client().get('/')
assert res.status == '200 OK'
assert res.headers['X-Frame-Options'] == 'DENY'
<|code_end|>
, predict the immediate next line with the help of imports:
import tests.hakoblog # noqa: F401
from tests.util import web_client, global_user, random_string
and context (classes, functions, sometimes code) from other files:
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | assert res.headers['X-Content-Type-Options'] == 'nosniff' |
Continue the code snippet: <|code_start|>
def test_security_header():
with global_user(random_string(5)):
res = web_client().get('/')
assert res.status == '200 OK'
assert res.headers['X-Frame-Options'] == 'DENY'
<|code_end|>
. Use current file imports:
import tests.hakoblog # noqa: F401
from tests.util import web_client, global_user, random_string
and context (classes, functions, or code) from other files:
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | assert res.headers['X-Content-Type-Options'] == 'nosniff' |
Using the snippet: <|code_start|>
class DB:
def __init__(self):
self.conn = MySQLdb.connect(
db=CONFIG.DATABASE,
host=CONFIG.DATABASE_HOST,
user=CONFIG.DATABASE_USER,
password=CONFIG.DATABASE_PASS,
<|code_end|>
, determine the next line of code. You have imports:
import MySQLdb
import MySQLdb.cursors
from hakoblog.config import CONFIG
and context (class names, function names, or code) available:
# Path: hakoblog/config.py
# CONFIG = config()
. Output only the next line. | cursorclass=MySQLdb.cursors.DictCursor, |
Given snippet: <|code_start|>
@web.route("/entry/<int:entry_id>")
def entry(entry_id):
blog = BlogAction.ensure_global_blog_created(get_db())
entry = EntryLoader.find_by_id(get_db(), entry_id)
if entry is None:
abort(404)
if entry.blog_id != blog.id:
abort(403)
return render_template("entry.html", blog=blog, entry=entry)
@web.route("/-/post", methods=["GET"])
def post_get():
blog = BlogAction.ensure_global_blog_created(get_db())
return render_template("post.html", blog=blog)
@web.route("/-/post", methods=["POST"])
def post_post():
blog = BlogAction.ensure_global_blog_created(get_db())
title = request.form["title"]
body = request.form["body"]
blog_id = int(request.form["blog_id"])
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import (
Flask,
g as flask_g,
render_template,
request,
abort,
url_for,
redirect,
)
from hakoblog.db import DB
from hakoblog.config import CONFIG
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from hakoblog.action.entry import EntryAction
and context:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/config.py
# CONFIG = config()
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: hakoblog/action/entry.py
# class EntryAction:
# @classmethod
# def post(cls, db, blog_id, title, body):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO entry (
# id, blog_id, title, body, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s, %s
# )
# """,
# (new_id, blog_id, title, body, now, now),
# )
# return new_id
#
# @classmethod
# def edit(cls, db, entry_id, title, body):
# now = datetime.now()
# with db.cursor() as cursor:
# cursor.execute(
# """
# UPDATE entry SET
# title = %s,
# body = %s,
# modified = %s
# WHERE id = %s
# """,
# (title, body, now, entry_id),
# )
#
# @classmethod
# def delete(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# DELETE FROM entry
# WHERE id = %s
# """,
# (entry_id,),
# )
which might include code, classes, or functions. Output only the next line. | if int(blog_id) != blog.id: |
Predict the next line for this snippet: <|code_start|>
web = Flask(__name__)
web.config.from_object(CONFIG)
def get_db():
db = getattr(flask_g, "_database", None)
if db is None:
db = flask_g._database = DB()
return db
@web.teardown_appcontext
def close_connection(exception):
db = getattr(flask_g, "_database", None)
if db is not None:
<|code_end|>
with the help of current file imports:
from flask import (
Flask,
g as flask_g,
render_template,
request,
abort,
url_for,
redirect,
)
from hakoblog.db import DB
from hakoblog.config import CONFIG
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from hakoblog.action.entry import EntryAction
and context from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/config.py
# CONFIG = config()
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: hakoblog/action/entry.py
# class EntryAction:
# @classmethod
# def post(cls, db, blog_id, title, body):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO entry (
# id, blog_id, title, body, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s, %s
# )
# """,
# (new_id, blog_id, title, body, now, now),
# )
# return new_id
#
# @classmethod
# def edit(cls, db, entry_id, title, body):
# now = datetime.now()
# with db.cursor() as cursor:
# cursor.execute(
# """
# UPDATE entry SET
# title = %s,
# body = %s,
# modified = %s
# WHERE id = %s
# """,
# (title, body, now, entry_id),
# )
#
# @classmethod
# def delete(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# DELETE FROM entry
# WHERE id = %s
# """,
# (entry_id,),
# )
, which may contain function names, class names, or code. Output only the next line. | db.close() |
Given snippet: <|code_start|>
@web.route("/entry/<int:entry_id>")
def entry(entry_id):
blog = BlogAction.ensure_global_blog_created(get_db())
entry = EntryLoader.find_by_id(get_db(), entry_id)
if entry is None:
abort(404)
if entry.blog_id != blog.id:
abort(403)
return render_template("entry.html", blog=blog, entry=entry)
@web.route("/-/post", methods=["GET"])
def post_get():
blog = BlogAction.ensure_global_blog_created(get_db())
return render_template("post.html", blog=blog)
@web.route("/-/post", methods=["POST"])
def post_post():
blog = BlogAction.ensure_global_blog_created(get_db())
title = request.form["title"]
body = request.form["body"]
blog_id = int(request.form["blog_id"])
if int(blog_id) != blog.id:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import (
Flask,
g as flask_g,
render_template,
request,
abort,
url_for,
redirect,
)
from hakoblog.db import DB
from hakoblog.config import CONFIG
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from hakoblog.action.entry import EntryAction
and context:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/config.py
# CONFIG = config()
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: hakoblog/action/entry.py
# class EntryAction:
# @classmethod
# def post(cls, db, blog_id, title, body):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO entry (
# id, blog_id, title, body, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s, %s
# )
# """,
# (new_id, blog_id, title, body, now, now),
# )
# return new_id
#
# @classmethod
# def edit(cls, db, entry_id, title, body):
# now = datetime.now()
# with db.cursor() as cursor:
# cursor.execute(
# """
# UPDATE entry SET
# title = %s,
# body = %s,
# modified = %s
# WHERE id = %s
# """,
# (title, body, now, entry_id),
# )
#
# @classmethod
# def delete(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# DELETE FROM entry
# WHERE id = %s
# """,
# (entry_id,),
# )
which might include code, classes, or functions. Output only the next line. | abort(400) |
Given snippet: <|code_start|>
web = Flask(__name__)
web.config.from_object(CONFIG)
def get_db():
db = getattr(flask_g, "_database", None)
if db is None:
db = flask_g._database = DB()
return db
@web.teardown_appcontext
def close_connection(exception):
db = getattr(flask_g, "_database", None)
if db is not None:
db.close()
@web.after_request
def add_secure_headers(response):
print(response)
response.headers.add("X-Frame-Options", "DENY")
response.headers.add("X-Content-Type-Options", "nosniff")
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from flask import (
Flask,
g as flask_g,
render_template,
request,
abort,
url_for,
redirect,
)
from hakoblog.db import DB
from hakoblog.config import CONFIG
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from hakoblog.action.entry import EntryAction
and context:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/config.py
# CONFIG = config()
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: hakoblog/action/entry.py
# class EntryAction:
# @classmethod
# def post(cls, db, blog_id, title, body):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO entry (
# id, blog_id, title, body, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s, %s
# )
# """,
# (new_id, blog_id, title, body, now, now),
# )
# return new_id
#
# @classmethod
# def edit(cls, db, entry_id, title, body):
# now = datetime.now()
# with db.cursor() as cursor:
# cursor.execute(
# """
# UPDATE entry SET
# title = %s,
# body = %s,
# modified = %s
# WHERE id = %s
# """,
# (title, body, now, entry_id),
# )
#
# @classmethod
# def delete(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# DELETE FROM entry
# WHERE id = %s
# """,
# (entry_id,),
# )
which might include code, classes, or functions. Output only the next line. | response.headers.add("X-XSS-Protection", "1;mode=block") |
Here is a snippet: <|code_start|>
web = Flask(__name__)
web.config.from_object(CONFIG)
def get_db():
db = getattr(flask_g, "_database", None)
if db is None:
db = flask_g._database = DB()
return db
@web.teardown_appcontext
def close_connection(exception):
db = getattr(flask_g, "_database", None)
if db is not None:
db.close()
@web.after_request
def add_secure_headers(response):
print(response)
response.headers.add("X-Frame-Options", "DENY")
<|code_end|>
. Write the next line using the current file imports:
from flask import (
Flask,
g as flask_g,
render_template,
request,
abort,
url_for,
redirect,
)
from hakoblog.db import DB
from hakoblog.config import CONFIG
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from hakoblog.action.entry import EntryAction
and context from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/config.py
# CONFIG = config()
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: hakoblog/action/entry.py
# class EntryAction:
# @classmethod
# def post(cls, db, blog_id, title, body):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO entry (
# id, blog_id, title, body, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s, %s
# )
# """,
# (new_id, blog_id, title, body, now, now),
# )
# return new_id
#
# @classmethod
# def edit(cls, db, entry_id, title, body):
# now = datetime.now()
# with db.cursor() as cursor:
# cursor.execute(
# """
# UPDATE entry SET
# title = %s,
# body = %s,
# modified = %s
# WHERE id = %s
# """,
# (title, body, now, entry_id),
# )
#
# @classmethod
# def delete(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# DELETE FROM entry
# WHERE id = %s
# """,
# (entry_id,),
# )
, which may include functions, classes, or code. Output only the next line. | response.headers.add("X-Content-Type-Options", "nosniff") |
Predict the next line for this snippet: <|code_start|> with global_user(random_string(5)):
res = web_client().get('/-/post')
assert res.status == '200 OK'
def test_post_create_entry():
db = DB()
with global_user(random_string(5)), web_client() as wc:
blog = BlogAction.ensure_global_blog_created(db)
res = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=blog.id,
))
assert res.status == '302 FOUND'
assert res.headers['Location'] == url_for('index', _external=True)
entry = EntryLoader.find_entries(db, blog.id, limit=1)[0]
assert entry.title == 'はろー'
assert entry.body == 'こんにちは'
def test_post_create_entry_bad_request():
with global_user(random_string(5)), web_client() as wc:
res1 = wc.post('/-/post', data=dict())
assert res1.status == '400 BAD REQUEST'
<|code_end|>
with the help of current file imports:
import tests.hakoblog # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string
and context from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
, which may contain function names, class names, or code. Output only the next line. | res2 = wc.post('/-/post', data=dict( |
Given the code snippet: <|code_start|>
def test_post_create_entry():
db = DB()
with global_user(random_string(5)), web_client() as wc:
blog = BlogAction.ensure_global_blog_created(db)
res = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=blog.id,
))
assert res.status == '302 FOUND'
assert res.headers['Location'] == url_for('index', _external=True)
entry = EntryLoader.find_entries(db, blog.id, limit=1)[0]
assert entry.title == 'はろー'
assert entry.body == 'こんにちは'
def test_post_create_entry_bad_request():
with global_user(random_string(5)), web_client() as wc:
res1 = wc.post('/-/post', data=dict())
assert res1.status == '400 BAD REQUEST'
res2 = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=-1,
<|code_end|>
, generate the next line using the imports in this file:
import tests.hakoblog # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string
and context (functions, classes, or occasionally code) from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | )) |
Given the code snippet: <|code_start|>
def test_post_show_form():
with global_user(random_string(5)):
res = web_client().get('/-/post')
assert res.status == '200 OK'
def test_post_create_entry():
db = DB()
with global_user(random_string(5)), web_client() as wc:
blog = BlogAction.ensure_global_blog_created(db)
res = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=blog.id,
))
assert res.status == '302 FOUND'
assert res.headers['Location'] == url_for('index', _external=True)
entry = EntryLoader.find_entries(db, blog.id, limit=1)[0]
assert entry.title == 'はろー'
assert entry.body == 'こんにちは'
def test_post_create_entry_bad_request():
with global_user(random_string(5)), web_client() as wc:
res1 = wc.post('/-/post', data=dict())
<|code_end|>
, generate the next line using the imports in this file:
import tests.hakoblog # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string
and context (functions, classes, or occasionally code) from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | assert res1.status == '400 BAD REQUEST' |
Given the code snippet: <|code_start|>
def test_post_show_form():
with global_user(random_string(5)):
res = web_client().get('/-/post')
<|code_end|>
, generate the next line using the imports in this file:
import tests.hakoblog # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string
and context (functions, classes, or occasionally code) from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | assert res.status == '200 OK' |
Predict the next line for this snippet: <|code_start|>
def test_post_create_entry():
db = DB()
with global_user(random_string(5)), web_client() as wc:
blog = BlogAction.ensure_global_blog_created(db)
res = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=blog.id,
))
assert res.status == '302 FOUND'
assert res.headers['Location'] == url_for('index', _external=True)
entry = EntryLoader.find_entries(db, blog.id, limit=1)[0]
assert entry.title == 'はろー'
assert entry.body == 'こんにちは'
def test_post_create_entry_bad_request():
with global_user(random_string(5)), web_client() as wc:
res1 = wc.post('/-/post', data=dict())
assert res1.status == '400 BAD REQUEST'
res2 = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=-1,
<|code_end|>
with the help of current file imports:
import tests.hakoblog # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string
and context from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
, which may contain function names, class names, or code. Output only the next line. | )) |
Predict the next line after this snippet: <|code_start|> res = web_client().get('/-/post')
assert res.status == '200 OK'
def test_post_create_entry():
db = DB()
with global_user(random_string(5)), web_client() as wc:
blog = BlogAction.ensure_global_blog_created(db)
res = wc.post('/-/post', data=dict(
title='はろー',
body='こんにちは',
blog_id=blog.id,
))
assert res.status == '302 FOUND'
assert res.headers['Location'] == url_for('index', _external=True)
entry = EntryLoader.find_entries(db, blog.id, limit=1)[0]
assert entry.title == 'はろー'
assert entry.body == 'こんにちは'
def test_post_create_entry_bad_request():
with global_user(random_string(5)), web_client() as wc:
res1 = wc.post('/-/post', data=dict())
assert res1.status == '400 BAD REQUEST'
res2 = wc.post('/-/post', data=dict(
<|code_end|>
using the current file's imports:
import tests.hakoblog # noqa: F401
from flask import url_for
from hakoblog.db import DB
from hakoblog.action.blog import BlogAction
from hakoblog.loader.entry import EntryLoader
from tests.util import web_client, global_user, random_string
and any relevant context from other files:
# Path: hakoblog/db.py
# class DB:
# def __init__(self):
# self.conn = MySQLdb.connect(
# db=CONFIG.DATABASE,
# host=CONFIG.DATABASE_HOST,
# user=CONFIG.DATABASE_USER,
# password=CONFIG.DATABASE_PASS,
# cursorclass=MySQLdb.cursors.DictCursor,
# charset="utf8",
# )
# self.conn.autocommit(True)
#
# def cursor(self):
# return self.conn.cursor()
#
# def close(self):
# self.conn.close()
#
# def uuid_short(self):
# with self.conn.cursor() as cursor:
# cursor.execute("SELECT UUID_SHORT() as uuid")
# return cursor.fetchone().get("uuid")
#
# Path: hakoblog/action/blog.py
# class BlogAction:
# @classmethod
# def create(self, db, owner_id, title):
# now = datetime.now()
# new_id = db.uuid_short()
# with db.cursor() as cursor:
# cursor.execute(
# """
# INSERT INTO blog (
# id, owner_id, title, created, modified
# ) VALUES (
# %s, %s, %s, %s, %s
# )
# """,
# (new_id, owner_id, title, now, now),
# )
# return new_id
#
# @classmethod
# def ensure_global_blog_created(cls, db):
# global_user = UserAction.ensure_global_user_created(db)
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# if blog is None:
# cls.create(db, global_user.id, "%s's blog" % (global_user.name,))
# blog = BlogLoader.find_by_owner_id(db, global_user.id)
#
# return blog
#
# Path: hakoblog/loader/entry.py
# class EntryLoader:
# @classmethod
# def find_by_id(cls, db, entry_id):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE id = %s
# LIMIT 1
# """,
# (entry_id,),
# )
# row = cursor.fetchone()
#
# if row is None:
# return None
#
# return Entry(**row)
#
# @classmethod
# def find_entries(cls, db, blog_id, limit=30):
# with db.cursor() as cursor:
# cursor.execute(
# """
# SELECT id, blog_id, title, body, created, modified
# FROM entry
# WHERE blog_id = %s
# ORDER BY created DESC
# LIMIT %s
# """,
# (blog_id, limit),
# )
# rows = cursor.fetchall()
#
# return [Entry(**r) for r in rows]
#
# Path: tests/util.py
# def web_client():
# return web.test_client()
#
# @contextmanager
# def global_user(name):
# prev_name = CONFIG.GLOBAL_USER_NAME
# CONFIG.GLOBAL_USER_NAME = name
# yield name
# CONFIG.GLOBAL_USER_NAME = prev_name
#
# def random_string(length, seq=string.digits + string.ascii_letters):
# sr = random.SystemRandom()
# return ''.join([sr.choice(seq) for i in range(length)])
. Output only the next line. | title='はろー', |
Predict the next line for this snippet: <|code_start|> "-q", "--quiet", action="store_true", dest="quiet", default=False
)
parser.add_argument("--every", nargs="*", dest="every", default=[])
if not command:
parser.add_argument("command", nargs="*")
at_or_in = parser.add_mutually_exclusive_group()
at_or_in.add_argument("--start-at", nargs="*", dest="at", default=[])
at_or_in.add_argument("--start-in", nargs="*", dest="in", default=[])
try:
vals = vars(parser.parse_args(argument.split(" ")))
except Exception as exc:
raise BadArgument() from exc
if not (vals["at"] or vals["in"]):
raise BadArgument("You must provide one of `--start-in` or `--start-at`")
if not command and not vals["command"]:
raise BadArgument("You have to provide a command to run")
command = command or " ".join(vals["command"])
for delta in ("in", "every"):
if vals[delta]:
parsed = parse_timedelta(" ".join(vals[delta]))
if not parsed:
raise BadArgument("I couldn't understand that time interval")
if delta == "in":
start = datetime.now(timezone.utc) + parsed
<|code_end|>
with the help of current file imports:
import argparse
import dataclasses
from datetime import datetime, timedelta, timezone
from typing import NamedTuple, Optional, Tuple
from redbot.core.commands import BadArgument, Context
from .time_utils import parse_time, parse_timedelta
and context from other files:
# Path: scheduler/time_utils.py
# def parse_time(datetimestring: str):
# ret = parser.parse(datetimestring, tzinfos=dict(gen_tzinfos()))
# ret = ret.astimezone(pytz.utc)
# return ret
#
# def parse_timedelta(argument: str) -> Optional[timedelta]:
# matches = TIME_RE.match(argument)
# if matches:
# params = {k: int(v) for k, v in matches.groupdict().items() if v}
# if params:
# return timedelta(**params)
# return None
, which may contain function names, class names, or code. Output only the next line. | else: |
Predict the next line after this snippet: <|code_start|>
class NoExitParser(argparse.ArgumentParser):
def error(self, message):
raise BadArgument()
@dataclasses.dataclass()
class Schedule:
start: datetime
command: str
recur: Optional[timedelta] = None
quiet: bool = False
def to_tuple(self) -> Tuple[str, datetime, Optional[timedelta]]:
return self.command, self.start, self.recur
@classmethod
async def convert(cls, ctx: Context, argument: str):
start: datetime
command: Optional[str] = None
recur: Optional[timedelta] = None
command, *arguments = argument.split(" -- ")
if arguments:
argument = " -- ".join(arguments)
else:
command = None
<|code_end|>
using the current file's imports:
import argparse
import dataclasses
from datetime import datetime, timedelta, timezone
from typing import NamedTuple, Optional, Tuple
from redbot.core.commands import BadArgument, Context
from .time_utils import parse_time, parse_timedelta
and any relevant context from other files:
# Path: scheduler/time_utils.py
# def parse_time(datetimestring: str):
# ret = parser.parse(datetimestring, tzinfos=dict(gen_tzinfos()))
# ret = ret.astimezone(pytz.utc)
# return ret
#
# def parse_timedelta(argument: str) -> Optional[timedelta]:
# matches = TIME_RE.match(argument)
# if matches:
# params = {k: int(v) for k, v in matches.groupdict().items() if v}
# if params:
# return timedelta(**params)
# return None
. Output only the next line. | parser = NoExitParser(description="Scheduler event parsing", add_help=False) |
Using the snippet: <|code_start|>from __future__ import annotations
log = logging.getLogger("red.sinbadcogs.rss")
DONT_HTML_SCRUB = ["link", "source", "updated", "updated_parsed"]
USABLE_FIELDS = [
"author",
"author_detail",
"description",
"comments",
"content",
"contributors",
"created",
"updated",
<|code_end|>
, determine the next line of code. You have imports:
import asyncio
import logging
import string
import urllib.parse
import aiohttp
import discord
import feedparser
from datetime import datetime
from functools import partial
from types import MappingProxyType
from typing import Any, Dict, Generator, List, Optional, cast
from bs4 import BeautifulSoup as bs4
from redbot.core import checks, commands
from redbot.core.config import Config
from redbot.core.utils.chat_formatting import box, pagify
from .cleanup import html_to_text
from .converters import FieldAndTerm, NonEveryoneRole, TriState
and context (class names, function names, or code) available:
# Path: rss/cleanup.py
# def html_to_text(html_data): # https://stackoverflow.com/a/7778368
# """Converts HTML to plain text (stripping tags and converting entities).
# >>> html_to_text('<a href="#">Demo<!--...--> <em>(¬ \u0394ημώ)</em></a>')
# 'Demo (\xac \u0394\u03b7\u03bc\u03ce)'
#
# "Plain text" doesn't mean result can safely be used as-is in HTML.
# >>> html_to_text('<script>alert("Hello");</script>')
# '<script>alert("Hello");</script>'
#
# Always use html.escape to sanitize text before using in an HTML context!
#
# HTMLParser will do its best to make sense of invalid HTML.
# >>> html_to_text('x < y < z <!--b')
# 'x < y < z '
#
# Unrecognized named entities are included as-is. ''' is recognized,
# despite being XML only.
# >>> html_to_text('&nosuchentity; ' ')
# "&nosuchentity; ' "
# """
# html_data = WhitespaceHandler.sub("\n", html_data)
# s = HTMLTextExtractor()
# s.feed(html_data)
# return s.get_text()
#
# Path: rss/converters.py
# class FieldAndTerm(NamedTuple):
# field: str
# term: str
#
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> FieldAndTerm:
#
# try:
# field, term = arg.casefold().split(maxsplit=1)
# except ValueError:
# raise commands.BadArgument("Must provide a field and a term to match")
#
# return cls(field, term)
#
# class NonEveryoneRole(discord.Role):
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> discord.Role:
# role: discord.Role = await _role_converter.convert(ctx, arg)
# if role.is_default():
# raise commands.BadArgument("You can't set this for the everyone role")
# return role
#
# class TriState:
# def __init__(self, state):
# self.state = state
#
# @classmethod
# async def convert(cls, ctx, arg):
# return cls(_tristate(arg))
. Output only the next line. | "updated_parsed", |
Next line prediction: <|code_start|>from __future__ import annotations
log = logging.getLogger("red.sinbadcogs.rss")
DONT_HTML_SCRUB = ["link", "source", "updated", "updated_parsed"]
USABLE_FIELDS = [
"author",
"author_detail",
"description",
"comments",
"content",
"contributors",
"created",
"updated",
<|code_end|>
. Use current file imports:
(import asyncio
import logging
import string
import urllib.parse
import aiohttp
import discord
import feedparser
from datetime import datetime
from functools import partial
from types import MappingProxyType
from typing import Any, Dict, Generator, List, Optional, cast
from bs4 import BeautifulSoup as bs4
from redbot.core import checks, commands
from redbot.core.config import Config
from redbot.core.utils.chat_formatting import box, pagify
from .cleanup import html_to_text
from .converters import FieldAndTerm, NonEveryoneRole, TriState)
and context including class names, function names, or small code snippets from other files:
# Path: rss/cleanup.py
# def html_to_text(html_data): # https://stackoverflow.com/a/7778368
# """Converts HTML to plain text (stripping tags and converting entities).
# >>> html_to_text('<a href="#">Demo<!--...--> <em>(¬ \u0394ημώ)</em></a>')
# 'Demo (\xac \u0394\u03b7\u03bc\u03ce)'
#
# "Plain text" doesn't mean result can safely be used as-is in HTML.
# >>> html_to_text('<script>alert("Hello");</script>')
# '<script>alert("Hello");</script>'
#
# Always use html.escape to sanitize text before using in an HTML context!
#
# HTMLParser will do its best to make sense of invalid HTML.
# >>> html_to_text('x < y < z <!--b')
# 'x < y < z '
#
# Unrecognized named entities are included as-is. ''' is recognized,
# despite being XML only.
# >>> html_to_text('&nosuchentity; ' ')
# "&nosuchentity; ' "
# """
# html_data = WhitespaceHandler.sub("\n", html_data)
# s = HTMLTextExtractor()
# s.feed(html_data)
# return s.get_text()
#
# Path: rss/converters.py
# class FieldAndTerm(NamedTuple):
# field: str
# term: str
#
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> FieldAndTerm:
#
# try:
# field, term = arg.casefold().split(maxsplit=1)
# except ValueError:
# raise commands.BadArgument("Must provide a field and a term to match")
#
# return cls(field, term)
#
# class NonEveryoneRole(discord.Role):
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> discord.Role:
# role: discord.Role = await _role_converter.convert(ctx, arg)
# if role.is_default():
# raise commands.BadArgument("You can't set this for the everyone role")
# return role
#
# class TriState:
# def __init__(self, state):
# self.state = state
#
# @classmethod
# async def convert(cls, ctx, arg):
# return cls(_tristate(arg))
. Output only the next line. | "updated_parsed", |
Given the code snippet: <|code_start|>from __future__ import annotations
log = logging.getLogger("red.sinbadcogs.rss")
DONT_HTML_SCRUB = ["link", "source", "updated", "updated_parsed"]
USABLE_FIELDS = [
"author",
"author_detail",
"description",
"comments",
"content",
"contributors",
"created",
"updated",
"updated_parsed",
"link",
"name",
"published",
"published_parsed",
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import logging
import string
import urllib.parse
import aiohttp
import discord
import feedparser
from datetime import datetime
from functools import partial
from types import MappingProxyType
from typing import Any, Dict, Generator, List, Optional, cast
from bs4 import BeautifulSoup as bs4
from redbot.core import checks, commands
from redbot.core.config import Config
from redbot.core.utils.chat_formatting import box, pagify
from .cleanup import html_to_text
from .converters import FieldAndTerm, NonEveryoneRole, TriState
and context (functions, classes, or occasionally code) from other files:
# Path: rss/cleanup.py
# def html_to_text(html_data): # https://stackoverflow.com/a/7778368
# """Converts HTML to plain text (stripping tags and converting entities).
# >>> html_to_text('<a href="#">Demo<!--...--> <em>(¬ \u0394ημώ)</em></a>')
# 'Demo (\xac \u0394\u03b7\u03bc\u03ce)'
#
# "Plain text" doesn't mean result can safely be used as-is in HTML.
# >>> html_to_text('<script>alert("Hello");</script>')
# '<script>alert("Hello");</script>'
#
# Always use html.escape to sanitize text before using in an HTML context!
#
# HTMLParser will do its best to make sense of invalid HTML.
# >>> html_to_text('x < y < z <!--b')
# 'x < y < z '
#
# Unrecognized named entities are included as-is. ''' is recognized,
# despite being XML only.
# >>> html_to_text('&nosuchentity; ' ')
# "&nosuchentity; ' "
# """
# html_data = WhitespaceHandler.sub("\n", html_data)
# s = HTMLTextExtractor()
# s.feed(html_data)
# return s.get_text()
#
# Path: rss/converters.py
# class FieldAndTerm(NamedTuple):
# field: str
# term: str
#
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> FieldAndTerm:
#
# try:
# field, term = arg.casefold().split(maxsplit=1)
# except ValueError:
# raise commands.BadArgument("Must provide a field and a term to match")
#
# return cls(field, term)
#
# class NonEveryoneRole(discord.Role):
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> discord.Role:
# role: discord.Role = await _role_converter.convert(ctx, arg)
# if role.is_default():
# raise commands.BadArgument("You can't set this for the everyone role")
# return role
#
# class TriState:
# def __init__(self, state):
# self.state = state
#
# @classmethod
# async def convert(cls, ctx, arg):
# return cls(_tristate(arg))
. Output only the next line. | "publisher", |
Based on the snippet: <|code_start|>from __future__ import annotations
log = logging.getLogger("red.sinbadcogs.rss")
DONT_HTML_SCRUB = ["link", "source", "updated", "updated_parsed"]
USABLE_FIELDS = [
"author",
"author_detail",
"description",
"comments",
"content",
"contributors",
"created",
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
import string
import urllib.parse
import aiohttp
import discord
import feedparser
from datetime import datetime
from functools import partial
from types import MappingProxyType
from typing import Any, Dict, Generator, List, Optional, cast
from bs4 import BeautifulSoup as bs4
from redbot.core import checks, commands
from redbot.core.config import Config
from redbot.core.utils.chat_formatting import box, pagify
from .cleanup import html_to_text
from .converters import FieldAndTerm, NonEveryoneRole, TriState
and context (classes, functions, sometimes code) from other files:
# Path: rss/cleanup.py
# def html_to_text(html_data): # https://stackoverflow.com/a/7778368
# """Converts HTML to plain text (stripping tags and converting entities).
# >>> html_to_text('<a href="#">Demo<!--...--> <em>(¬ \u0394ημώ)</em></a>')
# 'Demo (\xac \u0394\u03b7\u03bc\u03ce)'
#
# "Plain text" doesn't mean result can safely be used as-is in HTML.
# >>> html_to_text('<script>alert("Hello");</script>')
# '<script>alert("Hello");</script>'
#
# Always use html.escape to sanitize text before using in an HTML context!
#
# HTMLParser will do its best to make sense of invalid HTML.
# >>> html_to_text('x < y < z <!--b')
# 'x < y < z '
#
# Unrecognized named entities are included as-is. ''' is recognized,
# despite being XML only.
# >>> html_to_text('&nosuchentity; ' ')
# "&nosuchentity; ' "
# """
# html_data = WhitespaceHandler.sub("\n", html_data)
# s = HTMLTextExtractor()
# s.feed(html_data)
# return s.get_text()
#
# Path: rss/converters.py
# class FieldAndTerm(NamedTuple):
# field: str
# term: str
#
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> FieldAndTerm:
#
# try:
# field, term = arg.casefold().split(maxsplit=1)
# except ValueError:
# raise commands.BadArgument("Must provide a field and a term to match")
#
# return cls(field, term)
#
# class NonEveryoneRole(discord.Role):
# @classmethod
# async def convert(cls, ctx: commands.Context, arg: str) -> discord.Role:
# role: discord.Role = await _role_converter.convert(ctx, arg)
# if role.is_default():
# raise commands.BadArgument("You can't set this for the everyone role")
# return role
#
# class TriState:
# def __init__(self, state):
# self.state = state
#
# @classmethod
# async def convert(cls, ctx, arg):
# return cls(_tristate(arg))
. Output only the next line. | "updated", |
Using the snippet: <|code_start|> now = datetime.now(timezone.utc)
next_run_at = now + timedelta(seconds=self.next_call_delay)
embed = discord.Embed(color=color, timestamp=next_run_at)
embed.title = f"Now viewing {index} of {page_count} selected tasks"
embed.add_field(name="Command", value=f"[p]{self.content}")
embed.add_field(name="Channel", value=self.channel.mention)
embed.add_field(name="Creator", value=self.author.mention)
embed.add_field(name="Task ID", value=self.uid)
try:
fmt_date = self.initial.strftime("%A %B %-d, %Y at %-I%p %Z")
except ValueError: # Windows
# This looks less natural, but I'm not doing this piecemeal to emulate.
fmt_date = self.initial.strftime("%A %B %d, %Y at %I%p %Z")
if self.recur:
try:
fmt_date = self.initial.strftime("%A %B %-d, %Y at %-I%p %Z")
except ValueError: # Windows
# This looks less natural, but I'm not doing this piecemeal to emulate.
fmt_date = self.initial.strftime("%A %B %d, %Y at %I%p %Z")
if self.initial > now:
description = (
f"{self.nicename} starts running on {fmt_date}."
f"\nIt repeats every {humanize_timedelta(timedelta=self.recur)}"
)
else:
description = (
f"{self.nicename} started running on {fmt_date}."
<|code_end|>
, determine the next line of code. You have imports:
import contextlib
import attr
import discord
from datetime import datetime, timedelta, timezone
from typing import Optional, cast
from redbot.core.utils.chat_formatting import humanize_timedelta
from .message import SchedulerMessage
and context (class names, function names, or code) available:
# Path: scheduler/message.py
# class SchedulerMessage(discord.Message):
# """
# Subclassed discord message with neutered coroutines.
#
# Extremely butchered class for a specific use case.
# Be careful when using this in other use cases.
# """
#
# def __init__(
# self, *, content: str, author: discord.Member, channel: discord.TextChannel
# ) -> None:
# # auto current time
# self.id = discord.utils.time_snowflake(datetime.utcnow())
# # important properties for even being processed
# self.author = author
# self.channel = channel
# self.content = content
# self.guild = channel.guild # type: ignore
# # this attribute being in almost everything (and needing to be) is a pain
# self._state = self.guild._state # type: ignore
# # sane values below, fresh messages which are commands should exhibit these.
# self.call = None
# self.type = discord.MessageType.default
# self.tts = False
# self.pinned = False
# # suport for attachments somehow later maybe?
# self.attachments: List[discord.Attachment] = []
# # mentions
# self.mention_everyone = self.channel.permissions_for(
# self.author
# ).mention_everyone and bool(EVERYONE_REGEX.match(self.content))
# # pylint: disable=E1133
# # pylint improperly detects the inherited properties here as not being iterable
# # This should be fixed with typehint support added to upstream lib later
# self.mentions: List[Union[discord.User, discord.Member]] = list(
# filter(None, [self.guild.get_member(idx) for idx in self.raw_mentions])
# )
# self.channel_mentions: List[discord.TextChannel] = list(
# filter(
# None,
# [
# self.guild.get_channel(idx) # type: ignore
# for idx in self.raw_channel_mentions
# ],
# )
# )
# self.role_mentions: List[discord.Role] = list(
# filter(None, [self.guild.get_role(idx) for idx in self.raw_role_mentions])
# )
. Output only the next line. | f"\nIt repeats every {humanize_timedelta(timedelta=self.recur)}" |
Here is a snippet: <|code_start|>from __future__ import annotations
GuildList = List[discord.Guild]
GuildSet = Set[discord.Guild]
UserLike = Union[discord.Member, discord.User]
def mock_user(idx: int) -> UserLike:
return cast(discord.User, discord.Object(id=idx))
async def create_case(
bot: Red,
guild: discord.Guild,
created_at: datetime,
action_type: str,
user: UserLike,
<|code_end|>
. Write the next line using the current file imports:
import asyncio
import io
import json
import logging
import discord
from datetime import datetime
from typing import (
AsyncIterator,
Collection,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Union,
cast,
)
from discord.ext.commands import Greedy
from redbot.core import checks, commands
from redbot.core.bot import Red
from redbot.core.config import Config
from redbot.core.data_manager import cog_data_path
from redbot.core.modlog import create_case as _red_create_case
from redbot.core.utils.chat_formatting import box, pagify
from .converters import MentionOrID, ParserError, SyndicatedConverter
and context from other files:
# Path: bansync/converters.py
# class MentionOrID(NamedTuple):
# id: int
#
# @classmethod
# async def convert(cls, ctx: Context, argument: str):
#
# match = _id_regex.match(argument) or _mention_regex.match(argument)
# if match:
# return cls(int(match.group(1)))
#
# raise BadArgument()
#
# class ParserError(Exception):
# pass
#
# class SyndicatedConverter:
# """
# Parser based converter.
#
# Takes sources, and either
# destinations, a flag to automatically determine destinations, or both
# """
#
# sources: Set[discord.Guild]
# dests: Set[discord.Guild]
# usr: Union[discord.Member, discord.User]
# shred_ratelimits: bool = False
# auto: bool = False
#
# def to_dict(self) -> dict:
# return {
# "sources": self.sources,
# "dests": self.dests,
# "usr": self.usr,
# "shred_ratelimits": self.shred_ratelimits,
# "auto": self.auto,
# }
#
# @classmethod
# async def convert(cls, ctx: Context, argument: str):
#
# parser = NoExitParser(description="Syndicated Ban Syntax", add_help=False)
# parser.add_argument("--sources", nargs="*", dest="sources", default=[])
# parser.add_argument("--destinations", nargs="*", dest="dests", default=[])
# parser.add_argument(
# "--auto-destinations", action="store_true", default=False, dest="auto"
# )
# parser.add_argument(
# "--shred-ratelimits",
# action="store_true",
# default=False,
# dest="shred_ratelimits",
# )
#
# vals = parser.parse_args(shlex.split(argument))
#
# guilds = set(ctx.bot.guilds)
#
# sources = set(filter(lambda g: str(g.id) in vals.sources, guilds))
# if not sources:
# raise ParserError("I need at least 1 source.")
#
# if vals.auto:
# destinations = guilds - sources
# elif vals.dests:
# destinations = set()
# for guild in guilds:
# to_comp = str(guild.id)
# if to_comp in vals.dests and to_comp not in sources:
# destinations.add(guild)
# else:
# raise ParserError(
# "I need either at least one destination, "
# " to be told to automatically determine destinations, "
# "or a combination of both to add extra destinations beyond the automatic."
# )
#
# return cls(
# sources=sources,
# dests=destinations,
# shred_ratelimits=vals.shred_ratelimits,
# auto=vals.auto,
# usr=ctx.author,
# )
, which may include functions, classes, or code. Output only the next line. | moderator: Optional[UserLike] = None, |
Given snippet: <|code_start|>from __future__ import annotations
GuildList = List[discord.Guild]
GuildSet = Set[discord.Guild]
UserLike = Union[discord.Member, discord.User]
def mock_user(idx: int) -> UserLike:
return cast(discord.User, discord.Object(id=idx))
async def create_case(
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import io
import json
import logging
import discord
from datetime import datetime
from typing import (
AsyncIterator,
Collection,
Dict,
Generator,
List,
Optional,
Set,
Tuple,
Union,
cast,
)
from discord.ext.commands import Greedy
from redbot.core import checks, commands
from redbot.core.bot import Red
from redbot.core.config import Config
from redbot.core.data_manager import cog_data_path
from redbot.core.modlog import create_case as _red_create_case
from redbot.core.utils.chat_formatting import box, pagify
from .converters import MentionOrID, ParserError, SyndicatedConverter
and context:
# Path: bansync/converters.py
# class MentionOrID(NamedTuple):
# id: int
#
# @classmethod
# async def convert(cls, ctx: Context, argument: str):
#
# match = _id_regex.match(argument) or _mention_regex.match(argument)
# if match:
# return cls(int(match.group(1)))
#
# raise BadArgument()
#
# class ParserError(Exception):
# pass
#
# class SyndicatedConverter:
# """
# Parser based converter.
#
# Takes sources, and either
# destinations, a flag to automatically determine destinations, or both
# """
#
# sources: Set[discord.Guild]
# dests: Set[discord.Guild]
# usr: Union[discord.Member, discord.User]
# shred_ratelimits: bool = False
# auto: bool = False
#
# def to_dict(self) -> dict:
# return {
# "sources": self.sources,
# "dests": self.dests,
# "usr": self.usr,
# "shred_ratelimits": self.shred_ratelimits,
# "auto": self.auto,
# }
#
# @classmethod
# async def convert(cls, ctx: Context, argument: str):
#
# parser = NoExitParser(description="Syndicated Ban Syntax", add_help=False)
# parser.add_argument("--sources", nargs="*", dest="sources", default=[])
# parser.add_argument("--destinations", nargs="*", dest="dests", default=[])
# parser.add_argument(
# "--auto-destinations", action="store_true", default=False, dest="auto"
# )
# parser.add_argument(
# "--shred-ratelimits",
# action="store_true",
# default=False,
# dest="shred_ratelimits",
# )
#
# vals = parser.parse_args(shlex.split(argument))
#
# guilds = set(ctx.bot.guilds)
#
# sources = set(filter(lambda g: str(g.id) in vals.sources, guilds))
# if not sources:
# raise ParserError("I need at least 1 source.")
#
# if vals.auto:
# destinations = guilds - sources
# elif vals.dests:
# destinations = set()
# for guild in guilds:
# to_comp = str(guild.id)
# if to_comp in vals.dests and to_comp not in sources:
# destinations.add(guild)
# else:
# raise ParserError(
# "I need either at least one destination, "
# " to be told to automatically determine destinations, "
# "or a combination of both to add extra destinations beyond the automatic."
# )
#
# return cls(
# sources=sources,
# dests=destinations,
# shred_ratelimits=vals.shred_ratelimits,
# auto=vals.auto,
# usr=ctx.author,
# )
which might include code, classes, or functions. Output only the next line. | bot: Red, |
Using the snippet: <|code_start|>from __future__ import annotations
CHANNEL_RE = re.compile(r"^<#(\d{15,21})>$|^(\d{15,21})$")
class GlobalTextChannel(NamedTuple):
matched_channel: discord.TextChannel
@classmethod
async def convert(cls, ctx: commands.Context, argument: str):
bot = ctx.bot
match = CHANNEL_RE.match(argument)
channel = None
<|code_end|>
, determine the next line of code. You have imports:
import re
import discord
from typing import NamedTuple
from redbot.core import commands
from .helpers import embed_from_msg, find_messages
and context (class names, function names, or code) available:
# Path: quotetools/helpers.py
# def embed_from_msg(message: discord.Message) -> discord.Embed:
# channel = message.channel
# assert isinstance(channel, discord.TextChannel), "mypy" # nosec
# guild = channel.guild
# content = role_mention_cleanup(message)
# author = message.author
# avatar = author.avatar_url
# footer = f"Said in {guild.name} #{channel.name}"
#
# try:
# color = author.color if author.color.value != 0 else None
# except AttributeError: # happens if message author not in guild anymore.
# color = None
# em = discord.Embed(description=content, timestamp=message.created_at)
# if color:
# em.color = color
#
# em.set_author(name=f"{author.name}", icon_url=avatar)
# em.set_footer(icon_url=guild.icon_url, text=footer)
# if message.attachments:
# a = message.attachments[0]
# fname = a.filename
# url = a.url
# if fname.split(".")[-1] in ["png", "jpg", "gif", "jpeg"]:
# em.set_image(url=url)
# else:
# em.add_field(
# name="Message has an attachment", value=f"[{fname}]({url})", inline=True
# )
# em.add_field(
# name="Does this appear to be out of context?",
# value=f"[Click to jump to original message]({message.jump_url})",
# inline=False,
# )
# return em
#
# async def find_messages(
# ctx: commands.Context,
# ids: Sequence[int],
# channels: Optional[Sequence[discord.TextChannel]] = None,
# ) -> Sequence[discord.Message]:
#
# channels = channels or await eligible_channels(ctx)
#
# # dict order preserved py3.6+
# accumulated: Dict[int, Optional[discord.Message]] = {i: None for i in ids}
#
# # This can find ineligible messages, but we strip later to avoid researching
# accumulated.update({m.id: m for m in ctx.bot.cached_messages if m.id in ids})
#
# for i in ids:
# if accumulated[i] is not None:
# continue
# m = await find_msg_fallback(channels, i)
# if m:
# accumulated[i] = m
#
# filtered = [m for m in accumulated.values() if m and m.channel in channels]
# return filtered
. Output only the next line. | if match: |
Given the following code snippet before the placeholder: <|code_start|> """Takes a channel, removes that channel from the clone list"""
await self.ar_config.channel(channel).clear()
await ctx.tick()
@aa_active()
@checks.admin_or_permissions(manage_channels=True)
@autoroomset.command(name="listautorooms")
async def listclones(self, ctx: GuildContext):
"""Lists the current autorooms"""
clist = []
for c in ctx.guild.voice_channels:
if await self.ar_config.channel(c).autoroom():
clist.append("({0.id}) {0.name}".format(c))
output = ", ".join(clist)
page_gen = cast(Generator[str, None, None], pagify(output))
try:
for page in page_gen:
await ctx.send(page)
finally:
page_gen.close()
@aa_active()
@checks.admin_or_permissions(manage_channels=True)
@autoroomset.command(name="toggleowner")
async def toggleowner(self, ctx: GuildContext, val: bool = None):
"""toggles if the creator of the autoroom owns it
requires the "Manage Channels" permission
Defaults to false"""
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
import discord
from datetime import datetime, timedelta
from typing import Generator, cast
from redbot.core import checks, commands
from redbot.core.utils.antispam import AntiSpam
from redbot.core.utils.chat_formatting import pagify
from .abcs import MixedMeta
from .checks import aa_active
from redbot.core.commands import GuildContext
from redbot.core.commands import Context as GuildContext # type: ignore
and context including class names, function names, and sometimes code from other files:
# Path: roomtools/abcs.py
# class MixedMeta(abc.ABC):
# """
# mypy is nice, but I need this for it to shut up about composite classes.
# """
#
# def __init__(self, *args):
# self.bot: Red
# self._antispam: dict
# self.antispam_intervals: list
# self.tmpc_config: Config
# self.ar_config: Config
# self.qualified_name: str
#
# Path: roomtools/checks.py
# def aa_active():
# async def check(ctx: commands.Context):
# if not ctx.guild:
# return False
# cog = ctx.bot.get_cog("RoomTools")
# if TYPE_CHECKING:
# assert isinstance(cog, RoomTools) # nosec
# if not cog:
# return False
# return await cog.ar_config.guild(ctx.guild).active()
#
# return commands.check(check)
. Output only the next line. | if val is None: |
Given the code snippet: <|code_start|> clist.append("({0.id}) {0.name}".format(c))
output = ", ".join(clist)
page_gen = cast(Generator[str, None, None], pagify(output))
try:
for page in page_gen:
await ctx.send(page)
finally:
page_gen.close()
@aa_active()
@checks.admin_or_permissions(manage_channels=True)
@autoroomset.command(name="toggleowner")
async def toggleowner(self, ctx: GuildContext, val: bool = None):
"""toggles if the creator of the autoroom owns it
requires the "Manage Channels" permission
Defaults to false"""
if val is None:
val = not await self.ar_config.guild(ctx.guild).ownership()
await self.ar_config.guild(ctx.guild).ownership.set(val)
message = (
"Autorooms are now owned be their creator"
if val
else "Autorooms are no longer owned by their creator"
)
await ctx.send(message)
@aa_active()
@checks.admin_or_permissions(manage_channels=True)
@autoroomset.command(name="creatorname")
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import discord
from datetime import datetime, timedelta
from typing import Generator, cast
from redbot.core import checks, commands
from redbot.core.utils.antispam import AntiSpam
from redbot.core.utils.chat_formatting import pagify
from .abcs import MixedMeta
from .checks import aa_active
from redbot.core.commands import GuildContext
from redbot.core.commands import Context as GuildContext # type: ignore
and context (functions, classes, or occasionally code) from other files:
# Path: roomtools/abcs.py
# class MixedMeta(abc.ABC):
# """
# mypy is nice, but I need this for it to shut up about composite classes.
# """
#
# def __init__(self, *args):
# self.bot: Red
# self._antispam: dict
# self.antispam_intervals: list
# self.tmpc_config: Config
# self.ar_config: Config
# self.qualified_name: str
#
# Path: roomtools/checks.py
# def aa_active():
# async def check(ctx: commands.Context):
# if not ctx.guild:
# return False
# cog = ctx.bot.get_cog("RoomTools")
# if TYPE_CHECKING:
# assert isinstance(cog, RoomTools) # nosec
# if not cog:
# return False
# return await cog.ar_config.guild(ctx.guild).active()
#
# return commands.check(check)
. Output only the next line. | async def togglecreatorname( |
Here is a snippet: <|code_start|>
class Moo:
@classmethod
async def convert(cls, ctx, arg):
if arg[:3].lower() == "moo":
return cls()
raise commands.BadArgument()
<|code_end|>
. Write the next line using the current file imports:
import json
import random
from typing import List, Optional
from redbot.core import commands
from redbot.core.data_manager import bundled_data_path
from redbot.core.utils.chat_formatting import box
from .cows import cowsay
and context from other files:
# Path: fortune/cows.py
# def cowsay(text, length=40) -> str:
# return build_bubble(text, length) + COW_BASE
, which may include functions, classes, or code. Output only the next line. | class Fortune(commands.Cog): |
Continue the code snippet: <|code_start|>from __future__ import annotations
log = logging.getLogger("red.sinbadcogs.modnotes")
class Note(NamedTuple):
uid: int
author_id: int
subject_id: int
guild_id: int
note: str
created_at: int
def embed(self, ctx, color) -> discord.Embed:
e = discord.Embed(
description=self.note,
timestamp=datetime.fromtimestamp(self.created_at),
color=color,
)
author = ctx.guild.get_member(self.author_id)
subject = ctx.guild.get_member(self.subject_id)
a_str = (
<|code_end|>
. Use current file imports:
import asyncio
import logging
import discord
from datetime import datetime
from typing import Iterator, Literal, NamedTuple, Optional
from redbot.core import checks, commands
from redbot.core.bot import Red
from redbot.core.data_manager import cog_data_path
from redbot.core.utils import menus
from .apsw_wrapper import Connection
from .converters import MemberOrID
and context (classes, functions, or code) from other files:
# Path: modnotes/apsw_wrapper.py
# class Connection(apsw.Connection, ContextManagerMixin):
# pass
#
# Path: modnotes/converters.py
# class MemberOrID(NamedTuple):
# member: Optional[discord.Member]
# id: int
#
# @classmethod
# async def convert(cls, ctx: Context, argument: str):
#
# with contextlib.suppress(Exception):
# m = await _discord_member_converter_instance.convert(ctx, argument)
# return cls(m, m.id)
#
# match = _id_regex.match(argument) or _mention_regex.match(argument)
# if match:
# return cls(None, int(match.group(1)))
#
# raise BadArgument()
. Output only the next line. | f"{author} ({self.author_id})" |
Based on the snippet: <|code_start|>from __future__ import annotations
log = logging.getLogger("red.sinbadcogs.modnotes")
class Note(NamedTuple):
uid: int
author_id: int
subject_id: int
guild_id: int
note: str
created_at: int
def embed(self, ctx, color) -> discord.Embed:
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
import logging
import discord
from datetime import datetime
from typing import Iterator, Literal, NamedTuple, Optional
from redbot.core import checks, commands
from redbot.core.bot import Red
from redbot.core.data_manager import cog_data_path
from redbot.core.utils import menus
from .apsw_wrapper import Connection
from .converters import MemberOrID
and context (classes, functions, sometimes code) from other files:
# Path: modnotes/apsw_wrapper.py
# class Connection(apsw.Connection, ContextManagerMixin):
# pass
#
# Path: modnotes/converters.py
# class MemberOrID(NamedTuple):
# member: Optional[discord.Member]
# id: int
#
# @classmethod
# async def convert(cls, ctx: Context, argument: str):
#
# with contextlib.suppress(Exception):
# m = await _discord_member_converter_instance.convert(ctx, argument)
# return cls(m, m.id)
#
# match = _id_regex.match(argument) or _mention_regex.match(argument)
# if match:
# return cls(None, int(match.group(1)))
#
# raise BadArgument()
. Output only the next line. | e = discord.Embed( |
Predict the next line for this snippet: <|code_start|># TODO: Pull the logic out of d.py converter to not do this here...
async def handle_color(ctx, to_set) -> int:
x: int
try:
conv = discord.ext.commands.ColourConverter()
x = (await conv.convert(ctx, to_set)).value
except Exception:
if isinstance(to_set, str) and to_set.startswith("#"):
x = int(to_set.lstrip("#"), 16)
else:
x = int(to_set)
return x
# TODO : Use schema here. Will allow giving back reasonable error messages on failures.
async def embed_from_userstr(ctx: commands.Context, string: str) -> discord.Embed:
ret: dict = {"initable": {}, "settable": {}, "fields": []}
string = string_preprocessor(string)
parsed = yaml.safe_load(string)
ret["fields"] = [
field_data for _index, field_data in sorted(parsed.get("fields", {}).items())
]
for outer_key in ["initable", "settable"]:
for inner_key in template[outer_key].keys():
to_set = parsed.get(inner_key, {})
if to_set:
if inner_key == "timestamp":
<|code_end|>
with the help of current file imports:
import re
import discord
import yaml
import yaml.reader
from redbot.core import commands
from .serialize import deserialize_embed, template
from .time_utils import parse_time
and context from other files:
# Path: embedmaker/serialize.py
# def serialize_embed(embed: discord.Embed) -> dict:
# def deserialize_embed(conf: dict) -> discord.Embed:
, which may contain function names, class names, or code. Output only the next line. | to_set = handle_timestamp(to_set) |
Given snippet: <|code_start|> ts = float(to_set)
return ts
# TODO: Pull the logic out of d.py converter to not do this here...
async def handle_color(ctx, to_set) -> int:
x: int
try:
conv = discord.ext.commands.ColourConverter()
x = (await conv.convert(ctx, to_set)).value
except Exception:
if isinstance(to_set, str) and to_set.startswith("#"):
x = int(to_set.lstrip("#"), 16)
else:
x = int(to_set)
return x
# TODO : Use schema here. Will allow giving back reasonable error messages on failures.
async def embed_from_userstr(ctx: commands.Context, string: str) -> discord.Embed:
ret: dict = {"initable": {}, "settable": {}, "fields": []}
string = string_preprocessor(string)
parsed = yaml.safe_load(string)
ret["fields"] = [
field_data for _index, field_data in sorted(parsed.get("fields", {}).items())
]
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import re
import discord
import yaml
import yaml.reader
from redbot.core import commands
from .serialize import deserialize_embed, template
from .time_utils import parse_time
and context:
# Path: embedmaker/serialize.py
# def serialize_embed(embed: discord.Embed) -> dict:
# def deserialize_embed(conf: dict) -> discord.Embed:
which might include code, classes, or functions. Output only the next line. | for outer_key in ["initable", "settable"]: |
Next line prediction: <|code_start|> A / 2
B = FloatTensor().resizeAs(A).geometric(0.9)
myeval('B')
myeval('A + B')
myeval('A - B')
myexec('A += B')
myeval('A')
myexec('A -= B')
myeval('A')
def test_pytorch_Float_constructors():
FloatTensor = PyTorch.FloatTensor
a = FloatTensor(3, 2, 5)
assert(len(a.size()) == 3)
a = FloatTensor(3, 2, 5, 6)
assert(len(a.size()) == 4)
def test_Pytorch_Float_operator_plus():
FloatTensor = PyTorch.FloatTensor
a = FloatTensor(3, 2, 5)
b = FloatTensor(3, 2, 5)
a.uniform()
b.uniform()
res = a + b
for i in range(3 * 2 * 5):
assert(abs(res.storage()[i] - (a.storage()[i] + b.storage()[i])) < 0.000001)
<|code_end|>
. Use current file imports:
(import PyTorch
import numpy
import inspect
from test.test_helpers import myeval, myexec)
and context including class names, function names, or small code snippets from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
#
# def myexec(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr)
# exec(expr, parent_vars)
. Output only the next line. | def test_Pytorch_Float_operator_plusequals(): |
Given the code snippet: <|code_start|> PyTorch.manualSeed(123)
numpy.random.seed(123)
DoubleTensor = PyTorch.DoubleTensor
D = PyTorch.DoubleTensor(5, 3).fill(1)
print('D', D)
D[2][2] = 4
print('D', D)
D[3].fill(9)
print('D', D)
D.narrow(1, 2, 1).fill(0)
print('D', D)
print(PyTorch.DoubleTensor(3, 4).uniform())
print(PyTorch.DoubleTensor(3, 4).normal())
print(PyTorch.DoubleTensor(3, 4).cauchy())
print(PyTorch.DoubleTensor(3, 4).exponential())
print(PyTorch.DoubleTensor(3, 4).logNormal())
print(PyTorch.DoubleTensor(3, 4).bernoulli())
print(PyTorch.DoubleTensor(3, 4).geometric())
print(PyTorch.DoubleTensor(3, 4).geometric())
PyTorch.manualSeed(3)
print(PyTorch.DoubleTensor(3, 4).geometric())
PyTorch.manualSeed(3)
print(PyTorch.DoubleTensor(3, 4).geometric())
<|code_end|>
, generate the next line using the imports in this file:
import PyTorch
import numpy
import inspect
from test.test_helpers import myeval, myexec
and context (functions, classes, or occasionally code) from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
#
# def myexec(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr)
# exec(expr, parent_vars)
. Output only the next line. | print(type(PyTorch.DoubleTensor(2, 3))) |
Given the following code snippet before the placeholder: <|code_start|>from __future__ import print_function, division
def test_refcount():
D = PyTorch.FloatTensor(1000, 1000).fill(1)
myeval('D.isContiguous()')
myeval('D.refCount')
assert D.refCount == 1
print('\nget storage into Ds')
Ds = D.storage()
myeval('D.refCount')
myeval('Ds.refCount')
assert D.refCount == 1
<|code_end|>
, predict the next line using imports from the current file:
import PyTorch
import gc
from test.test_helpers import myeval
and context including class names, function names, and sometimes code from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
. Output only the next line. | assert Ds.refCount == 2 |
Predict the next line after this snippet: <|code_start|>from __future__ import print_function
def test_long_tensor():
PyTorch.manualSeed(123)
print('test_long_tensor')
<|code_end|>
using the current file's imports:
import PyTorch
from test.test_helpers import myeval, myexec
and any relevant context from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
#
# def myexec(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr)
# exec(expr, parent_vars)
. Output only the next line. | a = PyTorch.LongTensor(3, 2).geometric() |
Next line prediction: <|code_start|>from __future__ import print_function
def test_long_tensor():
PyTorch.manualSeed(123)
print('test_long_tensor')
a = PyTorch.LongTensor(3, 2).geometric()
<|code_end|>
. Use current file imports:
(import PyTorch
from test.test_helpers import myeval, myexec)
and context including class names, function names, or small code snippets from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
#
# def myexec(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr)
# exec(expr, parent_vars)
. Output only the next line. | print('a', a) |
Predict the next line for this snippet: <|code_start|>]
%}
{% for typedict in types -%}
{%- set Real = typedict['Real'] -%}
{%- set real = typedict['real'] -%}
def test_pytorch{{Real}}():
PyTorch.manualSeed(123)
numpy.random.seed(123)
{{Real}}Tensor = PyTorch.{{Real}}Tensor
{% if Real == 'Float' -%}
A = numpy.random.rand(6).reshape(3, 2).astype(numpy.float32)
B = numpy.random.rand(8).reshape(2, 4).astype(numpy.float32)
C = A.dot(B)
print('C', C)
print('calling .asTensor...')
tensorA = PyTorch.asFloatTensor(A)
tensorB = PyTorch.asFloatTensor(B)
print(' ... asTensor called')
print('tensorA', tensorA)
tensorA.set2d(1, 1, 56.4)
tensorA.set2d(2, 0, 76.5)
print('tensorA', tensorA)
<|code_end|>
with the help of current file imports:
import PyTorch
import numpy
import inspect
from test.test_helpers import myeval, myexec
and context from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
#
# def myexec(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr)
# exec(expr, parent_vars)
, which may contain function names, class names, or code. Output only the next line. | print('A', A) |
Next line prediction: <|code_start|>
print('add 7 to tensorA')
tensorA2 = tensorA + 7
print('tensorA2', tensorA2)
print('tensorA', tensorA)
tensorAB = tensorA * tensorB
print('tensorAB', tensorAB)
print('A.dot(B)', A.dot(B))
print('tensorA[2]', tensorA[2])
{% endif -%}
D = PyTorch.{{Real}}Tensor(5, 3).fill(1)
print('D', D)
D[2][2] = 4
print('D', D)
D[3].fill(9)
print('D', D)
D.narrow(1, 2, 1).fill(0)
print('D', D)
{% if Real in ['Float', 'Double'] -%}
print(PyTorch.{{Real}}Tensor(3, 4).uniform())
print(PyTorch.{{Real}}Tensor(3, 4).normal())
print(PyTorch.{{Real}}Tensor(3, 4).cauchy())
<|code_end|>
. Use current file imports:
(import PyTorch
import numpy
import inspect
from test.test_helpers import myeval, myexec)
and context including class names, function names, or small code snippets from other files:
# Path: test/test_helpers.py
# def myeval(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr, ':', eval(expr, parent_vars))
#
# def myexec(expr):
# parent_vars = inspect.stack()[1][0].f_locals
# print(expr)
# exec(expr, parent_vars)
. Output only the next line. | print(PyTorch.{{Real}}Tensor(3, 4).exponential()) |
Given snippet: <|code_start|>
def test_brackets_of_simple_peak():
y = array((10, 11, 12, 11, 10))
left, right = _choose_brackets(y)
assert list(left) == [1, 2]
assert list(right) == [2, 3]
def test_brackets_of_small_plateau():
y = array((10, 11, 12, 12, 11, 10))
left, right = _choose_brackets(y)
assert list(left) == [1, 2, 3]
assert list(right) == [2, 3, 4]
def test_brackets_of_wide_plateau():
y = array((10, 11, 12, 12, 12, 12, 12, 11, 10))
left, right = _choose_brackets(y)
assert list(left) == [1, 2, 5, 6]
assert list(right) == [2, 3, 6, 7]
def test_simple_maxima():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from numpy import array
from skyfield.searchlib import _choose_brackets, _identify_maxima
and context:
# Path: skyfield/searchlib.py
# def _choose_brackets(y):
# """Return the indices between which we should search for maxima of `y`."""
# dsd = diff(sign(diff(y)))
# indices = flatnonzero(dsd < 0)
# left = reshape(add.outer(indices, [0, 1]), -1)
# left = _remove_adjacent_duplicates(left)
# right = left + 1
# return left, right
#
# def _identify_maxima(x, y):
# """Return the maxima we can see in the series y as simple points."""
# dsd = diff(sign(diff(y)))
#
# # Choose every point that is higher than the two adjacent points.
# indices = flatnonzero(dsd == -2) + 1
# peak_x = x.take(indices)
# peak_y = y.take(indices)
#
# # Also choose the midpoint between the edges of a plateau, if both
# # edges are in view. First we eliminate runs of zeroes, then look
# # for adjacent -1 values, then map those back to the main array.
# indices = flatnonzero(dsd)
# dsd2 = dsd.take(indices)
# minus_ones = dsd2 == -1
# plateau_indices = flatnonzero(minus_ones[:-1] & minus_ones[1:])
# plateau_left_indices = indices.take(plateau_indices)
# plateau_right_indices = indices.take(plateau_indices + 1) + 2
# plateau_x = x.take(plateau_left_indices) + x.take(plateau_right_indices)
# plateau_x /= 2.0
# plateau_y = y.take(plateau_left_indices + 1)
#
# x = concatenate((peak_x, plateau_x))
# y = concatenate((peak_y, plateau_y))
# indices = argsort(x)
# return x[indices], y[indices]
which might include code, classes, or functions. Output only the next line. | x = array((2451545.0, 2451546.0, 2451547.0)) |
Based on the snippet: <|code_start|>
def test_brackets_of_small_plateau():
y = array((10, 11, 12, 12, 11, 10))
left, right = _choose_brackets(y)
assert list(left) == [1, 2, 3]
assert list(right) == [2, 3, 4]
def test_brackets_of_wide_plateau():
y = array((10, 11, 12, 12, 12, 12, 12, 11, 10))
left, right = _choose_brackets(y)
assert list(left) == [1, 2, 5, 6]
assert list(right) == [2, 3, 6, 7]
def test_simple_maxima():
x = array((2451545.0, 2451546.0, 2451547.0))
y = array((11, 12, 11))
x, y = _identify_maxima(x, y)
assert list(x) == [2451546.0]
assert list(y) == [12]
def test_maxima_of_small_plateau():
x = array((2451545.0, 2451546.0, 2451547.0, 2451548.0))
y = array((11, 12, 12, 11))
x, y = _identify_maxima(x, y)
assert list(x) == [2451546.5]
assert list(y) == [12]
def test_both_kinds_of_maxima_at_once():
# We put what could be maxima at each end, to make sure they are not
# detected as when we can't confirm them.
<|code_end|>
, predict the immediate next line with the help of imports:
from numpy import array
from skyfield.searchlib import _choose_brackets, _identify_maxima
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/searchlib.py
# def _choose_brackets(y):
# """Return the indices between which we should search for maxima of `y`."""
# dsd = diff(sign(diff(y)))
# indices = flatnonzero(dsd < 0)
# left = reshape(add.outer(indices, [0, 1]), -1)
# left = _remove_adjacent_duplicates(left)
# right = left + 1
# return left, right
#
# def _identify_maxima(x, y):
# """Return the maxima we can see in the series y as simple points."""
# dsd = diff(sign(diff(y)))
#
# # Choose every point that is higher than the two adjacent points.
# indices = flatnonzero(dsd == -2) + 1
# peak_x = x.take(indices)
# peak_y = y.take(indices)
#
# # Also choose the midpoint between the edges of a plateau, if both
# # edges are in view. First we eliminate runs of zeroes, then look
# # for adjacent -1 values, then map those back to the main array.
# indices = flatnonzero(dsd)
# dsd2 = dsd.take(indices)
# minus_ones = dsd2 == -1
# plateau_indices = flatnonzero(minus_ones[:-1] & minus_ones[1:])
# plateau_left_indices = indices.take(plateau_indices)
# plateau_right_indices = indices.take(plateau_indices + 1) + 2
# plateau_x = x.take(plateau_left_indices) + x.take(plateau_right_indices)
# plateau_x /= 2.0
# plateau_y = y.take(plateau_left_indices + 1)
#
# x = concatenate((peak_x, plateau_x))
# y = concatenate((peak_y, plateau_y))
# indices = argsort(x)
# return x[indices], y[indices]
. Output only the next line. | y = array((12, 11, 12, 12, 11, 13, 11, 12, 12)) |
Given the code snippet: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
'jupiter': 1047.3486,
'saturn': 3497.898,
'uranus': 22902.98,
'neptune': 19412.24,
'pluto': 135200000.0,
'sun': 1.0,
'moon': 27068700.387534,
<|code_end|>
, generate the next line using the imports in this file:
from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | } |
Using the snippet: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
'jupiter': 1047.3486,
'saturn': 3497.898,
'uranus': 22902.98,
'neptune': 19412.24,
'pluto': 135200000.0,
'sun': 1.0,
'moon': 27068700.387534,
}
<|code_end|>
, determine the next line of code. You have imports:
from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of
and context (class names, function names, or code) available:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | def add_deflection(position, observer, ephemeris, t, |
Based on the snippet: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
'jupiter': 1047.3486,
'saturn': 3497.898,
'uranus': 22902.98,
'neptune': 19412.24,
'pluto': 135200000.0,
'sun': 1.0,
'moon': 27068700.387534,
<|code_end|>
, predict the immediate next line with the help of imports:
from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | } |
Next line prediction: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
'jupiter': 1047.3486,
'saturn': 3497.898,
'uranus': 22902.98,
'neptune': 19412.24,
'pluto': 135200000.0,
<|code_end|>
. Use current file imports:
(from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of)
and context including class names, function names, or small code snippets from other files:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | 'sun': 1.0, |
Predict the next line after this snippet: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
'jupiter': 1047.3486,
'saturn': 3497.898,
'uranus': 22902.98,
'neptune': 19412.24,
'pluto': 135200000.0,
'sun': 1.0,
'moon': 27068700.387534,
}
<|code_end|>
using the current file's imports:
from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of
and any relevant context from other files:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | def add_deflection(position, observer, ephemeris, t, |
Using the snippet: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
'jupiter': 1047.3486,
<|code_end|>
, determine the next line of code. You have imports:
from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of
and context (class names, function names, or code) available:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | 'saturn': 3497.898, |
Predict the next line for this snippet: <|code_start|>
deflectors = ['sun', 'jupiter', 'saturn', 'moon', 'venus', 'uranus', 'neptune']
rmasses = {
# earth-moon barycenter: 328900.561400
'mercury': 6023600.0,
'venus': 408523.71,
'earth': 332946.050895,
'mars': 3098708.0,
<|code_end|>
with the help of current file imports:
from numpy import abs, einsum, sqrt, where
from .constants import C, AU_M, C_AUDAY, GS
from .functions import _AVOID_DIVIDE_BY_ZERO, dots, length_of
and context from other files:
# Path: skyfield/constants.py
# C = 299792458.0 # m/s
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# C_AUDAY = C * DAY_S / AU_M
#
# GS = 1.32712440017987e+20
#
# Path: skyfield/functions.py
# _AVOID_DIVIDE_BY_ZERO = finfo(float64).tiny
#
# def dots(v, u):
# """Given one or more vectors in `v` and `u`, return their dot products.
#
# This works whether `v` and `u` each have the shape ``(3,)``, or
# whether they are each whole arrays of corresponding x, y, and z
# coordinates and have shape ``(3, N)``.
#
# """
# return (v * u).sum(axis=0)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
, which may contain function names, class names, or code. Output only the next line. | 'jupiter': 1047.3486, |
Based on the snippet: <|code_start|>#!/usr/bin/env python3
ATTRIBUTES = (
'J', 'delta_t', 'dut1', 'gmst',
# (lambda t: t.toordinal()),
'tai_fraction', 'tdb_fraction', 'ut1_fraction',
)
def main():
ts = load.timescale()
t = ts.utc(2020, 10, 24)
for attribute in ATTRIBUTES:
step_width, up, down = measure_step_width(ts, t.whole, attribute)
step_width_s = step_width * 24 * 60 * 60
print('{:14} {:12.6g} seconds {} steps up, {} steps down'.format(
attribute, step_width_s, up, down))
def measure_step_width(ts, whole, attribute):
samples = np.arange(-500, 501)
widths = []
for tenth in 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0:
exp = -30
while True:
tt_fraction = tenth + samples * 10 ** exp
t = Time(ts, whole, tt_fraction)
output = getattr(t, attribute)
diff = np.diff(output)
steps_up = (diff > 0.0).sum()
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from skyfield.api import Time, load
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | steps_down = (diff < 0.0).sum() |
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python3
ATTRIBUTES = (
'J', 'delta_t', 'dut1', 'gmst',
# (lambda t: t.toordinal()),
'tai_fraction', 'tdb_fraction', 'ut1_fraction',
)
def main():
ts = load.timescale()
t = ts.utc(2020, 10, 24)
for attribute in ATTRIBUTES:
step_width, up, down = measure_step_width(ts, t.whole, attribute)
step_width_s = step_width * 24 * 60 * 60
print('{:14} {:12.6g} seconds {} steps up, {} steps down'.format(
attribute, step_width_s, up, down))
def measure_step_width(ts, whole, attribute):
samples = np.arange(-500, 501)
widths = []
<|code_end|>
with the help of current file imports:
import numpy as np
from skyfield.api import Time, load
and context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
, which may contain function names, class names, or code. Output only the next line. | for tenth in 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0: |
Continue the code snippet: <|code_start|> 'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH"""
assert repr(v) == """\
<VectorSum of 2 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH>"""
assert str(v.at(t)) == "\
<Barycentric BCRS position and velocity at date t center=0 target=399>"
v = earth + Topos('38.9215 N', '77.0669 W', elevation_m=92.0)
assert str(v) == """\
Sum of 3 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH
Geodetic 399 EARTH -> IERS2010 latitude +38.9215 N longitude -77.0669 E elevation 92.0 m"""
assert repr(v) == """\
<VectorSum of 3 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH
Geodetic 399 EARTH -> IERS2010 latitude +38.9215 N longitude -77.0669 E elevation 92.0 m>"""
assert str(v.at(t)) == """\
<Barycentric BCRS position and velocity at date t center=0 target=IERS2010 latitude +38.9215 N longitude -77.0669 E elevation 92.0 m>"""
v = earth - mars
assert str(v) == """\
<|code_end|>
. Use current file imports:
from assay import assert_raises
from skyfield.api import Topos, load
from skyfield.positionlib import Geocentric
and context (classes, functions, or code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/positionlib.py
# class Geocentric(ICRF):
# """An |xyz| position measured from the center of the Earth.
#
# A geocentric position is the difference between the position of the
# Earth at a given instant and the position of a target body at the
# same instant, without accounting for light-travel time or the effect
# of relativity on the light itself.
#
# Its ``.position`` and ``.velocity`` vectors have |xyz| axes that
# are those of the Geocentric Celestial Reference System (GCRS), an
# inertial system that is an update to J2000 and that does not rotate
# with the Earth itself.
#
# """
# _default_center = 399
#
# def itrf_xyz(self):
# """Deprecated; instead, call ``.frame_xyz(itrs)``. \
# See `reference_frames`."""
# return self.frame_xyz(framelib.itrs)
#
# def subpoint(self):
# """Deprecated; instead, call either ``iers2010.subpoint(pos)`` or \
# ``wgs84.subpoint(pos)``."""
# from .toposlib import iers2010
# return iers2010.subpoint(self)
. Output only the next line. | Sum of 4 vectors: |
Given the code snippet: <|code_start|>
def test_negation():
ts = load.timescale()
t = ts.utc(2020, 8, 30, 16, 5)
usno = Topos('38.9215 N', '77.0669 W', elevation_m=92.0)
neg = -usno
p1 = usno.at(t)
p2 = neg.at(t)
assert (p1.position.au == - p2.position.au).all()
assert (p1.velocity.au_per_d == - p2.velocity.au_per_d).all()
# A second negation should return the unwrapped original.
neg = -neg
assert neg is usno
def test_vectors():
ts = load.timescale()
t = ts.tt(2017, 1, 23, 10, 44)
planets = load('de421.bsp')
earth = planets['earth']
mars = planets['mars']
v = earth
assert str(v) == """\
Sum of 2 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH"""
<|code_end|>
, generate the next line using the imports in this file:
from assay import assert_raises
from skyfield.api import Topos, load
from skyfield.positionlib import Geocentric
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/positionlib.py
# class Geocentric(ICRF):
# """An |xyz| position measured from the center of the Earth.
#
# A geocentric position is the difference between the position of the
# Earth at a given instant and the position of a target body at the
# same instant, without accounting for light-travel time or the effect
# of relativity on the light itself.
#
# Its ``.position`` and ``.velocity`` vectors have |xyz| axes that
# are those of the Geocentric Celestial Reference System (GCRS), an
# inertial system that is an update to J2000 and that does not rotate
# with the Earth itself.
#
# """
# _default_center = 399
#
# def itrf_xyz(self):
# """Deprecated; instead, call ``.frame_xyz(itrs)``. \
# See `reference_frames`."""
# return self.frame_xyz(framelib.itrs)
#
# def subpoint(self):
# """Deprecated; instead, call either ``iers2010.subpoint(pos)`` or \
# ``wgs84.subpoint(pos)``."""
# from .toposlib import iers2010
# return iers2010.subpoint(self)
. Output only the next line. | assert repr(v) == """\ |
Based on the snippet: <|code_start|> ts = load.timescale()
t = ts.tt(2017, 1, 23, 10, 44)
planets = load('de421.bsp')
earth = planets['earth']
mars = planets['mars']
v = earth
assert str(v) == """\
Sum of 2 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH"""
assert repr(v) == """\
<VectorSum of 2 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH>"""
assert str(v.at(t)) == "\
<Barycentric BCRS position and velocity at date t center=0 target=399>"
v = earth + Topos('38.9215 N', '77.0669 W', elevation_m=92.0)
assert str(v) == """\
Sum of 3 vectors:
'de421.bsp' segment 0 SOLAR SYSTEM BARYCENTER -> 3 EARTH BARYCENTER
'de421.bsp' segment 3 EARTH BARYCENTER -> 399 EARTH
Geodetic 399 EARTH -> IERS2010 latitude +38.9215 N longitude -77.0669 E elevation 92.0 m"""
<|code_end|>
, predict the immediate next line with the help of imports:
from assay import assert_raises
from skyfield.api import Topos, load
from skyfield.positionlib import Geocentric
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/positionlib.py
# class Geocentric(ICRF):
# """An |xyz| position measured from the center of the Earth.
#
# A geocentric position is the difference between the position of the
# Earth at a given instant and the position of a target body at the
# same instant, without accounting for light-travel time or the effect
# of relativity on the light itself.
#
# Its ``.position`` and ``.velocity`` vectors have |xyz| axes that
# are those of the Geocentric Celestial Reference System (GCRS), an
# inertial system that is an update to J2000 and that does not rotate
# with the Earth itself.
#
# """
# _default_center = 399
#
# def itrf_xyz(self):
# """Deprecated; instead, call ``.frame_xyz(itrs)``. \
# See `reference_frames`."""
# return self.frame_xyz(framelib.itrs)
#
# def subpoint(self):
# """Deprecated; instead, call either ``iers2010.subpoint(pos)`` or \
# ``wgs84.subpoint(pos)``."""
# from .toposlib import iers2010
# return iers2010.subpoint(self)
. Output only the next line. | assert repr(v) == """\ |
Given the code snippet: <|code_start|>
def test_lunar_eclipses():
# The documentation test already confirms the dates of these two
# eclipses; here, we confirm that the data structures all match.
ts = load.timescale()
eph = load('de421.bsp')
t0 = ts.utc(2019, 1, 1)
<|code_end|>
, generate the next line using the imports in this file:
from skyfield.api import load
from skyfield import eclipselib
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/eclipselib.py
# LUNAR_ECLIPSES = [
# 'Penumbral',
# 'Partial',
# 'Total',
# ]
# def lunar_eclipses(start_time, end_time, eph):
# def f(t):
. Output only the next line. | t1 = ts.utc(2020, 1, 1) |
Predict the next line after this snippet: <|code_start|>
def test_lunar_eclipses():
# The documentation test already confirms the dates of these two
# eclipses; here, we confirm that the data structures all match.
ts = load.timescale()
eph = load('de421.bsp')
t0 = ts.utc(2019, 1, 1)
t1 = ts.utc(2020, 1, 1)
t, y, details = eclipselib.lunar_eclipses(t0, t1, eph)
assert len(t) == len(y) == 2
<|code_end|>
using the current file's imports:
from skyfield.api import load
from skyfield import eclipselib
and any relevant context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/eclipselib.py
# LUNAR_ECLIPSES = [
# 'Penumbral',
# 'Partial',
# 'Total',
# ]
# def lunar_eclipses(start_time, end_time, eph):
# def f(t):
. Output only the next line. | for name, item in details.items(): |
Here is a snippet: <|code_start|> sat = api.EarthSatellite(*tle[1:3], name=tle[0])
topos = api.Topos('42.3581 N', '71.0636 W')
timescale = api.load.timescale()
t0 = timescale.tai(2014, 11, 10)
t1 = timescale.tai(2014, 11, 11)
horizon = 20
nexpected = 12
times, yis = sat.find_events(topos, t0, t1, 20.0)
assert(verify_sat_almanac(times, yis, sat, topos, horizon, nexpected))
def test_sat_almanac_tricky():
# Various tricky satellites
# Integral: 3 days high eccentricity.
# ANIK-F1R Geo always visible from Boston
# PALAPA D Geo never visible from Boston
# Ariane 5B GTO
# Swift Low-inclination LEO never visible from Boston
# Grace-FO 2 Low polar orbit
tles = """\
INTEGRAL
1 27540U 02048A 20007.25125384 .00001047 00000-0 00000+0 0 9992
2 27540 51.8988 127.5680 8897013 285.8757 2.8911 0.37604578 17780
ANIK F-1R
1 28868U 05036A 20011.46493281 -.00000066 00000-0 00000+0 0 9999
2 28868 0.0175 50.4632 0002403 284.1276 195.8977 1.00270824 52609
PALAPA D
1 35812U 09046A 20008.38785173 -.00000341 +00000-0 +00000-0 0 9999
2 35812 000.0518 095.9882 0002721 218.8296 045.1595 01.00269700038098
<|code_end|>
. Write the next line using the current file imports:
from skyfield import api
and context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
, which may include functions, classes, or code. Output only the next line. | Ariane 5B |
Continue the code snippet: <|code_start|> axes.xaxis.set_minor_locator(HourLocator([0, 6, 12, 18]))
axes.xaxis.set_major_formatter(DateFormatter('0h\n%Y %b %d\n%A'))
axes.xaxis.set_minor_formatter(DateFormatter('%Hh'))
for label in ax.xaxis.get_ticklabels(which='both'):
label.set_horizontalalignment('left')
axes.yaxis.set_major_formatter('{x:.0f} km')
axes.tick_params(which='both', length=0)
# Load the satellite's final TLE entry.
sat = EarthSatellite(
'1 34602U 09013A 13314.96046236 .14220718 20669-5 50412-4 0 930',
'2 34602 096.5717 344.5256 0009826 296.2811 064.0942 16.58673376272979',
'GOCE',
)
# Build the time range `t` over which to plot, plus other values.
ts = load.timescale()
t = ts.tt_jd(np.arange(sat.epoch.tt - 2.0, sat.epoch.tt + 2.0, 0.005))
reentry = ts.utc(2013, 11, 11, 0, 16)
earth_radius_km = 6371.0
# Compute geocentric positions for the satellite.
g = sat.at(t)
valid = [m is None for m in g.message]
# Start a new figure.
<|code_end|>
. Use current file imports:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.dates import HourLocator, DateFormatter
from skyfield.api import load, EarthSatellite
and context (classes, functions, or code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | fig, ax = plt.subplots() |
Next line prediction: <|code_start|> 'GOCE',
)
# Build the time range `t` over which to plot, plus other values.
ts = load.timescale()
t = ts.tt_jd(np.arange(sat.epoch.tt - 2.0, sat.epoch.tt + 2.0, 0.005))
reentry = ts.utc(2013, 11, 11, 0, 16)
earth_radius_km = 6371.0
# Compute geocentric positions for the satellite.
g = sat.at(t)
valid = [m is None for m in g.message]
# Start a new figure.
fig, ax = plt.subplots()
# Draw the blue curve.
x = t.utc_datetime()
y = np.where(valid, g.distance().km - earth_radius_km, np.nan)
ax.plot(x, y)
# Label the TLE epoch.
x = sat.epoch.utc_datetime()
y = sat.at(sat.epoch).distance().km - earth_radius_km
ax.plot(x, y, 'k.')
<|code_end|>
. Use current file imports:
(import numpy as np
from matplotlib import pyplot as plt
from matplotlib.dates import HourLocator, DateFormatter
from skyfield.api import load, EarthSatellite)
and context including class names, function names, or small code snippets from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | ax.text(x, y - 9, 'Epoch of TLE data ', ha='right') |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
line1 = '1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993'
line2 = '2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106'
# Here are numbers from HORIZONS, which I copied into the test below:
#
#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons
#...
#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB
# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05
# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
<|code_end|>
. Use current file imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and context (classes, functions, or code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
. Output only the next line. | hp = array([ |
Predict the next line after this snippet: <|code_start|>#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
[-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
]).T
hv = array([
[-1.751248694205384E-3, 4.065407557020968E-3, 1.363540232307603E-4],
[2.143876266215405E-3, -3.752167957502106E-3, 9.484159290242074E-4],
]).T
two_meters = 2.0 / AU_M
three_km_per_hour = 3.0 * 24.0 / AU_KM
t = ts.tdb(2018, 7, 4)
p = s.at(t)
assert abs(p.position.au - hp[:,0]).max() < two_meters
assert abs(p.velocity.au_per_d - hv[:,0]).max() < three_km_per_hour
t = ts.tdb(2018, 7, [4, 5])
p = s.at(t)
assert abs(p.position.au - hp).max() < two_meters
<|code_end|>
using the current file's imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and any relevant context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
. Output only the next line. | assert abs(p.velocity.au_per_d - hv).max() < three_km_per_hour |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
line1 = '1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993'
line2 = '2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106'
# Here are numbers from HORIZONS, which I copied into the test below:
#
#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons
#...
#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB
# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05
# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
[-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
<|code_end|>
, determine the next line of code. You have imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and context (class names, function names, or code) available:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
. Output only the next line. | ]).T |
Given snippet: <|code_start|># VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
[-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
]).T
hv = array([
[-1.751248694205384E-3, 4.065407557020968E-3, 1.363540232307603E-4],
[2.143876266215405E-3, -3.752167957502106E-3, 9.484159290242074E-4],
]).T
two_meters = 2.0 / AU_M
three_km_per_hour = 3.0 * 24.0 / AU_KM
t = ts.tdb(2018, 7, 4)
p = s.at(t)
assert abs(p.position.au - hp[:,0]).max() < two_meters
assert abs(p.velocity.au_per_d - hv[:,0]).max() < three_km_per_hour
t = ts.tdb(2018, 7, [4, 5])
p = s.at(t)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and context:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
which might include code, classes, or functions. Output only the next line. | assert abs(p.position.au - hp).max() < two_meters |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
line1 = '1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993'
line2 = '2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106'
# Here are numbers from HORIZONS, which I copied into the test below:
#
#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons
#...
#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB
# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05
# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and context:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
which might include code, classes, or functions. Output only the next line. | [-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5], |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
line1 = '1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993'
line2 = '2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106'
# Here are numbers from HORIZONS, which I copied into the test below:
#
#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons
#...
#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB
# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05
# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
[-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
]).T
<|code_end|>
. Use current file imports:
(from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD)
and context including class names, function names, or small code snippets from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
. Output only the next line. | hv = array([ |
Here is a snippet: <|code_start|>#
#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons
#...
#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB
# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05
# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
[-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
]).T
hv = array([
[-1.751248694205384E-3, 4.065407557020968E-3, 1.363540232307603E-4],
[2.143876266215405E-3, -3.752167957502106E-3, 9.484159290242074E-4],
]).T
two_meters = 2.0 / AU_M
three_km_per_hour = 3.0 * 24.0 / AU_KM
t = ts.tdb(2018, 7, 4)
p = s.at(t)
<|code_end|>
. Write the next line using the current file imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
, which may include functions, classes, or code. Output only the next line. | assert abs(p.position.au - hp[:,0]).max() < two_meters |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
line1 = '1 25544U 98067A 18184.80969102 .00001614 00000-0 31745-4 0 9993'
line2 = '2 25544 51.6414 295.8524 0003435 262.6267 204.2868 15.54005638121106'
# Here are numbers from HORIZONS, which I copied into the test below:
#
#Ephemeris / WWW_USER Wed Jul 4 19:16:45 2018 Pasadena, USA / Horizons
#...
#2458303.500000000 = A.D. 2018-Jul-04 00:00:00.0000 TDB
# X = 2.633404251158200E-05 Y = 1.015087620439817E-05 Z = 3.544778677556393E-05
# VX=-1.751248694205384E-03 VY= 4.065407557020968E-03 VZ= 1.363540232307603E-04
#2458304.500000000 = A.D. 2018-Jul-05 00:00:00.0000 TDB
# X =-2.136440257814821E-05 Y =-2.084170814514480E-05 Z =-3.415494123796893E-05
# VX= 2.143876266215405E-03 VY=-3.752167957502106E-03 VZ= 9.484159290242074E-04
# TODO: try with array of dates
def test_iss_against_horizons():
ts = api.load.timescale()
s = EarthSatellite(line1, line2)
hp = array([
[2.633404251158200E-5, 1.015087620439817E-5, 3.544778677556393E-5],
[-2.136440257814821E-5, -2.084170814514480E-5, -3.415494123796893E-5],
]).T
hv = array([
<|code_end|>
. Use current file imports:
from numpy import array
from skyfield import api
from skyfield.api import EarthSatellite, load
from skyfield.constants import AU_KM, AU_M
from skyfield.sgp4lib import TEME_to_ITRF
from skyfield.timelib import julian_date
from ..constants import DEG2RAD
and context (classes, functions, or code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/constants.py
# AU_KM = 149597870.700
#
# AU_M = 149597870700 # per IAU 2012 Resolution B2
#
# Path: skyfield/sgp4lib.py
# def TEME_to_ITRF(jd_ut1, rTEME, vTEME, xp=0.0, yp=0.0, fraction_ut1=0.0):
# """Deprecated: use the TEME and ITRS frame objects instead."""
# theta, theta_dot = theta_GMST1982(jd_ut1, fraction_ut1)
# angular_velocity = multiply.outer(_zero_zero_minus_one, theta_dot)
#
# R = rot_z(-theta)
#
# if len(rTEME.shape) == 1:
# rPEF = (R).dot(rTEME)
# vPEF = (R).dot(vTEME) + _cross(angular_velocity, rPEF)
# else:
# rPEF = mxv(R, rTEME)
# vPEF = mxv(R, vTEME) + _cross(angular_velocity, rPEF)
#
# if xp == 0.0 and yp == 0.0:
# rITRF = rPEF
# vITRF = vPEF
# else:
# W = (rot_x(yp)).dot(rot_y(xp))
# rITRF = (W).dot(rPEF)
# vITRF = (W).dot(vPEF)
# return rITRF, vITRF
#
# Path: skyfield/timelib.py
# def julian_date(year, month=1, day=1, hour=0, minute=0, second=0.0):
# """Given a proleptic Gregorian calendar date and time, build a Julian date.
#
# The difference between a “Julian day” and a “Julian date” is that
# the “day” is the integer part, while the “date” includes a fraction
# indicating the time.
#
# """
# return julian_day(year, month, day) - 0.5 + (
# second + minute * 60.0 + hour * 3600.0) / DAY_S
#
# Path: skyfield/constants.py
# DEG2RAD = 0.017453292519943296
. Output only the next line. | [-1.751248694205384E-3, 4.065407557020968E-3, 1.363540232307603E-4], |
Given the code snippet: <|code_start|>
ts = load.timescale()
eph = load('de421.bsp')
sun = eph['sun']
earth = eph['earth']
#bluffton = earth + api.wgs84.latlon(40.8939, -83.8917)
bluffton = api.wgs84.latlon(40.8939, -83.8917)
<|code_end|>
, generate the next line using the imports in this file:
from skyfield import almanac, api
from skyfield.api import load, tau
from numpy import arccos, sin, cos
from time import time
import numpy as np
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | t0 = ts.utc(2020, 1, 1) |
Using the snippet: <|code_start|> slope = rise / run
timebump = adjustment / slope
print(timebump)
t3 = ts.tt_jd(t2.tt + timebump)
ha3, dec3, _ = observer.at(t3).observe(body).apparent().hadec()
setting_ha3 = _sunrise_hour_angle_radians(geo.latitude, dec3, stdalt)
rising_ha3 = - setting_ha3
print(ha3.radians - rising_ha3)
print(max(abs((ha3.radians - rising_ha3))) / tau * 24.0 * 3600.0,
'seconds')
return t3
# adjustment = stdalt - alt.radians
# print(max(abs(adjustment)) / tau * 24.0 * 3600.0,
# 'radians adj, in seconds of day (approx)')
# print(max(adjustment / tau * 24.0 * 3600.0),
# 'max')
#ha, dec, _ = observer.at(t).observe(body).apparent().hadec()
#find_sunrise(earth + bluffton, sun, stdalt, t0, t1)
T0 = time()
t_new = find_sunrise(earth + bluffton, sun, stdalt, t0, t1)
DUR_NEW = time() - T0
<|code_end|>
, determine the next line of code. You have imports:
from skyfield import almanac, api
from skyfield.api import load, tau
from numpy import arccos, sin, cos
from time import time
import numpy as np
and context (class names, function names, or code) available:
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | T0 = time() |
Predict the next line for this snippet: <|code_start|> i, = np.nonzero(np.diff(difference) < 0.0)
print(i)
a = tau - difference[i]
b = difference[i + 1]
print(a)
print(b)
tt = t.tt
new_tt = (b * tt[i] + a * tt[i+1]) / (a + b)
print(tt)
print(new_tt)
t2 = ts.tt_jd(new_tt)
ha2, dec2, _ = observer.at(t2).observe(body).apparent().hadec()
setting_ha2 = _sunrise_hour_angle_radians(geo.latitude, dec2, stdalt)
rising_ha2 = - setting_ha2
# alt, az, _ = observer.at(t).observe(body).apparent().altaz()
# print(alt.degrees, 'alt')
# print(alt.radians, 'alt radians')
# print(stdalt, 'desired radians')
# try a->t ?
adjustment = rising_ha2 - ha2.radians
print(max(abs(adjustment)) / tau * 24.0 * 3600.0,
'max adjustment (~seconds of day)')
rise = ha2.radians - ha.radians[i]
run = t2.tt - t[i].tt
slope = rise / run
<|code_end|>
with the help of current file imports:
from skyfield import almanac, api
from skyfield.api import load, tau
from numpy import arccos, sin, cos
from time import time
import numpy as np
and context from other files:
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
, which may contain function names, class names, or code. Output only the next line. | timebump = adjustment / slope |
Next line prediction: <|code_start|> rise = ha2.radians - ha.radians[i]
run = t2.tt - t[i].tt
slope = rise / run
timebump = adjustment / slope
print(timebump)
t3 = ts.tt_jd(t2.tt + timebump)
ha3, dec3, _ = observer.at(t3).observe(body).apparent().hadec()
setting_ha3 = _sunrise_hour_angle_radians(geo.latitude, dec3, stdalt)
rising_ha3 = - setting_ha3
print(ha3.radians - rising_ha3)
print(max(abs((ha3.radians - rising_ha3))) / tau * 24.0 * 3600.0,
'seconds')
return t3
# adjustment = stdalt - alt.radians
# print(max(abs(adjustment)) / tau * 24.0 * 3600.0,
# 'radians adj, in seconds of day (approx)')
# print(max(adjustment / tau * 24.0 * 3600.0),
# 'max')
#ha, dec, _ = observer.at(t).observe(body).apparent().hadec()
#find_sunrise(earth + bluffton, sun, stdalt, t0, t1)
T0 = time()
t_new = find_sunrise(earth + bluffton, sun, stdalt, t0, t1)
<|code_end|>
. Use current file imports:
(from skyfield import almanac, api
from skyfield.api import load, tau
from numpy import arccos, sin, cos
from time import time
import numpy as np)
and context including class names, function names, or small code snippets from other files:
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | DUR_NEW = time() - T0 |
Given snippet: <|code_start|>
ts = api.load.timescale()
t0 = ts.tt(-1000, 1, 1)
t1 = ts.tt(2000, 1, 1)
days = int(t1 - t0)
if 1:
t = ts.tt(-1000, 1, range(days))
gy, gm, gd = t.tt_calendar()[:3]
ts.julian_calendar_cutoff = 99999999999999999 #api.GREGORIAN_START
jy, jm, jd = t.tt_calendar()[:3]
print(gd - jd)
# import numpy as np
# t = np.arange(0.0, 2.0, 0.01)
# s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t.J, gd - jd, '.') #, label='label', linestyle='--')
ax.axvline(325, color='blue')
#ax.plot(325, 0, '.') #, label='label', linestyle='--')
# ax.set(xlabel='time (s)', ylabel='voltage (mV)', title='Title')
# ax.set_aspect(aspect=1.0)
ax.grid()
# plt.legend()
ax.set_ylim(-10, 15)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from skyfield import almanac
from skyfield import api
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
and context:
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
which might include code, classes, or functions. Output only the next line. | fig.savefig('tmp.png') |
Based on the snippet: <|code_start|>
ts = api.load.timescale()
t0 = ts.tt(-1000, 1, 1)
t1 = ts.tt(2000, 1, 1)
days = int(t1 - t0)
if 1:
t = ts.tt(-1000, 1, range(days))
<|code_end|>
, predict the immediate next line with the help of imports:
from skyfield import almanac
from skyfield import api
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
#
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | gy, gm, gd = t.tt_calendar()[:3] |
Here is a snippet: <|code_start|>
# Compare with USNO:
# http://aa.usno.navy.mil/cgi-bin/aa_moonill2.pl?form=1&year=2018&task=00&tz=-05
def test_fraction_illuminated():
ts = api.load.timescale()
t0 = ts.utc(2018, 9, range(9, 19), 5)
e = api.load('de421.bsp')
i = almanac.fraction_illuminated(e, 'moon', t0[-1]).round(2)
assert i == 0.62
i = almanac.fraction_illuminated(e, 'moon', t0).round(2)
assert list(i) == [0, 0, 0.03, 0.08, 0.15, 0.24, 0.33, 0.43, 0.52, 0.62]
# Compare with USNO:
# http://aa.usno.navy.mil/seasons?year=2018&tz=+0
def test_seasons():
ts = api.load.timescale()
t0 = ts.utc(2018, 9, 20)
t1 = ts.utc(2018, 12, 31)
e = api.load('de421.bsp')
t, y = almanac.find_discrete(t0, t1, almanac.seasons(e))
strings = t.utc_strftime('%Y-%m-%d %H:%M')
<|code_end|>
. Write the next line using the current file imports:
from skyfield import api, almanac
and context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
, which may include functions, classes, or code. Output only the next line. | print(strings) |
Next line prediction: <|code_start|> ts = api.load.timescale()
t0 = ts.utc(2018, 9, 11)
t1 = ts.utc(2018, 9, 30)
e = api.load('de421.bsp')
t, y = almanac.find_discrete(t0, t1, almanac.moon_phases(e))
strings = t.utc_strftime('%Y-%m-%d %H:%M')
assert strings == ['2018-09-16 23:15', '2018-09-25 02:52']
assert (y == (1, 2)).all()
def test_moon_nodes():
ts = api.load.timescale()
e = api.load('de421.bsp')
t0 = ts.utc(2022, 1, 13)
t1 = ts.utc(2022, 1, 31)
t, y = almanac.find_discrete(t0, t1, almanac.moon_nodes(e))
strings = t.utc_strftime('%Y-%m-%d %H:%M')
assert strings == ['2022-01-13 04:19', '2022-01-27 06:15']
assert list(y) == [1, 0]
def test_oppositions_conjunctions():
ts = api.load.timescale()
t0 = ts.utc(2019, 1, 1)
t1 = ts.utc(2021, 1, 1)
e = api.load('de421.bsp')
f = almanac.oppositions_conjunctions(e, e['mars'])
t, y = almanac.find_discrete(t0, t1, f)
strings = t.utc_strftime('%Y-%m-%d %H:%M')
assert strings == ['2019-09-02 10:42', '2020-10-13 23:26']
assert (y == (0, 1)).all()
<|code_end|>
. Use current file imports:
(from skyfield import api, almanac)
and context including class names, function names, or small code snippets from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
. Output only the next line. | def test_oppositions_conjunctions_of_moon(): |
Predict the next line after this snippet: <|code_start|>
Angle(angle=another_angle)
Angle(radians=value)
Angle(degrees=value)
Angle(hours=value)
where `value` can be either a Python float, a list of Python floats,
or a NumPy array of floats"""
class Angle(Unit):
def __init__(self, angle=None, radians=None, degrees=None, hours=None,
preference=None, signed=False):
if angle is not None:
if not isinstance(angle, Angle):
raise ValueError(_instantiation_instructions)
self.radians = angle.radians
elif radians is not None:
self.radians = _to_array(radians)
elif degrees is not None:
self._degrees = degrees = _to_array(_unsexagesimalize(degrees))
self.radians = degrees / 360.0 * tau
elif hours is not None:
self._hours = hours = _to_array(_unsexagesimalize(hours))
self.radians = hours / 24.0 * tau
self.preference = (preference if preference is not None
else 'hours' if hours is not None
else 'degrees')
<|code_end|>
using the current file's imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and any relevant context from other files:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | self.signed = signed |
Here is a snippet: <|code_start|> """Units per day of Terrestrial Time."""
return self._per_day
@reify
def per_hour(self):
"""Units per hour of Terrestrial Time."""
return self._per_day / 24.0
@reify
def per_minute(self):
"""Units per minute of Terrestrial Time."""
return self._per_day / 1440.0
@reify
def per_second(self):
"""Units per second of Terrestrial Time."""
return self._per_day / 86400.0
# Angle units.
_instantiation_instructions = """to instantiate an Angle, try one of:
Angle(angle=another_angle)
Angle(radians=value)
Angle(degrees=value)
Angle(hours=value)
where `value` can be either a Python float, a list of Python floats,
or a NumPy array of floats"""
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context from other files:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
, which may include functions, classes, or code. Output only the next line. | class Angle(Unit): |
Using the snippet: <|code_start|> """Units per day of Terrestrial Time."""
return self._per_day
@reify
def per_hour(self):
"""Units per hour of Terrestrial Time."""
return self._per_day / 24.0
@reify
def per_minute(self):
"""Units per minute of Terrestrial Time."""
return self._per_day / 1440.0
@reify
def per_second(self):
"""Units per second of Terrestrial Time."""
return self._per_day / 86400.0
# Angle units.
_instantiation_instructions = """to instantiate an Angle, try one of:
Angle(angle=another_angle)
Angle(radians=value)
Angle(degrees=value)
Angle(hours=value)
where `value` can be either a Python float, a list of Python floats,
or a NumPy array of floats"""
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context (class names, function names, or code) available:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | class Angle(Unit): |
Here is a snippet: <|code_start|>
where `value` can be either a Python float, a list of Python floats,
or a NumPy array of floats"""
class Angle(Unit):
def __init__(self, angle=None, radians=None, degrees=None, hours=None,
preference=None, signed=False):
if angle is not None:
if not isinstance(angle, Angle):
raise ValueError(_instantiation_instructions)
self.radians = angle.radians
elif radians is not None:
self.radians = _to_array(radians)
elif degrees is not None:
self._degrees = degrees = _to_array(_unsexagesimalize(degrees))
self.radians = degrees / 360.0 * tau
elif hours is not None:
self._hours = hours = _to_array(_unsexagesimalize(hours))
self.radians = hours / 24.0 * tau
self.preference = (preference if preference is not None
else 'hours' if hours is not None
else 'degrees')
self.signed = signed
@classmethod
def from_degrees(cls, degrees, signed=False):
degrees = _to_array(_unsexagesimalize(degrees))
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context from other files:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
, which may include functions, classes, or code. Output only the next line. | self = cls.__new__(cls) |
Using the snippet: <|code_start|> def per_second(self):
"""Units per second of Terrestrial Time."""
return self._per_day / 86400.0
# Angle units.
_instantiation_instructions = """to instantiate an Angle, try one of:
Angle(angle=another_angle)
Angle(radians=value)
Angle(degrees=value)
Angle(hours=value)
where `value` can be either a Python float, a list of Python floats,
or a NumPy array of floats"""
class Angle(Unit):
def __init__(self, angle=None, radians=None, degrees=None, hours=None,
preference=None, signed=False):
if angle is not None:
if not isinstance(angle, Angle):
raise ValueError(_instantiation_instructions)
self.radians = angle.radians
elif radians is not None:
self.radians = _to_array(radians)
elif degrees is not None:
self._degrees = degrees = _to_array(_unsexagesimalize(degrees))
self.radians = degrees / 360.0 * tau
<|code_end|>
, determine the next line of code. You have imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context (class names, function names, or code) available:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | elif hours is not None: |
Here is a snippet: <|code_start|>class Angle(Unit):
def __init__(self, angle=None, radians=None, degrees=None, hours=None,
preference=None, signed=False):
if angle is not None:
if not isinstance(angle, Angle):
raise ValueError(_instantiation_instructions)
self.radians = angle.radians
elif radians is not None:
self.radians = _to_array(radians)
elif degrees is not None:
self._degrees = degrees = _to_array(_unsexagesimalize(degrees))
self.radians = degrees / 360.0 * tau
elif hours is not None:
self._hours = hours = _to_array(_unsexagesimalize(hours))
self.radians = hours / 24.0 * tau
self.preference = (preference if preference is not None
else 'hours' if hours is not None
else 'degrees')
self.signed = signed
@classmethod
def from_degrees(cls, degrees, signed=False):
degrees = _to_array(_unsexagesimalize(degrees))
self = cls.__new__(cls)
self.degrees = degrees
self.radians = degrees / 360.0 * tau
self.preference = 'degrees'
<|code_end|>
. Write the next line using the current file imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context from other files:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
, which may include functions, classes, or code. Output only the next line. | self.signed = signed |
Given snippet: <|code_start|>class Angle(Unit):
def __init__(self, angle=None, radians=None, degrees=None, hours=None,
preference=None, signed=False):
if angle is not None:
if not isinstance(angle, Angle):
raise ValueError(_instantiation_instructions)
self.radians = angle.radians
elif radians is not None:
self.radians = _to_array(radians)
elif degrees is not None:
self._degrees = degrees = _to_array(_unsexagesimalize(degrees))
self.radians = degrees / 360.0 * tau
elif hours is not None:
self._hours = hours = _to_array(_unsexagesimalize(hours))
self.radians = hours / 24.0 * tau
self.preference = (preference if preference is not None
else 'hours' if hours is not None
else 'degrees')
self.signed = signed
@classmethod
def from_degrees(cls, degrees, signed=False):
degrees = _to_array(_unsexagesimalize(degrees))
self = cls.__new__(cls)
self.degrees = degrees
self.radians = degrees / 360.0 * tau
self.preference = 'degrees'
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
which might include code, classes, or functions. Output only the next line. | self.signed = signed |
Based on the snippet: <|code_start|># Angle units.
_instantiation_instructions = """to instantiate an Angle, try one of:
Angle(angle=another_angle)
Angle(radians=value)
Angle(degrees=value)
Angle(hours=value)
where `value` can be either a Python float, a list of Python floats,
or a NumPy array of floats"""
class Angle(Unit):
def __init__(self, angle=None, radians=None, degrees=None, hours=None,
preference=None, signed=False):
if angle is not None:
if not isinstance(angle, Angle):
raise ValueError(_instantiation_instructions)
self.radians = angle.radians
elif radians is not None:
self.radians = _to_array(radians)
elif degrees is not None:
self._degrees = degrees = _to_array(_unsexagesimalize(degrees))
self.radians = degrees / 360.0 * tau
elif hours is not None:
self._hours = hours = _to_array(_unsexagesimalize(hours))
self.radians = hours / 24.0 * tau
<|code_end|>
, predict the immediate next line with the help of imports:
import numpy as np
from numpy import abs, copysign, isnan
from .constants import AU_KM, AU_M, C, DAY_S, tau
from .descriptorlib import reify
from .functions import _to_array, length_of
from astropy.units import au
from astropy.units import au, d
from astropy.units import rad
from astropy.coordinates import Angle
from astropy.units import rad
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/constants.py
# AU_M = 149597870700 # per IAU 2012 Resolution B2
# AU_KM = 149597870.700
# ASEC360 = 1296000.0
# DAY_S = 86400.0
# ASEC2RAD = 4.848136811095359935899141e-6
# DEG2RAD = 0.017453292519943296
# RAD2DEG = 57.295779513082321
# C = 299792458.0 # m/s
# ANGVEL = 7.2921150e-5 # radians/s
# ERAD = 6378136.6 # meters
# IERS_2010_INVERSE_EARTH_FLATTENING = 298.25642
# GS = 1.32712440017987e+20
# T0 = 2451545.0
# B1950 = 2433282.4235
# C_AUDAY = C * DAY_S / AU_M
#
# Path: skyfield/descriptorlib.py
# class reify(object):
# """Adapted from Pyramid's `reify()` memoizing decorator."""
# def __init__(self, method):
# self.method = method
# update_wrapper(self, method)
#
# def __get__(self, instance, objtype=None):
# if instance is None:
# return self
# value = self.method(instance)
# instance.__dict__[self.__name__] = value
# return value
#
# Path: skyfield/functions.py
# def _to_array(value):
# """Convert plain Python sequences into NumPy arrays.
#
# This helps Skyfield endpoints convert caller-provided tuples and
# lists into NumPy arrays. If the ``value`` is not a sequence, then
# it is coerced to a Numpy float object, but not an actual array.
#
# """
# if hasattr(value, 'shape'):
# return value
# elif hasattr(value, '__len__'):
# return array(value)
# else:
# return float64(value)
#
# def length_of(xyz):
# """Given a 3-element array |xyz|, return its length.
#
# The three elements can be simple scalars, or the array can be two
# dimensions and offer three whole series of x, y, and z coordinates.
#
# """
# return sqrt((xyz * xyz).sum(axis=0))
. Output only the next line. | self.preference = (preference if preference is not None |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(version_of('sgp4')))
ts = load.timescale()
fmt = '%Y-%m-%d'
final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60)
print('Built-in leap seconds table ends with leap second at: {0}'
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
daily_tt = arrays['tt_jd_minus_arange']
daily_tt += np.arange(len(daily_tt))
start = ts.tt_jd(daily_tt[0])
end = ts.tt_jd(daily_tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
.format(start.utc_strftime(fmt), end.utc_strftime(fmt)))
def version_of(distribution):
try:
d = pkg_resources.get_distribution(distribution)
<|code_end|>
, predict the next line using imports from the current file:
import pkg_resources
import numpy as np
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
and context including class names, function names, and sometimes code from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/functions.py
# def load_bundled_npy(filename):
# """Load a binary NumPy array file that is bundled with Skyfield."""
# data = get_data('skyfield', 'data/{0}'.format(filename))
# return load(BytesIO(data))
. Output only the next line. | except pkg_resources.DistributionNotFound: |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
def main():
print('Skyfield version: {0}'.format(skyfield.__version__))
print('jplephem version: {0}'.format(version_of('jplephem')))
print('sgp4 version: {0}'.format(version_of('sgp4')))
ts = load.timescale()
fmt = '%Y-%m-%d'
final_leap = (ts._leap_tai[-1] - 1) / (24 * 60 * 60)
print('Built-in leap seconds table ends with leap second at: {0}'
.format(ts.tai_jd(final_leap).utc_strftime()))
arrays = load_bundled_npy('iers.npz')
daily_tt = arrays['tt_jd_minus_arange']
daily_tt += np.arange(len(daily_tt))
start = ts.tt_jd(daily_tt[0])
end = ts.tt_jd(daily_tt[-1])
print('Built-in ∆T table from finals2000A.all covers: {0} to {1}'
<|code_end|>
, generate the next line using the imports in this file:
import pkg_resources
import numpy as np
import skyfield
from skyfield.api import load
from skyfield.functions import load_bundled_npy
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/functions.py
# def load_bundled_npy(filename):
# """Load a binary NumPy array file that is bundled with Skyfield."""
# data = get_data('skyfield', 'data/{0}'.format(filename))
# return load(BytesIO(data))
. Output only the next line. | .format(start.utc_strftime(fmt), end.utc_strftime(fmt))) |
Continue the code snippet: <|code_start|>
ts = load.timescale()
ephem = load('de430t.bsp')
earth = ephem['earth']
sun = ephem['sun']
moon = ephem['moon']
mars = ephem['mars barycenter']
greenwich = earth + Topos(latitude_degrees=(51, 28, 40), longitude_degrees=(0, 0, -5))
<|code_end|>
. Use current file imports:
from skyfield.api import load, Topos, EarthSatellite, Star
from almanac2 import seasons, moon_phases, meridian_transits, culminations, twilights, risings_settings
and context (classes, functions, or code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | iss_tle = """\ |
Continue the code snippet: <|code_start|>
ts = load.timescale()
ephem = load('de430t.bsp')
earth = ephem['earth']
sun = ephem['sun']
<|code_end|>
. Use current file imports:
from skyfield.api import load, Topos, EarthSatellite, Star
from almanac2 import seasons, moon_phases, meridian_transits, culminations, twilights, risings_settings
and context (classes, functions, or code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | moon = ephem['moon'] |
Predict the next line after this snippet: <|code_start|>
ts = load.timescale()
ephem = load('de430t.bsp')
earth = ephem['earth']
<|code_end|>
using the current file's imports:
from skyfield.api import load, Topos, EarthSatellite, Star
from almanac2 import seasons, moon_phases, meridian_transits, culminations, twilights, risings_settings
and any relevant context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
. Output only the next line. | sun = ephem['sun'] |
Predict the next line for this snippet: <|code_start|>
ts = load.timescale()
ephem = load('de430t.bsp')
earth = ephem['earth']
sun = ephem['sun']
<|code_end|>
with the help of current file imports:
from skyfield.api import load, Topos, EarthSatellite, Star
from almanac2 import seasons, moon_phases, meridian_transits, culminations, twilights, risings_settings
and context from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
, which may contain function names, class names, or code. Output only the next line. | moon = ephem['moon'] |
Predict the next line after this snippet: <|code_start|> mag = m._earth_magnitude(0.983331936476, 1.41317594650699, 8.7897)
assert abs(-3.269 - mag) < 0.0005
mag = m._earth_magnitude(0.983356079811, 0.26526856764726, 4.1369)
assert abs(-6.909 - mag) < 0.0005
mag = m._earth_magnitude(0.983356467727, 0.62933287342927, 175.6869)
assert abs(1.122 - mag) < 0.0005
args = [
A[0.983331936476, 0.983356079811, 0.983356467727],
A[1.41317594650699, 0.26526856764726, 0.62933287342927],
A[8.7897, 4.1369, 175.6869],
]
magnitudes = m._earth_magnitude(*args)
expected = [-3.269, -6.909, 1.122]
np.allclose(magnitudes, expected, 0, 0.0005, equal_nan=True)
def test_mars_magnitude_function():
mag = m._mars_magnitude(1.381191244505, 0.37274381097911, 4.8948)
assert abs(-2.862 - mag) < 0.1
mag = m._mars_magnitude(1.664150453905, 2.58995164518460, 11.5877)
assert abs(1.788 - mag) < 0.1
mag = m._mars_magnitude(1.591952180003, 3.85882552272013, 167.9000)
assert abs(8.977 - mag) < 0.1
args = [
A[1.381191244505, 1.664150453905, 1.591952180003],
A[0.37274381097911, 2.58995164518460, 3.85882552272013],
A[4.8948, 11.5877, 167.9000],
]
magnitudes = m._mars_magnitude(*args)
<|code_end|>
using the current file's imports:
import numpy as np
from numpy import nan
from skyfield import magnitudelib as m
from skyfield.tests.conventions import A
and any relevant context from other files:
# Path: skyfield/magnitudelib.py
# _SATURN_POLE = array([0.08547883, 0.07323576, 0.99364475])
# _URANUS_POLE = array([-0.21199958 -0.94155916 -0.26176809])
# _FUNCTIONS = {
# 199: _mercury_magnitude,
# 299: _venus_magnitude,
# 399: _earth_magnitude,
# 499: _mars_magnitude,
# 599: _jupiter_magnitude,
# 699: _saturn_magnitude,
# 799: _uranus_magnitude,
# 899: _neptune_magnitude,
#
# # Some planets can be reasonably identified with their barycenter.
# 1: _mercury_magnitude,
# 2: _venus_magnitude,
# 4: _mars_magnitude,
# 5: _jupiter_magnitude,
# 6: _saturn_magnitude,
# 7: _uranus_magnitude,
# 8: _neptune_magnitude,
# }
# def planetary_magnitude(position):
# def _mercury_magnitude(r, delta, ph_ang):
# def _venus_magnitude(r, delta, ph_ang):
# def _earth_magnitude(r, delta, ph_ang):
# def _mars_magnitude(r, delta, ph_ang):
# def _jupiter_magnitude(r, delta, ph_ang):
# def _saturn_magnitude(r, delta, ph_ang, sun_sub_lat, earth_sub_lat, rings=True):
# def _uranus_magnitude(r, delta, ph_ang,
# sun_sub_lat_planetog, earth_sub_lat_planetog):
# def _neptune_magnitude(r, delta, ph_ang, year):
#
# Path: skyfield/tests/conventions.py
# class A(object):
# __getitem__ = np.array
. Output only the next line. | expected = [-2.862, 1.788, 8.977] |
Continue the code snippet: <|code_start|> assert np.isnan(mag)
args = [
A[9.014989659493, 9.438629261423, 9.026035315474, 9.026035315474],
A[8.03160470546889, 8.47601935508925, 10.1321497654765, 10.1321497654765],
A[0.1055, 1.8569, 169.8958, 169.8958],
A[-26.224864126755417, -8.016972372600742, 29.097094546361053, 29.097094546361053],
A[-26.332275658328648, -7.458535528992841, -26.672903610681395, -26.672903610681395],
A[True, False, False, True],
]
magnitudes = m._saturn_magnitude(*args)
expected = [-0.552, 0.567, 5.206, nan]
np.allclose(magnitudes, expected, 0, 0.0005, equal_nan=True)
def test_uranus_magnitude_function():
mag = m._uranus_magnitude(18.321003215845, 17.3229728525108, 0.0410, -20.29, -20.28)
assert abs(5.381 - mag) < 0.0005
mag = m._uranus_magnitude(20.096361095266, 21.0888470145276, 0.0568, 1.02, 0.97)
assert abs(6.025 - mag) < 0.0005
mag = m._uranus_magnitude(19.38003071775, 11.1884243801383, 161.7728, -71.16, 55.11)
assert abs(8.318 - mag) < 0.0005
args = [
A[18.321003215845, 20.096361095266, 19.38003071775],
A[17.3229728525108, 21.0888470145276, 11.1884243801383],
A[0.0410, 0.0568, 161.7728],
A[-20.29, 1.02, -71.16],
A[-20.28, 0.97, 55.11],
]
magnitudes = m._uranus_magnitude(*args)
<|code_end|>
. Use current file imports:
import numpy as np
from numpy import nan
from skyfield import magnitudelib as m
from skyfield.tests.conventions import A
and context (classes, functions, or code) from other files:
# Path: skyfield/magnitudelib.py
# _SATURN_POLE = array([0.08547883, 0.07323576, 0.99364475])
# _URANUS_POLE = array([-0.21199958 -0.94155916 -0.26176809])
# _FUNCTIONS = {
# 199: _mercury_magnitude,
# 299: _venus_magnitude,
# 399: _earth_magnitude,
# 499: _mars_magnitude,
# 599: _jupiter_magnitude,
# 699: _saturn_magnitude,
# 799: _uranus_magnitude,
# 899: _neptune_magnitude,
#
# # Some planets can be reasonably identified with their barycenter.
# 1: _mercury_magnitude,
# 2: _venus_magnitude,
# 4: _mars_magnitude,
# 5: _jupiter_magnitude,
# 6: _saturn_magnitude,
# 7: _uranus_magnitude,
# 8: _neptune_magnitude,
# }
# def planetary_magnitude(position):
# def _mercury_magnitude(r, delta, ph_ang):
# def _venus_magnitude(r, delta, ph_ang):
# def _earth_magnitude(r, delta, ph_ang):
# def _mars_magnitude(r, delta, ph_ang):
# def _jupiter_magnitude(r, delta, ph_ang):
# def _saturn_magnitude(r, delta, ph_ang, sun_sub_lat, earth_sub_lat, rings=True):
# def _uranus_magnitude(r, delta, ph_ang,
# sun_sub_lat_planetog, earth_sub_lat_planetog):
# def _neptune_magnitude(r, delta, ph_ang, year):
#
# Path: skyfield/tests/conventions.py
# class A(object):
# __getitem__ = np.array
. Output only the next line. | expected = [5.381, 6.025, 8.318] |
Given snippet: <|code_start|>
# Compare with Hong Kong Observatory:
# https://www.hko.gov.hk/tc/gts/astronomy/Solar_Term.htm access at 2019-12-14
def test_solar_terms():
ts = api.load.timescale()
e = api.load('de421.bsp')
f = skyfield.almanac_east_asia.solar_terms(e)
# https://en.wikipedia.org/wiki/Lichun
t0 = ts.utc(2019, 2, 2)
t1 = ts.utc(2019, 2, 5)
t, y = almanac.find_discrete(t0, t1, f)
strings = t.utc_strftime('%Y-%m-%d %H:%M')
assert strings == ['2019-02-04 03:14']
assert (y == (21)).all()
# https://en.wikipedia.org/wiki/Lixia
t0 = ts.utc(2019, 5, 4)
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import skyfield.almanac_east_asia
from skyfield import api, almanac
and context:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
which might include code, classes, or functions. Output only the next line. | t1 = ts.utc(2019, 5, 6) |
Based on the snippet: <|code_start|>
# Compare with Hong Kong Observatory:
# https://www.hko.gov.hk/tc/gts/astronomy/Solar_Term.htm access at 2019-12-14
def test_solar_terms():
ts = api.load.timescale()
e = api.load('de421.bsp')
f = skyfield.almanac_east_asia.solar_terms(e)
# https://en.wikipedia.org/wiki/Lichun
t0 = ts.utc(2019, 2, 2)
t1 = ts.utc(2019, 2, 5)
t, y = almanac.find_discrete(t0, t1, f)
strings = t.utc_strftime('%Y-%m-%d %H:%M')
<|code_end|>
, predict the immediate next line with the help of imports:
import skyfield.almanac_east_asia
from skyfield import api, almanac
and context (classes, functions, sometimes code) from other files:
# Path: skyfield/api.py
# N = E = +1.0
# S = W = -1.0
#
# Path: skyfield/almanac.py
# def phase_angle(ephemeris, body, t):
# def fraction_illuminated(ephemeris, body, t):
# def seasons(ephemeris):
# def season_at(t):
# def moon_phase(ephemeris, t):
# def moon_phases(ephemeris):
# def moon_phase_at(t):
# def moon_nodes(ephemeris):
# def moon_node_at(t):
# def oppositions_conjunctions(ephemeris, target):
# def leading_or_trailing(t):
# def meridian_transits(ephemeris, target, topos):
# def west_of_meridian_at(t):
# def sunrise_sunset(ephemeris, topos):
# def is_sun_up_at(t):
# def dark_twilight_day(ephemeris, topos):
# def is_it_dark_twilight_day_at(t):
# def risings_and_settings(ephemeris, target, topos,
# horizon_degrees=-34.0/60.0, radius_degrees=0): #?
# def is_body_up_at(t):
# SEASONS = [
# 'Spring',
# 'Summer',
# 'Autumn',
# 'Winter',
# ]
# SEASON_EVENTS = [
# 'Vernal Equinox',
# 'Summer Solstice',
# 'Autumnal Equinox',
# 'Winter Solstice',
# ]
# SEASON_EVENTS_NEUTRAL = [
# 'March Equinox',
# 'June Solstice',
# 'September Equinox',
# 'December Solstice',
# ]
# MOON_PHASES = [
# 'New Moon',
# 'First Quarter',
# 'Full Moon',
# 'Last Quarter',
# ]
# MOON_NODES = [
# 'descending',
# 'ascending',
# ]
# CONJUNCTIONS = [
# 'conjunction',
# 'opposition',
# ]
# MERIDIAN_TRANSITS = ['Antimeridian transit', 'Meridian transit']
# TWILIGHTS = {
# 0: 'Night',
# 1: 'Astronomical twilight',
# 2: 'Nautical twilight',
# 3: 'Civil twilight',
# 4: 'Day',
# }
. Output only the next line. | assert strings == ['2019-02-04 03:14'] |
Given the code snippet: <|code_start|>
def a(*args):
return array(args)
def test_intersect_line_and_sphere():
near, far = intersect_line_and_sphere(a(1000, 0, 0), a(2, 0, 0), 1)
assert near == 1.0
assert far == 3.0
near, far = intersect_line_and_sphere(a(-1000, 0, 0), a(3, 0, 0), 1)
assert near == -4.0
assert far == -2.0
near, far = intersect_line_and_sphere(a(0, 0.5, 0), a(0, 5, 0), 2)
assert near == 3.0
assert far == 7.0
near, far = intersect_line_and_sphere(a(1000, 0, 0), a(0, 5, 0), 2)
<|code_end|>
, generate the next line using the imports in this file:
from numpy import array, isnan
from skyfield.geometry import intersect_line_and_sphere
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/geometry.py
# def intersect_line_and_sphere(endpoint, center, radius):
# """Compute distance to intersections of a line and a sphere.
#
# Given a line through the origin (0,0,0) and an |xyz| ``endpoint``,
# and a sphere with the |xyz| ``center`` and scalar ``radius``,
# return the distance from the origin to their two intersections.
#
# If the line is tangent to the sphere, the two intersections will be
# at the same distance. If the line does not intersect the sphere,
# two ``nan`` values will be returned.
#
# """
# # See http://paulbourke.net/geometry/circlesphere/index.html#linesphere
# # Names "b" and "c" designate the familiar values from the quadratic
# # formula; happily, a = 1 because we use a unit vector for the line.
#
# minus_b = 2.0 * (endpoint / length_of(endpoint) * center).sum(axis=0)
# c = (center * center).sum(axis=0) - radius * radius
# discriminant = minus_b * minus_b - 4 * c
# dsqrt = discriminant ** where(discriminant < 0, nan, 0.5) # avoid sqrt(<0)
# return (minus_b - dsqrt) / 2.0, (minus_b + dsqrt) / 2.0
. Output only the next line. | assert isnan(near) |
Given the code snippet: <|code_start|>
def test_reverse_terra_with_zero_iterations():
# With zero iterations, should return "geocentric" rather than
# "geodetic" (="correct") longitude and latitude.
lat, lon, elevation = reverse_terra(array([1, 0, 1]), 0, iterations=0)
assert abs(lat - tau / 8) < 1e-16
<|code_end|>
, generate the next line using the imports in this file:
from numpy import array, sqrt
from skyfield.earthlib import AU_M, ERAD, reverse_terra, tau
and context (functions, classes, or occasionally code) from other files:
# Path: skyfield/earthlib.py
# def terra(latitude, longitude, elevation, gast):
# def reverse_terra(xyz_au, gast, iterations=3):
# def compute_limb_angle(position_au, observer_au):
# def sidereal_time(t):
# def earth_rotation_angle(jd_ut1, fraction_ut1=0.0):
# def refraction(alt_degrees, temperature_C, pressure_mbar):
# def refract(alt_degrees, temperature_C, pressure_mbar):
# R = sqrt(x*x + y*y)
# C = 1.0
# C = 1.0 / sqrt(1.0 - e2 * (sin(lat) ** 2.0))
. Output only the next line. | assert lon == 0.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.