index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
33,759
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/Threads/toggle_thread.py
|
import pyWinhook as pyHook
import pythoncom
from win10toast import ToastNotifier
from config import *
def ToggleThread(program_state, thread_lock):
def OnKeyPress(event):
print(event.Key)
if event.Key == TOGGLE_KEY:
if program_state.isSet():
program_state.clear()
toaster.show_toast(APP_NAME, "Toggled OFF", threaded=True, duration=TOAST_SHOW_SEC)
else:
program_state.set()
toaster.show_toast(APP_NAME, "Toggled ON", threaded=True, duration=TOAST_SHOW_SEC)
return True
toaster = ToastNotifier()
new_hook = pyHook.HookManager()
new_hook.KeyDown = OnKeyPress
new_hook.HookKeyboard()
pythoncom.PumpMessages()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,760
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/main.py
|
from config import *
if __name__ == '__main__':
try:
if PROGRAM_MODE == 'Controller_server':
import ControllerServer
ControllerServer.main()
if PROGRAM_MODE == 'Controller_client':
import ControllerClient
ControllerClient.main()
else:
import SniffKey
SniffKey.main()
except Exception as err:
logging.error(err)
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,761
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/ControllerClient.py
|
import logging
from sys import platform
if platform == "linux":
import pyxhook as pyhook
elif platform == "win32":
import pythoncom
import pyWinhook as pyhook
from config import *
if COMMS_TYPE == 'Wifi':
from Handlers.SocketHandler import SocketHandler as CommsHandler
else:
from Handlers.BtCommsHandler import BtCommsHandler as CommsHandler
keybind_funcs = {}
logging.basicConfig(handlers=[logging.FileHandler(filename=LOG_FILE,
encoding='utf-8')],
level=LOGGING_LEVEL)
def main():
LoadKeysFromConfig()
if COMMS_TYPE == 'Wifi':
comms_socket = CommsHandler(CLIENT_HOST, CLIENT_PORT, SERVER_HOST, SERVER_PORT)
else:
comms_socket = CommsHandler(BT_SERVER_HOST, BT_SERVER_PORT, 'Client')
comms_socket.Open()
def OnKeyPress(event):
print(event.Key)
if event.Key in keybind_funcs.keys():
keybind_funcs[event.Key](comms_socket)
# if event.Key == "grave":
# new_hook.cancel()
return True
new_hook = pyhook.HookManager()
new_hook.KeyDown = OnKeyPress
new_hook.HookKeyboard()
try:
if platform == "linux":
new_hook.start()
elif platform == "win32":
pythoncom.PumpMessages()
except KeyboardInterrupt:
# User cancelled from command line.
comms_socket.Close()
pass
except Exception as ex:
# Write exceptions to the log file, for analysis later.
comms_socket.Close()
msg = 'Error while catching events:\n {}'.format(ex)
pyhook.print_err(msg)
logging.error(msg)
def AddKeybindFunc(key, func):
keybind_funcs[key] = func
def NextSlideSend(comms_socket):
comms_socket.SendMsg("next")
print("NextSlideSend")
def PrevSlideSend(comms_socket):
comms_socket.SendMsg("prev")
print("PrevSlideSend")
def LoadKeysFromConfig():
for next_key in NEXT_KEYS:
AddKeybindFunc(next_key, NextSlideSend)
for prev_key in PREV_KEYS:
AddKeybindFunc(prev_key, PrevSlideSend)
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,762
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/Handlers/PptHandler.py
|
from win32com import client
class PptHandler:
def __init__(self):
self.win32 = client
def GrabPptSession(self):
try:
self.ppt_app = self.win32.GetActiveObject("PowerPoint.Application")
self.active_ppt = self.ppt_app.activePresentation.SlideShowWindow
return True
except Exception as ex:
return False
def NextSlide(self):
self.active_ppt.View.Next()
def PrevSlide(self):
self.active_ppt.View.Previous()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,763
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/Threads/controller_thread.py
|
from time import sleep
import pythoncom
from Handlers.PptHandler import PptHandler
from config import *
def ControllerThread(program_state, thread_lock, command_bind_funcs, comms_msg_queue):
pythoncom.CoInitialize()
slide_handler = PptHandler()
while True:
thread_lock.acquire()
if program_state.isSet() and comms_msg_queue:
msg = comms_msg_queue.pop(0)
thread_lock.release()
if (msg in command_bind_funcs.keys()) and (slide_handler.GrabPptSession()):
command_bind_funcs[msg](slide_handler)
else:
thread_lock.release()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,764
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/config.py
|
import logging
import confuse
class MyConfiguration(confuse.Configuration):
def config_dir(self):
return './'
config_yaml = MyConfiguration('PPTController')
APP_NAME = config_yaml["APP_NAME"].get()
COMMS_TYPE = config_yaml["COMMS_TYPE"].get()
PROGRAM_MODE = config_yaml["PROGRAM_MODE"].get()
SERVER_HOST = config_yaml["WIFI_SOCKET_SERVER"]["HOST"].get()
SERVER_PORT = config_yaml["WIFI_SOCKET_SERVER"]["PORT"].get()
BT_SERVER_HOST = config_yaml["BT_SOCKET_SERVER"]["HOST"].get()
BT_SERVER_PORT = config_yaml["BT_SOCKET_SERVER"]["PORT"].get()
LOG_FILE = config_yaml["LOG_FILE"].get()
LOGGING_LEVEL = logging.getLevelName(config_yaml["LOGGING_LEVEL"].get())
if PROGRAM_MODE == "Controller_server":
TOGGLE_KEY = config_yaml["CONTROLLER_SERVER"]["TOGGLE_KEY"].get()
TOAST_SHOW_SEC = config_yaml["CONTROLLER_SERVER"]["TOAST_SHOW_SEC"].get()
elif PROGRAM_MODE == "Controller_client":
CLIENT_HOST = config_yaml["CONTROLLER_CLIENT"]["WIFI_SOCKET_CLIENT"]["HOST"].get()
CLIENT_PORT = config_yaml["CONTROLLER_CLIENT"]["WIFI_SOCKET_CLIENT"]["PORT"].get()
NEXT_KEYS = config_yaml["CONTROLLER_CLIENT"]["NEXT_KEYS"].get()
PREV_KEYS = config_yaml["CONTROLLER_CLIENT"]["PREV_KEYS"].get()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,765
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/Threads/bt_comms_thread.py
|
from Handlers.BtCommsHandler import BtCommsHandler
from config import *
def CommsThread(program_state, thread_lock, comms_msg_queue):
comms_socket = BtCommsHandler(BT_SERVER_HOST, BT_SERVER_PORT, "Server")
comms_socket.Open()
while True:
data = comms_socket.RecvMsg()
if program_state.isSet():
thread_lock.acquire()
comms_msg_queue.append(data)
thread_lock.release()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,766
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/Handlers/SocketHandler.py
|
import socket
class SocketHandler:
def __init__(self, own_host, own_port, server_host="", server_port=0, comms_buff_size=1024):
self.own_host= own_host
self.own_port = own_port
self.server = (server_host, server_port)
self.comms_buff_size = comms_buff_size
self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def SendMsg(self, msg):
self.s.sendto(msg.encode('utf-8'), self.server)
def RecvMsg(self):
data, addr = self.s.recvfrom(self.comms_buff_size)
data = data.decode('utf-8')
return(data, addr)
def Open(self):
self.s.bind((self.own_host,self.own_port))
def Close(self):
self.s.close()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,767
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/SniffKey.py
|
import logging
from sys import platform
if platform == "linux":
import pyxhook as pyhook
elif platform == "win32":
import pythoncom
import pyWinhook as pyhook
from config import *
logging.basicConfig(handlers=[logging.FileHandler(filename=LOG_FILE,
encoding='utf-8')],
level=LOGGING_LEVEL)
def main():
def OnKeyPress(event):
print(event.Key)
# if event.Key == "grave":
# new_hook.cancel()
return True
new_hook = pyhook.HookManager()
new_hook.KeyDown = OnKeyPress
new_hook.HookKeyboard()
try:
if platform == "linux":
new_hook.start()
elif platform == "win32":
pythoncom.PumpMessages()
except KeyboardInterrupt:
# User cancelled from command line.
pass
except Exception as ex:
# Write exceptions to the log file, for analysis later.
msg = 'Error while catching events:\n {}'.format(ex)
pyhook.print_err(msg)
logging.error(msg)
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,768
|
Jasperabez/PPTSynchro
|
refs/heads/master
|
/Handlers/BtCommsHandler.py
|
import errno
import winerror
import socket
import logging
class BtCommsHandler:
def __init__(self, server_mac_addr,server_port, role, comms_buff_size=1024):
self.comms_buff_size = comms_buff_size
self.server_port = server_port
self.server_mac_addr = server_mac_addr
self.role = role
def Open(self):
if self.role == 'Server':
self.s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
self.s.bind((self.server_mac_addr, self.server_port))
self.s.listen(1)
self.ServerAccept()
return True
else:
def ClientOpen(self):
try:
self.s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
self.s.connect((self.server_mac_addr, self.server_port))
return True
except OSError as err:
print(err)
if err.errno == 113:
return False
elif err.errno == errno.ECONNREFUSED:
return False
elif err.errno == errno.ECONNRESET:
return False
else:
logging.error(err)
raise OSError(err)
while not ClientOpen(self):
pass
return True
def ServerAccept(self):
self.client_s, self.client_address = self.s.accept()
return True
def SendMsg(self, msg):
if self.role == 'Server':
try:
self.client_s.send(msg.encode('utf-8'))
except ConnectionResetError:
self.client_s.close()
self.ServerAccept()
self.client_s.send(msg.encode('utf-8'))
else:
try:
self.s.send(msg.encode('utf-8'))
except (ConnectionResetError, ConnectionAbortedError) as err:
self.Close()
self.Open()
self.s.send(msg.encode('utf-8'))
def RecvMsg(self):
if self.role == 'Server':
data = self.client_s.recv(self.comms_buff_size)
if not data:
self.client_s.close()
self.ServerAccept()
data = self.client_s.recv(self.comms_buff_size)
else:
if not data:
self.Close()
self.Open()
self.s.recv(self.comms_buff_size)
data = data.decode('utf-8')
return data
def Close(self):
if self.role == "Server":
self.client_s.close()
self.s.close()
|
{"/Threads/comms_thread.py": ["/Handlers/SocketHandler.py", "/config.py"], "/ControllerServer.py": ["/config.py", "/Threads/toggle_thread.py", "/Threads/controller_thread.py", "/Threads/comms_thread.py", "/Threads/bt_comms_thread.py"], "/Threads/toggle_thread.py": ["/config.py"], "/main.py": ["/config.py", "/ControllerServer.py", "/ControllerClient.py", "/SniffKey.py"], "/ControllerClient.py": ["/config.py", "/Handlers/SocketHandler.py", "/Handlers/BtCommsHandler.py"], "/Threads/controller_thread.py": ["/Handlers/PptHandler.py", "/config.py"], "/Threads/bt_comms_thread.py": ["/Handlers/BtCommsHandler.py", "/config.py"], "/SniffKey.py": ["/config.py"]}
|
33,776
|
whdtjdgld/RESTAPI_STUDY
|
refs/heads/main
|
/quickstart/serializers.py
|
from rest_framework import serializers
from .models import comment, quiz
# λ°μ΄ν°λ₯Ό json(κ°μ₯ 보νΈμ ), xmlλ± λ°μ΄ν°λ‘ λ³ν
class QuizSerializer(serializers.ModelSerializer):
class Meta:
model = quiz
fields = ('title', 'body', 'image', 'answer')
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = comment
fields = '__all__'
|
{"/quickstart/serializers.py": ["/quickstart/models.py"], "/quickstart/views.py": ["/quickstart/models.py", "/quickstart/serializers.py"]}
|
33,777
|
whdtjdgld/RESTAPI_STUDY
|
refs/heads/main
|
/quickstart/views.py
|
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import comment, quiz
from .serializers import CommentSerializer, QuizSerializer
import random
from rest_framework import viewsets
# urls μμ λμ΄μ apiμ 보μ¬μ§λ views
@api_view(['GET']) # HELLO API λ get λ©μλλ‘
def helloAPI(request):
return Response("Hello World")
@api_view(['GET'])
def randomQuiz(request, id):
totalQuizs = quiz.objects.all()
randomQuizs = random.sample(list(totalQuizs), id)
serializer = QuizSerializer(randomQuizs, many=True) # many=T λ€μ λ°μ΄ν°λ μ§λ ¬ν
return Response(serializer.data)
class QuizViewset(viewsets.ModelViewSet):
queryset = quiz.objects.all()
serializer_class = QuizSerializer
class CommentViewset(viewsets.ModelViewSet):
queryset = comment.objects.all()
serializer_class = CommentSerializer
|
{"/quickstart/serializers.py": ["/quickstart/models.py"], "/quickstart/views.py": ["/quickstart/models.py", "/quickstart/serializers.py"]}
|
33,778
|
whdtjdgld/RESTAPI_STUDY
|
refs/heads/main
|
/quickstart/models.py
|
from django.db import models
# Create your models here.
class quiz(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
answer = models.IntegerField()
image = models.ImageField(upload_to="%Y/%m/%d") # μ μ₯κ²½λ‘κ° λ
/ μ/ μΌ λλ ν 리λ‘
class comment(models.Model):
text = models.CharField(max_length=200)
post = models.ForeignKey('quiz', verbose_name="comments", on_delete=models.CASCADE, blank=True)
|
{"/quickstart/serializers.py": ["/quickstart/models.py"], "/quickstart/views.py": ["/quickstart/models.py", "/quickstart/serializers.py"]}
|
33,779
|
whdtjdgld/RESTAPI_STUDY
|
refs/heads/main
|
/quickstart/migrations/0003_comment.py
|
# Generated by Django 3.1 on 2021-07-06 08:26
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('quickstart', '0002_quiz_image'),
]
operations = [
migrations.CreateModel(
name='comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.CharField(max_length=200)),
('post', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, to='quickstart.quiz', verbose_name='comments')),
],
),
]
|
{"/quickstart/serializers.py": ["/quickstart/models.py"], "/quickstart/views.py": ["/quickstart/models.py", "/quickstart/serializers.py"]}
|
33,780
|
whdtjdgld/RESTAPI_STUDY
|
refs/heads/main
|
/API/urls.py
|
"""API URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.conf.urls import url
from quickstart import views
from django.urls import include, path
from django.contrib import admin
from rest_framework import routers
from django.conf import settings
from django.conf.urls.static import static
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
# router urlμ μλμΌλ‘ λ§΅ν
router = routers.DefaultRouter()
router.register(r'quizs', views.QuizViewset)
router.register(r'comments', views.CommentViewset)
# 2.0 μ΄νλ‘λ url 보λ€λ path κ±°λκ² λ§λ€ μλλ‘
# app λ΄ url μ°λνλ κ³³
urlpatterns = [
path('admin/', admin.site.urls),
path('quizs/', include('quickstart.urls')), # ~ quizs/ appλ΄ urls λ°λΌκ° -> views ν¨μ νΈμΆ
url(r'^', include(router.urls)), # localhost:8000 μΌλ router.urls
url(r"^api-auth/", include('rest_framework.urls', namespace='rest_framework')),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
# MEDIA_URL μ λν μμ²μ΄ μμ λ MEDIA_ROOT μμ μΌμ μ²λ¦¬νκ²λλ€.
|
{"/quickstart/serializers.py": ["/quickstart/models.py"], "/quickstart/views.py": ["/quickstart/models.py", "/quickstart/serializers.py"]}
|
33,781
|
paparakri/raspBatteryServer
|
refs/heads/master
|
/backend_client.py
|
import ftplib
import os
import webbrowser
from tkinter import *
from tkinter import filedialog as fd
ftp = ftplib.FTP()
LARGE_FONT = ('Verdana',20)
def checkIfMain():
print(ftp.pwd())
return str(ftp.pwd())
def enterFolder_back(folderName):
ftp.cwd(folderName)
def Connect(HOST,username,password):
PORT = 5555
return_var = ''
try:
ftp.connect(HOST,PORT)
return_var = 'Connected\n'
except ConnectionRefusedError:
return_var = 'Sorry But The Server Might Be Down In The Moment\n'
return(return_var)
except OSError:
return_var = return_var + 'Sorry...You Do Not Have an Active Internet Connection\n'
return(return_var)
try:
ftp.login(username, password)
return_var = return_var + 'You Loged In\n'
except AttributeError:
return_var = return_var + 'You Aren not connected to the Server\n'
except:
return_var = return_var + 'Sorry...Wrong Username or Password\n'
return(return_var)
def createFolder(folderName):
ftp.mkd(folderName)
def Delete(filefordelete):
try:
ftp.delete(filefordelete)
listItems_back()
except:
warning = Tk()
l1 = Label(warning,text='This Will Delete All The Items In The Folder',font=LARGE_FONT)
l1.grid(column=0,row=0)
def deleteFolder():
warning.destroy()
ftp.cwd(filefordelete)
files4delete = ftp.nlst()
for file in files4delete:
ftp.delete(file)
ftp.cwd('../')
ftp.rmd(filefordelete)
return 0
b1 = Button(warning,text='Okay',command=deleteFolder)
b1.grid(column=0,row=1)
warning.mainloop()
return 0
def download_back(FileName):
downloadsFolder = os.path.expanduser(r'~\Downloads')
if '.' in FileName:
local_filename = os.path.join(downloadsFolder, FileName)
file = open(local_filename, 'wb')
ftp.retrbinary('RETR ' + FileName, file.write)
return_var = 'You Downloaded {} In The Directory {}'.format(FileName,local_filename)
else:
downloadedFolder = r'{}\{}'.format(downloadsFolder,FileName)
os.mkdir(downloadedFolder)
ftp.cwd(FileName)
file4download = ftp.nlst()
for file in file4download:
localFilename = os.path.join(downloadedFolder, file)
file4writing = open(localFilename, 'wb')
ftp.retrbinary('RETR ' + file, file4writing.write)
ftp.cwd('../')
def listItems_back():
return_list = []
files = ftp.nlst()
for i in files:
if i != '_DS_Store':
return_list.append(i)
else:
pass
return(return_list)
def chooseFile():
file = fd.askopenfilename()
tuplefd = os.path.split(os.path.abspath(file))
direc = tuplefd[0]
file = tuplefd[1]
os.chdir(direc)
try:
f = open(file, 'rb')
storfile = 'STOR {}'.format(file)
ftp.storbinary(storfile, f)
return_var = 'You Uploaded {}'.format(file)
except AttributeError:
return_var = 'Sorry.. You Must First Connect To The Server\n'
return(return_var)
|
{"/frontendClient.py": ["/backend_client.py"]}
|
33,782
|
paparakri/raspBatteryServer
|
refs/heads/master
|
/frontendClient.py
|
from tkinter import *
from tkinter import filedialog as fd
import socket
import backend_client
empty = ' '
LARGE_FONT = ('Verdana',20)
MEDIUM_FONT = ('Verdana',15)
SMALL_FONT = ('Calibri (Body)',10)
#Command Functions
def goBack():
backend_client.enterFolder_back('../')
t1.insert(END,'You Went To The Previous Folder\n')
listItems()
def doubleClick():
backend_client.enterFolder_back(selected_tuple)
t1.insert(END,'You Entered Folder {}\n'.format(selected_tuple))
listItems()
def upload():
backend_client.chooseFile()
listItems()
def delete():
global selected_tuple
backend_client.Delete(selected_tuple)
t1.insert(END,'Deleted: {}\n'.format(selected_tuple))
listItems()
def Connect():
global Le1, Le2, loginWindow
global connectionValue
connectionValue = False
rVal = backend_client.Connect('insert your ip address',Le1.get(),Le2.get())
if 'Sorry' in rVal:
error(rVal)
else:
connectionValue = True
loginWindow.destroy()
def Download():
global selected_tuple
instertedString = backend_client.download_back(selected_tuple)
t1.insert(END,'Downloaded Item\nSaved In The Downloads Folder\n')
def listItems():
list_items = backend_client.listItems_back()
list1.delete(0,END)
t1.insert(END, 'You Listed the Server Items\n')
for item in list_items:
if '.' in item:
list1.insert(END, item)
else:
item += ' (Folder)'
list1.insert(END, item)
def get_selected_row(event):
global selected_tuple
index = list1.curselection()[0]
selected_tuple = list1.get(index)
if ' (Folder)' in selected_tuple:
selected_tuple = selected_tuple[:-29]
def Clear():
t1.delete(1.0,END)
#--------------------------------------------------------------------------
def error(text2print):
errorWindow = Tk()
l1 = Label(errorWindow,text=text2print,font=MEDIUM_FONT)
l1.grid(column=0,row=0)
errorWindow.mainloop()
def mainActivity():
global mainActivity
mainActivity = Tk()
photo = PhotoImage(file='logo.png')
photoLabel = Label(mainActivity,image=photo)
photoLabel.grid(column=1,row=1)
empty1 = Label(mainActivity,text=empty)
empty1.grid(column=0,row=0)
empty2 = Label(mainActivity,text=empty)
empty2.grid(column=2,row=0)
empty3 = Label(mainActivity,text='')
empty3.grid(column=1,row=4)
l1 = Label(mainActivity,text='RaspBattery Project',font=MEDIUM_FONT)
l1.grid(column=1,row=2)
b1 = Button(mainActivity,text='Login',command=loginWindow)
b1.grid(column=1,row=3)
mainActivity.mainloop()
def loginWindow():
global mainActivity
mainActivity.destroy()
global loginWindow
loginWindow = Tk()
Ll1 = Label(loginWindow,text='Username')
Ll1.grid(column=0,row=0)
global Le1
Le1 = Entry(loginWindow)
Le1.grid(column=1,row=0)
Ll2 = Label(loginWindow,text='PassWord')
Ll2.grid(column=0,row=1)
global Le2
Le2 = Entry(loginWindow)
Le2.grid(column=1,row=1)
Lb1 = Button(loginWindow,text='Login',command=Connect)
Lb1.grid(column=1,row=2)
loginWindow.mainloop()
def folderWindow():
global folderWindow
folderWindow = Tk()
l1 = Label(folderWindow,text='Folder Name',font=MEDIUM_FONT)
l1.grid(column=1,row=0)
e1 = Entry(folderWindow)
e1.grid(column=1,row=1)
def callback():
backend_client.createFolder(e1.get())
t1.insert(END,'Created Folder: {}\n'.format(e1.get()))
folderWindow.destroy()
listItems()
b2 = Button(folderWindow,text='Create Folder',command=callback)
b2.grid(column=1,row=2)
folderWindow.mainloop()
#Main Function
mainActivity()
global connectionValue
if connectionValue == True:
homeActivity = Tk()
photo = PhotoImage(file='logo.png')
photoLabel = Label(homeActivity,image=photo)
photoLabel.grid(column=0,row=0)
list1 = Listbox(homeActivity,height=15,width=35)
list1.grid(row=1,column=0,rowspan=7)
list1.bind('<<ListboxSelect>>', get_selected_row)
list1.bind('<Double-1>', doubleClick)
l1 = Label(homeActivity,text='Console')
l1.grid(column=2,row=1)
t1 = Text(homeActivity,height=15,width=35)
t1.grid(column=2,row=1,rowspan=7)
t1.config(highlightbackground="grey")
t1.insert(END, 'Connected\n')
b1 = Button(homeActivity,text='List Items',command=listItems,font=SMALL_FONT)
b1.grid(column=1,row=1)
b2 = Button(homeActivity,text='Create Folder',command=folderWindow)
b2.grid(column=1,row=2)
b3 = Button(homeActivity,text='Delete File',command=delete)
b3.grid(column=1,row=3)
b4 = Button(homeActivity,text='Download',command=Download)
b4.grid(column=1,row=4)
b5 = Button(homeActivity,text='Upload File',command=upload)
b5.grid(column=1,row=5)
b6 = Button(homeActivity,text='Enter Folder',command=enterFolder)
b6.grid(column=1,row=6)
b7 = Button(homeActivity,text='Previous Folder',command=goBack)
b7.grid(column=1,row=7)
homeActivity.mainloop()
|
{"/frontendClient.py": ["/backend_client.py"]}
|
33,783
|
paparakri/raspBatteryServer
|
refs/heads/master
|
/FTPServer.py
|
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
import os, socket
HOSTNAME = [l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]
PORT = 5555
print ("Starting Server...")
directory = os.path.expanduser(r"the folder which you want to act as a server")
authorizer = DummyAuthorizer()
authorizer.add_user("admin", "123", directory, perm='elradfmw')
authorizer.add_user("user", "321", directory, perm='elradfmw')
handler = FTPHandler
handler.authorizer = authorizer
connection = (HOSTNAME, PORT)
server = FTPServer(connection, handler)
server.serve_forever()
|
{"/frontendClient.py": ["/backend_client.py"]}
|
33,794
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/model.py
|
"""The Satellite class."""
from sgp4.alpha5 import from_alpha5
from sgp4.earth_gravity import wgs72old, wgs72, wgs84
from sgp4.ext import invjday, jday
from sgp4.io import twoline2rv
from sgp4.propagation import sgp4, sgp4init
WGS72OLD = 0
WGS72 = 1
WGS84 = 2
gravity_constants = wgs72old, wgs72, wgs84 # indexed using enum values above
minutes_per_day = 1440.
class Satrec(object):
"""Slow Python-only version of the satellite object."""
# Approximate the behavior of the C-accelerated class by locking
# down attribute access, to avoid folks accidentally writing code
# against this class and adding extra attributes, then moving to a
# computer where the C-accelerated class is used and having their
# code suddenly produce errors.
__slots__ = (
'Om', 'a', 'alta', 'altp', 'am', 'argpdot', 'argpo', 'atime', 'aycof',
'bstar', 'cc1', 'cc4', 'cc5', 'classification', 'con41', 'd2', 'd2201',
'd2211', 'd3', 'd3210', 'd3222', 'd4', 'd4410', 'd4422', 'd5220',
'd5232', 'd5421', 'd5433', 'dedt', 'del1', 'del2', 'del3', 'delmo',
'didt', 'dmdt', 'dnodt', 'domdt', 'e3', 'ecco', 'ee2', 'elnum', 'em',
'ephtype', 'epoch', 'epochdays', 'epochyr', 'error', 'error_message',
'eta', 'gsto', 'im', 'inclo', 'init', 'intldesg', 'irez', 'isimp',
'j2', 'j3', 'j3oj2', 'j4', 'jdsatepoch', 'mdot', 'method', 'mm', 'mo',
'mu', 'nddot', 'ndot', 'nm', 'no_kozai', 'no_unkozai', 'nodecf',
'nodedot', 'nodeo', 'om', 'omgcof', 'operationmode', 'peo', 'pgho',
'pho', 'pinco', 'plo', 'radiusearthkm', 'revnum', 'satnum_str', 'se2',
'se3', 'sgh2', 'sgh3', 'sgh4', 'sh2', 'sh3', 'si2', 'si3', 'sinmao',
'sl2', 'sl3', 'sl4', 't', 't2cof', 't3cof', 't4cof', 't5cof', 'tumin',
'x1mth2', 'x7thm1', 'xfact', 'xgh2', 'xgh3', 'xgh4',
'xh2', 'xh3', 'xi2', 'xi3', 'xke', 'xl2', 'xl3', 'xl4', 'xlamo',
'xlcof', 'xli', 'xmcof', 'xni', 'zmol', 'zmos',
'jdsatepochF'
)
array = None # replaced, if needed, with NumPy array()
@property
def no(self):
return self.no_kozai
@property
def satnum(self):
return from_alpha5(self.satnum_str)
@classmethod
def twoline2rv(cls, line1, line2, whichconst=WGS72):
whichconst = gravity_constants[whichconst]
self = cls()
twoline2rv(line1, line2, whichconst, 'i', self)
# Expose the same attribute types as the C++ code.
self.ephtype = int(self.ephtype.strip() or '0')
self.revnum = int(self.revnum)
# Install a fancy split JD of the kind the C++ natively supports.
# We rebuild it from the TLE year and day to maintain precision.
year = self.epochyr
days, fraction = divmod(self.epochdays, 1.0)
self.jdsatepoch = year * 365 + (year - 1) // 4 + days + 1721044.5
self.jdsatepochF = round(fraction, 8) # exact number of digits in TLE
# Remove the legacy datetime "epoch", which is not provided by
# the C++ version of the object.
del self.epoch
# Undo my non-standard 4-digit year
self.epochyr %= 100
return self
def sgp4init(self, whichconst, opsmode, satnum, epoch, bstar,
ndot, nddot, ecco, argpo, inclo, mo, no_kozai, nodeo):
whichconst = gravity_constants[whichconst]
whole, fraction = divmod(epoch, 1.0)
whole_jd = whole + 2433281.5
# Go out on a limb: if `epoch` has no decimal digits past the 8
# decimal places stored in a TLE, then assume the user is trying
# to specify an exact decimal fraction.
if round(epoch, 8) == epoch:
fraction = round(fraction, 8)
self.jdsatepoch = whole_jd
self.jdsatepochF = fraction
y, m, d, H, M, S = invjday(whole_jd)
jan0 = jday(y, 1, 0, 0, 0, 0.0)
self.epochyr = y % 100
self.epochdays = whole_jd - jan0 + fraction
self.classification = 'U'
sgp4init(whichconst, opsmode, satnum, epoch, bstar, ndot, nddot,
ecco, argpo, inclo, mo, no_kozai, nodeo, self)
def sgp4(self, jd, fr):
tsince = ((jd - self.jdsatepoch) * minutes_per_day +
(fr - self.jdsatepochF) * minutes_per_day)
r, v = sgp4(self, tsince)
return self.error, r, v
def sgp4_tsince(self, tsince):
r, v = sgp4(self, tsince)
return self.error, r, v
def sgp4_array(self, jd, fr):
"""Compute positions and velocities for the times in a NumPy array.
Given NumPy arrays ``jd`` and ``fr`` of the same length that
supply the whole part and the fractional part of one or more
Julian dates, return a tuple ``(e, r, v)`` of three vectors:
* ``e``: nonzero for any dates that produced errors, 0 otherwise.
* ``r``: position vectors in kilometers.
* ``v``: velocity vectors in kilometers per second.
"""
# Import NumPy the first time sgp4_array() is called.
array = self.array
if array is None:
from numpy import array
Satrec.array = array
results = []
z = list(zip(jd, fr))
for jd_i, fr_i in z:
results.append(self.sgp4(jd_i, fr_i))
elist, rlist, vlist = zip(*results)
e = array(elist)
r = array(rlist)
v = array(vlist)
r.shape = v.shape = len(jd), 3
return e, r, v
class SatrecArray(object):
"""Slow Python-only version of the satellite array."""
__slots__ = ('_satrecs',)
array = None # replaced with NumPy array(), if the user tries calling
def __init__(self, satrecs):
self._satrecs = satrecs
# Import NumPy the first time a SatrecArray is instantiated.
if self.array is None:
from numpy import array
SatrecArray.array = array
def sgp4(self, jd, fr):
"""Compute positions and velocities for the satellites in this array.
Given NumPy scalars or arrays ``jd`` and ``fr`` supplying the
whole part and the fractional part of one or more Julian dates,
return a tuple ``(e, r, v)`` of three vectors that are each as
long as ``jd`` and ``fr``:
* ``e``: nonzero for any dates that produced errors, 0 otherwise.
* ``r``: (x,y,z) position vector in kilometers.
* ``v``: (dx,dy,dz) velocity vector in kilometers per second.
"""
results = []
z = list(zip(jd, fr))
for satrec in self._satrecs:
for jd_i, fr_i in z:
results.append(satrec.sgp4(jd_i, fr_i))
elist, rlist, vlist = zip(*results)
e = self.array(elist)
r = self.array(rlist)
v = self.array(vlist)
jdlen = len(jd)
mylen = len(self._satrecs)
e.shape = (mylen, jdlen)
r.shape = v.shape = (mylen, jdlen, 3)
return e, r, v
class Satellite(object):
"""The old Satellite object, for compatibility with sgp4 1.x."""
jdsatepochF = 0.0 # for compatibility with new Satrec; makes tests simpler
def propagate(self, year, month=1, day=1, hour=0, minute=0, second=0.0):
"""Return a position and velocity vector for a given date and time."""
j = jday(year, month, day, hour, minute, second)
m = (j - self.jdsatepoch) * minutes_per_day
r, v = sgp4(self, m)
return r, v
no = Satrec.no
satnum = Satrec.satnum
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,795
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/wrapper.py
|
from . import vallado_cpp
class Satrec(vallado_cpp.Satrec):
"""High-speed computation of satellite positions and velocities."""
__slots__ = ()
def sgp4_array(self, jd, fr):
"""Compute positions and velocities for the times in a NumPy array.
Given NumPy arrays ``jd`` and ``fr`` of the same length that
supply the whole part and the fractional part of one or more
Julian dates, return a tuple ``(e, r, v)`` of three vectors:
* ``e``: nonzero for any dates that produced errors, 0 otherwise.
* ``r``: position vectors in kilometers.
* ``v``: velocity vectors in kilometers per second.
"""
jd = jd.astype('float64', copy=False)
fr = fr.astype('float64', copy=False)
eshape = jd.shape
fshape = eshape[0], 3
array = type(jd)
e = array(eshape, 'uint8')
r = array(fshape, 'float64')
v = array(fshape, 'float64')
self._sgp4(jd, fr, e, r, v)
return e, r, v
class SatrecArray(vallado_cpp.SatrecArray):
"""High-speed satellite array for computing positions and velocities."""
__slots__ = ()
def sgp4(self, jd, fr):
"""Compute positions and velocities for the satellites in this array.
Given NumPy scalars or arrays ``jd`` and ``fr`` supplying the
whole part and the fractional part of one or more Julian dates,
return a tuple ``(e, r, v)`` of three vectors:
* ``e``: nonzero for any dates that produced errors, 0 otherwise.
* ``r``: position vectors in kilometers.
* ``v``: velocity vectors in kilometers per second.
The first dimension of each output vector has the same length as
this satellite array, the second dimension the same length as
the input date arrays, and the third dimension has length 3.
"""
jd = jd.astype('float64', copy=False)
fr = fr.astype('float64', copy=False)
ilength = len(self)
jlength, = jd.shape
eshape = ilength, jlength
fshape = ilength, jlength, 3
array = type(jd)
e = array(eshape, 'uint8')
r = array(fshape, 'float64')
v = array(fshape, 'float64')
self._sgp4(jd, fr, e, r, v)
return e, r, v
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,796
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/bin/print_attributes.py
|
#!/usr/bin/env python
from __future__ import print_function
from fileinput import input
from sgp4.vallado_cpp import Satrec
def main():
lines = iter(input())
for line in lines:
name = line
line1 = next(lines)
line2 = next(lines)
sat = Satrec.twoline2rv(line1, line2)
for name in dir(sat):
if name.startswith('_') or name in ('sgp4', 'twoline2rv'):
continue
value = getattr(sat, name)
print(name, value)
print()
if __name__ == '__main__':
try:
main()
except BrokenPipeError:
pass
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,797
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/api.py
|
"""Public API that tries to import C++ module, but falls back to Python."""
__all__ = (
'SGP4_ERRORS', 'Satrec', 'SatrecArray', 'WGS72OLD', 'WGS72', 'WGS84',
'accelerated', 'jday', 'days2mdhms',
)
from .functions import jday, days2mdhms
SGP4_ERRORS = {
1: 'mean eccentricity is outside the range 0.0 to 1.0',
2: 'nm is less than zero',
3: 'perturbed eccentricity is outside the range 0.0 to 1.0',
4: 'semilatus rectum is less than zero',
5: '(error 5 no longer in use; it meant the satellite was underground)',
6: 'mrt is less than 1.0 which indicates the satellite has decayed',
}
try:
from .wrapper import Satrec, SatrecArray
accelerated = True
except ImportError:
from .model import Satrec, SatrecArray
from .model import WGS72OLD, WGS72, WGS84
accelerated = False
else:
from .vallado_cpp import WGS72OLD, WGS72, WGS84
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,798
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/omm.py
|
"""Support for the new Orbit Mean-Elements Message format for TLE data."""
import csv
import xml.etree.ElementTree as ET
from datetime import datetime
from math import pi
from sgp4.api import WGS72
def parse_csv(file):
return csv.DictReader(file)
def parse_xml(file):
root = ET.parse(file).getroot()
for segment in root.findall('.//segment'):
metadata = segment.find('metadata')
data = segment.find('data')
meanElements = data.find('meanElements')
tleParameters = data.find('tleParameters')
fields = {}
for element in metadata, meanElements, tleParameters:
fields.update((field.tag, field.text) for field in element)
yield fields
_epoch0 = datetime(1949, 12, 31)
_to_radians = pi / 180.0
_ndot_units = 1036800.0 / pi # See SGP4.cpp for details.
_nddot_units = 2985984000.0 / 2.0 / pi # See SGP4.cpp for details.
def initialize(sat, fields):
sat.classification = fields['CLASSIFICATION_TYPE']
sat.intldesg = fields['OBJECT_ID'][2:].replace('-', '')
sat.ephtype = int(fields['EPHEMERIS_TYPE'])
sat.elnum = int(fields['ELEMENT_SET_NO'])
sat.revnum = int(fields['REV_AT_EPOCH'])
epoch_datetime = datetime.strptime(fields['EPOCH'], '%Y-%m-%dT%H:%M:%S.%f')
epoch = (epoch_datetime - _epoch0).total_seconds() / 86400.0
argpo = float(fields['ARG_OF_PERICENTER']) * _to_radians
bstar = float(fields['BSTAR'])
ecco = float(fields['ECCENTRICITY'])
inclo = float(fields['INCLINATION']) * _to_radians
mo = float(fields['MEAN_ANOMALY']) * _to_radians
nddot = float(fields['MEAN_MOTION_DDOT']) / _nddot_units
ndot = float(fields['MEAN_MOTION_DOT']) / _ndot_units
no_kozai = float(fields['MEAN_MOTION']) / 720.0 * pi
nodeo = float(fields['RA_OF_ASC_NODE']) * _to_radians
satnum = int(fields['NORAD_CAT_ID'])
sat.sgp4init(WGS72, 'i', satnum, epoch, bstar, ndot, nddot, ecco,
argpo, inclo, mo, no_kozai, nodeo)
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,799
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/__init__.py
|
# -*- coding: utf-8 -*-
"""Track Earth satellites given TLE data, using up-to-date 2020 SGP4 routines.
This package compiles the official C++ code from `Revisiting Spacetrack
Report #3`_ (AIAA 2006-6753) β specifically, the 2023 MayΒ 09 release
from David Valladoβs `Fundamentals of Astrodynamics and Applications`_
webpage β and uses it to compute the positions of satellites in Earth
orbit. Satellite orbital elements can be loaded from either a legacy
TLE file or from a modern OMM element set, both of which you can fetch
from a site like `CelesTrak <https://celestrak.com/>`_.
.. _Revisiting Spacetrack Report #3: https://celestrak.org/publications/AIAA/2006-6753/
.. _Fundamentals of Astrodynamics and Applications: https://celestrak.org/software/vallado-sw.php
If your machine canβt install or compile the C++ code, then this package
falls back to using a slower pure-Python implementation of SGP4. Tests
make sure that its positions **agree to within 0.1Β mm** with the
standard version of the algorithm β an error far less than the
1β3Β km/day by which satellites themselves deviate from the ideal orbits
described in TLE files.
An accelerated routine is available that, given a series of times and of
satellites, computes a whole array of output positions using a fast C++
loop. See the βArray Accelerationβ section below.
Note that the SGP4 propagator returns raw *x,y,z* Cartesian coordinates
in a βTrue Equator Mean Equinoxβ (TEME) reference frame thatβs centered
on the Earth but does not rotate with it β an βEarth centered inertialβ
(ECI) reference frame. The SGP4 propagator itself does not implement
the math to convert these positions into more official ECI frames like
J2000 or the ICRS, nor into any Earth-centered Earth-fixed (ECEF) frames
like the ITRS, nor into latitudes and longitudes through an Earth
ellipsoid like WGS84. For conversions into these other coordinate
frames, look for a comprehensive astronomy library, like the `Skyfield
<https://rhodesmill.org/skyfield/>`_ library that is built atop this one
(see the `section on Earth satellites
<https://rhodesmill.org/skyfield/earth-satellites.html>`_ in its
documentation).
Usage
-----
You will probably first want to to check whether your machine has
successfully installed the fast SGP4 C++ code, or is using the slow
Python version (in which case this value will be false):
>>> from sgp4.api import accelerated
>>> print(accelerated)
True
This library uses the same function names as the official C++ code, to
help users who are already familiar with SGP4 in other languages. Here
is how to compute the x,y,z position and velocity for the International
Space Station at 20:42:00 on 2019Β DecemberΒ 9:
>>> from sgp4.api import Satrec
>>>
>>> s = '1 25544U 98067A 19343.69339541 .00001764 00000-0 38792-4 0 9991'
>>> t = '2 25544 51.6439 211.2001 0007417 17.6667 85.6398 15.50103472202482'
>>> satellite = Satrec.twoline2rv(s, t)
>>>
>>> jd, fr = 2458826.5, 0.8625
>>> e, r, v = satellite.sgp4(jd, fr)
>>> e
0
>>> print(r) # True Equator Mean Equinox position (km)
(-6088.92..., -936.13..., -2866.44...)
>>> print(v) # True Equator Mean Equinox velocity (km/s)
(-1.525..., -5.538..., 5.068...)
As input, you can provide either:
* A simple floating-point Julian Date for ``jd`` and the value 0.0 for
``fr``, if you are happy with the precision of a 64-bit floating point
number. Note that modern Julian Dates are greater than 2,450,000
which means that nearly half of the precision of a 64-bit float will
be consumed by the whole part that specifies the day. The remaining
digits will provide a precision for the fraction of around 20.1Β Β΅s.
This should be no problem for the accuracy of your result β satellite
positions usually off by a few kilometers anyway, far less than a
satellite moves in 20.1Β Β΅s β but if you run a solver that dives down
into the microseconds while searching for a rising or setting time,
the solver might be bothered by the 20.1Β Β΅s plateau between each jump
in the satelliteβs position.
* Or, you can provide a coarse date ``jd`` plus a very precise fraction
``fr`` that supplies the rest of the value. The Julian Date for which
the satellite position is computed is the sum of the two values. One
common practice is to provide the whole number as ``jd`` and the
fraction as ``fr``; another is to have ``jd`` carry the fraction 0.5
since UTC midnight occurs halfway through each Julian Date. Either
way, splitting the value allows a solver to run all the way down into
the nanoseconds and still see SGP4 respond smoothly to tiny date
adjustments with tiny changes in the resulting satellite position.
Here is how to intrepret the results:
* ``e`` will be a non-zero error code if the satellite position could
not be computed for the given date. You can ``from sgp4.api import
SGP4_ERRORS`` to access a dictionary mapping error codes to error
messages explaining what each code means.
* ``r`` measures the satellite position in **kilometers** from the
center of the earth in the idiosyncratic True Equator Mean Equinox
coordinate frame used by SGP4.
* ``v`` velocity is the rate at which the position is changing,
expressed in **kilometers per second**.
If your application does not natively handle Julian dates, you can
compute ``jd`` and ``fr`` from calendar dates using ``jday()``.
>>> from sgp4.api import jday
>>> jd, fr = jday(2019, 12, 9, 20, 42, 0)
>>> jd
2458826.5
>>> fr
0.8625
Double-checking your TLE lines
------------------------------
Because TLE is an old punch-card fixed-width format, itβs very sensitive
to whether exactly the right number of spaces are positioned in exactly
the right columns. If you suspect that your satellite elements arenβt
getting loaded correctly, try calling the slow pure-Python version of
``twoline2rv()``, which performs extra checks that the fast C++ doesnβt:
>>> from sgp4.earth_gravity import wgs72
>>> from sgp4.io import twoline2rv
>>> assert twoline2rv(s, t, wgs72)
Any TLE formatting errors will be raised as a ``ValueError``.
Using OMM elements instead of TLE
---------------------------------
The industry is migrating away from the original TLE format, because it
will soon run out of satellite numbers.
* Some TLE files now use a new βAlpha-5β convention that expands the
range of satellite numbers by using an initial letter; for example,
βE8493β means satellite 148493. This library supports the Alpha-5
convention and should return the correct integer in Python.
* Some authorities are now distributing satellite elements in an βOMMβ
Orbit Mean Elements Message format that replaces the TLE format. You
can learn about OMM in Dr.Β T.S. Kelsoβs `βA New Way to Obtain GP Dataβ
<https://celestrak.com/NORAD/documentation/gp-data-formats.php>`_ at
the CelesTrak site.
You can already try out experimental support for OMM:
>>> from sgp4 import omm
Reading OMM data takes two steps, because OMM supports several different
text formats. First, parse the input text to recover the field names
and values that it stores; second, build a Python satellite object from
those field values. For example, to load OMM from XML:
>>> with open('sample_omm.xml') as f:
... fields = next(omm.parse_xml(f))
>>> sat = Satrec()
>>> omm.initialize(sat, fields)
Or, to load OMM from CSV:
>>> with open('sample_omm.csv') as f:
... fields = next(omm.parse_csv(f))
>>> sat = Satrec()
>>> omm.initialize(sat, fields)
Either way, the satellite object should wind up properly initialized and
ready to start producing positions.
If you are interested in saving satellite parameters using the new OMM
format, then read the section on βExportβ below.
Epoch
-----
Over a given satelliteβs lifetime, dozens or hundreds of different TLE
records will be produced as its orbit evolves. Each TLE record
specifies the βepoch dateβ for which it is most accurate. Typically a
TLE is only useful for a couple of weeks to either side of its epoch
date, beyond which its predictions become unreliable.
Satellite objects natively provide their epoch as a two-digit year and
then a fractional number of days into the year:
>>> satellite.epochyr
19
>>> satellite.epochdays
343.69339541
Because Sputnik was launched in 1957, satellite element sets will never
refer to an earlier year, so years 57 through 99 mean 1957β1999 while 0
through 56 mean 2000β2056. The TLE format will presumably be obsolete
in 2057 and have to be upgraded to 4-digit years.
To turn the number of days and its fraction into a calendar date and
time, use the ``days2mdhms()`` function.
>>> from sgp4.api import days2mdhms
>>> month, day, hour, minute, second = days2mdhms(19, 343.69339541)
>>> month
12
>>> day
9
>>> hour
16
>>> minute
38
>>> second
29.363424
The SGP4 library also translates those two numbers into a Julian date
and fractional Julian date, since Julian dates are more commonly used in
astronomy.
>>> satellite.jdsatepoch
2458826.5
>>> satellite.jdsatepochF
0.69339541
Finally, a convenience function is available in the library if you need
the epoch date and time as Python ``datetime``.
>>> from sgp4.conveniences import sat_epoch_datetime
>>> sat_epoch_datetime(satellite)
datetime.datetime(2019, 12, 9, 16, 38, 29, 363423, tzinfo=UTC)
Array Acceleration
------------------
To avoid the expense of running a Python loop when you have many dates
and times for which you want a position, you can pass your Julian dates
as arrays. The array routine is only faster if your machine has
successfully installed or compiled the SGP4 C++ code, so you might want
to check first:
>>> from sgp4.api import accelerated
>>> print(accelerated)
True
To call the array routine, make NumPy arrays for ``jd`` and ``fr`` that
are the same length:
>>> import numpy as np
>>> np.set_printoptions(precision=2)
>>> jd = np.array((2458826, 2458826, 2458826, 2458826))
>>> fr = np.array((0.0001, 0.0002, 0.0003, 0.0004))
>>> e, r, v = satellite.sgp4_array(jd, fr)
>>> print(e)
[0 0 0 0]
>>> print(r)
[[-3431.31 2620.15 -5252.97]
[-3478.86 2575.14 -5243.87]
[-3526.09 2529.89 -5234.28]
[-3572.98 2484.41 -5224.19]]
>>> print(v)
[[-5.52 -5.19 1.02]
[-5.49 -5.22 1.08]
[-5.45 -5.25 1.14]
[-5.41 -5.28 1.2 ]]
To avoid the expense of Python loops when you have many satellites and
dates, build a ``SatrecArray`` from several individual satellites. Its
``sgp4()`` method will expect both ``jd`` and ``fr`` to be NumPy arrays,
so if you only have one date, be sure to provide NumPy arrays of length
one. Here is a sample computation for 2 satellites and 4 dates:
>>> u = '1 20580U 90037B 19342.88042116 .00000361 00000-0 11007-4 0 9996'
>>> w = '2 20580 28.4682 146.6676 0002639 185.9222 322.7238 15.09309432427086'
>>> satellite2 = Satrec.twoline2rv(u, w)
>>> from sgp4.api import SatrecArray
>>> a = SatrecArray([satellite, satellite2])
>>> e, r, v = a.sgp4(jd, fr)
>>> np.set_printoptions(precision=2)
>>> print(e)
[[0 0 0 0]
[0 0 0 0]]
>>> print(r)
[[[-3431.31 2620.15 -5252.97]
[-3478.86 2575.14 -5243.87]
[-3526.09 2529.89 -5234.28]
[-3572.98 2484.41 -5224.19]]
<BLANKLINE>
[[ 5781.85 2564. -2798.22]
[ 5749.36 2618.59 -2814.63]
[ 5716.35 2672.94 -2830.78]
[ 5682.83 2727.05 -2846.68]]]
>>> print(v)
[[[-5.52 -5.19 1.02]
[-5.49 -5.22 1.08]
[-5.45 -5.25 1.14]
[-5.41 -5.28 1.2 ]]
<BLANKLINE>
[[-3.73 6.33 -1.91]
[-3.79 6.3 -1.88]
[-3.85 6.28 -1.85]
[-3.91 6.25 -1.83]]]
Export
------
If you have a ``Satrec`` you want to share with friends or persist to a
file, thereβs an export routine that will turn it back into a TLE:
>>> from sgp4 import exporter
>>> line1, line2 = exporter.export_tle(satellite)
>>> line1
'1 25544U 98067A 19343.69339541 .00001764 00000-0 38792-4 0 9991'
>>> line2
'2 25544 51.6439 211.2001 0007417 17.6667 85.6398 15.50103472202482'
Happily, these are exactly the two TLE lines that we used to create this
satellite object:
>>> (s == line1) and (t == line2)
True
Another export routine is available that produces the fields defined by
the new OMM format (see the βOMMβ section above):
>>> from pprint import pprint
>>> fields = exporter.export_omm(satellite, 'ISS (ZARYA)')
>>> pprint(fields)
{'ARG_OF_PERICENTER': 17.6667,
'BSTAR': 3.8792e-05,
'CENTER_NAME': 'EARTH',
'CLASSIFICATION_TYPE': 'U',
'ECCENTRICITY': 0.0007417,
'ELEMENT_SET_NO': 999,
'EPHEMERIS_TYPE': 0,
'EPOCH': '2019-12-09T16:38:29.363423',
'INCLINATION': 51.6439,
'MEAN_ANOMALY': 85.6398,
'MEAN_ELEMENT_THEORY': 'SGP4',
'MEAN_MOTION': 15.501034720000002,
'MEAN_MOTION_DDOT': 0.0,
'MEAN_MOTION_DOT': 1.764e-05,
'NORAD_CAT_ID': 25544,
'OBJECT_ID': '1998-067A',
'OBJECT_NAME': 'ISS (ZARYA)',
'RA_OF_ASC_NODE': 211.2001,
'REF_FRAME': 'TEME',
'REV_AT_EPOCH': 20248,
'TIME_SYSTEM': 'UTC'}
Gravity
-------
The SGP4 algorithm operates atop a set of constants specifying how
strong the Earthβs gravity is. The most recent official paper on SGP4
(see below) specifies that βWe use WGS-72 as the default valueβ, so this
Python module uses the same default. But in case you want to use either
the old legacy version of the WGS-72 constants, or else the non-standard
but more modern WGS-84 constants, the ``twoline2rv()`` constructor takes
an optional argument:
>>> from sgp4.api import WGS72OLD, WGS72, WGS84
>>> satellite3 = Satrec.twoline2rv(s, t, WGS84)
You will in general get less accurate results if you choose WGS-84.
Even though it reflects more recent and accurate measures of the Earth,
satellite TLEs across the industry are most likely generated with WGS-72
as their basis. The positions you generate will better agree with the
real positions of each satellite if you use the same underlying gravity
constants as were used to generate the TLE.
Providing your own elements
---------------------------
If instead of parsing a TLE you want to specify orbital elements
directly, you can pass them as floating point numbers to a satellite
objectβs ``sgp4init()`` method. For example, hereβs how to build the
same International Space Station orbit that we loaded from a TLE in the
first code example above:
>>> satellite2 = Satrec()
>>> satellite2.sgp4init(
... WGS72, # gravity model
... 'i', # 'a' = old AFSPC mode, 'i' = improved mode
... 25544, # satnum: Satellite number
... 25545.69339541, # epoch: days since 1949 December 31 00:00 UT
... 3.8792e-05, # bstar: drag coefficient (1/earth radii)
... 0.0, # ndot: ballistic coefficient (radians/minute^2)
... 0.0, # nddot: mean motion 2nd derivative (radians/minute^3)
... 0.0007417, # ecco: eccentricity
... 0.3083420829620822, # argpo: argument of perigee (radians)
... 0.9013560935706996, # inclo: inclination (radians)
... 1.4946964807494398, # mo: mean anomaly (radians)
... 0.06763602333248933, # no_kozai: mean motion (radians/minute)
... 3.686137125541276, # nodeo: R.A. of ascending node (radians)
... )
These numbers donβt look the same as the numbers in the TLE, because the
underlying ``sgp4init()`` routine uses different units: radians rather
than degrees. But this is the same orbit and will produce the same
positions.
Note that ``ndot`` and ``nddot`` are ignored by the SGP4 propagator, so
you can leave them ``0.0`` without any effect on the resulting satellite
positions. But they do at least get saved to the satellite object, and
written out if you write the parameters to a TLE or OMM file (see the
βExportβ section, above).
To compute the βepochβ argument, take the epochβs Julian date and
subtract 2433281.5 days.
While the underlying ``sgp4init()`` routine leaves the attributes
``epochyr``, ``epochdays``, ``jdsatepoch``, and ``jdsatepochF`` unset,
this library goes ahead and sets them anyway for you, using the epoch
you provided.
See the next section for the complete list of attributes that are
available from the satellite record once it has been initialized.
Attributes
----------
There are several dozen ``Satrec`` attributes that expose data from the
underlying C++ SGP4 record. They fall into the following categories.
*Identification*
These are copied directly from the TLE record but arenβt used by the
propagation math.
| ``satnum_str`` β Satellite number, as a 5-character string.
| ``satnum`` β Satellite number, converted to an integer.
| ``classification`` β ``'U'``, ``'C'``, or ``'S'``
indicating the element set is Unclassified, Classified, or Secret.
| ``ephtype`` β Integer βephemeris typeβ, used internally by space
agencies to mark element sets that are not ready for publication;
this field should always be ``0`` in published TLEs.
| ``elnum`` β Element set number.
| ``revnum`` β Satelliteβs revolution number at the moment of the epoch,
presumably counting from 1 following launch.
*Orbital Elements*
These are the orbital parameters, copied verbatim from the text of the
TLE record. They describe the orbit at the moment of the TLEβs epoch
and so remain constant even as the satellite record is used over and
over again to propagate positions for different times.
| ``epochyr`` β Epoch date: the last two digits of the year.
| ``epochdays`` β Epoch date: the number of days into the year,
including a decimal fraction for the UTC time of day.
| ``ndot`` β First time derivative of the mean motion
(loaded from the TLE, but otherwise ignored).
| ``nddot`` β Second time derivative of the mean motion
(loaded from the TLE, but otherwise ignored).
| ``bstar`` β Ballistic drag coefficient B* (1/earthΒ radii).
| ``inclo`` β Inclination (radians).
| ``nodeo`` β Right ascension of ascending node (radians).
| ``ecco`` β Eccentricity.
| ``argpo`` β Argument of perigee (radians).
| ``mo`` β Mean anomaly (radians).
| ``no_kozai`` β Mean motion (radians/minute).
| ``no`` β Alias for ``no_kozai``, for compatibility with old code.
You can also access the epoch as a Julian date:
| ``jdsatepoch`` β Whole part of the epochβs Julian date.
| ``jdsatepochF`` β Fractional part of the epochβs Julian date.
*Computed Orbit Properties*
These are computed when the satellite is first loaded,
as a convenience for callers who might be interested in them.
They arenβt used by the SGP4 propagator itself.
| ``a`` β Semi-major axis (earthΒ radii).
| ``altp`` β Altitude of the satellite at perigee
(earthΒ radii, assuming a spherical Earth).
| ``alta`` β Altitude of the satellite at apogee
(earthΒ radii, assuming a spherical Earth).
| ``argpdot`` β Rate at which the argument of perigee is changing
(radians/minute).
| ``gsto`` β Greenwich Sidereal Time at the satelliteβs epoch (radians).
| ``mdot`` β Rate at which the mean anomaly is changing (radians/minute)
| ``nodedot`` β Rate at which the right ascension of the ascending node
is changing (radians/minute).
*Propagator Mode*
| ``operationmode`` β A single character that directs SGP4
to either operate in its modern ``'i'`` improved mode
or in its legacy ``'a'`` AFSPC mode.
| ``method`` β A single character, chosen automatically
when the orbital elements were loaded, that indicates whether SGP4
has chosen to use its built-in ``'n'`` Near Earth
or ``'d'`` Deep Space mode for this satellite.
*Result of Most Recent Propagation*
| ``t`` β
The time you gave when you most recently asked SGP4
to compute this satelliteβs position,
measured in minutes before (negative) or after (positive)
the satelliteβs epoch.
| ``error`` β
Error code produced by the most recent SGP4 propagation
you performed with this element set.
The possible ``error`` codes are:
0. No error.
1. Mean eccentricity is outside the range 0Β β€Β eΒ <Β 1.
2. Mean motion has fallen below zero.
3. Perturbed eccentricity is outside the range 0Β β€Β eΒ β€Β 1.
4. Length of the orbitβs semi-latus rectum has fallen below zero.
5. (No longer used.)
6. Orbit has decayed: the computed position is underground.
(The position is still returned, in case the vector is helpful
to software that might be searching for the moment of re-entry.)
*Mean Elements From Most Recent Propagation*
Partway through each propagation, the SGP4 routine saves a set of
βsingly averaged mean elementsβ that describe the orbitβs shape at the
moment for which a position is being computed. They are averaged with
respect to the mean anomaly and include the effects of secular gravity,
atmospheric drag, and β in Deep Space mode β of those pertubations from
the Sun and Moon that SGP4 averages over an entire revolution of each of
those bodies. They omit both the shorter-term and longer-term periodic
pertubations from the Sun and Moon that SGP4 applies right before
computing each position.
| ``am`` β Average semi-major axis (earthΒ radii).
| ``em`` β Average eccentricity.
| ``im`` β Average inclination (radians).
| ``Om`` β Average right ascension of ascending node (radians).
| ``om`` β Average argument of perigee (radians).
| ``mm`` β Average mean anomaly (radians).
| ``nm`` β Average mean motion (radians/minute).
*Gravity Model Parameters*
When the satellite record is initialized, your choice of gravity model
results in a slate of eight constants being copied in:
| ``tumin`` β Minutes in one βtime unitβ.
| ``xke`` β The reciprocal of ``tumin``.
| ``mu`` β Earthβs gravitational parameter (kmΒ³/sΒ²).
| ``radiusearthkm`` β Radius of the earth (km).
| ``j2``, ``j3``, ``j4`` β Un-normalized zonal harmonic values Jβ, Jβ, and Jβ.
| ``j3oj2`` β The ratio Jβ/Jβ.
Printing satellite attributes
-----------------------------
If you want to print out a satellite, this library provides a convenient
βattribute dumpβ routine that takes a satellite and generates lines that
list its attributes::
from sys import stdout
from sgp4.conveniences import dump_satrec
stdout.writelines(dump_satrec(satellite))
If you want to compare two satellites, then simply pass a second
argument; the second satelliteβs attributes will be printed in a second
column next to those of the first. ::
stdout.writelines(dump_satrec(satellite, satellite2))
Validation against the official algorithm
-----------------------------------------
This implementation passes all of the automated tests in the August 2010
release of the reference implementation of SGP4 by Vallado etΒ al., who
originally published their revision of SGP4 inΒ 2006:
Vallado, David A., Paul Crawford, Richard Hujsak, and T.S. Kelso,
βRevisiting Spacetrack Report #3,β presented at the AIAA/AAS
Astrodynamics Specialist Conference, Keystone, CO, 2006 August
21β24.
If you would like to review the paper, it is `available online
<https://www.celestrak.com/publications/AIAA/2006-6753/>`_. You can
always download the latest version of their code for comparison against
this Python module (or other implementations) at `AIAA-2006-6753.zip
<https://www.celestrak.com/publications/AIAA/2006-6753/AIAA-2006-6753.zip>`_.
For developers
--------------
Developers can check out this full project from GitHub:
https://github.com/brandon-rhodes/python-sgp4
To run its unit tests, install PythonΒ 2, PythonΒ 3, and the ``tox``
testing tool. The tests runing in PythonΒ 2 will exercise the fallback
pure-Python version of the routines, while PythonΒ 3 exercises the fast
new C++ accelerated code::
cd python-sgp4
tox
Legacy API
----------
Before this library pivoted to wrapping Vallado's official C++ code and
was operating in pure Python only, it had a slightly quirkier API, which
is still supported for compatibility with older clients. You can learn
about it by reading the documentation from version 1.4 or earlier:
https://pypi.org/project/sgp4/1.4/
Changelog
---------
2023-04-27 β 2.22
* Added a ``satnum_str`` attribute, exposing the fact that the C++ now
stores the satellite number as a string; and check that ``satnum`` is
never greater than 339999.
* Fixed the units of the ``nddot`` attribute when the value is loaded
from an OMM record. (Since the TLE computation itself ignores this
attribute, this did not affect any satellite positions.)
* Enhanced the fallback Python version of ``twoline2rv()`` to verify
that TLE lines are ASCII, and added documentation using it to
double-check TLEs that might suffer from non-ASCII characters.
* If the user doesnβt set a satelliteβs ``classification``, it now
defaults to ``'U'`` for βunclassifiedβ.
2022-04-06 β 2.21
* Added ``dump_satrec()`` to the ``sgp4.conveniences`` module.
* Fixed the ``Satrec`` attribute ``.error``, which was previously
building a nonsense integer from the wrong data in memory.
* Removed ``.whichconst`` from Python ``Satrec``, to help users avoid
writing code that will break when the C++ extension is available.
2021-07-01 β 2.20
* Taught ``sgp4init()`` to round both ``epochdays`` and ``jdsatepochF``
to the same 8 decimal places used for the date fraction in a TLE, if
the user-supplied ``epoch`` itself has 8 or fewer digits behind the
decimal point. This should make it easier to build satellites that
round-trip to TLE format with perfect accuracy.
* Fixed how ``export_tle()`` formats the BSTAR field when its value, if
written in scientific notation, has a positive exponent.
* Fixed the ``epochyr`` assigned by ``sgp4init()`` so years before 2000
have two digits instead of three (for example, so that 1980 produces
an ``epochyr`` of 80 instead of 980).
2021-04-22 β 2.19
* Extended the documentation on the Python Package Index and in the
module docstring so it lists every ``Satrec`` attribute that this
library exposes; even the more obscure ones might be useful to folks
working to analyze satellite orbits.
2021-03-08 β 2.18
* If a TLE satellite number lacks the required 5 digits,
``twoline2rv()`` now gives the underlying C++ library a little help so
it can still parse the classification and international designator
correctly.
* The ``Satrec`` attributes ``jdsatepoch``, ``jdsatepochF``,
``epochyr``, and ``epochdays`` are now writeable, so users can adjust
their values manually β which should make up for the fact that the
``sgp4init()`` method canβt set them with full floating point
precision.
| 2021-02-17 β 2.17 β Fixed where in the output array the ``sgp4_array()`` method writes NaN values when an SGP4 propagation fails.
| 2021-02-12 β 2.16 β Fixed ``days2mdhms()`` rounding to always match TLE epoch.
| 2021-01-08 β 2.15 β Fixed parsing of the ``satnum`` TLE field in the Python fallback code, when the field has a leading space; added OMM export routine.
| 2020-12-16 β 2.14 β New data formats: added OMM message support for both XML and CSV, and added support for the new Alpha-5 extension to TLE files.
| 2020-10-14 β 2.13 β Enhanced ``sgp4init()`` with custom code that also sets the ``epochdays`` and ``epochyr`` satellite attributes.
| 2020-05-28 β 2.12 β Moved the decision of whether to set the locale during ``twoline2rv()`` from import time to runtime, for users who change locales after their application is up and running.
| 2020-05-24 β 2.11 β Fixed a regression in how dates are split into hours, minutes, and seconds that would sometimes produce a time whose second=60, crashing the pure-Python version of the library.
| 2020-05-22 β 2.10 β Switch the locale temporarily to ``C`` during the C++ accelerated ``twoline2rv()``, since it does not protect its ``sscanf()`` calls from locales that, like German, expect comma decimal points instead of the period decimal points always used in a TLE.
| 2020-05-21 β 2.9 β Added ``sat_epoch_datetime()``, expanded documentation around converting a satellite epoch to a date and time, and started rounding the epoch to exactly the digits provided in the TLE; and removed the ``Satrec.epoch`` attribute from Python fallback code to better match the C++ version.
| 2020-05-07 β 2.8 β New function ``jday_datetime()`` is now available in the ``sgp4.conveniences`` module, thanks to Egemen Imre.
| 2020-04-24 β 2.7 β New method ``sgp4init()`` (thank you, Chris Lewicki!) is available.
| 2020-04-20 β 2.6 β New routine ``export_tle()`` (thank you, Egemen Imre!) is available. Improved how the accelerated C++ backend parses the ``intldesg`` string and the ``revnum`` integer.
| 2020-03-22 β 2.5 β Gave the new accelerated ``twoline2rv()`` an optional argument that lets the user choose a non-standard set of gravity constants.
| 2020-02-25 β 2.4 β Improved the ``jday()`` docstring; made the old legacy Python resilient if the day of the month is out-of-range (past the end of the month) in a TLE; and Mark Rutten fixed the C++ so it compiles on Windows!
| 2020-02-04 β 2.3 β Removed experimental code that caused performance problems for users with Numba installed.
| 2020-02-02 β 2.2 β A second release on Palindrome Day: fix the Satrec ``.epochyr`` attribute so it behaves the same way in Python as it does in the official C library, where it is only the last 2 digits of the year; and make ``.no`` available in the Python fallback case as well.
| 2020-02-02 β 2.1 β Add vectorized array method to Satrec object; add ``.no`` attribute to new Satrec object to support old code that has not migrated to the new name ``.no_kozai``; gave Python wrapper classes ``__slots__`` to avoid the expense of a per-object attribute dictionary.
| 2020-01-30 β 2.0 β Rewrite API to use genuine Vallado C++ code on those systems where it can be compiled; add accelerated vectorized array interface; make ``gstime()`` a public function; clarify format error message.
| 2015-01-15 β 1.4 β Display detailed help when TLE input does not match format.
| 2014-06-26 β 1.3 β Return ``(NaN,NaN,NaN)`` vectors on error and set ``.error_message``
| 2013-11-29 β 1.2 β Made ``epochyr`` 4 digits; add ``datetime`` for ``.epoch``
| 2012-11-22 β 1.1 β PythonΒ 3 compatibility; more documentation
| 2012-08-27 β 1.0 β Initial release
"""
__version__ = '2.22'
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,800
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/wulfgar.py
|
"""Support test functions, in a module small enough to carry inline."""
from importlib import import_module
from unittest import TestCase
__unittest = 1 # Tell unittest not to include run() in test tracebacks.
def add_test_functions(loader, tests, module_name):
"""Run our main documentation as a test and test functions in this file."""
def wrap_test_function(test):
def run(self):
return test()
return run
module = import_module(module_name)
test_methods = dict((name, wrap_test_function(getattr(module, name)))
for name in dir(module) if name.startswith('test_'))
TestFunctions = type('TestFunctions', (TestCase,), test_methods)
TestFunctions.__module__ = module_name
tests.addTest(loader.loadTestsFromTestCase(TestFunctions))
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,801
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/exporter.py
|
"""Export orbit data to a Two-Line-Element representation.
Contributed by Egemen Imre https://github.com/egemenimre
"""
from math import pi
from sgp4.io import compute_checksum
from sgp4.conveniences import sat_epoch_datetime
# Define constants
_deg2rad = pi / 180.0 # 0.0174532925199433
_xpdotp = 1440.0 / (2.0 * pi) # 229.1831180523293
def export_tle(satrec):
"""Generate the TLE for a given `Satrec` object; returns two strings."""
# --------------------- Start generating line 1 ---------------------
# Build the list by appending successive items
pieces = ['1 ', satrec.satnum_str]
append = pieces.append
# Add classification code (use "U" if empty)
classification = getattr(satrec, 'classification', 'U')
append(classification.strip() or 'U')
append(' ')
# Add int'l designator and pad to 8 chars
intldesg = getattr(satrec, 'intldesg', '')
append('{0:8} '.format(intldesg))
# Add epoch year and days in YYDDD.DDDDDDDD format
epochyr = satrec.epochyr
# Undo non-standard 4-digit year for old satrec objects
epochyr %= 100
append(str(epochyr).zfill(2) + "{:012.8f}".format(satrec.epochdays) + " ")
# Add First Time Derivative of the Mean Motion (don't use "+")
append("{0: 8.8f}".format(satrec.ndot * (_xpdotp * 1440.0)).replace("0", "", 1) + " ")
# Add Second Time Derivative of Mean Motion
append(_abbreviate_rate(satrec.nddot * _xpdotp * 20736000.0, '-0'))
# Add BSTAR
append(_abbreviate_rate(satrec.bstar * 10.0, '+0'))
# Add Ephemeris Type and Element Number
ephtype = getattr(satrec, 'ephtype', 0)
elnum = getattr(satrec, 'elnum', 0)
append('{0} {1:4}'.format(ephtype, elnum))
# Join all the parts and add the Checksum
line1 = ''.join(pieces)
line1 += str(compute_checksum(line1))
# --------------------- Start generating line 2 ---------------------
# Reset the str array
pieces = ['2 ', satrec.satnum_str]
append = pieces.append
# Add the inclination (deg)
if not 0 <= satrec.inclo <= pi:
raise ValueError("Inclination must be between 0 and pi, got %r", satrec.inclo)
append(' {0:8.4f} '.format(satrec.inclo / _deg2rad))
# Add the RAAN (deg)
if not 0 <= satrec.nodeo <= 2 * pi:
raise ValueError("RAAN must be between 0 and 2 pi, got %r", satrec.nodeo)
append("{0:8.4f}".format(satrec.nodeo / _deg2rad).rjust(8, " ") + " ")
# Add the eccentricity (delete the leading zero an decimal point)
append("{0:8.7f}".format(satrec.ecco).replace("0.", "") + " ")
# Add the Argument of Perigee (deg)
if not 0 <= satrec.argpo <= 2 * pi:
raise ValueError("Argument of Perigee must be between 0 and 2 pi, got %r", satrec.argpo)
append("{0:8.4f}".format(satrec.argpo / _deg2rad).rjust(8, " ") + " ")
# Add the Mean Anomaly (deg)
if not 0 <= satrec.mo <= 2 * pi:
raise ValueError("Mean Anomaly must be between 0 and 2 pi, got %r", satrec.mo)
append("{0:8.4f}".format(satrec.mo / _deg2rad).rjust(8, " ") + " ")
# Add the Mean Motion (revs/day)
append("{0:11.8f}".format(satrec.no_kozai * _xpdotp).rjust(8, " "))
# Add the rev number at epoch
append(str(satrec.revnum).rjust(5))
# Join all the parts and add the Checksum
line2 = ''.join(pieces)
line2 += str(compute_checksum(line2))
return line1, line2
def _abbreviate_rate(value, zero_exponent_string):
return (
'{0: 4.4e} '.format(value)
.replace('.', '')
.replace('e+00', zero_exponent_string)
.replace('e-0', '-')
.replace('e+0', '+')
)
def export_omm(satrec, object_name):
launch_year = int(satrec.intldesg[:2])
launch_year += 1900 + (launch_year < 57) * 100
object_id = '{0}-{1}'.format(launch_year, satrec.intldesg[2:])
return {
"OBJECT_NAME": object_name,
"OBJECT_ID": object_id,
"CENTER_NAME": "EARTH",
"REF_FRAME": "TEME",
"TIME_SYSTEM": "UTC",
"MEAN_ELEMENT_THEORY": "SGP4",
"EPOCH": sat_epoch_datetime(satrec).strftime('%Y-%m-%dT%H:%M:%S.%f'),
"MEAN_MOTION": satrec.no_kozai * _xpdotp,
"ECCENTRICITY": satrec.ecco,
"INCLINATION": satrec.inclo / _deg2rad,
"RA_OF_ASC_NODE": satrec.nodeo / _deg2rad,
"ARG_OF_PERICENTER": satrec.argpo / _deg2rad,
"MEAN_ANOMALY": satrec.mo / _deg2rad,
"EPHEMERIS_TYPE": satrec.ephtype,
"CLASSIFICATION_TYPE": satrec.classification,
"NORAD_CAT_ID": satrec.satnum,
"ELEMENT_SET_NO": satrec.elnum,
"REV_AT_EPOCH": satrec.revnum,
"BSTAR": satrec.bstar,
"MEAN_MOTION_DOT": satrec.ndot * (_xpdotp * 1440.0),
"MEAN_MOTION_DDOT": satrec.nddot * (_xpdotp * 1440.0 * 1440),
}
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,802
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/ext.py
|
# -*- coding: utf-8 -*-
"""Utility routines from "sgp4ext.cpp"."""
from math import (acos, asinh, atan2, copysign, cos, fabs, fmod,
pi, sin, sinh, sqrt, tan)
from .functions import days2mdhms
undefined = None
"""
/* -----------------------------------------------------------------------------
*
* function mag
*
* this procedure finds the magnitude of a vector. the tolerance is set to
* 0.000001, thus the 1.0e-12 for the squared test of underflows.
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* vec - vector
*
* outputs :
* vec - answer stored in fourth component
*
* locals :
* none.
*
* coupling :
* none.
* --------------------------------------------------------------------------- */
"""
def mag(x):
return sqrt(x[0]*x[0] + x[1]*x[1] + x[2]*x[2]);
"""
/* -----------------------------------------------------------------------------
*
* procedure cross
*
* this procedure crosses two vectors.
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* vec1 - vector number 1
* vec2 - vector number 2
*
* outputs :
* outvec - vector result of a x b
*
* locals :
* none.
*
* coupling :
* mag magnitude of a vector
---------------------------------------------------------------------------- */
"""
def cross(vec1, vec2, outvec):
outvec[0]= vec1[1]*vec2[2] - vec1[2]*vec2[1];
outvec[1]= vec1[2]*vec2[0] - vec1[0]*vec2[2];
outvec[2]= vec1[0]*vec2[1] - vec1[1]*vec2[0];
"""
/* -----------------------------------------------------------------------------
*
* function dot
*
* this function finds the dot product of two vectors.
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* vec1 - vector number 1
* vec2 - vector number 2
*
* outputs :
* dot - result
*
* locals :
* none.
*
* coupling :
* none.
*
* --------------------------------------------------------------------------- */
"""
def dot(x, y):
return (x[0]*y[0] + x[1]*y[1] + x[2]*y[2]);
"""
/* -----------------------------------------------------------------------------
*
* procedure angle
*
* this procedure calculates the angle between two vectors. the output is
* set to 999999.1 to indicate an undefined value. be sure to check for
* this at the output phase.
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* vec1 - vector number 1
* vec2 - vector number 2
*
* outputs :
* theta - angle between the two vectors -pi to pi
*
* locals :
* temp - temporary real variable
*
* coupling :
* dot dot product of two vectors
* --------------------------------------------------------------------------- */
"""
def angle(vec1, vec2):
small = 0.00000001;
undefined = 999999.1;
magv1 = mag(vec1);
magv2 = mag(vec2);
if magv1*magv2 > small*small:
temp= dot(vec1,vec2) / (magv1*magv2);
if fabs(temp) > 1.0:
temp = copysign(1.0, temp)
return acos( temp );
else:
return undefined;
"""
/* -----------------------------------------------------------------------------
*
* function newtonnu
*
* this function solves keplers equation when the true anomaly is known.
* the mean and eccentric, parabolic, or hyperbolic anomaly is also found.
* the parabolic limit at 168Β° is arbitrary. the hyperbolic anomaly is also
* limited. the hyperbolic sine is used because it's not double valued.
*
* author : david vallado 719-573-2600 27 may 2002
*
* revisions
* vallado - fix small 24 sep 2002
*
* inputs description range / units
* ecc - eccentricity 0.0 to
* nu - true anomaly -2pi to 2pi rad
*
* outputs :
* e0 - eccentric anomaly 0.0 to 2pi rad 153.02 Β°
* m - mean anomaly 0.0 to 2pi rad 151.7425 Β°
*
* locals :
* e1 - eccentric anomaly, next value rad
* sine - sine of e
* cose - cosine of e
* ktr - index
*
* coupling :
* asinh - arc hyperbolic sine
*
* references :
* vallado 2007, 85, alg 5
* --------------------------------------------------------------------------- */
"""
def newtonnu(ecc, nu):
# --------------------- implementation ---------------------
e0= 999999.9;
m = 999999.9;
small = 0.00000001;
# --------------------------- circular ------------------------
if fabs(ecc) < small:
m = nu;
e0= nu;
else:
# ---------------------- elliptical -----------------------
if ecc < 1.0-small:
sine= ( sqrt( 1.0 -ecc*ecc ) * sin(nu) ) / ( 1.0 +ecc*cos(nu) );
cose= ( ecc + cos(nu) ) / ( 1.0 + ecc*cos(nu) );
e0 = atan2( sine,cose );
m = e0 - ecc*sin(e0);
else:
# -------------------- hyperbolic --------------------
if ecc > 1.0 + small:
if ecc > 1.0 and fabs(nu)+0.00001 < pi-acos(1.0 /ecc):
sine= ( sqrt( ecc*ecc-1.0 ) * sin(nu) ) / ( 1.0 + ecc*cos(nu) );
e0 = asinh( sine );
m = ecc*sinh(e0) - e0;
else:
# ----------------- parabolic ---------------------
if fabs(nu) < 168.0*pi/180.0:
e0= tan( nu*0.5 );
m = e0 + (e0*e0*e0)/3.0;
if ecc < 1.0:
m = fmod( m,2.0 *pi );
if m < 0.0:
m = m + 2.0 *pi;
e0 = fmod( e0,2.0 *pi );
return e0, m
"""
/* -----------------------------------------------------------------------------
*
* function rv2coe
*
* this function finds the classical orbital elements given the geocentric
* equatorial position and velocity vectors.
*
* author : david vallado 719-573-2600 21 jun 2002
*
* revisions
* vallado - fix special cases 5 sep 2002
* vallado - delete extra check in inclination code 16 oct 2002
* vallado - add constant file use 29 jun 2003
* vallado - add mu 2 apr 2007
*
* inputs description range / units
* r - ijk position vector km
* v - ijk velocity vector km / s
* mu - gravitational parameter km3 / s2
*
* outputs :
* p - semilatus rectum km
* a - semimajor axis km
* ecc - eccentricity
* incl - inclination 0.0 to pi rad
* omega - longitude of ascending node 0.0 to 2pi rad
* argp - argument of perigee 0.0 to 2pi rad
* nu - true anomaly 0.0 to 2pi rad
* m - mean anomaly 0.0 to 2pi rad
* arglat - argument of latitude (ci) 0.0 to 2pi rad
* truelon - true longitude (ce) 0.0 to 2pi rad
* lonper - longitude of periapsis (ee) 0.0 to 2pi rad
*
* locals :
* hbar - angular momentum h vector km2 / s
* ebar - eccentricity e vector
* nbar - line of nodes n vector
* c1 - v**2 - u/r
* rdotv - r dot v
* hk - hk unit vector
* sme - specfic mechanical energy km2 / s2
* i - index
* e - eccentric, parabolic,
* hyperbolic anomaly rad
* temp - temporary variable
* typeorbit - type of orbit ee, ei, ce, ci
*
* coupling :
* mag - magnitude of a vector
* cross - cross product of two vectors
* angle - find the angle between two vectors
* newtonnu - find the mean anomaly
*
* references :
* vallado 2007, 126, alg 9, ex 2-5
* --------------------------------------------------------------------------- */
"""
def rv2coe(r, v, mu):
hbar = [None, None, None]
nbar = [None, None, None]
ebar = [None, None, None]
typeorbit = [None, None, None];
twopi = 2.0 * pi;
halfpi = 0.5 * pi;
small = 0.00000001;
undefined = 999999.1;
infinite = 999999.9;
# ------------------------- implementation -----------------
magr = mag( r );
magv = mag( v );
# ------------------ find h n and e vectors ----------------
cross( r,v, hbar );
magh = mag( hbar );
if magh > small:
nbar[0]= -hbar[1];
nbar[1]= hbar[0];
nbar[2]= 0.0;
magn = mag( nbar );
c1 = magv*magv - mu /magr;
rdotv = dot( r,v );
for i in range(0, 3):
ebar[i]= (c1*r[i] - rdotv*v[i])/mu;
ecc = mag( ebar );
# ------------ find a e and semi-latus rectum ----------
sme= ( magv*magv*0.5 ) - ( mu /magr );
if fabs( sme ) > small:
a= -mu / (2.0 *sme);
else:
a= infinite;
p = magh*magh/mu;
# ----------------- find inclination -------------------
hk= hbar[2]/magh;
incl= acos( hk );
# -------- determine type of orbit for later use --------
# ------ elliptical, parabolic, hyperbolic inclined -------
typeorbit = 'ei'
if ecc < small:
# ---------------- circular equatorial ---------------
if incl < small or fabs(incl-pi) < small:
typeorbit = 'ce'
else:
# -------------- circular inclined ---------------
typeorbit = 'ci'
else:
# - elliptical, parabolic, hyperbolic equatorial --
if incl < small or fabs(incl-pi) < small:
typeorbit = 'ee'
# ---------- find longitude of ascending node ------------
if magn > small:
temp= nbar[0] / magn;
if fabs(temp) > 1.0:
temp = copysign(1.0, temp)
omega= acos( temp );
if nbar[1] < 0.0:
omega= twopi - omega;
else:
omega= undefined;
# ---------------- find argument of perigee ---------------
if typeorbit == 'ei':
argp = angle( nbar,ebar);
if ebar[2] < 0.0:
argp= twopi - argp;
else:
argp= undefined;
# ------------ find true anomaly at epoch -------------
if typeorbit[0] == 'e':
nu = angle( ebar,r);
if rdotv < 0.0:
nu= twopi - nu;
else:
nu= undefined;
# ---- find argument of latitude - circular inclined -----
if typeorbit == 'ci':
arglat = angle( nbar,r );
if r[2] < 0.0:
arglat= twopi - arglat;
m = arglat;
else:
arglat= undefined;
# -- find longitude of perigee - elliptical equatorial ----
if ecc > small and typeorbit == 'ee':
temp= ebar[0]/ecc;
if fabs(temp) > 1.0:
temp = copysign(1.0, temp)
lonper= acos( temp );
if ebar[1] < 0.0:
lonper= twopi - lonper;
if incl > halfpi:
lonper= twopi - lonper;
else:
lonper= undefined;
# -------- find true longitude - circular equatorial ------
if magr > small and typeorbit == 'ce':
temp= r[0]/magr;
if fabs(temp) > 1.0:
temp = copysign(1.0, temp)
truelon= acos( temp );
if r[1] < 0.0:
truelon= twopi - truelon;
if incl > halfpi:
truelon= twopi - truelon;
m = truelon;
else:
truelon= undefined;
# ------------ find mean anomaly for all orbits -----------
if typeorbit[0] == 'e':
e, m = newtonnu(ecc, nu);
else:
p = undefined;
a = undefined;
ecc = undefined;
incl = undefined;
omega= undefined;
argp = undefined;
nu = undefined;
m = undefined;
arglat = undefined;
truelon= undefined;
lonper = undefined;
return p, a, ecc, incl, omega, argp, nu, m, arglat, truelon, lonper
"""
/* -----------------------------------------------------------------------------
*
* procedure jday
*
* this procedure finds the julian date given the year, month, day, and time.
* the julian date is defined by each elapsed day since noon, jan 1, 4713 bc.
*
* algorithm : calculate the answer in one step for efficiency
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* year - year 1900 .. 2100
* mon - month 1 .. 12
* day - day 1 .. 28,29,30,31
* hr - universal time hour 0 .. 23
* min - universal time min 0 .. 59
* sec - universal time sec 0.0 .. 59.999
*
* outputs :
* jd - julian date days from 4713 bc
*
* locals :
* none.
*
* coupling :
* none.
*
* references :
* vallado 2007, 189, alg 14, ex 3-14
*
* --------------------------------------------------------------------------- */
"""
def jday(year, mon, day, hr, minute, sec):
return (367.0 * year -
7.0 * (year + ((mon + 9.0) // 12.0)) * 0.25 // 1.0 +
275.0 * mon // 9.0 +
day + 1721013.5 +
((sec / 60.0 + minute) / 60.0 + hr) / 24.0 # ut in days
# - 0.5*sgn(100.0*year + mon - 190002.5) + 0.5;
)
"""
/* -----------------------------------------------------------------------------
*
* procedure invjday
*
* this procedure finds the year, month, day, hour, minute and second
* given the julian date. tu can be ut1, tdt, tdb, etc.
*
* algorithm : set up starting values
* find leap year - use 1900 because 2000 is a leap year
* find the elapsed days through the year in a loop
* call routine to find each individual value
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* jd - julian date days from 4713 bc
*
* outputs :
* year - year 1900 .. 2100
* mon - month 1 .. 12
* day - day 1 .. 28,29,30,31
* hr - hour 0 .. 23
* min - minute 0 .. 59
* sec - second 0.0 .. 59.999
*
* locals :
* days - day of year plus fractional
* portion of a day days
* tu - julian centuries from 0 h
* jan 0, 1900
* temp - temporary double values
* leapyrs - number of leap years from 1900
*
* coupling :
* days2mdhms - finds month, day, hour, minute and second given days and year
*
* references :
* vallado 2007, 208, alg 22, ex 3-13
* --------------------------------------------------------------------------- */
"""
def invjday(jd):
# --------------- find year and days of the year ---------------
temp = jd - 2415019.5;
tu = temp / 365.25;
year = 1900 + int(tu // 1.0);
leapyrs = int(((year - 1901) * 0.25) // 1.0);
# optional nudge by 8.64x10-7 sec to get even outputs
days = temp - ((year - 1900) * 365.0 + leapyrs) + 0.00000000001;
# ------------ check for case of beginning of a year -----------
if (days < 1.0):
year = year - 1;
leapyrs = int(((year - 1901) * 0.25) // 1.0);
days = temp - ((year - 1900) * 365.0 + leapyrs);
# ----------------- find remaing data -------------------------
mon, day, hr, minute, sec = days2mdhms(year, days, None);
sec = sec - 0.00000086400;
return year, mon, day, hr, minute, sec
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,803
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/conveniences.py
|
"""Various conveniences.
Higher-level libraries like Skyfield that use this one usually have
their own date and time handling. But for folks using this library by
itself, native Python datetime handling could be convenient.
"""
import datetime as dt
import sgp4
from .functions import days2mdhms, jday
class _UTC(dt.tzinfo):
'UTC'
zero = dt.timedelta(0)
def __repr__(self):
return 'UTC'
def dst(self, datetime):
return self.zero
def tzname(self, datetime):
return 'UTC'
def utcoffset(self, datetime):
return self.zero
UTC = _UTC()
def jday_datetime(datetime):
"""Return two floats that, when added, produce the specified Julian date.
The first float returned gives the date, while the second float
provides an additional offset for the particular hour, minute, and
second of that date. Because the second float is much smaller in
magnitude it can, unlike the first float, be accurate down to very
small fractions of a second.
>>> jd, fr = jday(2020, 2, 11, 13, 57, 0)
>>> jd
2458890.5
>>> fr
0.58125
Note that the first float, which gives the moment of midnight that
commences the given calendar date, always carries the fraction
``.5`` because Julian dates begin and end at noon. This made Julian
dates more convenient for astronomers in Europe, by making the whole
night belong to a single Julian date.
The input is a native `datetime` object. Timezone of the input is
converted internally to UTC.
"""
u = datetime.astimezone(UTC)
year = u.year
mon = u.month
day = u.day
hr = u.hour
minute = u.minute
sec = u.second + u.microsecond * 1e-6
return jday(year, mon, day, hr, minute, sec)
def sat_epoch_datetime(sat):
"""Return the epoch of the given satellite as a Python datetime."""
year = sat.epochyr
year += 1900 + (year < 57) * 100
days = sat.epochdays
month, day, hour, minute, second = days2mdhms(year, days)
if month == 12 and day > 31: # for that time the ISS epoch was "Dec 32"
year += 1
month = 1
day -= 31
second, fraction = divmod(second, 1.0)
second = int(second)
micro = int(fraction * 1e6)
return dt.datetime(year, month, day, hour, minute, second, micro, UTC)
_ATTRIBUTES = None
def dump_satrec(sat, sat2=None):
"""Yield lines that list the attributes of one or two satellites."""
global _ATTRIBUTES
if _ATTRIBUTES is None:
_ATTRIBUTES = []
for line in sgp4.__doc__.splitlines():
if line.endswith('*'):
title = line.strip('*')
_ATTRIBUTES.append(title)
elif line.startswith('| ``'):
pieces = line.split('``')
_ATTRIBUTES.append(pieces[1])
i = 2
while pieces[i] == ', ':
_ATTRIBUTES.append(pieces[i+1])
i += 2
for item in _ATTRIBUTES:
if item[0].isupper():
title = item
yield '\n'
yield '# -------- {0} --------\n'.format(title)
else:
name = item
value = getattr(sat, item, '(not set)')
line = '{0} = {1!r}\n'.format(item, value)
if sat2 is not None:
value2 = getattr(sat2, name, '(not set)')
verdict = '==' if (value == value2) else '!='
line = '{0:39} {1} {2!r}\n'.format(line[:-1], verdict, value2)
yield line
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,804
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/functions.py
|
"""General-purpose routines.
It seemed a shame for the ``api`` module to have to import large legacy
modules to offer simple date handling, so this small module holds the
routines instead.
"""
def jday(year, mon, day, hr, minute, sec):
"""Return two floats that, when added, produce the specified Julian date.
The first float returned gives the date, while the second float
provides an additional offset for the particular hour, minute, and
second of that date. Because the second float is much smaller in
magnitude it can, unlike the first float, be accurate down to very
small fractions of a second.
>>> jd, fr = jday(2020, 2, 11, 13, 57, 0)
>>> jd
2458890.5
>>> fr
0.58125
Note that the first float, which gives the moment of midnight that
commences the given calendar date, always carries the fraction
``.5`` because Julian dates begin and end at noon. This made
Julian dates more convenient for astronomers in Europe, by making
the whole night belong to a single Julian date.
This function is a simple translation to Python of the C++ routine
``jday()`` in Vallado's ``SGP4.cpp``.
"""
jd = (367.0 * year
- 7 * (year + ((mon + 9) // 12.0)) * 0.25 // 1.0
+ 275 * mon / 9.0 // 1.0
+ day
+ 1721013.5)
fr = (sec + minute * 60.0 + hr * 3600.0) / 86400.0;
return jd, fr
def days2mdhms(year, days, round_to_microsecond=6):
"""Convert a float point number of days into the year into date and time.
Given the integer year plus the "day of the year" where 1.0 means
the beginning of January 1, 2.0 means the beginning of January 2,
and so forth, return the Gregorian calendar month, day, hour,
minute, and floating point seconds.
>>> days2mdhms(2000, 1.0) # January 1
(1, 1, 0, 0, 0.0)
>>> days2mdhms(2000, 32.0) # February 1
(2, 1, 0, 0, 0.0)
>>> days2mdhms(2000, 366.0) # December 31, since 2000 was a leap year
(12, 31, 0, 0, 0.0)
The floating point seconds are rounded to an even number of
microseconds if ``round_to_microsecond`` is true.
"""
second = days * 86400.0
if round_to_microsecond:
second = round(second, round_to_microsecond)
minute, second = divmod(second, 60.0)
if round_to_microsecond:
second = round(second, round_to_microsecond)
minute = int(minute)
hour, minute = divmod(minute, 60)
day_of_year, hour = divmod(hour, 24)
is_leap = year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
month, day = _day_of_year_to_month_day(day_of_year, is_leap)
if month == 13: # behave like the original in case of overflow
month = 12
day += 31
return month, day, int(hour), int(minute), second
def _day_of_year_to_month_day(day_of_year, is_leap):
"""Core logic for turning days into months, for easy testing."""
february_bump = (2 - is_leap) * (day_of_year >= 60 + is_leap)
august = day_of_year >= 215
month, day = divmod(2 * (day_of_year - 1 + 30 * august + february_bump), 61)
month += 1 - august
day //= 2
day += 1
return month, day
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,805
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/io.py
|
"""Read the TLE earth satellite file format.
This is a minimally-edited copy of "sgp4io.cpp".
"""
import re
from datetime import datetime
from math import pi, pow
from sgp4.ext import days2mdhms, invjday, jday
from sgp4.propagation import sgp4init
INT_RE = re.compile(r'[+-]?\d*')
FLOAT_RE = re.compile(r'[+-]?\d*(\.\d*)?')
LINE1 = '1 NNNNNC NNNNNAAA NNNNN.NNNNNNNN +.NNNNNNNN +NNNNN-N +NNNNN-N N NNNNN'
LINE2 = '2 NNNNN NNN.NNNN NNN.NNNN NNNNNNN NNN.NNNN NNN.NNNN NN.NNNNNNNNNNNNNN'
error_message = """TLE format error
The Two-Line Element (TLE) format was designed for punch cards, and so
is very strict about the position of every period, space, and digit.
Your line does not quite match. Here is the official format for line {0}
with an N where each digit should go, followed by the line you provided:
{1}
{2}"""
"""
/* ----------------------------------------------------------------
*
* sgp4io.cpp
*
* this file contains a function to read two line element sets. while
* not formerly part of the sgp4 mathematical theory, it is
* required for practical implemenation.
*
* companion code for
* fundamentals of astrodynamics and applications
* 2007
* by david vallado
*
* (w) 719-573-2600, email dvallado@agi.com
*
* current :
* 27 Aug 10 david vallado
* fix input format and delete unused variables in twoline2rv
* changes :
* 3 sep 08 david vallado
* add operationmode for afspc (a) or improved (i)
* 9 may 07 david vallado
* fix year correction to 57
* 27 mar 07 david vallado
* misc fixes to manual inputs
* 14 aug 06 david vallado
* original baseline
* ---------------------------------------------------------------- */
"""
"""
/* -----------------------------------------------------------------------------
*
* function twoline2rv
*
* this function converts the two line element set character string data to
* variables and initializes the sgp4 variables. several intermediate varaibles
* and quantities are determined. note that the result is a structure so multiple
* satellites can be processed simultaneously without having to reinitialize. the
* verification mode is an important option that permits quick checks of any
* changes to the underlying technical theory. this option works using a
* modified tle file in which the start, stop, and delta time values are
* included at the end of the second line of data. this only works with the
* verification mode. the catalog mode simply propagates from -1440 to 1440 min
* from epoch and is useful when performing entire catalog runs.
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs :
* longstr1 - first line of the tle
* longstr2 - second line of the tle
* typerun - type of run verification 'v', catalog 'c',
* manual 'm'
* typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd'
* opsmode - mode of operation afspc or improved 'a', 'i'
* whichconst - which set of constants to use 72, 84
*
* outputs :
* satrec - structure containing all the sgp4 satellite information
*
* coupling :
* getgravconst-
* days2mdhms - conversion of days to month, day, hour, minute, second
* jday - convert day month year hour minute second into julian date
* sgp4init - initialize the sgp4 variables
*
* references :
* norad spacetrack report #3
* vallado, crawford, hujsak, kelso 2006
--------------------------------------------------------------------------- */
"""
def twoline2rv(longstr1, longstr2, whichconst, opsmode='i', satrec=None):
"""Return a Satellite imported from two lines of TLE data.
Provide the two TLE lines as strings `longstr1` and `longstr2`,
and select which standard set of gravitational constants you want
by providing `gravity_constants`:
`sgp4.earth_gravity.wgs72` - Standard WGS 72 model
`sgp4.earth_gravity.wgs84` - More recent WGS 84 model
`sgp4.earth_gravity.wgs72old` - Legacy support for old SGP4 behavior
Normally, computations are made using various recent improvements
to the algorithm. If you want to turn some of these off and go
back into "opsmode" mode, then set `opsmode` to `a`.
"""
deg2rad = pi / 180.0; # 0.0174532925199433
xpdotp = 1440.0 / (2.0 *pi); # 229.1831180523293
# For compatibility with our 1.x API, build an old Satellite object
# if the caller fails to supply a satrec. In that case we perform
# the necessary import here to avoid an import loop.
if satrec is None:
from sgp4.model import Satellite
satrec = Satellite()
satrec.error = 0;
line = longstr1.rstrip()
try:
longstr1.encode('ascii')
longstr2.encode('ascii')
except UnicodeEncodeError:
r1 = repr(longstr1)[1:-1]
r2 = repr(longstr2)[1:-1]
raise ValueError('your TLE lines are broken because they contain'
' non-ASCII characters:\n\n%s\n%s' % (r1, r2))
if (len(line) >= 64 and
line.startswith('1 ') and
line[8] == ' ' and
line[23] == '.' and
line[32] == ' ' and
line[34] == '.' and
line[43] == ' ' and
line[52] == ' ' and
line[61] == ' ' and
line[63] == ' '):
satrec.satnum_str = line[2:7]
satrec.classification = line[7] or 'U'
satrec.intldesg = line[9:17].rstrip()
two_digit_year = int(line[18:20])
satrec.epochdays = float(line[20:32])
satrec.ndot = float(line[33:43])
satrec.nddot = float(line[44] + '.' + line[45:50])
nexp = int(line[50:52])
satrec.bstar = float(line[53] + '.' + line[54:59])
ibexp = int(line[59:61])
satrec.ephtype = line[62]
satrec.elnum = int(line[64:68])
else:
raise ValueError(error_message.format(1, LINE1, line))
line = longstr2.rstrip()
if (len(line) >= 69 and
line.startswith('2 ') and
line[7] == ' ' and
line[11] == '.' and
line[16] == ' ' and
line[20] == '.' and
line[25] == ' ' and
line[33] == ' ' and
line[37] == '.' and
line[42] == ' ' and
line[46] == '.' and
line[51] == ' '):
if satrec.satnum_str != line[2:7]:
raise ValueError('Object numbers in lines 1 and 2 do not match')
satrec.inclo = float(line[8:16])
satrec.nodeo = float(line[17:25])
satrec.ecco = float('0.' + line[26:33].replace(' ', '0'))
satrec.argpo = float(line[34:42])
satrec.mo = float(line[43:51])
satrec.no_kozai = float(line[52:63])
satrec.revnum = line[63:68]
#except (AssertionError, IndexError, ValueError):
else:
raise ValueError(error_message.format(2, LINE2, line))
# ---- find no, ndot, nddot ----
satrec.no_kozai = satrec.no_kozai / xpdotp; # rad/min
satrec.nddot= satrec.nddot * pow(10.0, nexp);
satrec.bstar= satrec.bstar * pow(10.0, ibexp);
# ---- convert to sgp4 units ----
satrec.ndot = satrec.ndot / (xpdotp*1440.0); # ? * minperday
satrec.nddot= satrec.nddot / (xpdotp*1440.0*1440);
# ---- find standard orbital elements ----
satrec.inclo = satrec.inclo * deg2rad;
satrec.nodeo = satrec.nodeo * deg2rad;
satrec.argpo = satrec.argpo * deg2rad;
satrec.mo = satrec.mo * deg2rad;
"""
// ----------------------------------------------------------------
// find sgp4epoch time of element set
// remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch)
// and minutes from the epoch (time)
// ----------------------------------------------------------------
// ---------------- temp fix for years from 1957-2056 -------------------
// --------- correct fix will occur when year is 4-digit in tle ---------
"""
if two_digit_year < 57:
year = two_digit_year + 2000;
else:
year = two_digit_year + 1900;
mon,day,hr,minute,sec = days2mdhms(year, satrec.epochdays);
sec_whole, sec_fraction = divmod(sec, 1.0)
satrec.epochyr = year
satrec.jdsatepoch = jday(year,mon,day,hr,minute,sec);
try:
satrec.epoch = datetime(year, mon, day, hr, minute, int(sec_whole),
int(sec_fraction * 1000000.0 // 1.0))
except ValueError:
# Sometimes a TLE says something like "2019 + 366.82137887 days"
# which would be December 32nd which causes a ValueError.
year, mon, day, hr, minute, sec = invjday(satrec.jdsatepoch)
satrec.epoch = datetime(year, mon, day, hr, minute, int(sec_whole),
int(sec_fraction * 1000000.0 // 1.0))
# ---------------- initialize the orbit at sgp4epoch -------------------
sgp4init(whichconst, opsmode, satrec.satnum_str, satrec.jdsatepoch-2433281.5, satrec.bstar,
satrec.ndot, satrec.nddot, satrec.ecco, satrec.argpo, satrec.inclo, satrec.mo,
satrec.no_kozai, satrec.nodeo, satrec)
return satrec
def verify_checksum(*lines):
"""Verify the checksum of one or more TLE lines.
Raises `ValueError` if any of the lines fails its checksum, and
includes the failing line in the error message.
"""
for line in lines:
checksum = line[68:69]
if not checksum.isdigit():
continue
checksum = int(checksum)
computed = compute_checksum(line)
if checksum != computed:
complaint = ('TLE line gives its checksum as {}'
' but in fact tallies to {}:\n{}')
raise ValueError(complaint.format(checksum, computed, line))
def fix_checksum(line):
"""Return a new copy of the TLE `line`, with the correct checksum appended.
This discards any existing checksum at the end of the line, if a
checksum is already present.
"""
return line[:68].ljust(68) + str(compute_checksum(line))
def compute_checksum(line):
"""Compute the TLE checksum for the given line."""
return sum((int(c) if c.isdigit() else c == '-') for c in line[0:68]) % 10
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,806
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/alpha5.py
|
"""Alpha 5 encoding of satellite numbers to fit in 5 characters."""
def to_alpha5(n):
if n < 100000:
return '%05d' % n
if n > 339999:
raise ValueError('satellite number cannot exceed 339999,'
" whose Alpha 5 encoding is 'Z9999'")
i, n = divmod(n, 10000)
i += ord('A') - 10
if i >= ord('I'): i += 1
if i >= ord('O'): i += 1
return '%c%04d' % (i, n)
def from_alpha5(s):
if not s[0].isalpha():
return int(s)
c, s = s[0], s[1:]
n = ord(c) - ord('A') + 10
n -= c > 'I'
n -= c > 'O'
return n * 10000 + int(s)
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,807
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/earth_gravity.py
|
"""Three earth-gravity models for use with SGP4."""
from collections import namedtuple
from sgp4.propagation import getgravconst
EarthGravity = namedtuple(
'EarthGravity',
'tumin mu radiusearthkm xke j2 j3 j4 j3oj2',
)
wgs72old = EarthGravity(*getgravconst('wgs72old'))
wgs72 = EarthGravity(*getgravconst('wgs72'))
wgs84 = EarthGravity(*getgravconst('wgs84'))
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,808
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/propagation.py
|
"""The sgp4 procedures for analytical propagation of a satellite.
I have made the rather unorthodox decision to leave as much of this C++
code alone as possible: if a line of code would run without change in
Python, then I refused to re-indent it or remove its terminal semicolon,
so that in the future it will be easier to keep updating this file as
the original author's C++ continues to improve. Thus, 5-space
indentation (!) prevails in this file.
I have even kept all of the C++ block comments (by turning them into
Python string constants) to make this easier to navigate and maintain,
as well as to make it more informative for people who encounter this
code for the first time here in its Python form.
| - Brandon Rhodes
| Common Grounds Coffee House, Bluffton, Ohio
| On a very hot August day in 2012
"""
from math import atan2, cos, fabs, pi, sin, sqrt
from sgp4.alpha5 import to_alpha5
deg2rad = pi / 180.0;
_nan = float('NaN')
false = (_nan, _nan, _nan)
true = True
twopi = 2.0 * pi
"""
/* ----------------------------------------------------------------
*
* sgp4unit.cpp
*
* this file contains the sgp4 procedures for analytical propagation
* of a satellite. the code was originally released in the 1980 and 1986
* spacetrack papers. a detailed discussion of the theory and history
* may be found in the 2006 aiaa paper by vallado, crawford, hujsak,
* and kelso.
*
* companion code for
* fundamentals of astrodynamics and applications
* 2013
* by david vallado
*
* (w) 719-573-2600, email dvallado@agi.com, davallado@gmail.com
*
* current :
* 7 dec 15 david vallado
* fix jd, jdfrac
* changes :
* 3 nov 14 david vallado
* update to msvs2013 c++
* 30 aug 10 david vallado
* delete unused variables in initl
* replace pow integer 2, 3 with multiplies for speed
* 3 nov 08 david vallado
* put returns in for error codes
* 29 sep 08 david vallado
* fix atime for faster operation in dspace
* add operationmode for afspc (a) or improved (i)
* performance mode
* 16 jun 08 david vallado
* update small eccentricity check
* 16 nov 07 david vallado
* misc fixes for better compliance
* 20 apr 07 david vallado
* misc fixes for constants
* 11 aug 06 david vallado
* chg lyddane choice back to strn3, constants, misc doc
* 15 dec 05 david vallado
* misc fixes
* 26 jul 05 david vallado
* fixes for paper
* note that each fix is preceded by a
* comment with "sgp4fix" and an explanation of
* what was changed
* 10 aug 04 david vallado
* 2nd printing baseline working
* 14 may 01 david vallado
* 2nd edition baseline
* 80 norad
* original baseline
* ---------------------------------------------------------------- */
"""
"""
/* -----------------------------------------------------------------------------
*
* procedure dpper
*
* this procedure provides deep space long period periodic contributions
* to the mean elements. by design, these periodics are zero at epoch.
* this used to be dscom which included initialization, but it's really a
* recurring function.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* e3 -
* ee2 -
* peo -
* pgho -
* pho -
* pinco -
* plo -
* se2 , se3 , sgh2, sgh3, sgh4, sh2, sh3, si2, si3, sl2, sl3, sl4 -
* t -
* xh2, xh3, xi2, xi3, xl2, xl3, xl4 -
* zmol -
* zmos -
* ep - eccentricity 0.0 - 1.0
* inclo - inclination - needed for lyddane modification
* nodep - right ascension of ascending node
* argpp - argument of perigee
* mp - mean anomaly
*
* outputs :
* ep - eccentricity 0.0 - 1.0
* inclp - inclination
* nodep - right ascension of ascending node
* argpp - argument of perigee
* mp - mean anomaly
*
* locals :
* alfdp -
* betdp -
* cosip , sinip , cosop , sinop ,
* dalf -
* dbet -
* dls -
* f2, f3 -
* pe -
* pgh -
* ph -
* pinc -
* pl -
* sel , ses , sghl , sghs , shl , shs , sil , sinzf , sis ,
* sll , sls
* xls -
* xnoh -
* zf -
* zm -
*
* coupling :
* none.
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def _dpper(satrec, inclo, init, ep, inclp, nodep, argpp, mp, opsmode):
# Copy satellite attributes into local variables for convenience
# and symmetry in writing formulae.
e3 = satrec.e3
ee2 = satrec.ee2
peo = satrec.peo
pgho = satrec.pgho
pho = satrec.pho
pinco = satrec.pinco
plo = satrec.plo
se2 = satrec.se2
se3 = satrec.se3
sgh2 = satrec.sgh2
sgh3 = satrec.sgh3
sgh4 = satrec.sgh4
sh2 = satrec.sh2
sh3 = satrec.sh3
si2 = satrec.si2
si3 = satrec.si3
sl2 = satrec.sl2
sl3 = satrec.sl3
sl4 = satrec.sl4
t = satrec.t
xgh2 = satrec.xgh2
xgh3 = satrec.xgh3
xgh4 = satrec.xgh4
xh2 = satrec.xh2
xh3 = satrec.xh3
xi2 = satrec.xi2
xi3 = satrec.xi3
xl2 = satrec.xl2
xl3 = satrec.xl3
xl4 = satrec.xl4
zmol = satrec.zmol
zmos = satrec.zmos
# ---------------------- constants -----------------------------
zns = 1.19459e-5;
zes = 0.01675;
znl = 1.5835218e-4;
zel = 0.05490;
# --------------- calculate time varying periodics -----------
zm = zmos + zns * t;
# be sure that the initial call has time set to zero
if init == 'y':
zm = zmos;
zf = zm + 2.0 * zes * sin(zm);
sinzf = sin(zf);
f2 = 0.5 * sinzf * sinzf - 0.25;
f3 = -0.5 * sinzf * cos(zf);
ses = se2* f2 + se3 * f3;
sis = si2 * f2 + si3 * f3;
sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf;
sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf;
shs = sh2 * f2 + sh3 * f3;
zm = zmol + znl * t;
if init == 'y':
zm = zmol;
zf = zm + 2.0 * zel * sin(zm);
sinzf = sin(zf);
f2 = 0.5 * sinzf * sinzf - 0.25;
f3 = -0.5 * sinzf * cos(zf);
sel = ee2 * f2 + e3 * f3;
sil = xi2 * f2 + xi3 * f3;
sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf;
sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf;
shll = xh2 * f2 + xh3 * f3;
pe = ses + sel;
pinc = sis + sil;
pl = sls + sll;
pgh = sghs + sghl;
ph = shs + shll;
if init == 'n':
pe = pe - peo;
pinc = pinc - pinco;
pl = pl - plo;
pgh = pgh - pgho;
ph = ph - pho;
inclp = inclp + pinc;
ep = ep + pe;
sinip = sin(inclp);
cosip = cos(inclp);
"""
/* ----------------- apply periodics directly ------------ */
// sgp4fix for lyddane choice
// strn3 used original inclination - this is technically feasible
// gsfc used perturbed inclination - also technically feasible
// probably best to readjust the 0.2 limit value and limit discontinuity
// 0.2 rad = 11.45916 deg
// use next line for original strn3 approach and original inclination
// if (inclo >= 0.2)
// use next line for gsfc version and perturbed inclination
"""
if inclp >= 0.2:
ph /= sinip
pgh -= cosip * ph
argpp += pgh
nodep += ph
mp += pl
else:
# ---- apply periodics with lyddane modification ----
sinop = sin(nodep);
cosop = cos(nodep);
alfdp = sinip * sinop;
betdp = sinip * cosop;
dalf = ph * cosop + pinc * cosip * sinop;
dbet = -ph * sinop + pinc * cosip * cosop;
alfdp = alfdp + dalf;
betdp = betdp + dbet;
nodep = nodep % twopi if nodep >= 0.0 else -(-nodep % twopi)
# sgp4fix for afspc written intrinsic functions
# nodep used without a trigonometric function ahead
if nodep < 0.0 and opsmode == 'a':
nodep = nodep + twopi;
xls = mp + argpp + pl + pgh + (cosip - pinc * sinip) * nodep
xnoh = nodep;
nodep = atan2(alfdp, betdp);
# sgp4fix for afspc written intrinsic functions
# nodep used without a trigonometric function ahead
if nodep < 0.0 and opsmode == 'a':
nodep = nodep + twopi;
if fabs(xnoh - nodep) > pi:
if nodep < xnoh:
nodep = nodep + twopi;
else:
nodep = nodep - twopi;
mp += pl
argpp = xls - mp - cosip * nodep;
return ep, inclp, nodep, argpp, mp
"""
/*-----------------------------------------------------------------------------
*
* procedure dscom
*
* this procedure provides deep space common items used by both the secular
* and periodics subroutines. input is provided as shown. this routine
* used to be called dpper, but the functions inside weren't well organized.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* epoch -
* ep - eccentricity
* argpp - argument of perigee
* tc -
* inclp - inclination
* nodep - right ascension of ascending node
* np - mean motion
*
* outputs :
* sinim , cosim , sinomm , cosomm , snodm , cnodm
* day -
* e3 -
* ee2 -
* em - eccentricity
* emsq - eccentricity squared
* gam -
* peo -
* pgho -
* pho -
* pinco -
* plo -
* rtemsq -
* se2, se3 -
* sgh2, sgh3, sgh4 -
* sh2, sh3, si2, si3, sl2, sl3, sl4 -
* s1, s2, s3, s4, s5, s6, s7 -
* ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3 -
* sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 -
* xgh2, xgh3, xgh4, xh2, xh3, xi2, xi3, xl2, xl3, xl4 -
* nm - mean motion
* z1, z2, z3, z11, z12, z13, z21, z22, z23, z31, z32, z33 -
* zmol -
* zmos -
*
* locals :
* a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 -
* betasq -
* cc -
* ctem, stem -
* x1, x2, x3, x4, x5, x6, x7, x8 -
* xnodce -
* xnoi -
* zcosg , zsing , zcosgl , zsingl , zcosh , zsinh , zcoshl , zsinhl ,
* zcosi , zsini , zcosil , zsinil ,
* zx -
* zy -
*
* coupling :
* none.
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def _dscom(
epoch, ep, argpp, tc, inclp,
nodep, np,
e3, ee2,
peo, pgho, pho,
pinco, plo, se2, se3,
sgh2, sgh3, sgh4, sh2, sh3,
si2, si3, sl2, sl3, sl4,
xgh2, xgh3, xgh4, xh2,
xh3, xi2, xi3, xl2, xl3,
xl4, zmol, zmos,
):
# -------------------------- constants -------------------------
zes = 0.01675;
zel = 0.05490;
c1ss = 2.9864797e-6;
c1l = 4.7968065e-7;
zsinis = 0.39785416;
zcosis = 0.91744867;
zcosgs = 0.1945905;
zsings = -0.98088458;
# --------------------- local variables ------------------------
nm = np;
em = ep;
snodm = sin(nodep);
cnodm = cos(nodep);
sinomm = sin(argpp);
cosomm = cos(argpp);
sinim = sin(inclp);
cosim = cos(inclp);
emsq = em * em;
betasq = 1.0 - emsq;
rtemsq = sqrt(betasq);
# ----------------- initialize lunar solar terms ---------------
peo = 0.0;
pinco = 0.0;
plo = 0.0;
pgho = 0.0;
pho = 0.0;
day = epoch + 18261.5 + tc / 1440.0;
xnodce = (4.5236020 - 9.2422029e-4 * day) % twopi
stem = sin(xnodce);
ctem = cos(xnodce);
zcosil = 0.91375164 - 0.03568096 * ctem;
zsinil = sqrt(1.0 - zcosil * zcosil);
zsinhl = 0.089683511 * stem / zsinil;
zcoshl = sqrt(1.0 - zsinhl * zsinhl);
gam = 5.8351514 + 0.0019443680 * day;
zx = 0.39785416 * stem / zsinil;
zy = zcoshl * ctem + 0.91744867 * zsinhl * stem;
zx = atan2(zx, zy);
zx = gam + zx - xnodce;
zcosgl = cos(zx);
zsingl = sin(zx);
# ------------------------- do solar terms ---------------------
zcosg = zcosgs;
zsing = zsings;
zcosi = zcosis;
zsini = zsinis;
zcosh = cnodm;
zsinh = snodm;
cc = c1ss;
xnoi = 1.0 / nm;
for lsflg in 1, 2:
a1 = zcosg * zcosh + zsing * zcosi * zsinh;
a3 = -zsing * zcosh + zcosg * zcosi * zsinh;
a7 = -zcosg * zsinh + zsing * zcosi * zcosh;
a8 = zsing * zsini;
a9 = zsing * zsinh + zcosg * zcosi * zcosh;
a10 = zcosg * zsini;
a2 = cosim * a7 + sinim * a8;
a4 = cosim * a9 + sinim * a10;
a5 = -sinim * a7 + cosim * a8;
a6 = -sinim * a9 + cosim * a10;
x1 = a1 * cosomm + a2 * sinomm;
x2 = a3 * cosomm + a4 * sinomm;
x3 = -a1 * sinomm + a2 * cosomm;
x4 = -a3 * sinomm + a4 * cosomm;
x5 = a5 * sinomm;
x6 = a6 * sinomm;
x7 = a5 * cosomm;
x8 = a6 * cosomm;
z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3;
z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4;
z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4;
z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * emsq;
z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * emsq;
z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * emsq;
z11 = -6.0 * a1 * a5 + emsq * (-24.0 * x1 * x7-6.0 * x3 * x5);
z12 = -6.0 * (a1 * a6 + a3 * a5) + emsq * \
(-24.0 * (x2 * x7 + x1 * x8) - 6.0 * (x3 * x6 + x4 * x5));
z13 = -6.0 * a3 * a6 + emsq * (-24.0 * x2 * x8 - 6.0 * x4 * x6);
z21 = 6.0 * a2 * a5 + emsq * (24.0 * x1 * x5 - 6.0 * x3 * x7);
z22 = 6.0 * (a4 * a5 + a2 * a6) + emsq * \
(24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8));
z23 = 6.0 * a4 * a6 + emsq * (24.0 * x2 * x6 - 6.0 * x4 * x8);
z1 = z1 + z1 + betasq * z31;
z2 = z2 + z2 + betasq * z32;
z3 = z3 + z3 + betasq * z33;
s3 = cc * xnoi;
s2 = -0.5 * s3 / rtemsq;
s4 = s3 * rtemsq;
s1 = -15.0 * em * s4;
s5 = x1 * x3 + x2 * x4;
s6 = x2 * x3 + x1 * x4;
s7 = x2 * x4 - x1 * x3;
# ----------------------- do lunar terms -------------------
if lsflg == 1:
ss1 = s1;
ss2 = s2;
ss3 = s3;
ss4 = s4;
ss5 = s5;
ss6 = s6;
ss7 = s7;
sz1 = z1;
sz2 = z2;
sz3 = z3;
sz11 = z11;
sz12 = z12;
sz13 = z13;
sz21 = z21;
sz22 = z22;
sz23 = z23;
sz31 = z31;
sz32 = z32;
sz33 = z33;
zcosg = zcosgl;
zsing = zsingl;
zcosi = zcosil;
zsini = zsinil;
zcosh = zcoshl * cnodm + zsinhl * snodm;
zsinh = snodm * zcoshl - cnodm * zsinhl;
cc = c1l;
zmol = (4.7199672 + 0.22997150 * day - gam) % twopi
zmos = (6.2565837 + 0.017201977 * day) % twopi
# ------------------------ do solar terms ----------------------
se2 = 2.0 * ss1 * ss6;
se3 = 2.0 * ss1 * ss7;
si2 = 2.0 * ss2 * sz12;
si3 = 2.0 * ss2 * (sz13 - sz11);
sl2 = -2.0 * ss3 * sz2;
sl3 = -2.0 * ss3 * (sz3 - sz1);
sl4 = -2.0 * ss3 * (-21.0 - 9.0 * emsq) * zes;
sgh2 = 2.0 * ss4 * sz32;
sgh3 = 2.0 * ss4 * (sz33 - sz31);
sgh4 = -18.0 * ss4 * zes;
sh2 = -2.0 * ss2 * sz22;
sh3 = -2.0 * ss2 * (sz23 - sz21);
# ------------------------ do lunar terms ----------------------
ee2 = 2.0 * s1 * s6;
e3 = 2.0 * s1 * s7;
xi2 = 2.0 * s2 * z12;
xi3 = 2.0 * s2 * (z13 - z11);
xl2 = -2.0 * s3 * z2;
xl3 = -2.0 * s3 * (z3 - z1);
xl4 = -2.0 * s3 * (-21.0 - 9.0 * emsq) * zel;
xgh2 = 2.0 * s4 * z32;
xgh3 = 2.0 * s4 * (z33 - z31);
xgh4 = -18.0 * s4 * zel;
xh2 = -2.0 * s2 * z22;
xh3 = -2.0 * s2 * (z23 - z21);
return (
snodm, cnodm, sinim, cosim, sinomm,
cosomm,day, e3, ee2, em,
emsq, gam, peo, pgho, pho,
pinco, plo, rtemsq, se2, se3,
sgh2, sgh3, sgh4, sh2, sh3,
si2, si3, sl2, sl3, sl4,
s1, s2, s3, s4, s5,
s6, s7, ss1, ss2, ss3,
ss4, ss5, ss6, ss7, sz1,
sz2, sz3, sz11, sz12, sz13,
sz21, sz22, sz23, sz31, sz32,
sz33, xgh2, xgh3, xgh4, xh2,
xh3, xi2, xi3, xl2, xl3,
xl4, nm, z1, z2, z3,
z11, z12, z13, z21, z22,
z23, z31, z32, z33, zmol,
zmos
)
"""
/*-----------------------------------------------------------------------------
*
* procedure dsinit
*
* this procedure provides deep space contributions to mean motion dot due
* to geopotential resonance with half day and one day orbits.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* cosim, sinim-
* emsq - eccentricity squared
* argpo - argument of perigee
* s1, s2, s3, s4, s5 -
* ss1, ss2, ss3, ss4, ss5 -
* sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33 -
* t - time
* tc -
* gsto - greenwich sidereal time rad
* mo - mean anomaly
* mdot - mean anomaly dot (rate)
* no - mean motion
* nodeo - right ascension of ascending node
* nodedot - right ascension of ascending node dot (rate)
* xpidot -
* z1, z3, z11, z13, z21, z23, z31, z33 -
* eccm - eccentricity
* argpm - argument of perigee
* inclm - inclination
* mm - mean anomaly
* xn - mean motion
* nodem - right ascension of ascending node
*
* outputs :
* em - eccentricity
* argpm - argument of perigee
* inclm - inclination
* mm - mean anomaly
* nm - mean motion
* nodem - right ascension of ascending node
* irez - flag for resonance 0-none, 1-one day, 2-half day
* atime -
* d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 -
* dedt -
* didt -
* dmdt -
* dndt -
* dnodt -
* domdt -
* del1, del2, del3 -
* ses , sghl , sghs , sgs , shl , shs , sis , sls
* theta -
* xfact -
* xlamo -
* xli -
* xni
*
* locals :
* ainv2 -
* aonv -
* cosisq -
* eoc -
* f220, f221, f311, f321, f322, f330, f441, f442, f522, f523, f542, f543 -
* g200, g201, g211, g300, g310, g322, g410, g422, g520, g521, g532, g533 -
* sini2 -
* temp -
* temp1 -
* theta -
* xno2 -
*
* coupling :
* getgravconst
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def _dsinit(
# sgp4fix no longer needed pass in xke
# whichconst,
xke,
cosim, emsq, argpo, s1, s2,
s3, s4, s5, sinim, ss1,
ss2, ss3, ss4, ss5, sz1,
sz3, sz11, sz13, sz21, sz23,
sz31, sz33, t, tc, gsto,
mo, mdot, no, nodeo, nodedot,
xpidot, z1, z3, z11, z13,
z21, z23, z31, z33, ecco,
eccsq, em, argpm, inclm, mm,
nm, nodem,
irez,
atime, d2201, d2211, d3210, d3222,
d4410, d4422, d5220, d5232, d5421,
d5433, dedt, didt, dmdt,
dnodt, domdt, del1, del2, del3,
xfact, xlamo, xli, xni,
):
q22 = 1.7891679e-6;
q31 = 2.1460748e-6;
q33 = 2.2123015e-7;
root22 = 1.7891679e-6;
root44 = 7.3636953e-9;
root54 = 2.1765803e-9;
rptim = 4.37526908801129966e-3; # equates to 7.29211514668855e-5 rad/sec
root32 = 3.7393792e-7;
root52 = 1.1428639e-7;
x2o3 = 2.0 / 3.0;
znl = 1.5835218e-4;
zns = 1.19459e-5;
# sgp4fix identify constants and allow alternate values
# just xke is used here so pass it in rather than have multiple calls
# xke = whichconst.xke
# -------------------- deep space initialization ------------
irez = 0;
if 0.0034906585 < nm < 0.0052359877:
irez = 1;
if 8.26e-3 <= nm <= 9.24e-3 and em >= 0.5:
irez = 2;
# ------------------------ do solar terms -------------------
ses = ss1 * zns * ss5;
sis = ss2 * zns * (sz11 + sz13);
sls = -zns * ss3 * (sz1 + sz3 - 14.0 - 6.0 * emsq);
sghs = ss4 * zns * (sz31 + sz33 - 6.0);
shs = -zns * ss2 * (sz21 + sz23);
# sgp4fix for 180 deg incl
if inclm < 5.2359877e-2 or inclm > pi - 5.2359877e-2:
shs = 0.0;
if sinim != 0.0:
shs = shs / sinim;
sgs = sghs - cosim * shs;
# ------------------------- do lunar terms ------------------
dedt = ses + s1 * znl * s5;
didt = sis + s2 * znl * (z11 + z13);
dmdt = sls - znl * s3 * (z1 + z3 - 14.0 - 6.0 * emsq);
sghl = s4 * znl * (z31 + z33 - 6.0);
shll = -znl * s2 * (z21 + z23);
# sgp4fix for 180 deg incl
if inclm < 5.2359877e-2 or inclm > pi - 5.2359877e-2:
shll = 0.0;
domdt = sgs + sghl;
dnodt = shs;
if sinim != 0.0:
domdt = domdt - cosim / sinim * shll;
dnodt = dnodt + shll / sinim;
# ----------- calculate deep space resonance effects --------
dndt = 0.0;
theta = (gsto + tc * rptim) % twopi
em = em + dedt * t;
inclm = inclm + didt * t;
argpm = argpm + domdt * t;
nodem = nodem + dnodt * t;
mm = mm + dmdt * t;
"""
// sgp4fix for negative inclinations
// the following if statement should be commented out
//if (inclm < 0.0)
// {
// inclm = -inclm;
// argpm = argpm - pi;
// nodem = nodem + pi;
// }
"""
# -------------- initialize the resonance terms -------------
if irez != 0:
aonv = pow(nm / xke, x2o3);
# ---------- geopotential resonance for 12 hour orbits ------
if irez == 2:
cosisq = cosim * cosim;
emo = em;
em = ecco;
emsqo = emsq;
emsq = eccsq;
eoc = em * emsq;
g201 = -0.306 - (em - 0.64) * 0.440;
if em <= 0.65:
g211 = 3.616 - 13.2470 * em + 16.2900 * emsq;
g310 = -19.302 + 117.3900 * em - 228.4190 * emsq + 156.5910 * eoc;
g322 = -18.9068 + 109.7927 * em - 214.6334 * emsq + 146.5816 * eoc;
g410 = -41.122 + 242.6940 * em - 471.0940 * emsq + 313.9530 * eoc;
g422 = -146.407 + 841.8800 * em - 1629.014 * emsq + 1083.4350 * eoc;
g520 = -532.114 + 3017.977 * em - 5740.032 * emsq + 3708.2760 * eoc;
else:
g211 = -72.099 + 331.819 * em - 508.738 * emsq + 266.724 * eoc;
g310 = -346.844 + 1582.851 * em - 2415.925 * emsq + 1246.113 * eoc;
g322 = -342.585 + 1554.908 * em - 2366.899 * emsq + 1215.972 * eoc;
g410 = -1052.797 + 4758.686 * em - 7193.992 * emsq + 3651.957 * eoc;
g422 = -3581.690 + 16178.110 * em - 24462.770 * emsq + 12422.520 * eoc;
if em > 0.715:
g520 =-5149.66 + 29936.92 * em - 54087.36 * emsq + 31324.56 * eoc;
else:
g520 = 1464.74 - 4664.75 * em + 3763.64 * emsq;
if em < 0.7:
g533 = -919.22770 + 4988.6100 * em - 9064.7700 * emsq + 5542.21 * eoc;
g521 = -822.71072 + 4568.6173 * em - 8491.4146 * emsq + 5337.524 * eoc;
g532 = -853.66600 + 4690.2500 * em - 8624.7700 * emsq + 5341.4 * eoc;
else:
g533 =-37995.780 + 161616.52 * em - 229838.20 * emsq + 109377.94 * eoc;
g521 =-51752.104 + 218913.95 * em - 309468.16 * emsq + 146349.42 * eoc;
g532 =-40023.880 + 170470.89 * em - 242699.48 * emsq + 115605.82 * eoc;
sini2= sinim * sinim;
f220 = 0.75 * (1.0 + 2.0 * cosim+cosisq);
f221 = 1.5 * sini2;
f321 = 1.875 * sinim * (1.0 - 2.0 * cosim - 3.0 * cosisq);
f322 = -1.875 * sinim * (1.0 + 2.0 * cosim - 3.0 * cosisq);
f441 = 35.0 * sini2 * f220;
f442 = 39.3750 * sini2 * sini2;
f522 = 9.84375 * sinim * (sini2 * (1.0 - 2.0 * cosim- 5.0 * cosisq) +
0.33333333 * (-2.0 + 4.0 * cosim + 6.0 * cosisq) );
f523 = sinim * (4.92187512 * sini2 * (-2.0 - 4.0 * cosim +
10.0 * cosisq) + 6.56250012 * (1.0+2.0 * cosim - 3.0 * cosisq));
f542 = 29.53125 * sinim * (2.0 - 8.0 * cosim+cosisq *
(-12.0 + 8.0 * cosim + 10.0 * cosisq));
f543 = 29.53125 * sinim * (-2.0 - 8.0 * cosim+cosisq *
(12.0 + 8.0 * cosim - 10.0 * cosisq));
xno2 = nm * nm;
ainv2 = aonv * aonv;
temp1 = 3.0 * xno2 * ainv2;
temp = temp1 * root22;
d2201 = temp * f220 * g201;
d2211 = temp * f221 * g211;
temp1 = temp1 * aonv;
temp = temp1 * root32;
d3210 = temp * f321 * g310;
d3222 = temp * f322 * g322;
temp1 = temp1 * aonv;
temp = 2.0 * temp1 * root44;
d4410 = temp * f441 * g410;
d4422 = temp * f442 * g422;
temp1 = temp1 * aonv;
temp = temp1 * root52;
d5220 = temp * f522 * g520;
d5232 = temp * f523 * g532;
temp = 2.0 * temp1 * root54;
d5421 = temp * f542 * g521;
d5433 = temp * f543 * g533;
xlamo = (mo + nodeo + nodeo-theta - theta) % twopi
xfact = mdot + dmdt + 2.0 * (nodedot + dnodt - rptim) - no;
em = emo;
emsq = emsqo;
# ---------------- synchronous resonance terms --------------
if irez == 1:
g200 = 1.0 + emsq * (-2.5 + 0.8125 * emsq);
g310 = 1.0 + 2.0 * emsq;
g300 = 1.0 + emsq * (-6.0 + 6.60937 * emsq);
f220 = 0.75 * (1.0 + cosim) * (1.0 + cosim);
f311 = 0.9375 * sinim * sinim * (1.0 + 3.0 * cosim) - 0.75 * (1.0 + cosim);
f330 = 1.0 + cosim;
f330 = 1.875 * f330 * f330 * f330;
del1 = 3.0 * nm * nm * aonv * aonv;
del2 = 2.0 * del1 * f220 * g200 * q22;
del3 = 3.0 * del1 * f330 * g300 * q33 * aonv;
del1 = del1 * f311 * g310 * q31 * aonv;
xlamo = (mo + nodeo + argpo - theta) % twopi
xfact = mdot + xpidot - rptim + dmdt + domdt + dnodt - no;
# ------------ for sgp4, initialize the integrator ----------
xli = xlamo;
xni = no;
atime = 0.0;
nm = no + dndt;
return (
em, argpm, inclm, mm,
nm, nodem,
irez, atime,
d2201, d2211, d3210, d3222,
d4410, d4422, d5220, d5232,
d5421, d5433, dedt, didt,
dmdt, dndt, dnodt, domdt,
del1, del2, del3, xfact,
xlamo, xli, xni,
)
"""
/*-----------------------------------------------------------------------------
*
* procedure dspace
*
* this procedure provides deep space contributions to mean elements for
* perturbing third body. these effects have been averaged over one
* revolution of the sun and moon. for earth resonance effects, the
* effects have been averaged over no revolutions of the satellite.
* (mean motion)
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 -
* dedt -
* del1, del2, del3 -
* didt -
* dmdt -
* dnodt -
* domdt -
* irez - flag for resonance 0-none, 1-one day, 2-half day
* argpo - argument of perigee
* argpdot - argument of perigee dot (rate)
* t - time
* tc -
* gsto - gst
* xfact -
* xlamo -
* no - mean motion
* atime -
* em - eccentricity
* ft -
* argpm - argument of perigee
* inclm - inclination
* xli -
* mm - mean anomaly
* xni - mean motion
* nodem - right ascension of ascending node
*
* outputs :
* atime -
* em - eccentricity
* argpm - argument of perigee
* inclm - inclination
* xli -
* mm - mean anomaly
* xni -
* nodem - right ascension of ascending node
* dndt -
* nm - mean motion
*
* locals :
* delt -
* ft -
* theta -
* x2li -
* x2omi -
* xl -
* xldot -
* xnddt -
* xndt -
* xomi -
*
* coupling :
* none -
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def _dspace(
irez,
d2201, d2211, d3210, d3222, d4410,
d4422, d5220, d5232, d5421, d5433,
dedt, del1, del2, del3, didt,
dmdt, dnodt, domdt, argpo, argpdot,
t, tc, gsto, xfact, xlamo,
no,
atime, em, argpm, inclm, xli,
mm, xni, nodem, nm,
):
fasx2 = 0.13130908;
fasx4 = 2.8843198;
fasx6 = 0.37448087;
g22 = 5.7686396;
g32 = 0.95240898;
g44 = 1.8014998;
g52 = 1.0508330;
g54 = 4.4108898;
rptim = 4.37526908801129966e-3; # equates to 7.29211514668855e-5 rad/sec
stepp = 720.0;
stepn = -720.0;
step2 = 259200.0;
# ----------- calculate deep space resonance effects -----------
dndt = 0.0;
theta = (gsto + tc * rptim) % twopi
em = em + dedt * t;
inclm = inclm + didt * t;
argpm = argpm + domdt * t;
nodem = nodem + dnodt * t;
mm = mm + dmdt * t;
"""
// sgp4fix for negative inclinations
// the following if statement should be commented out
// if (inclm < 0.0)
// {
// inclm = -inclm;
// argpm = argpm - pi;
// nodem = nodem + pi;
// }
/* - update resonances : numerical (euler-maclaurin) integration - */
/* ------------------------- epoch restart ---------------------- */
// sgp4fix for propagator problems
// the following integration works for negative time steps and periods
// the specific changes are unknown because the original code was so convoluted
// sgp4fix take out atime = 0.0 and fix for faster operation
"""
ft = 0.0;
if irez != 0:
# sgp4fix streamline check
if atime == 0.0 or t * atime <= 0.0 or fabs(t) < fabs(atime):
atime = 0.0;
xni = no;
xli = xlamo;
# sgp4fix move check outside loop
if t > 0.0:
delt = stepp;
else:
delt = stepn;
iretn = 381; # added for do loop
# iret = 0; # added for loop
while iretn == 381:
# ------------------- dot terms calculated -------------
# ----------- near - synchronous resonance terms -------
if irez != 2:
xndt = del1 * sin(xli - fasx2) + del2 * sin(2.0 * (xli - fasx4)) + \
del3 * sin(3.0 * (xli - fasx6));
xldot = xni + xfact;
xnddt = del1 * cos(xli - fasx2) + \
2.0 * del2 * cos(2.0 * (xli - fasx4)) + \
3.0 * del3 * cos(3.0 * (xli - fasx6));
xnddt = xnddt * xldot;
else:
# --------- near - half-day resonance terms --------
xomi = argpo + argpdot * atime;
x2omi = xomi + xomi;
x2li = xli + xli;
xndt = (d2201 * sin(x2omi + xli - g22) + d2211 * sin(xli - g22) +
d3210 * sin(xomi + xli - g32) + d3222 * sin(-xomi + xli - g32)+
d4410 * sin(x2omi + x2li - g44)+ d4422 * sin(x2li - g44) +
d5220 * sin(xomi + xli - g52) + d5232 * sin(-xomi + xli - g52)+
d5421 * sin(xomi + x2li - g54) + d5433 * sin(-xomi + x2li - g54));
xldot = xni + xfact;
xnddt = (d2201 * cos(x2omi + xli - g22) + d2211 * cos(xli - g22) +
d3210 * cos(xomi + xli - g32) + d3222 * cos(-xomi + xli - g32) +
d5220 * cos(xomi + xli - g52) + d5232 * cos(-xomi + xli - g52) +
2.0 * (d4410 * cos(x2omi + x2li - g44) +
d4422 * cos(x2li - g44) + d5421 * cos(xomi + x2li - g54) +
d5433 * cos(-xomi + x2li - g54)));
xnddt = xnddt * xldot;
# ----------------------- integrator -------------------
# sgp4fix move end checks to end of routine
if fabs(t - atime) >= stepp:
# iret = 0;
iretn = 381;
else:
ft = t - atime;
iretn = 0;
if iretn == 381:
xli = xli + xldot * delt + xndt * step2;
xni = xni + xndt * delt + xnddt * step2;
atime = atime + delt;
nm = xni + xndt * ft + xnddt * ft * ft * 0.5;
xl = xli + xldot * ft + xndt * ft * ft * 0.5;
if irez != 1:
mm = xl - 2.0 * nodem + 2.0 * theta;
dndt = nm - no;
else:
mm = xl - nodem - argpm + theta;
dndt = nm - no;
nm = no + dndt;
return (
atime, em, argpm, inclm, xli,
mm, xni, nodem, dndt, nm,
)
"""
/*-----------------------------------------------------------------------------
*
* procedure initl
*
* this procedure initializes the spg4 propagator. all the initialization is
* consolidated here instead of having multiple loops inside other routines.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* satn - satellite number - not needed, placed in satrec
* xke - reciprocal of tumin
* j2 - j2 zonal harmonic
* ecco - eccentricity 0.0 - 1.0
* epoch - epoch time in days from jan 0, 1950. 0 hr
* inclo - inclination of satellite
* no - mean motion of satellite
*
* outputs :
* ainv - 1.0 / a
* ao - semi major axis
* con41 -
* con42 - 1.0 - 5.0 cos(i)
* cosio - cosine of inclination
* cosio2 - cosio squared
* eccsq - eccentricity squared
* method - flag for deep space 'd', 'n'
* omeosq - 1.0 - ecco * ecco
* posq - semi-parameter squared
* rp - radius of perigee
* rteosq - square root of (1.0 - ecco*ecco)
* sinio - sine of inclination
* gsto - gst at time of observation rad
* no - mean motion of satellite
*
* locals :
* ak -
* d1 -
* del -
* adel -
* po -
*
* coupling :
* getgravconst- no longer used
* gstime - find greenwich sidereal time from the julian date
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def _initl(
# not needeed. included in satrec if needed later
# satn,
# sgp4fix assin xke and j2
# whichconst,
xke, j2,
ecco, epoch, inclo, no,
method,
opsmode,
):
# sgp4fix use old way of finding gst
# ----------------------- earth constants ----------------------
# sgp4fix identify constants and allow alternate values
# only xke and j2 are used here so pass them in directly
# tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 = whichconst
x2o3 = 2.0 / 3.0;
# ------------- calculate auxillary epoch quantities ----------
eccsq = ecco * ecco;
omeosq = 1.0 - eccsq;
rteosq = sqrt(omeosq);
cosio = cos(inclo);
cosio2 = cosio * cosio;
# ------------------ un-kozai the mean motion -----------------
ak = pow(xke / no, x2o3);
d1 = 0.75 * j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq);
del_ = d1 / (ak * ak);
adel = ak * (1.0 - del_ * del_ - del_ *
(1.0 / 3.0 + 134.0 * del_ * del_ / 81.0));
del_ = d1/(adel * adel);
no = no / (1.0 + del_);
ao = pow(xke / no, x2o3);
sinio = sin(inclo);
po = ao * omeosq;
con42 = 1.0 - 5.0 * cosio2;
con41 = -con42-cosio2-cosio2;
ainv = 1.0 / ao;
posq = po * po;
rp = ao * (1.0 - ecco);
method = 'n';
# sgp4fix modern approach to finding sidereal time
if opsmode == 'a':
# sgp4fix use old way of finding gst
# count integer number of days from 0 jan 1970
ts70 = epoch - 7305.0;
ds70 = (ts70 + 1.0e-8) // 1.0;
tfrac = ts70 - ds70;
# find greenwich location at epoch
c1 = 1.72027916940703639e-2;
thgr70= 1.7321343856509374;
fk5r = 5.07551419432269442e-15;
c1p2p = c1 + twopi;
gsto = (thgr70 + c1*ds70 + c1p2p*tfrac + ts70*ts70*fk5r) % twopi
if gsto < 0.0:
gsto = gsto + twopi;
else:
gsto = _gstime(epoch + 2433281.5);
return (
no,
method,
ainv, ao, con41, con42, cosio,
cosio2,eccsq, omeosq, posq,
rp, rteosq,sinio , gsto,
)
"""
/*-----------------------------------------------------------------------------
*
* procedure sgp4init
*
* this procedure initializes variables for sgp4.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* opsmode - mode of operation afspc or improved 'a', 'i'
* whichconst - which set of constants to use 72, 84
* satn - satellite number
* bstar - sgp4 type drag coefficient kg/m2er
* ecco - eccentricity
* epoch - epoch time in days from jan 0, 1950. 0 hr
* argpo - argument of perigee (output if ds)
* inclo - inclination
* mo - mean anomaly (output if ds)
* no - mean motion
* nodeo - right ascension of ascending node
*
* outputs :
* satrec - common values for subsequent calls
* return code - non-zero on error.
* 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er
* 2 - mean motion less than 0.0
* 3 - pert elements, ecc < 0.0 or ecc > 1.0
* 4 - semi-latus rectum < 0.0
* 5 - epoch elements are sub-orbital
* 6 - satellite has decayed
*
* locals :
* cnodm , snodm , cosim , sinim , cosomm , sinomm
* cc1sq , cc2 , cc3
* coef , coef1
* cosio4 -
* day -
* dndt -
* em - eccentricity
* emsq - eccentricity squared
* eeta -
* etasq -
* gam -
* argpm - argument of perigee
* nodem -
* inclm - inclination
* mm - mean anomaly
* nm - mean motion
* perige - perigee
* pinvsq -
* psisq -
* qzms24 -
* rtemsq -
* s1, s2, s3, s4, s5, s6, s7 -
* sfour -
* ss1, ss2, ss3, ss4, ss5, ss6, ss7 -
* sz1, sz2, sz3
* sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 -
* tc -
* temp -
* temp1, temp2, temp3 -
* tsi -
* xpidot -
* xhdot1 -
* z1, z2, z3 -
* z11, z12, z13, z21, z22, z23, z31, z32, z33 -
*
* coupling :
* getgravconst-
* initl -
* dscom -
* dpper -
* dsinit -
* sgp4 -
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def sgp4init(
whichconst, opsmode, satn, epoch,
xbstar, xndot, xnddot, xecco, xargpo,
xinclo, xmo, xno_kozai,
xnodeo, satrec,
):
"""
/* ------------------------ initialization --------------------- */
// sgp4fix divisor for divide by zero check on inclination
// the old check used 1.0 + cos(pi-1.0e-9), but then compared it to
// 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency
"""
temp4 = 1.5e-12;
# ----------- set all near earth variables to zero ------------
satrec.isimp = 0; satrec.method = 'n'; satrec.aycof = 0.0;
satrec.con41 = 0.0; satrec.cc1 = 0.0; satrec.cc4 = 0.0;
satrec.cc5 = 0.0; satrec.d2 = 0.0; satrec.d3 = 0.0;
satrec.d4 = 0.0; satrec.delmo = 0.0; satrec.eta = 0.0;
satrec.argpdot = 0.0; satrec.omgcof = 0.0; satrec.sinmao = 0.0;
satrec.t = 0.0; satrec.t2cof = 0.0; satrec.t3cof = 0.0;
satrec.t4cof = 0.0; satrec.t5cof = 0.0; satrec.x1mth2 = 0.0;
satrec.x7thm1 = 0.0; satrec.mdot = 0.0; satrec.nodedot = 0.0;
satrec.xlcof = 0.0; satrec.xmcof = 0.0; satrec.nodecf = 0.0;
# ----------- set all deep space variables to zero ------------
satrec.irez = 0; satrec.d2201 = 0.0; satrec.d2211 = 0.0;
satrec.d3210 = 0.0; satrec.d3222 = 0.0; satrec.d4410 = 0.0;
satrec.d4422 = 0.0; satrec.d5220 = 0.0; satrec.d5232 = 0.0;
satrec.d5421 = 0.0; satrec.d5433 = 0.0; satrec.dedt = 0.0;
satrec.del1 = 0.0; satrec.del2 = 0.0; satrec.del3 = 0.0;
satrec.didt = 0.0; satrec.dmdt = 0.0; satrec.dnodt = 0.0;
satrec.domdt = 0.0; satrec.e3 = 0.0; satrec.ee2 = 0.0;
satrec.peo = 0.0; satrec.pgho = 0.0; satrec.pho = 0.0;
satrec.pinco = 0.0; satrec.plo = 0.0; satrec.se2 = 0.0;
satrec.se3 = 0.0; satrec.sgh2 = 0.0; satrec.sgh3 = 0.0;
satrec.sgh4 = 0.0; satrec.sh2 = 0.0; satrec.sh3 = 0.0;
satrec.si2 = 0.0; satrec.si3 = 0.0; satrec.sl2 = 0.0;
satrec.sl3 = 0.0; satrec.sl4 = 0.0; satrec.gsto = 0.0;
satrec.xfact = 0.0; satrec.xgh2 = 0.0; satrec.xgh3 = 0.0;
satrec.xgh4 = 0.0; satrec.xh2 = 0.0; satrec.xh3 = 0.0;
satrec.xi2 = 0.0; satrec.xi3 = 0.0; satrec.xl2 = 0.0;
satrec.xl3 = 0.0; satrec.xl4 = 0.0; satrec.xlamo = 0.0;
satrec.zmol = 0.0; satrec.zmos = 0.0; satrec.atime = 0.0;
satrec.xli = 0.0; satrec.xni = 0.0;
# ------------------------ earth constants -----------------------
# sgp4fix identify constants and allow alternate values
# this is now the only call for the constants
(satrec.tumin, satrec.mu, satrec.radiusearthkm, satrec.xke,
satrec.j2, satrec.j3, satrec.j4, satrec.j3oj2) = whichconst;
# -------------------------------------------------------------------------
# The SGP4 library has changed `satn` from an integer to a string.
# But to avoid breaking our API contract with existing Python code,
# we are still willing to accept an integer.
if isinstance(satn, int):
satn = to_alpha5(satn)
satrec.error = 0;
satrec.operationmode = opsmode;
satrec.satnum_str = satn;
satrec.classification = 'U' # so attribute is not missing in Python
"""
// sgp4fix - note the following variables are also passed directly via satrec.
// it is possible to streamline the sgp4init call by deleting the "x"
// variables, but the user would need to set the satrec.* values first. we
// include the additional assignments in case twoline2rv is not used.
"""
satrec.bstar = xbstar;
# sgp4fix allow additional parameters in the struct
satrec.ndot = xndot;
satrec.nddot = xnddot;
satrec.ecco = xecco;
satrec.argpo = xargpo;
satrec.inclo = xinclo;
satrec.mo = xmo;
# sgp4fix rename variables to clarify which mean motion is intended
satrec.no_kozai= xno_kozai;
satrec.nodeo = xnodeo;
# single averaged mean elements
satrec.am = 0.0
satrec.em = 0.0
satrec.im = 0.0
satrec.Om = 0.0
satrec.mm = 0.0
satrec.nm = 0.0
# ------------------------ earth constants ----------------------- */
# sgp4fix identify constants and allow alternate values no longer needed
# getgravconst( whichconst, tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 );
ss = 78.0 / satrec.radiusearthkm + 1.0;
# sgp4fix use multiply for speed instead of pow
qzms2ttemp = (120.0 - 78.0) / satrec.radiusearthkm;
qzms2t = qzms2ttemp * qzms2ttemp * qzms2ttemp * qzms2ttemp;
x2o3 = 2.0 / 3.0;
satrec.init = 'y';
satrec.t = 0.0;
# sgp4fix remove satn as it is not needed in initl
(
satrec.no_unkozai,
method,
ainv, ao, satrec.con41, con42, cosio,
cosio2,eccsq, omeosq, posq,
rp, rteosq,sinio , satrec.gsto,
) = _initl(
satrec.xke, satrec.j2, satrec.ecco, epoch, satrec.inclo, satrec.no_kozai, satrec.method,
satrec.operationmode
);
satrec.a = pow( satrec.no_unkozai*satrec.tumin , (-2.0/3.0) );
satrec.alta = satrec.a*(1.0 + satrec.ecco) - 1.0;
satrec.altp = satrec.a*(1.0 - satrec.ecco) - 1.0;
"""
// sgp4fix remove this check as it is unnecessary
// the mrt check in sgp4 handles decaying satellite cases even if the starting
// condition is below the surface of te earth
// if (rp < 1.0)
// {
// printf("# *** satn%d epoch elts sub-orbital ***\n", satn);
// satrec.error = 5;
// }
"""
if omeosq >= 0.0 or satrec.no_unkozai >= 0.0:
satrec.isimp = 0;
if rp < 220.0 / satrec.radiusearthkm + 1.0:
satrec.isimp = 1;
sfour = ss;
qzms24 = qzms2t;
perige = (rp - 1.0) * satrec.radiusearthkm;
# - for perigees below 156 km, s and qoms2t are altered -
if perige < 156.0:
sfour = perige - 78.0;
if perige < 98.0:
sfour = 20.0;
# sgp4fix use multiply for speed instead of pow
qzms24temp = (120.0 - sfour) / satrec.radiusearthkm;
qzms24 = qzms24temp * qzms24temp * qzms24temp * qzms24temp;
sfour = sfour / satrec.radiusearthkm + 1.0;
pinvsq = 1.0 / posq;
tsi = 1.0 / (ao - sfour);
satrec.eta = ao * satrec.ecco * tsi;
etasq = satrec.eta * satrec.eta;
eeta = satrec.ecco * satrec.eta;
psisq = fabs(1.0 - etasq);
coef = qzms24 * pow(tsi, 4.0);
coef1 = coef / pow(psisq, 3.5);
cc2 = coef1 * satrec.no_unkozai * (ao * (1.0 + 1.5 * etasq + eeta *
(4.0 + etasq)) + 0.375 * satrec.j2 * tsi / psisq * satrec.con41 *
(8.0 + 3.0 * etasq * (8.0 + etasq)));
satrec.cc1 = satrec.bstar * cc2;
cc3 = 0.0;
if satrec.ecco > 1.0e-4:
cc3 = -2.0 * coef * tsi * satrec.j3oj2 * satrec.no_unkozai * sinio / satrec.ecco;
satrec.x1mth2 = 1.0 - cosio2;
satrec.cc4 = 2.0* satrec.no_unkozai * coef1 * ao * omeosq * \
(satrec.eta * (2.0 + 0.5 * etasq) + satrec.ecco *
(0.5 + 2.0 * etasq) - satrec.j2 * tsi / (ao * psisq) *
(-3.0 * satrec.con41 * (1.0 - 2.0 * eeta + etasq *
(1.5 - 0.5 * eeta)) + 0.75 * satrec.x1mth2 *
(2.0 * etasq - eeta * (1.0 + etasq)) * cos(2.0 * satrec.argpo)));
satrec.cc5 = 2.0 * coef1 * ao * omeosq * (1.0 + 2.75 *
(etasq + eeta) + eeta * etasq);
cosio4 = cosio2 * cosio2;
temp1 = 1.5 * satrec.j2 * pinvsq * satrec.no_unkozai;
temp2 = 0.5 * temp1 * satrec.j2 * pinvsq;
temp3 = -0.46875 * satrec.j4 * pinvsq * pinvsq * satrec.no_unkozai;
satrec.mdot = satrec.no_unkozai + 0.5 * temp1 * rteosq * satrec.con41 + 0.0625 * \
temp2 * rteosq * (13.0 - 78.0 * cosio2 + 137.0 * cosio4);
satrec.argpdot = (-0.5 * temp1 * con42 + 0.0625 * temp2 *
(7.0 - 114.0 * cosio2 + 395.0 * cosio4) +
temp3 * (3.0 - 36.0 * cosio2 + 49.0 * cosio4));
xhdot1 = -temp1 * cosio;
satrec.nodedot = xhdot1 + (0.5 * temp2 * (4.0 - 19.0 * cosio2) +
2.0 * temp3 * (3.0 - 7.0 * cosio2)) * cosio;
xpidot = satrec.argpdot+ satrec.nodedot;
satrec.omgcof = satrec.bstar * cc3 * cos(satrec.argpo);
satrec.xmcof = 0.0;
if satrec.ecco > 1.0e-4:
satrec.xmcof = -x2o3 * coef * satrec.bstar / eeta;
satrec.nodecf = 3.5 * omeosq * xhdot1 * satrec.cc1;
satrec.t2cof = 1.5 * satrec.cc1;
# sgp4fix for divide by zero with xinco = 180 deg
if fabs(cosio+1.0) > 1.5e-12:
satrec.xlcof = -0.25 * satrec.j3oj2 * sinio * (3.0 + 5.0 * cosio) / (1.0 + cosio);
else:
satrec.xlcof = -0.25 * satrec.j3oj2 * sinio * (3.0 + 5.0 * cosio) / temp4;
satrec.aycof = -0.5 * satrec.j3oj2 * sinio;
# sgp4fix use multiply for speed instead of pow
delmotemp = 1.0 + satrec.eta * cos(satrec.mo);
satrec.delmo = delmotemp * delmotemp * delmotemp;
satrec.sinmao = sin(satrec.mo);
satrec.x7thm1 = 7.0 * cosio2 - 1.0;
# --------------- deep space initialization -------------
if 2*pi / satrec.no_unkozai >= 225.0:
satrec.method = 'd';
satrec.isimp = 1;
tc = 0.0;
inclm = satrec.inclo;
(
snodm, cnodm, sinim, cosim, sinomm,
cosomm,day, satrec.e3, satrec.ee2, em,
emsq, gam, satrec.peo, satrec.pgho, satrec.pho,
satrec.pinco, satrec.plo, rtemsq, satrec.se2, satrec.se3,
satrec.sgh2, satrec.sgh3, satrec.sgh4, satrec.sh2, satrec.sh3,
satrec.si2, satrec.si3, satrec.sl2, satrec.sl3, satrec.sl4,
s1, s2, s3, s4, s5,
s6, s7, ss1, ss2, ss3,
ss4, ss5, ss6, ss7, sz1,
sz2, sz3, sz11, sz12, sz13,
sz21, sz22, sz23, sz31, sz32,
sz33, satrec.xgh2, satrec.xgh3, satrec.xgh4, satrec.xh2,
satrec.xh3, satrec.xi2, satrec.xi3, satrec.xl2, satrec.xl3,
satrec.xl4, nm, z1, z2, z3,
z11, z12, z13, z21, z22,
z23, z31, z32, z33, satrec.zmol,
satrec.zmos
) = _dscom(
epoch, satrec.ecco, satrec.argpo, tc, satrec.inclo, satrec.nodeo,
satrec.no_unkozai,
satrec.e3, satrec.ee2,
satrec.peo, satrec.pgho, satrec.pho, satrec.pinco,
satrec.plo, satrec.se2, satrec.se3,
satrec.sgh2, satrec.sgh3, satrec.sgh4,
satrec.sh2, satrec.sh3, satrec.si2, satrec.si3,
satrec.sl2, satrec.sl3, satrec.sl4,
satrec.xgh2, satrec.xgh3, satrec.xgh4, satrec.xh2,
satrec.xh3, satrec.xi2, satrec.xi3, satrec.xl2,
satrec.xl3, satrec.xl4,
satrec.zmol, satrec.zmos
);
(satrec.ecco, satrec.inclo, satrec.nodeo, satrec.argpo, satrec.mo
) = _dpper(
satrec, inclm, satrec.init,
satrec.ecco, satrec.inclo, satrec.nodeo, satrec.argpo, satrec.mo,
satrec.operationmode
);
argpm = 0.0;
nodem = 0.0;
mm = 0.0;
(
em, argpm, inclm, mm,
nm, nodem,
satrec.irez, satrec.atime,
satrec.d2201, satrec.d2211, satrec.d3210, satrec.d3222,
satrec.d4410, satrec.d4422, satrec.d5220, satrec.d5232,
satrec.d5421, satrec.d5433, satrec.dedt, satrec.didt,
satrec.dmdt, dndt, satrec.dnodt, satrec.domdt,
satrec.del1, satrec.del2, satrec.del3, satrec.xfact,
satrec.xlamo, satrec.xli, satrec.xni
) = _dsinit(
satrec.xke,
cosim, emsq, satrec.argpo, s1, s2, s3, s4, s5, sinim, ss1, ss2, ss3, ss4,
ss5, sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33, satrec.t, tc,
satrec.gsto, satrec.mo, satrec.mdot, satrec.no_unkozai, satrec.nodeo,
satrec.nodedot, xpidot, z1, z3, z11, z13, z21, z23, z31, z33,
satrec.ecco, eccsq, em, argpm, inclm, mm, nm, nodem,
satrec.irez, satrec.atime,
satrec.d2201, satrec.d2211, satrec.d3210, satrec.d3222 ,
satrec.d4410, satrec.d4422, satrec.d5220, satrec.d5232,
satrec.d5421, satrec.d5433, satrec.dedt, satrec.didt,
satrec.dmdt, satrec.dnodt, satrec.domdt,
satrec.del1, satrec.del2, satrec.del3, satrec.xfact,
satrec.xlamo, satrec.xli, satrec.xni
);
#----------- set variables if not deep space -----------
if satrec.isimp != 1:
cc1sq = satrec.cc1 * satrec.cc1;
satrec.d2 = 4.0 * ao * tsi * cc1sq;
temp = satrec.d2 * tsi * satrec.cc1 / 3.0;
satrec.d3 = (17.0 * ao + sfour) * temp;
satrec.d4 = 0.5 * temp * ao * tsi * (221.0 * ao + 31.0 * sfour) * \
satrec.cc1;
satrec.t3cof = satrec.d2 + 2.0 * cc1sq;
satrec.t4cof = 0.25 * (3.0 * satrec.d3 + satrec.cc1 *
(12.0 * satrec.d2 + 10.0 * cc1sq));
satrec.t5cof = 0.2 * (3.0 * satrec.d4 +
12.0 * satrec.cc1 * satrec.d3 +
6.0 * satrec.d2 * satrec.d2 +
15.0 * cc1sq * (2.0 * satrec.d2 + cc1sq));
"""
/* finally propogate to zero epoch to initialize all others. */
// sgp4fix take out check to let satellites process until they are actually below earth surface
// if(satrec.error == 0)
"""
sgp4(satrec, 0.0, whichconst);
satrec.init = 'n';
# sgp4fix return boolean. satrec.error contains any error codes
return true;
"""
/*-----------------------------------------------------------------------------
*
* procedure sgp4
*
* this procedure is the sgp4 prediction model from space command. this is an
* updated and combined version of sgp4 and sdp4, which were originally
* published separately in spacetrack report #3. this version follows the
* methodology from the aiaa paper (2006) describing the history and
* development of the code.
*
* author : david vallado 719-573-2600 28 jun 2005
*
* inputs :
* satrec - initialised structure from sgp4init() call.
* tsince - time eince epoch (minutes)
*
* outputs :
* r - position vector km
* v - velocity km/sec
* return code - non-zero on error.
* 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er
* 2 - mean motion less than 0.0
* 3 - pert elements, ecc < 0.0 or ecc > 1.0
* 4 - semi-latus rectum < 0.0
* 5 - epoch elements are sub-orbital
* 6 - satellite has decayed
*
* locals :
* am -
* axnl, aynl -
* betal -
* cosim , sinim , cosomm , sinomm , cnod , snod , cos2u ,
* sin2u , coseo1 , sineo1 , cosi , sini , cosip , sinip ,
* cosisq , cossu , sinsu , cosu , sinu
* delm -
* delomg -
* dndt -
* eccm -
* emsq -
* ecose -
* el2 -
* eo1 -
* eccp -
* esine -
* argpm -
* argpp -
* omgadf -
* pl -
* r -
* rtemsq -
* rdotl -
* rl -
* rvdot -
* rvdotl -
* su -
* t2 , t3 , t4 , tc
* tem5, temp , temp1 , temp2 , tempa , tempe , templ
* u , ux , uy , uz , vx , vy , vz
* inclm - inclination
* mm - mean anomaly
* nm - mean motion
* nodem - right asc of ascending node
* xinc -
* xincp -
* xl -
* xlm -
* mp -
* xmdf -
* xmx -
* xmy -
* nodedf -
* xnode -
* nodep -
* np -
*
* coupling :
* getgravconst-
* dpper
* dpspace
*
* references :
* hoots, roehrich, norad spacetrack report #3 1980
* hoots, norad spacetrack report #6 1986
* hoots, schumacher and glover 2004
* vallado, crawford, hujsak, kelso 2006
----------------------------------------------------------------------------*/
"""
def sgp4(satrec, tsince, whichconst=None):
mrt = 0.0
"""
/* ------------------ set mathematical constants --------------- */
// sgp4fix divisor for divide by zero check on inclination
// the old check used 1.0 + cos(pi-1.0e-9), but then compared it to
// 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency
"""
temp4 = 1.5e-12;
twopi = 2.0 * pi;
x2o3 = 2.0 / 3.0;
# sgp4fix identify constants and allow alternate values
# tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2 = whichconst
vkmpersec = satrec.radiusearthkm * satrec.xke/60.0;
# --------------------- clear sgp4 error flag -----------------
satrec.t = tsince;
satrec.error = 0;
satrec.error_message = None
# ------- update for secular gravity and atmospheric drag -----
xmdf = satrec.mo + satrec.mdot * satrec.t;
argpdf = satrec.argpo + satrec.argpdot * satrec.t;
nodedf = satrec.nodeo + satrec.nodedot * satrec.t;
argpm = argpdf;
mm = xmdf;
t2 = satrec.t * satrec.t;
nodem = nodedf + satrec.nodecf * t2;
tempa = 1.0 - satrec.cc1 * satrec.t;
tempe = satrec.bstar * satrec.cc4 * satrec.t;
templ = satrec.t2cof * t2;
if satrec.isimp != 1:
delomg = satrec.omgcof * satrec.t;
# sgp4fix use mutliply for speed instead of pow
delmtemp = 1.0 + satrec.eta * cos(xmdf);
delm = satrec.xmcof * \
(delmtemp * delmtemp * delmtemp -
satrec.delmo);
temp = delomg + delm;
mm = xmdf + temp;
argpm = argpdf - temp;
t3 = t2 * satrec.t;
t4 = t3 * satrec.t;
tempa = tempa - satrec.d2 * t2 - satrec.d3 * t3 - \
satrec.d4 * t4;
tempe = tempe + satrec.bstar * satrec.cc5 * (sin(mm) -
satrec.sinmao);
templ = templ + satrec.t3cof * t3 + t4 * (satrec.t4cof +
satrec.t * satrec.t5cof);
nm = satrec.no_unkozai;
em = satrec.ecco;
inclm = satrec.inclo;
if satrec.method == 'd':
tc = satrec.t;
(
atime, em, argpm, inclm, xli,
mm, xni, nodem, dndt, nm,
) = _dspace(
satrec.irez,
satrec.d2201, satrec.d2211, satrec.d3210,
satrec.d3222, satrec.d4410, satrec.d4422,
satrec.d5220, satrec.d5232, satrec.d5421,
satrec.d5433, satrec.dedt, satrec.del1,
satrec.del2, satrec.del3, satrec.didt,
satrec.dmdt, satrec.dnodt, satrec.domdt,
satrec.argpo, satrec.argpdot, satrec.t, tc,
satrec.gsto, satrec.xfact, satrec.xlamo,
satrec.no_unkozai, satrec.atime,
em, argpm, inclm, satrec.xli, mm, satrec.xni,
nodem, nm
);
if nm <= 0.0:
satrec.error_message = ('mean motion {0:f} is less than zero'
.format(nm))
satrec.error = 2;
# sgp4fix add return
return false, false;
am = pow((satrec.xke / nm),x2o3) * tempa * tempa;
nm = satrec.xke / pow(am, 1.5);
em = em - tempe;
# fix tolerance for error recognition
# sgp4fix am is fixed from the previous nm check
if em >= 1.0 or em < -0.001: # || (am < 0.95)
satrec.error_message = ('mean eccentricity {0:f} not within'
' range 0.0 <= e < 1.0'.format(em))
satrec.error = 1;
# sgp4fix to return if there is an error in eccentricity
return false, false;
# sgp4fix fix tolerance to avoid a divide by zero
if em < 1.0e-6:
em = 1.0e-6;
mm = mm + satrec.no_unkozai * templ;
xlm = mm + argpm + nodem;
emsq = em * em;
temp = 1.0 - emsq;
nodem = nodem % twopi if nodem >= 0.0 else -(-nodem % twopi)
argpm = argpm % twopi
xlm = xlm % twopi
mm = (xlm - argpm - nodem) % twopi
# sgp4fix recover singly averaged mean elements
satrec.am = am;
satrec.em = em;
satrec.im = inclm;
satrec.Om = nodem;
satrec.om = argpm;
satrec.mm = mm;
satrec.nm = nm;
# ----------------- compute extra mean quantities -------------
sinim = sin(inclm);
cosim = cos(inclm);
# -------------------- add lunar-solar periodics --------------
ep = em;
xincp = inclm;
argpp = argpm;
nodep = nodem;
mp = mm;
sinip = sinim;
cosip = cosim;
if satrec.method == 'd':
ep, xincp, nodep, argpp, mp = _dpper(
satrec, satrec.inclo,
'n', ep, xincp, nodep, argpp, mp, satrec.operationmode
);
if xincp < 0.0:
xincp = -xincp;
nodep = nodep + pi;
argpp = argpp - pi;
if ep < 0.0 or ep > 1.0:
satrec.error_message = ('perturbed eccentricity {0:f} not within'
' range 0.0 <= e <= 1.0'.format(ep))
satrec.error = 3;
# sgp4fix add return
return false, false;
# -------------------- long period periodics ------------------
if satrec.method == 'd':
sinip = sin(xincp);
cosip = cos(xincp);
satrec.aycof = -0.5*satrec.j3oj2*sinip;
# sgp4fix for divide by zero for xincp = 180 deg
if fabs(cosip+1.0) > 1.5e-12:
satrec.xlcof = -0.25 * satrec.j3oj2 * sinip * (3.0 + 5.0 * cosip) / (1.0 + cosip);
else:
satrec.xlcof = -0.25 * satrec.j3oj2 * sinip * (3.0 + 5.0 * cosip) / temp4;
axnl = ep * cos(argpp);
temp = 1.0 / (am * (1.0 - ep * ep));
aynl = ep* sin(argpp) + temp * satrec.aycof;
xl = mp + argpp + nodep + temp * satrec.xlcof * axnl;
# --------------------- solve kepler's equation ---------------
u = (xl - nodep) % twopi
eo1 = u;
tem5 = 9999.9;
ktr = 1;
# sgp4fix for kepler iteration
# the following iteration needs better limits on corrections
while fabs(tem5) >= 1.0e-12 and ktr <= 10:
sineo1 = sin(eo1);
coseo1 = cos(eo1);
tem5 = 1.0 - coseo1 * axnl - sineo1 * aynl;
tem5 = (u - aynl * coseo1 + axnl * sineo1 - eo1) / tem5;
if fabs(tem5) >= 0.95:
tem5 = 0.95 if tem5 > 0.0 else -0.95;
eo1 = eo1 + tem5;
ktr = ktr + 1;
# ------------- short period preliminary quantities -----------
ecose = axnl*coseo1 + aynl*sineo1;
esine = axnl*sineo1 - aynl*coseo1;
el2 = axnl*axnl + aynl*aynl;
pl = am*(1.0-el2);
if pl < 0.0:
satrec.error_message = ('semilatus rectum {0:f} is less than zero'
.format(pl))
satrec.error = 4;
# sgp4fix add return
return false, false;
else:
rl = am * (1.0 - ecose);
rdotl = sqrt(am) * esine/rl;
rvdotl = sqrt(pl) / rl;
betal = sqrt(1.0 - el2);
temp = esine / (1.0 + betal);
sinu = am / rl * (sineo1 - aynl - axnl * temp);
cosu = am / rl * (coseo1 - axnl + aynl * temp);
su = atan2(sinu, cosu);
sin2u = (cosu + cosu) * sinu;
cos2u = 1.0 - 2.0 * sinu * sinu;
temp = 1.0 / pl;
temp1 = 0.5 * satrec.j2 * temp;
temp2 = temp1 * temp;
# -------------- update for short period periodics ------------
if satrec.method == 'd':
cosisq = cosip * cosip;
satrec.con41 = 3.0*cosisq - 1.0;
satrec.x1mth2 = 1.0 - cosisq;
satrec.x7thm1 = 7.0*cosisq - 1.0;
mrt = rl * (1.0 - 1.5 * temp2 * betal * satrec.con41) + \
0.5 * temp1 * satrec.x1mth2 * cos2u;
su = su - 0.25 * temp2 * satrec.x7thm1 * sin2u;
xnode = nodep + 1.5 * temp2 * cosip * sin2u;
xinc = xincp + 1.5 * temp2 * cosip * sinip * cos2u;
mvt = rdotl - nm * temp1 * satrec.x1mth2 * sin2u / satrec.xke;
rvdot = rvdotl + nm * temp1 * (satrec.x1mth2 * cos2u +
1.5 * satrec.con41) / satrec.xke;
# --------------------- orientation vectors -------------------
sinsu = sin(su);
cossu = cos(su);
snod = sin(xnode);
cnod = cos(xnode);
sini = sin(xinc);
cosi = cos(xinc);
xmx = -snod * cosi;
xmy = cnod * cosi;
ux = xmx * sinsu + cnod * cossu;
uy = xmy * sinsu + snod * cossu;
uz = sini * sinsu;
vx = xmx * cossu - cnod * sinsu;
vy = xmy * cossu - snod * sinsu;
vz = sini * cossu;
# --------- position and velocity (in km and km/sec) ----------
_mr = mrt * satrec.radiusearthkm
r = (_mr * ux, _mr * uy, _mr * uz)
v = ((mvt * ux + rvdot * vx) * vkmpersec,
(mvt * uy + rvdot * vy) * vkmpersec,
(mvt * uz + rvdot * vz) * vkmpersec)
# sgp4fix for decaying satellites
if mrt < 1.0:
satrec.error_message = ('mrt {0:f} is less than 1.0 indicating'
' the satellite has decayed'.format(mrt))
satrec.error = 6;
return r, v;
"""
/* -----------------------------------------------------------------------------
*
* function gstime
*
* this function finds the greenwich sidereal time.
*
* author : david vallado 719-573-2600 1 mar 2001
*
* inputs description range / units
* jdut1 - julian date in ut1 days from 4713 bc
*
* outputs :
* gstime - greenwich sidereal time 0 to 2pi rad
*
* locals :
* temp - temporary variable for doubles rad
* tut1 - julian centuries from the
* jan 1, 2000 12 h epoch (ut1)
*
* coupling :
* none
*
* references :
* vallado 2004, 191, eq 3-45
* --------------------------------------------------------------------------- */
"""
def gstime(jdut1):
tut1 = (jdut1 - 2451545.0) / 36525.0;
temp = -6.2e-6* tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + \
(876600.0*3600 + 8640184.812866) * tut1 + 67310.54841; # sec
temp = (temp * deg2rad / 240.0) % twopi # 360/86400 = 1/240, to deg, to rad
# ------------------------ check quadrants ---------------------
if temp < 0.0:
temp += twopi;
return temp;
# The routine was originally marked private, so make it available under
# the old name for compatibility:
_gstime = gstime
"""
/* -----------------------------------------------------------------------------
*
* function getgravconst
*
* this function gets constants for the propagator. note that mu is identified to
* facilitiate comparisons with newer models. the common useage is wgs72.
*
* author : david vallado 719-573-2600 21 jul 2006
*
* inputs :
* whichconst - which set of constants to use wgs72old, wgs72, wgs84
*
* outputs :
* tumin - minutes in one time unit
* mu - earth gravitational parameter
* radiusearthkm - radius of the earth in km
* xke - reciprocal of tumin
* j2, j3, j4 - un-normalized zonal harmonic values
* j3oj2 - j3 divided by j2
*
* locals :
*
* coupling :
* none
*
* references :
* norad spacetrack report #3
* vallado, crawford, hujsak, kelso 2006
--------------------------------------------------------------------------- */
"""
def getgravconst(whichconst):
if whichconst == 'wgs72old':
mu = 398600.79964; # in km3 / s2
radiusearthkm = 6378.135; # km
xke = 0.0743669161;
tumin = 1.0 / xke;
j2 = 0.001082616;
j3 = -0.00000253881;
j4 = -0.00000165597;
j3oj2 = j3 / j2;
# ------------ wgs-72 constants ------------
elif whichconst == 'wgs72':
mu = 398600.8; # in km3 / s2
radiusearthkm = 6378.135; # km
xke = 60.0 / sqrt(radiusearthkm*radiusearthkm*radiusearthkm/mu);
tumin = 1.0 / xke;
j2 = 0.001082616;
j3 = -0.00000253881;
j4 = -0.00000165597;
j3oj2 = j3 / j2;
elif whichconst == 'wgs84':
# ------------ wgs-84 constants ------------
mu = 398600.5; # in km3 / s2
radiusearthkm = 6378.137; # km
xke = 60.0 / sqrt(radiusearthkm*radiusearthkm*radiusearthkm/mu);
tumin = 1.0 / xke;
j2 = 0.00108262998905;
j3 = -0.00000253215306;
j4 = -0.00000161098761;
j3oj2 = j3 / j2;
return tumin, mu, radiusearthkm, xke, j2, j3, j4, j3oj2
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,809
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/sgp4/tests.py
|
"""Test suite for SGP4."""
try:
from unittest2 import TestCase, main
except:
from unittest import TestCase, main
import datetime as dt
import re
import os
import sys
from doctest import DocTestSuite, ELLIPSIS
from math import pi, isnan
from pkgutil import get_data
try:
from io import StringIO
except ImportError:
from StringIO import StringIO
import numpy as np
from sgp4.api import WGS72OLD, WGS72, WGS84, Satrec, jday
from sgp4.earth_gravity import wgs72
from sgp4.ext import invjday, newtonnu, rv2coe
from sgp4.functions import days2mdhms, _day_of_year_to_month_day
from sgp4.propagation import sgp4, sgp4init
from sgp4 import api, conveniences, io, omm
from sgp4.exporter import export_omm, export_tle
import sgp4.model as model
_testcase = TestCase('setUp')
_testcase.maxDiff = 9999
assertEqual = _testcase.assertEqual
assertAlmostEqual = _testcase.assertAlmostEqual
assertRaises = _testcase.assertRaises
assertRaisesRegex = getattr(_testcase, 'assertRaisesRegex',
_testcase.assertRaisesRegexp)
error = 2e-7
rad = 180.0 / pi
LINE1 = '1 00005U 58002B 00179.78495062 .00000023 00000-0 28098-4 0 4753'
LINE2 = '2 00005 34.2682 348.7242 1859667 331.7664 19.3264 10.82419157413667'
BAD2 = '2 00007 34.2682 348.7242 1859667 331.7664 19.3264 10.82419157413669'
VANGUARD_ATTRS = {
# Identity
'satnum': 5,
'satnum_str': '00005',
'classification': 'U',
'operationmode': 'i',
# Time
'epochyr': 0,
'epochdays': 179.78495062,
'jdsatepoch': 2451722.5,
'jdsatepochF': 0.78495062,
# Orbit
'bstar': 2.8098e-05,
'ndot': 6.96919666594958e-13,
'nddot': 0.0,
'ecco': 0.1859667,
'argpo': 5.790416027488515,
'inclo': 0.5980929187319208,
'mo': 0.3373093125574321,
'no_kozai': 0.04722944544077857,
'nodeo': 6.08638547138321,
}
VANGUARD_EPOCH = 18441.78495062
# Handle deprecated assertRaisesRegexp, but allow its use Python 2.6 and 2.7
if sys.version_info[:2] == (2, 7) or sys.version_info[:2] == (2, 6):
TestCase.assertRaisesRegex = TestCase.assertRaisesRegexp
# ------------------------------------------------------------------------
# Core Attributes
#
def test_satrec_built_with_twoline2rv():
sat = Satrec.twoline2rv(LINE1, LINE2)
verify_vanguard_1(sat)
def test_legacy_built_with_twoline2rv():
sat = io.twoline2rv(LINE1, LINE2, wgs72)
verify_vanguard_1(sat, legacy=True)
def test_satrec_initialized_with_sgp4init():
sat = Satrec()
sat.sgp4init(
WGS72,
'i',
VANGUARD_ATTRS['satnum'],
VANGUARD_EPOCH,
*sgp4init_args(VANGUARD_ATTRS)
)
verify_vanguard_1(sat)
def test_satrec_initialized_with_sgp4init_in_afspc_mode():
sat = Satrec()
sat.sgp4init(
WGS72,
'a',
VANGUARD_ATTRS['satnum'],
VANGUARD_EPOCH,
*sgp4init_args(VANGUARD_ATTRS)
)
assertEqual(sat.operationmode, 'a')
def test_legacy_initialized_with_sgp4init():
sat = model.Satellite()
sgp4init(
wgs72, 'i', VANGUARD_ATTRS['satnum'], VANGUARD_EPOCH,
*sgp4init_args(VANGUARD_ATTRS) + (sat,)
)
verify_vanguard_1(sat, legacy=True)
# ------------------------------------------------------------------------
# Test array API
def test_whether_array_logic_writes_nan_values_to_correct_row():
# https://github.com/brandon-rhodes/python-sgp4/issues/87
l1 = "1 44160U 19006AX 20162.79712247 +.00816806 +19088-3 +34711-2 0 9997"
l2 = "2 44160 095.2472 272.0808 0216413 032.6694 328.7739 15.58006382062511"
sat = Satrec.twoline2rv(l1, l2)
jd0 = np.array([2459054.5, 2459055.5])
jd1 = np.array([0.79712247, 0.79712247])
e, r, v = sat.sgp4_array(jd0, jd1)
assert list(e) == [6, 1]
assert np.isnan(r).tolist() == [[False, False, False], [True, True, True]]
assert np.isnan(v).tolist() == [[False, False, False], [True, True, True]]
# ------------------------------------------------------------------------
# Other Officially Supported Routines
#
def test_days2mdhms():
# See https://github.com/brandon-rhodes/python-sgp4/issues/64
tup = days2mdhms(2020, 133.35625)
assertEqual(tup, (5, 12, 8, 33, 0.0))
def test_jday2():
jd, fr = jday(2019, 10, 9, 16, 57, 15)
assertEqual(jd, 2458765.5)
assertAlmostEqual(fr, 0.7064236111111111)
def test_jday_datetime():
# define local time
# UTC equivalent: 2011-11-03 20:05:23+00:00
class UTC_plus_4(dt.tzinfo):
'UTC'
offset = dt.timedelta(hours=4)
def utcoffset(self, datetime):
return self.offset
def tzname(self, datetime):
return 'UTC plus 4'
def dst(self, datetime):
return self.offset
datetime_local = dt.datetime(2011, 11, 4, 0, 5, 23, 0, UTC_plus_4())
jd, fr = conveniences.jday_datetime(datetime_local)
# jd of this date is 2455868.5 + 0.8370717592592593
assertEqual(jd, 2455868.5)
assertAlmostEqual(fr, 0.8370717592592593)
def test_sat_epoch_datetime():
sat = Satrec.twoline2rv(LINE1, LINE2)
datetime = conveniences.sat_epoch_datetime(sat)
zone = conveniences.UTC
assertEqual(datetime, dt.datetime(2000, 6, 27, 18, 50, 19, 733568, zone))
def test_good_tle_checksum():
for line in LINE1, LINE2:
checksum = int(line[-1])
assertEqual(io.compute_checksum(line), checksum)
assertEqual(io.fix_checksum(line[:68]), line)
io.verify_checksum(line)
def test_bad_tle_checksum():
checksum = LINE1[-1]
assertEqual(checksum, '3')
bad = LINE1[:68] + '7'
assertRaises(ValueError, io.verify_checksum, bad)
assertEqual(io.fix_checksum(bad), LINE1)
def test_tle_export():
"""Check `export_tle()` round-trip using all the TLEs in the test file.
This iterates through the satellites in "SGP4-VER.TLE",
generates `Satrec` objects and exports the TLEs. These exported
TLEs are then compared to the original TLE, closing the loop (or
the round-trip).
"""
data = get_data(__name__, 'SGP4-VER.TLE')
tle_lines = iter(data.decode('ascii').splitlines())
# Skip these lines, known errors
# Resulting TLEs are equivalent (same values in the Satrec object), but they are not the same
# 25954: BSTAR = 0 results in a negative exp, not positive
# 29141: BSTAR = 0.13519 results in a negative exp, not positive
# 33333: Checksum error as expected on both lines
# 33334: Checksum error as expected on line 1
# 33335: Checksum error as expected on line 1
expected_errs_line1 = set([25954, 29141, 33333, 33334, 33335])
expected_errs_line2 = set([33333, 33335])
# Non-standard: omits the ephemeris type integer.
expected_errs_line1.add(11801)
for line1 in tle_lines:
if not line1.startswith('1'):
continue
line2 = next(tle_lines)
# trim lines to normal TLE string size
line1 = line1[:69]
line2 = line2[:69]
satrec = Satrec.twoline2rv(line1, line2)
satrec_old = io.twoline2rv(line1, line2, wgs72)
# Generate TLE from satrec
actual_line1, actual_line2 = export_tle(satrec)
actual_line1_old, actual_line2_old = export_tle(satrec_old)
if satrec.satnum not in expected_errs_line1:
assertEqual(actual_line1, line1)
assertEqual(actual_line1_old, line1)
if satrec.satnum not in expected_errs_line2:
assertEqual(actual_line2, line2)
assertEqual(actual_line2_old, line2)
def test_export_tle_raises_error_for_out_of_range_angles():
# See https://github.com/brandon-rhodes/python-sgp4/issues/70
for angle in 'inclo', 'nodeo', 'argpo', 'mo':
sat = Satrec()
wrong_vanguard_attrs = VANGUARD_ATTRS.copy()
wrong_vanguard_attrs[angle] = -1.0
sat.sgp4init(
WGS84, 'i', wrong_vanguard_attrs['satnum'], VANGUARD_EPOCH,
*sgp4init_args(wrong_vanguard_attrs)
)
assertRaises(ValueError, export_tle, sat)
def test_tle_import_export_round_trips():
for line1, line2 in [(
'1 44542U 19061A 21180.78220369 -.00000015 00000-0 -66561+1 0 9997',
'2 44542 54.7025 244.1098 0007981 318.8601 283.5781 1.86231125 12011',
)]:
sat = Satrec.twoline2rv(line1, line2)
outline1, outline2 = export_tle(sat)
assertEqual(line1, outline1)
assertEqual(line2, outline2)
def test_all_three_gravity_models_with_twoline2rv():
# The numbers below are those produced by Vallado's C++ code.
# (Why does the Python version not produce the same values to
# high accuracy, instead of agreeing to only 4 places?)
assert_wgs72old(Satrec.twoline2rv(LINE1, LINE2, WGS72OLD))
assert_wgs72(Satrec.twoline2rv(LINE1, LINE2, WGS72))
assert_wgs84(Satrec.twoline2rv(LINE1, LINE2, WGS84))
# Not specifying a gravity model should select WGS72.
assert_wgs72(Satrec.twoline2rv(LINE1, LINE2))
def test_all_three_gravity_models_with_sgp4init():
# Gravity models specified with sgp4init() should also change the
# positions generated.
sat = Satrec()
args = sgp4init_args(VANGUARD_ATTRS)
sat.sgp4init(WGS72OLD, 'i', VANGUARD_ATTRS['satnum'], VANGUARD_EPOCH, *args)
assert_wgs72old(sat)
sat.sgp4init(WGS72, 'i', VANGUARD_ATTRS['satnum'], VANGUARD_EPOCH, *args)
assert_wgs72(sat)
sat.sgp4init(WGS84, 'i', VANGUARD_ATTRS['satnum'], VANGUARD_EPOCH, *args)
assert_wgs84(sat)
GRAVITY_DIGITS = (
# Why don't Python and C agree more closely?
4 if not api.accelerated
# Otherwise, try 10 digits. Note that at least 6 digits past the
# decimal point are necessary to let the test distinguish between
# WSG72OLD and WGS72. See:
# https://github.com/conda-forge/sgp4-feedstock/pull/19
# https://github.com/brandon-rhodes/python-sgp4/issues/69
else 10
)
def assert_wgs72old(sat):
e, r, v = sat.sgp4_tsince(309.67110720001529)
assertAlmostEqual(r[0], -3754.251473242793, GRAVITY_DIGITS)
assertAlmostEqual(r[1], 7876.346815095482, GRAVITY_DIGITS)
assertAlmostEqual(r[2], 4719.220855042922, GRAVITY_DIGITS)
def assert_wgs72(sat):
e, r, v = sat.sgp4_tsince(309.67110720001529)
assertAlmostEqual(r[0], -3754.2514743216166, GRAVITY_DIGITS)
assertAlmostEqual(r[1], 7876.346817439062, GRAVITY_DIGITS)
assertAlmostEqual(r[2], 4719.220856478582, GRAVITY_DIGITS)
def assert_wgs84(sat):
e, r, v = sat.sgp4_tsince(309.67110720001529)
assertAlmostEqual(r[0], -3754.2437675772426, GRAVITY_DIGITS)
assertAlmostEqual(r[1], 7876.3549956188945, GRAVITY_DIGITS)
assertAlmostEqual(r[2], 4719.227897029576, GRAVITY_DIGITS)
# ------------------------------------------------------------------------
# Special Cases
#
def test_satnum_leading_spaces():
# https://github.com/brandon-rhodes/python-sgp4/issues/81
# https://github.com/brandon-rhodes/python-sgp4/issues/90
l1 = '1 4859U 21001A 21007.63955392 .00000000 00000+0 00000+0 0 9990'
l2 = '2 4859 000.0000 000.0000 0000000 000.0000 000.0000 01.00000000 09'
sat = Satrec.twoline2rv(l1, l2)
assertEqual(sat.satnum, 4859)
assertEqual(sat.classification, 'U')
assertEqual(sat.intldesg, '21001A')
def test_satnum_alpha5_encoding():
def make_sat(satnum_string):
return Satrec.twoline2rv(LINE1.replace('00005', satnum_string),
LINE2.replace('00005', satnum_string))
# Test cases from https://www.space-track.org/documentation#tle-alpha5
cases = [(100000, 'A0000'),
(148493, 'E8493'),
(182931, 'J2931'),
(234018, 'P4018'),
(301928, 'W1928'),
(339999, 'Z9999')]
for satnum, satnum_string in cases:
sat = make_sat(satnum_string)
assertEqual(sat.satnum, satnum)
assertEqual(sat.satnum_str, satnum_string)
args = sgp4init_args(VANGUARD_ATTRS)
for satnum, satnum_string in cases:
sat.sgp4init(WGS72, 'i', satnum, VANGUARD_EPOCH, *args)
assertEqual(sat.satnum, satnum)
def test_satnum_that_is_too_large():
sat = Satrec()
with assertRaisesRegex(ValueError, 'cannot exceed 339999'):
sat.sgp4init(
WGS72,
'i',
340000,
VANGUARD_EPOCH,
*sgp4init_args(VANGUARD_ATTRS)
)
def test_intldesg_with_6_characters():
sat = Satrec.twoline2rv(LINE1, LINE2)
assertEqual(sat.intldesg, '58002B')
def test_intldesg_with_7_characters():
sat = Satrec.twoline2rv(
'1 39444U 13066AE 20110.89708219 .00000236 00000-0'
' 35029-4 0 9992',
'2 39444 97.5597 114.3769 0059573 102.0933 258.6965 '
'14.82098949344697',
)
assertEqual(sat.intldesg, '13066AE')
def test_1990s_satrec_initialized_with_sgp4init():
sat = Satrec()
sat.sgp4init(
WGS72,
'i',
VANGUARD_ATTRS['satnum'],
VANGUARD_EPOCH - 365.0, # change year 2000 to 1999
*sgp4init_args(VANGUARD_ATTRS)
)
assertEqual(sat.epochyr, 99)
def test_setters():
sat = Satrec()
sat.classification = 'S'
assert sat.classification == 'S'
sat.intldesg = 'abcdefg'
assert sat.intldesg == 'abcdefg'
sat.ephtype = 23
assert sat.ephtype == 23
sat.elnum = 123
assert sat.elnum == 123
sat.revnum = 1234
assert sat.revnum == 1234
sat.satnum_str = 'abcde'
assert sat.satnum_str == 'abcde'
def test_hyperbolic_orbit():
# Exercise the newtonnu() code path with asinh() to see whether
# we can replace it with the one from Python's math module.
e0, m = newtonnu(1.0, 2.9) # parabolic
assertAlmostEqual(e0, 8.238092752965605, places=12)
assertAlmostEqual(m, 194.60069989482898, places=12)
e0, m = newtonnu(1.1, 2.7) # hyperbolic
assertAlmostEqual(e0, 4.262200676156417, places=12)
assertAlmostEqual(m, 34.76134082028372, places=12)
def test_correct_epochyr():
# Make sure that the non-standard four-digit epochyr I switched
# to in the Python version of SGP4 is reverted back to the
# official behavior when that code is used behind Satrec.
sat = Satrec.twoline2rv(LINE1, LINE2)
assertEqual(sat.epochyr, 0)
def test_legacy_epochyr():
# Apparently I saw fit to change the meaning of this attribute
# in the Python version of SGP4.
sat = io.twoline2rv(LINE1, LINE2, wgs72)
assertEqual(sat.epochyr, 2000)
def test_support_for_old_no_attribute():
s = io.twoline2rv(LINE1, LINE2, wgs72)
assert s.no == s.no_kozai
def test_months_and_days():
# Make sure our hand-written months-and-days routine is perfect.
month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day_of_year = 1
for month, length in enumerate(month_lengths, 1):
for day in range(1, length + 1):
tup = _day_of_year_to_month_day(day_of_year, False)
assertEqual((month, day), tup)
day_of_year += 1
month_lengths[1] = 29 # February, during a leap year
day_of_year = 1
for month, length in enumerate(month_lengths, 1):
for day in range(1, length + 1):
tup = _day_of_year_to_month_day(day_of_year, True)
assertEqual((month, day), tup)
day_of_year += 1
def test_december_32():
# ISS [Orbit 606], whose date is 2019 plus 366.82137887 days.
# The core SGP4 routines handled this fine, but my hamfisted
# attempt to provide a Python datetime for "convenience" ran
# into an overflow.
a = '1 25544U 98067A 19366.82137887 .00016717 00000-0 10270-3 0 9129'
b = '2 25544 51.6392 96.6358 0005156 88.7140 271.4601 15.49497216 6061'
correct_epoch = dt.datetime(2020, 1, 1, 19, 42, 47, 134368)
# Legacy API.
sat = io.twoline2rv(a, b, wgs72)
assertEqual(sat.epoch, correct_epoch)
correct_epoch = correct_epoch.replace(tzinfo=conveniences.UTC)
# Modern API.
sat = Satrec.twoline2rv(a, b)
assertEqual(conveniences.sat_epoch_datetime(sat), correct_epoch)
def test_non_ascii_first_line():
if sys.version_info < (3,):
return
with assertRaisesRegex(ValueError, re.escape("""your TLE lines are broken because they contain non-ASCII characters:
1 00005U 58002B 00179.78495062 .00000023\\xa0 00000-0 28098-4 0 4753
2 00005 34.2682 348.7242 1859667 331.7664 19.3264 10.82419157413667""")):
io.twoline2rv(LINE1.replace('23 ', '23\xa0'), LINE2, wgs72)
def test_non_ascii_second_line():
if sys.version_info < (3,):
return
with assertRaisesRegex(ValueError, re.escape("""your TLE lines are broken because they contain non-ASCII characters:
1 00005U 58002B 00179.78495062 .00000023 00000-0 28098-4 0 4753
2 00005 \\xa034.2682\\xa0348.7242 1859667 331.7664 19.3264 10.82419157413667\
""")):
io.twoline2rv(LINE1, LINE2.replace(' 34', '\xa034'), wgs72)
def test_bad_first_line():
with assertRaisesRegex(ValueError, re.escape("""TLE format error
The Two-Line Element (TLE) format was designed for punch cards, and so
is very strict about the position of every period, space, and digit.
Your line does not quite match. Here is the official format for line 1
with an N where each digit should go, followed by the line you provided:
1 NNNNNC NNNNNAAA NNNNN.NNNNNNNN +.NNNNNNNN +NNNNN-N +NNNNN-N N NNNNN
1 00005U 58002B 00179.78495062 .000000234 00000-0 28098-4 0 4753""")):
io.twoline2rv(LINE1.replace('23 ', '234'), LINE2, wgs72)
def test_bad_second_line():
with assertRaisesRegex(ValueError, re.escape("""TLE format error
The Two-Line Element (TLE) format was designed for punch cards, and so
is very strict about the position of every period, space, and digit.
Your line does not quite match. Here is the official format for line 2
with an N where each digit should go, followed by the line you provided:
2 NNNNN NNN.NNNN NNN.NNNN NNNNNNN NNN.NNNN NNN.NNNN NN.NNNNNNNNNNNNNN
2 00005 34 .268234 8.7242 1859667 331.7664 19.3264 10.82419157413667""")):
io.twoline2rv(LINE1, LINE2.replace(' 34', '34 '), wgs72)
def test_mismatched_lines():
msg = "Object numbers in lines 1 and 2 do not match"
with assertRaisesRegex(ValueError, re.escape(msg)):
io.twoline2rv(LINE1, BAD2, wgs72)
# ------------------------------------------------------------------------
# Helper routines
#
def verify_vanguard_1(sat, legacy=False):
attrs = VANGUARD_ATTRS
if legacy:
attrs = attrs.copy()
del attrs['epochyr']
del attrs['epochdays']
del attrs['jdsatepoch']
del attrs['jdsatepochF']
for name, value in attrs.items():
try:
assertEqual(getattr(sat, name), value)
except AssertionError as e:
message, = e.args
e.args = ('for attribute %s, %s' % (name, message),)
raise e
def sgp4init_args(d):
"""Given a dict of orbital parameters, return them in sgp4init order."""
return (d['bstar'], d['ndot'], d['nddot'], d['ecco'], d['argpo'],
d['inclo'], d['mo'], d['no_kozai'], d['nodeo'])
# ----------------------------------------------------------------------
# INTEGRATION TEST
#
# This runs both new and old satellite objects against every example
# computation in the official `tcppver.out` test case file. Instead of
# trying to parse the file, it instead re-generates it using Python
# satellite objects, then compares the resulting text with the file.
def test_satrec_against_tcppver_using_julian_dates():
def invoke(satrec, tsince):
whole, fraction = divmod(tsince / 1440.0, 1.0)
jd = satrec.jdsatepoch + whole
fr = satrec.jdsatepochF + fraction
e, r, v = satrec.sgp4(jd, fr)
assert e == satrec.error
return e, r, v
run_satellite_against_tcppver(Satrec.twoline2rv, invoke, [1,1,6,6,4,3,6])
def test_satrec_against_tcppver_using_tsince():
def invoke(satrec, tsince):
e, r, v = satrec.sgp4_tsince(tsince)
assert e == satrec.error
return e, r, v
run_satellite_against_tcppver(Satrec.twoline2rv, invoke, [1,1,6,6,4,3,6])
def test_legacy_against_tcppver():
def make_legacy_satellite(line1, line2):
sat = io.twoline2rv(line1, line2, wgs72)
return sat
def run_legacy_sgp4(satrec, tsince):
r, v = sgp4(satrec, tsince)
return (satrec.error, satrec.error_message), r, v
errs = [
(1, 'mean eccentricity -0.001329 not within range 0.0 <= e < 1.0'),
(1, 'mean eccentricity -0.001208 not within range 0.0 <= e < 1.0'),
(6, 'mrt 0.996159 is less than 1.0'
' indicating the satellite has decayed'),
(6, 'mrt 0.996252 is less than 1.0'
' indicating the satellite has decayed'),
(4, 'semilatus rectum -0.103223 is less than zero'),
(3, 'perturbed eccentricity -122.217193'
' not within range 0.0 <= e <= 1.0'),
(6, 'mrt 0.830534 is less than 1.0'
' indicating the satellite has decayed'),
]
run_satellite_against_tcppver(make_legacy_satellite, run_legacy_sgp4, errs)
def run_satellite_against_tcppver(twoline2rv, invoke, expected_errors):
# Check whether this library can produce (at least roughly) the
# output in tcppver.out.
data = get_data(__name__, 'tcppver.out')
data = data.replace(b'\r', b'')
tcppver_lines = data.decode('ascii').splitlines(True)
error_list = []
actual_lines = list(generate_test_output(twoline2rv, invoke, error_list))
assert len(tcppver_lines) == len(actual_lines) == 700
previous_data_line = None
linepairs = zip(tcppver_lines, actual_lines)
for lineno, (expected_line, actual_line) in enumerate(linepairs, start=1):
if actual_line == '(Use previous data line)':
actual_line = (' 0.00000000' +
previous_data_line[17:107])
# Compare the lines. The first seven fields are printed
# to very high precision, so we allow a small error due
# to rounding differences; the rest are printed to lower
# precision, and so can be compared textually.
if 'xx' in actual_line:
similar = (actual_line == expected_line)
else:
afields = actual_line.split()
efields = expected_line.split()
actual7 = [ float(a) for a in afields[:7] ]
expected7 = [ float(e) for e in efields[:7] ]
similar = (
len(actual7) == len(expected7)
and
all(
-error < (a - e) < error
for a, e in zip(actual7, expected7)
)
and
afields[7:] == efields[7:] # just compare text
)
if not similar:
raise ValueError(
'Line %d of output does not match:\n'
'\n'
'Expected: %r\n'
'Got back: %r'
% (lineno, expected_line, actual_line))
if 'xx' not in actual_line:
previous_data_line = actual_line
# Make sure we produced the correct list of errors.
assertEqual(error_list, expected_errors)
def generate_test_output(twoline2rv, invoke, error_list):
"""Generate lines like those in the test file tcppver.out.
This iterates through the satellites in "SGP4-VER.TLE", which are
each supplemented with a time start/stop/step over which we are
supposed to print results.
"""
data = get_data(__name__, 'SGP4-VER.TLE')
tle_lines = iter(data.decode('ascii').splitlines())
for line1 in tle_lines:
if not line1.startswith('1'):
continue
line2 = next(tle_lines)
satrec = twoline2rv(line1, line2)
yield '%ld xx\n' % (satrec.satnum,)
for line in generate_satellite_output(
satrec, invoke, line2, error_list):
yield line
def generate_satellite_output(satrec, invoke, line2, error_list):
"""Print a data line for each time in line2's start/stop/step field."""
mu = wgs72.mu
e, r, v = invoke(satrec, 0.0)
if isnan(r[0]) and isnan(r[1]) and isnan(r[2]):
error_list.append(e)
yield '(Use previous data line)'
return
yield format_short_line(0.0, r, v)
tstart, tend, tstep = (float(field) for field in line2[69:].split())
tsince = tstart
while tsince <= tend:
if tsince == tstart == 0.0:
tsince += tstep
continue # avoid duplicating the first line
e, r, v = invoke(satrec, tsince)
if e != 0 and e != (0, None):
error_list.append(e)
return
yield format_long_line(satrec, tsince, mu, r, v)
tsince += tstep
if tsince - tend < tstep - 1e-6: # do not miss last line!
e, r, v = invoke(satrec, tend)
if e != 0 and e != (0, None):
error_list.append(e)
return
yield format_long_line(satrec, tend, mu, r, v)
def format_short_line(tsince, r, v):
"""Short line, using the same format string that testcpp.cpp uses."""
return ' %16.8f %16.8f %16.8f %16.8f %12.9f %12.9f %12.9f\n' % (
tsince, r[0], r[1], r[2], v[0], v[1], v[2])
def format_long_line(satrec, tsince, mu, r, v):
"""Long line, using the same format string that testcpp.cpp uses."""
short = format_short_line(tsince, r, v).strip('\n')
jd = satrec.jdsatepoch + satrec.jdsatepochF + tsince / 1440.0
year, mon, day, hr, minute, sec = invjday(jd)
(p, a, ecc, incl, node, argp, nu, m, arglat, truelon, lonper
) = rv2coe(r, v, mu)
return short + (
' %14.6f %8.6f %10.5f %10.5f %10.5f %10.5f %10.5f'
' %5i%3i%3i %2i:%2i:%9.6f\n'
) % (
a, ecc, incl*rad, node*rad, argp*rad, nu*rad,
m*rad, year, mon, day, hr, minute, sec,
)
# ----------------------------------------------------------------------
# NEW "OMM" FORMAT TESTS
# https://celestrak.com/satcat/tle.php?CATNR=5
VANGUARD_TLE = """\
VANGUARD 1 \n\
1 00005U 58002B 20287.20333880 -.00000016 00000-0 -22483-4 0 9998
2 00005 34.2443 225.5254 1845686 162.2516 205.2356 10.84869164218149
"""
# The MARIO satellite was chosen by reading through stations.txt looking
# for an element set with every field nonzero, since a zero in any field
# would hide errors in our unit conversion: zero times any conversion
# factor is zero.
MARIO_TLE = """\
MARIO \n\
1 55123U 98067UQ 23115.44827133 .00787702 29408-3 15680-2 0 9999
2 55123 51.6242 216.2930 0014649 331.8976 28.1241 15.99081912 18396
"""
# https://celestrak.org/NORAD/elements/gp.php?CATNR=55123&FORMAT=XML
MARIO_XML = """\
<?xml version="1.0" encoding="UTF-8"?>
<ndm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://sanaregistry.org/r/ndmxml_unqualified/ndmxml-2.0.0-master-2.0.xsd">
<omm id="CCSDS_OMM_VERS" version="2.0">
<header><CREATION_DATE/><ORIGINATOR/></header><body><segment><metadata><OBJECT_NAME>MARIO</OBJECT_NAME><OBJECT_ID>1998-067UQ</OBJECT_ID><CENTER_NAME>EARTH</CENTER_NAME><REF_FRAME>TEME</REF_FRAME><TIME_SYSTEM>UTC</TIME_SYSTEM><MEAN_ELEMENT_THEORY>SGP4</MEAN_ELEMENT_THEORY></metadata><data><meanElements><EPOCH>2023-04-25T10:45:30.642912</EPOCH><MEAN_MOTION>15.99081912</MEAN_MOTION><ECCENTRICITY>.0014649</ECCENTRICITY><INCLINATION>51.6242</INCLINATION><RA_OF_ASC_NODE>216.2930</RA_OF_ASC_NODE><ARG_OF_PERICENTER>331.8976</ARG_OF_PERICENTER><MEAN_ANOMALY>28.1241</MEAN_ANOMALY></meanElements><tleParameters><EPHEMERIS_TYPE>0</EPHEMERIS_TYPE><CLASSIFICATION_TYPE>U</CLASSIFICATION_TYPE><NORAD_CAT_ID>55123</NORAD_CAT_ID><ELEMENT_SET_NO>999</ELEMENT_SET_NO><REV_AT_EPOCH>1839</REV_AT_EPOCH><BSTAR>.1568E-2</BSTAR><MEAN_MOTION_DOT>.787702E-2</MEAN_MOTION_DOT><MEAN_MOTION_DDOT>.29408E-3</MEAN_MOTION_DDOT></tleParameters></data></segment></body></omm>
</ndm>
"""
# https://celestrak.com/NORAD/elements/gp.php?CATNR=55123&FORMAT=CSV
MARIO_CSV = """\
OBJECT_NAME,OBJECT_ID,EPOCH,MEAN_MOTION,ECCENTRICITY,INCLINATION,RA_OF_ASC_NODE,ARG_OF_PERICENTER,MEAN_ANOMALY,EPHEMERIS_TYPE,CLASSIFICATION_TYPE,NORAD_CAT_ID,ELEMENT_SET_NO,REV_AT_EPOCH,BSTAR,MEAN_MOTION_DOT,MEAN_MOTION_DDOT
MARIO,1998-067UQ,2023-04-25T10:45:30.642912,15.99081912,.0014649,51.6242,216.2930,331.8976,28.1241,0,U,55123,999,1839,.1568E-2,.787702E-2,.29408E-3
"""
def test_omm_xml_matches_old_tle():
line0, line1, line2 = MARIO_TLE.splitlines()
sat1 = Satrec.twoline2rv(line1, line2)
fields = next(omm.parse_xml(StringIO(MARIO_XML)))
sat2 = Satrec()
omm.initialize(sat2, fields)
assert_satellites_match(sat1, sat2)
def test_omm_csv_matches_old_tle():
line0, line1, line2 = MARIO_TLE.splitlines()
sat1 = Satrec.twoline2rv(line1, line2)
fields = next(omm.parse_csv(StringIO(MARIO_CSV)))
sat2 = Satrec()
omm.initialize(sat2, fields)
assert_satellites_match(sat1, sat2)
def assert_satellites_match(sat1, sat2):
for attr in dir(sat1):
if attr.startswith('_'):
continue
value1 = getattr(sat1, attr, None)
if value1 is None:
continue
if callable(value1):
continue
value2 = getattr(sat2, attr)
assertEqual(value1, value2, '%s %r != %r' % (attr, value1, value2))
# Live example of OMM:
# https://celestrak.com/NORAD/elements/gp.php?INTDES=2020-025&FORMAT=JSON-PRETTY
def test_omm_export():
line0, line1, line2 = VANGUARD_TLE.splitlines()
sat = Satrec.twoline2rv(line1, line2)
fields = export_omm(sat, 'VANGUARD 1')
assertEqual(fields, {
'ARG_OF_PERICENTER': 162.2516,
'BSTAR': -2.2483e-05,
'CENTER_NAME': 'EARTH',
'CLASSIFICATION_TYPE': 'U',
'ECCENTRICITY': 0.1845686,
'ELEMENT_SET_NO': 999,
'EPHEMERIS_TYPE': 0,
'EPOCH': '2020-10-13T04:52:48.472320',
'INCLINATION': 34.2443,
'MEAN_ANOMALY': 205.2356,
'MEAN_ELEMENT_THEORY': 'SGP4',
'MEAN_MOTION': 10.84869164,
'MEAN_MOTION_DDOT': 0.0,
'MEAN_MOTION_DOT': -1.6e-07,
'NORAD_CAT_ID': 5,
'OBJECT_ID': '1958-002B',
'OBJECT_NAME': 'VANGUARD 1',
'RA_OF_ASC_NODE': 225.5254,
'REF_FRAME': 'TEME',
'REV_AT_EPOCH': 21814,
'TIME_SYSTEM': 'UTC',
})
# ----------------------------------------------------------------------
def load_tests(loader, tests, ignore):
"""Run our main documentation as a test, plus all test functions."""
from sgp4.wulfgar import add_test_functions
add_test_functions(loader, tests, __name__)
# Python 2.6 formats floating-point numbers a bit differently and
# breaks the doctest, so we only run the doctest on later versions.
if sys.version_info >= (2, 7):
def setUp(suite):
suite.olddir = os.getcwd()
os.chdir(os.path.dirname(__file__))
suite.oldaccel = api.accelerated
api.accelerated = True # so doctest passes under 2.7
def tearDown(suite):
os.chdir(suite.olddir)
api.accelerated = suite.oldaccel
options = dict(optionflags=ELLIPSIS, setUp=setUp, tearDown=tearDown)
tests.addTests(DocTestSuite('sgp4', **options))
tests.addTests(DocTestSuite('sgp4.conveniences', **options))
tests.addTests(DocTestSuite('sgp4.functions', **options))
return tests
if __name__ == '__main__':
main()
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,810
|
brandon-rhodes/python-sgp4
|
refs/heads/master
|
/setup.py
|
import os
import sys
from distutils.core import setup, Extension
import sgp4
description, long_description = sgp4.__doc__.split('\n', 1)
# Force compilation on Travis CI + Python 3 to make sure it keeps working.
optional = True
if sys.version_info[0] != 2 and os.environ.get('TRAVIS') == 'true':
optional = False
# It is hard to write C extensions that support both Python 2 and 3, so
# we opt here to support the acceleration only for Python 3.
ext_modules = []
if sys.version_info[0] == 3:
ext_modules.append(Extension(
'sgp4.vallado_cpp',
optional=optional,
sources=[
'extension/SGP4.cpp',
'extension/wrapper.cpp',
],
# TODO: can we safely figure out how to use a pair of options
# like these, adapted to as many platforms as possible, to use
# multiple processors when available?
# extra_compile_args=['-fopenmp'],
# extra_link_args=['-fopenmp'],
extra_compile_args=['-ffloat-store'],
))
# Read the package's "__version__" without importing it.
path = 'sgp4/__init__.py'
with open(path, 'rb') as f:
text = f.read().decode('utf-8')
text = text.replace('-*- coding: utf-8 -*-', '') # for Python 2.7
namespace = {}
eval(compile(text, path, 'exec'), namespace)
setup(name = 'sgp4',
version = namespace['__version__'],
description = description,
long_description = long_description,
license = 'MIT',
author = 'Brandon Rhodes',
author_email = 'brandon@rhodesmill.org',
url = 'https://github.com/brandon-rhodes/python-sgp4',
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Topic :: Scientific/Engineering :: Astronomy',
],
packages = ['sgp4'],
package_data = {'sgp4': ['SGP4-VER.TLE', 'sample*', 'tcppver.out']},
ext_modules = ext_modules,
)
|
{"/sgp4/model.py": ["/sgp4/alpha5.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/io.py", "/sgp4/propagation.py"], "/sgp4/wrapper.py": ["/sgp4/__init__.py"], "/sgp4/api.py": ["/sgp4/functions.py", "/sgp4/wrapper.py", "/sgp4/model.py"], "/sgp4/omm.py": ["/sgp4/api.py"], "/sgp4/exporter.py": ["/sgp4/io.py", "/sgp4/conveniences.py"], "/sgp4/ext.py": ["/sgp4/functions.py"], "/sgp4/conveniences.py": ["/sgp4/__init__.py", "/sgp4/functions.py"], "/sgp4/io.py": ["/sgp4/ext.py", "/sgp4/propagation.py", "/sgp4/model.py"], "/sgp4/earth_gravity.py": ["/sgp4/propagation.py"], "/sgp4/propagation.py": ["/sgp4/alpha5.py"], "/sgp4/tests.py": ["/sgp4/api.py", "/sgp4/earth_gravity.py", "/sgp4/ext.py", "/sgp4/functions.py", "/sgp4/propagation.py", "/sgp4/__init__.py", "/sgp4/exporter.py", "/sgp4/model.py", "/sgp4/wulfgar.py"], "/setup.py": ["/sgp4/__init__.py"]}
|
33,811
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/models.py
|
from django.db import models
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField
import re
RESERVED_SUBDOMAINS = [
'static',
'api',
'fud',
]
SUBDOMAIN_PATTERN = re.compile("^[a-z0-9](?:[a-z0-9\-]{0,61}[a-z0-9])?$")
def validate_subdomain(subdomain):
if subdomain in RESERVED_SUBDOMAINS:
raise ValidationError('The subdomain "%s" is reserved' % subdomain)
if SUBDOMAIN_PATTERN.match(subdomain) is None:
raise ValidationError('Allowed characters: a-z, 0-9 and -')
if subdomain.startswith('www'):
raise ValidationError('Subdomains starting with www* are not allowed')
class Restaurant(models.Model):
name = models.TextField()
subdomain = models.TextField(unique=True, validators=[validate_subdomain], db_index=True)
address = models.TextField(null=True, blank=True, default=None)
postal_code = models.TextField(null=True, blank=True, default=None)
city = models.TextField(null=True, blank=True, default=None)
phone_number = models.TextField(null=True, blank=True, default=None)
email = models.TextField(null=True, blank=True, default=None)
owner = models.ForeignKey(User)
class Meta:
db_table = 'restaurant'
def __str__(self):
return u'%s' % (self.name,)
class Menu(models.Model):
title = models.TextField()
content = JSONField()
restaurant = models.ForeignKey(Restaurant)
order = models.IntegerField(default=0)
class Meta:
db_table = 'menu'
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,812
|
mjuopperi/fud
|
refs/heads/master
|
/fud/settings/prod.py
|
import requests
from fud.util.email import SESEmailSender
from .base import *
try:
from .secrets import *
except ImportError:
pass
DEBUG = False
SECRET_KEY = FUD_SECRET_KEY
AWS_ACCESS_KEY = AWS_ACCESS_KEY
AWS_SECRET_ACCESS_KEY = AWS_SECRET_ACCESS_KEY
# HTTPS settings
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
BASE_DOMAIN = 'fud.fi'
ALLOWED_HOSTS = [
'.fud.fi',
]
# Add instance IP address to allowed hosts for load balancer health checks
EC2_PRIVATE_IP = None
try:
EC2_PRIVATE_IP = requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text
except requests.exceptions.RequestException:
pass
if EC2_PRIVATE_IP:
ALLOWED_HOSTS.append(EC2_PRIVATE_IP)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'fud',
'USER': DB_USER,
'PASSWORD': DB_PASSWORD,
'HOST': DB_HOST,
'PORT': '5432',
}
}
STATIC_ROOT = '/home/fud/server/static/'
REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'] = ['rest_framework.renderers.JSONRenderer']
DJOSER['DOMAIN'] = 'fud.fi'
EMAIL_SENDER = SESEmailSender
ADMIN_URL = r'^sÀÀtâkÀli/'
GOOGLE_MAPS_API_KEY = GOOGLE_MAPS_API_KEY
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,813
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_register.py
|
from restaurants.tests.functional.selenium_spec import SeleniumSpec
from restaurants.tests.util import *
User = get_user_model()
class RegisterSpec(SeleniumSpec):
def setUp(self):
User.objects.create_user('test-user', 'test-user@example.com', 'password')
self.selenium.delete_all_cookies()
def tearDown(self):
User.objects.all().delete()
Restaurant.objects.all().delete()
def test_register_with_valid_data(self):
self.login()
self._register({
'name': 'Test Restaurant',
'subdomain': 'test-restaurant',
'address': 'Address',
'postal_code': '12345',
'city': 'City',
'phone_number': '010-123456789',
'email': 'test.restaurant@fud.fi'
})
self.assertTrue(self.title_will_be('Test Restaurant'))
self.assertTrue(Restaurant.objects.filter(subdomain='test-restaurant').exists())
restaurant = Restaurant.objects.get(subdomain='test-restaurant')
self.assertEqual(restaurant.name, 'Test Restaurant')
self.assertEqual(restaurant.address, 'Address')
self.assertEqual(restaurant.postal_code, '12345')
self.assertEqual(restaurant.city, 'City')
self.assertEqual(restaurant.phone_number, '010-123456789')
self.assertEqual(restaurant.email, 'test.restaurant@fud.fi')
def test_register_with_invalid_data(self):
self.login()
self._register({
'name': 'Test Restaurant',
'subdomain': 'test restaurant'
})
self.assertTrue(self.will_have_text('#subdomain-error', 'Only lower case letters, numbers and dashes are allowed.'))
self.assertFalse(Restaurant.objects.filter(subdomain='test restaurant').exists())
def test_register_with_reserved_subdomain(self):
self.login()
self._register({
'name': 'Api Restaurant',
'subdomain': 'api'
})
self.assertTrue(self.will_have_text('#subdomain-error', 'Subdomain is reserved.'))
self.assertFalse(Restaurant.objects.filter(subdomain='api').exists())
def test_register_with_in_use_subdomain(self):
create_restaurant('test-restaurant')
self.login()
self._register({
'name': 'Test Restaurant',
'subdomain': 'test-restaurant'
})
self.assertTrue(self.will_be_visible('#subdomain-error'))
self.assertTrue(self.will_have_text('#subdomain-error', 'Subdomain is already in use.'))
def test_register_logged_out(self):
self._register({
'name': 'Test Restaurant',
'subdomain': 'test-restaurant'
})
self.assertTrue(self.will_be_visible('#error'))
self.assertTrue(self.will_have_text('#error', 'You need to be logged in to register a restaurant.'))
def _register(self, data):
self.selenium.get('%s%s' % (self.server_url(), "/register"))
for name, value in data.items():
input = self.selenium.find_element_by_name(name)
input.send_keys(value)
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,814
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_menus.py
|
import time
from restaurants.tests.functional.selenium_spec import SeleniumSpec
from restaurants.tests.util import *
User = get_user_model()
class RestaurantMenuSpec(SeleniumSpec):
def tearDown(self):
Restaurant.objects.all().delete()
Menu.objects.all().delete()
def test_render_menus(self):
restaurant, menu1, menu2 = self.create_restaurant_and_menus()
self.selenium.get('%s%s' % (self.live_server_subdomain_url(restaurant.subdomain), '/menu'))
self.will_be_visible('.menu-title.desktop[data-id="' + str(menu1.id) + '"]')
active_menu_title = self.find_title_by_id(menu1.id)
inactive_menu_title = self.find_title_by_id(menu2.id)
self.assertEqual(active_menu_title.text, menu1.title)
self.assertEqual(inactive_menu_title.text, menu2.title)
self.assertIn('active', active_menu_title.get_attribute('class').split(' '))
self.assertNotIn('active', inactive_menu_title.get_attribute('class').split(' '))
active_menu = self.find_menu_content_by_id(menu1.id)
inactive_menu = self.find_menu_content_by_id(menu2.id)
self.assertTrue(active_menu.is_displayed())
self.assertFalse(inactive_menu.is_displayed())
def test_change_menu(self):
restaurant, menu1, menu2 = self.create_restaurant_and_menus()
self.selenium.get('%s%s' % (self.live_server_subdomain_url(restaurant.subdomain), '/menu'))
self.will_be_visible('.menu-title.desktop[data-id="' + str(menu1.id) + '"]')
self.assertTrue(self.find_menu_content_by_id(menu1.id).is_displayed())
self.assertFalse(self.find_menu_content_by_id(menu2.id).is_displayed())
self.select_menu(menu2.id)
self.assertFalse(self.find_menu_content_by_id(menu1.id).is_displayed())
self.assertTrue(self.find_menu_content_by_id(menu2.id).is_displayed())
self.assertIn('active', self.find_title_by_id(menu2.id).get_attribute('class').split(' '))
def create_restaurant_and_menus(self):
restaurant = self.create_restaurant()
menu1 = create_menu(restaurant, 'Menu 1')
menu2 = create_menu(restaurant, 'Menu 2')
return restaurant, menu1, menu2
def find_menu_by_id(self, menu_id):
return self.selenium.find_element_by_css_selector('.menu[data-id="' + str(menu_id) + '"]')
def find_menu_content_by_id(self, menu_id):
return self.find_menu_by_id(menu_id).find_element_by_css_selector('.categories')
def find_title_by_id(self, menu_id):
return self.selenium.find_element_by_css_selector('.menu-title.desktop[data-id="' + str(menu_id) + '"]')
def select_menu(self, menu_id):
self.find_title_by_id(menu_id).click()
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,815
|
mjuopperi/fud
|
refs/heads/master
|
/fud/util/auth.py
|
from django.contrib.auth import get_user_model
from django.views.generic import View
from rest_framework.authentication import TokenAuthentication
User = get_user_model()
class TokenAuthenticatedView(View, TokenAuthentication):
def user_from_request(self):
if 'authToken' in self.request.COOKIES:
user, _ = self.authenticate_credentials(self.request.COOKIES['authToken'])
return user
else:
return None
def is_owner(self, restaurant):
user = self.user_from_request()
return user is not None and user == restaurant.owner
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,816
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/serializers.py
|
from rest_framework import serializers
from restaurants.models import Restaurant, Menu
class RestaurantSerializer(serializers.ModelSerializer):
class Meta:
model = Restaurant
fields = ('name', 'subdomain', 'address', 'postal_code', 'city', 'phone_number', 'email')
class MenuSerializer(serializers.ModelSerializer):
restaurant = serializers.CharField(source='restaurant.subdomain', read_only=True)
class Meta:
model = Menu
fields = ('id', 'title', 'content', 'restaurant', 'order')
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,817
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/api/test_menus.py
|
from rest_framework import status
from rest_framework.test import APITestCase
from restaurants.serializers import MenuSerializer
from restaurants.tests.util import *
User = get_user_model()
class MenuApiSpec(APITestCase):
def tearDown(self):
User.objects.all().delete()
Restaurant.objects.all().delete()
Menu.objects.all().delete()
def test_create_menu_for_own_restaurant(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant', user)
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/'
data = menu_data('Γ la carte')
response = self.client.post(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Menu.objects.filter(restaurant=restaurant).count(), 1)
menu = Menu.objects.get(restaurant=restaurant)
self.assertEqual(menu.restaurant, restaurant)
self.assertEqual(menu.title, 'Γ la carte')
self.assertEqual(render_json(menu.content), render_json(MENU_CONTENT))
def test_create_menu_for_other_restaurant(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/'
data = menu_data('Γ la carte')
response = self.client.post(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Menu.objects.filter(restaurant=restaurant).count(), 0)
def test_get_all_menus_of_restaurant(self):
restaurant,_ = create_restaurant('test-restaurant')
menus = [create_menu(restaurant), create_menu(restaurant)]
url = '/restaurants/' + restaurant.subdomain + '/menus'
response = self.client.get(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data.get('menus'), MenuSerializer(menus, many=True).data)
def test_get_menu_by_id(self):
restaurant,_ = create_restaurant('test-restaurant')
menu = create_menu(restaurant)
url = '/restaurants/' + restaurant.subdomain + '/menus/' + str(menu.id)
response = self.client.get(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, MenuSerializer(menu).data)
def test_update_menu_as_owner(self):
restaurant, user = create_restaurant('test-restaurant')
menu = create_menu(restaurant)
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/' + str(menu.id)
menu.title = 'changed'
data = MenuSerializer(menu).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Menu.objects.get(id=menu.id).title, 'changed')
def test_update_menu_as_other(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant')
menu = create_menu(restaurant, 'original-title')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/' + str(menu.id)
menu.title = 'changed'
data = MenuSerializer(menu).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Menu.objects.get(id=menu.id).title, 'original-title')
def test_delete_menu_as_owner(self):
restaurant, user = create_restaurant('test-restaurant')
menu = create_menu(restaurant)
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/' + str(menu.id)
response = self.client.delete(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertFalse(Menu.objects.filter(id=menu.id).exists())
def test_delete_menu_as_other(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant')
menu = create_menu(restaurant)
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/' + str(menu.id)
response = self.client.delete(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertTrue(Menu.objects.filter(id=menu.id).exists())
def test_update_multiple_menus(self):
restaurant, user = create_restaurant('test-restaurant')
menu1 = create_menu(restaurant)
menu2 = create_menu(restaurant)
menu3 = create_menu(restaurant, 'original-title')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/'
menu1.title = 'changed1'
menu2.title = 'changed2'
data = MenuSerializer([menu1, menu2], many=True).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Menu.objects.get(id=menu1.id).title, 'changed1')
self.assertEqual(Menu.objects.get(id=menu2.id).title, 'changed2')
self.assertEqual(Menu.objects.get(id=menu3.id).title, 'original-title')
def test_update_multiple_menus_with_nonexistent_menu(self):
restaurant, user = create_restaurant('test-restaurant')
menu = create_menu(restaurant)
menu.delete()
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/'
menu.title = 'changed1'
data = MenuSerializer([menu], many=True).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue(Menu.objects.filter(title=menu.title).exists())
def test_update_multiple_menus_with_other_restaurants_menu(self):
restaurant, user = create_restaurant('test-restaurant')
other_restaurant, _ = create_restaurant('other-restaurant')
menu = create_menu(other_restaurant, title='original-title')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/'
menu.title = 'changed1'
data = MenuSerializer([menu], many=True).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Menu.objects.get(id=menu.id).title, 'original-title')
created_id = response.data['menus'][0]['id']
self.assertTrue(Menu.objects.filter(id=created_id).exists())
self.assertEqual(Menu.objects.get(id=created_id).title, 'changed1')
def test_update_multiple_menus_with_invalid_data(self):
restaurant, user = create_restaurant('test-restaurant')
menu = create_menu(restaurant, title='original-title')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain + '/menus/'
menu.title = 'changed1'
data = MenuSerializer(menu).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertIn('Data must be a list.', response.data)
self.assertEqual(Menu.objects.get(id=menu.id).title, 'original-title')
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,818
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/apps.py
|
from django.apps import AppConfig
from django.conf import settings
class RestaurantsConfig(AppConfig):
name = 'restaurants'
verbose_name = 'Restaurants'
def ready(self):
if settings.DJOSER['SEND_ACTIVATION_EMAIL']:
from restaurants.signals.handlers import UserDisabler
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,819
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_login.py
|
from django.contrib.auth import get_user_model
from restaurants.tests.functional.selenium_spec import SeleniumSpec
User = get_user_model()
class LoginSpec(SeleniumSpec):
def setUp(self):
self.selenium.delete_all_cookies()
User.objects.create_user('test-user', 'test-user@example.com', 'password')
def tearDown(self):
User.objects.all().delete()
def test_login_with_valid_credentials(self):
self.selenium.get('%s%s' % (self.server_url(), "/login"))
username = self.selenium.find_element_by_name("username")
username.send_keys("test-user")
password = self.selenium.find_element_by_name("password")
password.send_keys("password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.title_will_be('Profile'))
self.assertTrue(self.will_have_text('.welcome', 'Hi, test-user!'))
self.assertTrue(self.will_have_text('.user h2 a', 'test-user'))
def test_login_with_invalid_credentials(self):
self.selenium.get('%s%s' % (self.server_url(), "/login"))
username = self.selenium.find_element_by_name("username")
username.send_keys("test-user")
password = self.selenium.find_element_by_name("password")
password.send_keys("incorrect")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('#error'))
error = self.selenium.find_element_by_css_selector('#error p')
self.assertEqual(error.text, 'Invalid username or password.')
def test_stay_logged_in_after_reload(self):
self.selenium.get('%s%s' % (self.server_url(), "/login"))
username = self.selenium.find_element_by_name("username")
username.send_keys("test-user")
password = self.selenium.find_element_by_name("password")
password.send_keys("password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.title_will_be('Profile'))
self.assertTrue(self.will_have_text('.user h2 a', 'test-user'))
self.selenium.refresh()
self.assertTrue(self.title_will_be('Profile'))
self.assertTrue(self.will_have_text('.welcome', 'Hi, test-user!'))
self.assertTrue(self.will_have_text('.user h2 a', 'test-user'))
self.assertNotEqual(self.selenium.current_url, self.server_url() + '/login')
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,820
|
mjuopperi/fud
|
refs/heads/master
|
/fud/urls/fud.py
|
from django.conf import settings
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(settings.ADMIN_URL, include(admin.site.urls)),
url(r'^', include('restaurants.urls.fud', namespace='restaurants')),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,821
|
mjuopperi/fud
|
refs/heads/master
|
/fud/settings/base.py
|
"""
Django settings for fud project.
Generated by 'django-admin startproject' using Django 1.8.4.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import json
import os
from fud.util.email import MockEmailSender
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.abspath(os.path.dirname(__name__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '+kzqr#ww(ic^9s89dy)rri3&$2ls^m*2=ccjr!$4h-590f+ah='
AWS_ACCESS_KEY = 'N/A'
AWS_SECRET_ACCESS_KEY = 'N/A'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'rest_framework',
'rest_framework.authtoken',
'djoser',
'restaurants.apps.RestaurantsConfig',
'subdomains',
'corsheaders',
)
MIDDLEWARE_CLASSES = (
'corsheaders.middleware.CorsMiddleware',
'subdomains.middleware.SubdomainURLRoutingMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
SITE_ID = 1
# Wildcard subdomains for restaurants
ROOT_URLCONF = 'fud.urls.restaurants'
SUBDOMAIN_URLCONFS = {
None: 'fud.urls.fud',
'www': 'fud.urls.fud',
'api': 'fud.urls.api',
}
CORS_ORIGIN_ALLOW_ALL = True
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'fud.util.context_processors.global_settings',
],
},
},
]
WSGI_APPLICATION = 'fud.wsgi.application'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'PAGE_SIZE': 10
}
DJOSER = {
'SITE_NAME': 'Fud',
'DOMAIN': 'localhost:8000',
'SEND_ACTIVATION_EMAIL': True,
'ACTIVATION_URL': 'activate/{uid}/{token}',
'PASSWORD_RESET_CONFIRM_URL': 'reset/{uid}/{token}'
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
# File revisions
filerevs_path = os.path.join(PROJECT_ROOT, 'restaurants/static/restaurants', 'rev-manifest.json')
try:
with open(filerevs_path) as filerevs_fh:
FILEREVS = json.load(filerevs_fh)
except IOError:
print('No file revisions found, continuing without')
FILEREVS = {}
EMAIL_SENDER = MockEmailSender
DEFAULT_FROM_EMAIL = 'noreply@fud.fi'
ADMIN_URL = r'^admin/'
GOOGLE_MAPS_API_KEY = 'AIzaSyAqxSmUBTxM_Tt3ZK1QdpYxqbOZmSNCDyQ'
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,822
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/urls/api.py
|
from django.conf.urls import url, include
from restaurants import views
app_name = 'restaurants'
urlpatterns = [
url(r'^auth/register/$', views.CustomRegistrationView.as_view()),
url(r'^auth/password/reset/$', views.CustomPasswordResetView.as_view()),
url(r'^auth/', include('djoser.urls.authtoken')),
url(r'^auth/validate-username/?$', views.UsernameValidationView.as_view(), name='validate-username'),
url(r'^restaurants/?$', views.RestaurantList.as_view()),
url(r'^restaurants/owned/?$', views.UserRestaurantList.as_view()),
url(r'^restaurants/validate-subdomain/?$', views.SubdomainValidationView.as_view(), name='validate-subdomain'),
url(r'^restaurants/(?P<subdomain>[\w-]+)/?$', views.RestaurantDetail.as_view()),
url(r'^restaurants/(?P<subdomain>[\w-]+)/menus/?$', views.MenuList.as_view()),
url(r'^restaurants/(?P<subdomain>[\w-]+)/menus/(?P<id>.+)/?$', views.MenuDetail.as_view()),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,823
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/permissions.py
|
from rest_framework import permissions
from restaurants.models import Restaurant
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
class RestaurantPermission():
"""
Custom permission to only allows owner of an restaurant to edit it's menus.
"""
@staticmethod
def has_permission(request, subdomain):
if request.method in permissions.SAFE_METHODS:
return True
else:
restaurant = Restaurant.objects.get(subdomain=subdomain)
return restaurant.owner == request.user
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,824
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/migrations/0003_menu_order_defaults.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-10-03 06:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('restaurants', '0002_menu_order'),
]
operations = [
migrations.AlterField(
model_name='menu',
name='order',
field=models.IntegerField(default=0),
),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,825
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/urls/fud.py
|
from django.conf.urls import url
from django.views.generic import RedirectView
from restaurants import views
from restaurants.templatetags.revisioned_staticfiles import revisioned_static_url
app_name = 'restaurants'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup/?', views.signup, name='signup'),
url(r'^login/?', views.login, name='login'),
url(r'^forgot/?', views.forgot, name='forgot'),
url(r'^reset/(?P<uid>.+)/(?P<token>.+)/?', views.reset, name='reset'),
url(r'^register/?', views.register, name='register'),
url(r'^activation/?', views.activation, name='activation'),
url(r'^activate/(?P<uid>.+)/(?P<token>.+)/?', views.activate, name='activate'),
url(r'^profile/?', views.profile, name='profile'),
url(r'^status-check/?', views.StatusCheck.as_view(), name='status-check'),
url(r'^favicon.ico$', RedirectView.as_view(url=revisioned_static_url('restaurants/favicon.ico'), permanent=False), name="favicon")
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,826
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/api/test_users.py
|
from django.contrib.auth import get_user_model
from rest_framework import status
from rest_framework.test import APITestCase
from restaurants.tests.util import *
User = get_user_model()
class AuthApiSpec(APITestCase):
def setUp(self):
User.objects.create_user('existing-user', 'existing@example.com', 'password')
def tearDown(self):
User.objects.all().delete()
def test_validate_username_existing(self):
url = '/auth/validate-username?username=existing-user'
response = self.client.get(url, HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, 'Username is already in use.')
def test_validate_username_new(self):
url = '/auth/validate-username?username=new-user'
response = self.client.get(url, HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, 'true')
def test_register_without_activating(self):
url = '/auth/register/'
data = signup_data()
response = self.client.post(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(User.objects.filter(username='test-user').exists())
self.assertFalse(User.objects.get(username='test-user').is_active)
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,827
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/api/test_restaurants.py
|
from rest_framework import status
from rest_framework.test import APITestCase
from restaurants.serializers import RestaurantSerializer
from restaurants.tests.util import *
User = get_user_model()
class RestaurantApiSpec(APITestCase):
def tearDown(self):
User.objects.all().delete()
Restaurant.objects.all().delete()
def test_validate_subdomain_existing(self):
existing_restaurant,_ = create_restaurant('existing')
url = '/restaurants/validate-subdomain?subdomain=' + existing_restaurant.subdomain
response = self.client.get(url, HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, 'Subdomain is already in use.')
def test_validate_subdomain_new(self):
url = '/restaurants/validate-subdomain?subdomain=new-subdomain'
response = self.client.get(url, HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, 'true')
def test_create_restaurant_logged_in(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
authenticate_requests(user, self.client)
url = '/restaurants'
data = restaurant_data()
response = self.client.post(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(Restaurant.objects.filter(subdomain='test-restaurant').exists())
self.assertEqual(Restaurant.objects.get(subdomain='test-restaurant').owner, user)
def test_create_restaurant_logged_out(self):
url = '/restaurants'
data = restaurant_data()
response = self.client.post(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertFalse(Restaurant.objects.filter(subdomain='test-restaurant').exists())
def test_create_restaurant_subdomain_conflict(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
existing_restaurant, existing_user = create_restaurant('existing')
authenticate_requests(user, self.client)
url = '/restaurants'
data = restaurant_data(subdomain=existing_restaurant.subdomain)
response = self.client.post(url, data, format='json', HTTP_HOST=API_HOST)
self.assertContains(response, 'Restaurant with this subdomain already exists.', status_code=status.HTTP_400_BAD_REQUEST)
self.assertEqual(Restaurant.objects.get(subdomain=existing_restaurant.subdomain).owner, existing_user)
def test_get_all_restaurants(self):
restaurants = [create_restaurant('first')[0], create_restaurant('second')[0]]
url = '/restaurants'
response = self.client.get(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data.get('results'), RestaurantSerializer(restaurants, many=True).data)
def test_get_restaurant_by_subdomain(self):
restaurant, _ = create_restaurant('test-restaurant')
url = '/restaurants/' + restaurant.subdomain
response = self.client.get(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data, RestaurantSerializer(restaurant).data)
def test_get_restaurant_not_found(self):
url = '/restaurants/' + 'restaurant'
response = self.client.get(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_update_restaurant_as_owner(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant', user)
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain
restaurant.address = 'test-address'
data = RestaurantSerializer(restaurant).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(Restaurant.objects.get(subdomain=restaurant.subdomain).address, 'test-address')
def test_update_restaurant_as_other(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain
restaurant.name = 'changed'
data = RestaurantSerializer(restaurant).data
response = self.client.put(url, data, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(Restaurant.objects.get(subdomain=restaurant.subdomain).name, 'test-restaurant')
def test_delete_restaurant_as_owner(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant', user)
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain
response = self.client.delete(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertFalse(Restaurant.objects.filter(subdomain=restaurant.subdomain).exists())
def test_delete_restaurant_as_other(self):
user = User.objects.create_user('test-user', 'test@example.com', 'password')
restaurant,_ = create_restaurant('test-restaurant')
authenticate_requests(user, self.client)
url = '/restaurants/' + restaurant.subdomain
response = self.client.delete(url, format='json', HTTP_HOST=API_HOST)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertTrue(Restaurant.objects.filter(subdomain=restaurant.subdomain).exists())
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,828
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/signals/handlers.py
|
from django.contrib.auth import get_user_model
from djoser.signals import user_registered
from django.dispatch import receiver
import logging
User = get_user_model()
logger = logging.getLogger(__name__)
class UserDisabler:
@receiver(user_registered)
def user_disabler(sender, user, **kwargs):
logger.debug('Disabling registered user ' + user.username + ' until email is validated')
user.is_active = False
user.save()
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,829
|
mjuopperi/fud
|
refs/heads/master
|
/fud/util/email.py
|
from django.conf import settings
from django.template.loader import get_template
from boto3.session import Session
TEMPLATE_BASE = 'restaurants/email/'
def _get_template(template_name, context):
return get_template(TEMPLATE_BASE + template_name).render(context)
class EmailSender:
@staticmethod
def send_email(to_email, from_email, context, subject_template_name,
plain_body_template_name, html_body_template_name=None):
raise NotImplementedError("Not implemented in the base class")
class MockEmailSender(EmailSender):
sentEmails = []
@staticmethod
def send_email(to_email, from_email, context, subject_template_name,
plain_body_template_name, html_body_template_name=None):
email = Email(to_email, from_email,
_get_template(subject_template_name, context).strip(),
_get_template(plain_body_template_name, context))
MockEmailSender.sentEmails.append(email)
email.print()
class Email():
def __init__(self, to_email, from_email, subject, body):
self.to_email = to_email
self.from_email = from_email
self.subject = subject
self.body = body
def print(self):
print('Mock email to ' + self.to_email + ' from ' + self.from_email)
print('Subject: ' + self.subject)
print('Body: ' + self.body)
class SESEmailSender(EmailSender):
@staticmethod
def send_email(to_email, from_email, context, subject_template_name,
plain_body_template_name, html_body_template_name=None):
subject = _get_template(subject_template_name, context).strip()
body = _get_template(plain_body_template_name, context)
SESUtil().send_email(to_email, from_email, subject, body)
class SESUtil:
def send_email(self, to_email, from_email, subject, body):
session = Session(settings.AWS_ACCESS_KEY,
settings.AWS_SECRET_ACCESS_KEY,
region_name='eu-west-1')
client = session.client('ses')
return client.send_email(
Source=from_email,
Destination=self._destination(to_email),
Message=self._message(subject, body),
)
@staticmethod
def _destination(to_email):
return {
'ToAddresses': [
to_email,
],
'CcAddresses': [],
'BccAddresses': []
}
@staticmethod
def _message(subject, body):
return {
'Subject': {
'Data': subject,
'Charset': 'utf-8'
},
'Body': {
'Text': {
'Data': body,
'Charset': 'utf-8'
}
}
}
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,830
|
mjuopperi/fud
|
refs/heads/master
|
/fud/settings/test.py
|
from .base import *
from subprocess import call
DEBUG = True
BASE_DOMAIN = 'testserver'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'fud_test',
'USER': 'fuduser',
'PASSWORD': 'kugganen',
'HOST': '192.168.33.10',
'PORT': '5432',
}
}
PASSWORD_HASHERS = [
'django.contrib.auth.hashers.MD5PasswordHasher',
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,831
|
mjuopperi/fud
|
refs/heads/master
|
/fud/urls/restaurants.py
|
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('restaurants.urls.restaurants', namespace='restaurants')),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,832
|
mjuopperi/fud
|
refs/heads/master
|
/fud/settings/dev.py
|
from .base import *
DEBUG = True
BASE_DOMAIN = 'fud.localhost'
ALLOWED_HOSTS = {
'.fud.localhost',
}
MIDDLEWARE_CLASSES = (
'fud.util.middleware.LocalhostRedirectionMiddleware',
) + MIDDLEWARE_CLASSES
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'fud',
'USER': 'fuduser',
'PASSWORD': 'kugganen',
'HOST': '192.168.33.10',
'PORT': '5432',
}
}
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,833
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_profile.py
|
from restaurants.tests.functional.selenium_spec import SeleniumSpec
from restaurants.tests.util import *
User = get_user_model()
class ProfileSpec(SeleniumSpec):
def setUp(self):
User.objects.create_user('test-user', 'test-user@example.com', 'password')
def tearDown(self):
User.objects.all().delete()
def test_redirect_to_login_if_not_logged_in(self):
self.selenium.get('%s%s' % (self.server_url(), "/profile"))
self.title_will_be('Login')
def test_change_email(self):
self.login()
self.selenium.find_element_by_css_selector('#change-email button.change').click()
email_input = self.selenium.find_element_by_css_selector('input[name="email"]')
email_input.clear()
email_input.send_keys('changed@example.com')
self.selenium.find_element_by_css_selector('#change-email button.save').click()
self.assertTrue(self.will_be_visible('#change-email .success'))
self.assertEqual(User.objects.get(username='test-user').email, 'changed@example.com')
def test_change_password(self):
self.login()
self.selenium.find_element_by_css_selector('#change-password button.change').click()
current_password = self.selenium.find_element_by_css_selector('input[name="current-password"]')
current_password.send_keys('password')
new_password = self.selenium.find_element_by_css_selector('input[name="new-password"]')
new_password.send_keys('changed')
self.selenium.find_element_by_css_selector('#change-password button.save').click()
self.assertTrue(self.will_be_visible('#change-password .success'))
self.assertTrue(User.objects.get(username='test-user').check_password('changed'))
def test_render_owned_restaurants(self):
user = User.objects.get(username='test-user')
restaurants = [create_restaurant('first', user)[0], create_restaurant('second', user)[0]]
self.login()
self.will_be_visible('#restaurants li a')
rendered = map((lambda x: x.text), self.selenium.find_elements_by_css_selector('#restaurants li a'))
self.assertIn(restaurants[0].name, rendered)
self.assertIn(restaurants[1].name, rendered)
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,834
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_forgot_password.py
|
import djoser.utils
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from restaurants.tests.functional.selenium_spec import SeleniumSpec
User = get_user_model()
class ForgotPasswordSpec(SeleniumSpec):
def setUp(self):
self.selenium.delete_all_cookies()
User.objects.create_user('test-user', 'test-user@example.com', 'password')
settings.EMAIL_SENDER.sentEmails = []
def tearDown(self):
User.objects.all().delete()
def test_send_password_reset_email_to_existing_user(self):
self.selenium.get('%s%s' % (self.server_url(), "/forgot"))
email = self.selenium.find_element_by_name("email")
email.send_keys("test-user@example.com")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('.success'))
user = User.objects.get(username='test-user')
uid = djoser.utils.encode_uid(user.pk)
token = default_token_generator.make_token(user)
path = "/reset/%s/%s" % (uid, token)
self.assertEqual(len(settings.EMAIL_SENDER.sentEmails), 1)
sent_email = settings.EMAIL_SENDER.sentEmails[0]
self.assertEqual(sent_email.subject, 'Reset your Fud.fi password')
self.assertIn(path, sent_email.body)
self.assertIn('Your username is: test-user', sent_email.body)
def test_do_not_change_password_with_invalid_uid(self):
user = User.objects.get(username='test-user')
token = default_token_generator.make_token(user)
self.selenium.get('%s%s%s' % (self.server_url(), "/reset/invalid-uid/", token))
new_password = self.selenium.find_element_by_name("new_password")
new_password.send_keys("new-password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('#error'))
self.assertFalse(user.check_password('new-password'))
def test_do_not_change_password_with_invalid_token(self):
user = User.objects.get(username='test-user')
uid = djoser.utils.encode_uid(user.pk)
self.selenium.get('%s%s%s%s' % (self.server_url(), "/reset/", uid, "/invalid-token"))
new_password = self.selenium.find_element_by_name("new_password")
new_password.send_keys("new-password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('#error'))
self.assertFalse(user.check_password('new-password'))
def test_change_password_with_valid_data(self):
user = User.objects.get(username='test-user')
uid = djoser.utils.encode_uid(user.pk)
token = default_token_generator.make_token(user)
self.selenium.get('%s%s%s%s%s' % (self.server_url(), "/reset/", uid, "/", token))
new_password = self.selenium.find_element_by_name("new_password")
new_password.send_keys("new-password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('.success'))
self.assertTrue(User.objects.get(username=user.username).check_password('new-password'))
def test_reset_password_and_login(self):
self.selenium.get('%s%s' % (self.server_url(), "/login"))
self.selenium.find_element_by_css_selector('a.forgot-password').click()
self.title_will_be('Forgot Password')
email = self.selenium.find_element_by_name("email")
email.send_keys("test-user@example.com")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('.success'))
self.assertEqual(len(settings.EMAIL_SENDER.sentEmails), 1)
user = User.objects.get(username='test-user')
uid = djoser.utils.encode_uid(user.pk)
token = default_token_generator.make_token(user)
path = "/reset/%s/%s" % (uid, token)
self.selenium.get('%s%s' % (self.server_url(), path))
self.assertTrue(self.title_will_be('Reset Password'))
new_password = self.selenium.find_element_by_name("new_password")
new_password.send_keys("new-password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.assertTrue(self.will_be_visible('.success'))
self.selenium.find_element_by_css_selector('.success p a').click()
self.assertTrue(self.title_will_be('Login'))
username = self.selenium.find_element_by_name("username")
username.send_keys("test-user")
password = self.selenium.find_element_by_name("password")
password.send_keys("new-password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.title_will_be('Profile')
self.assertTrue(self.will_have_text('.user h2 a', 'test-user'))
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,835
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/util.py
|
import os
import random
import string
from django.contrib.auth import get_user_model
from rest_framework.authtoken.models import Token
from rest_framework.renderers import JSONRenderer
from restaurants.models import Restaurant, Menu
User = get_user_model()
API_HOST = 'api.testserver'
def random_string(length=6):
return ''.join(random.choice(string.ascii_letters + string.digits) for n in range(length))
def random_username():
return 'user-' + random_string()
def random_restaurant_name():
return 'restaurant-' + random_string().lower()
def random_title():
return 'title-' + random_string()
def render_json(json):
JSONRenderer().render(json).decode('utf-8')
def authenticate_requests(user, client):
token, _ = Token.objects.get_or_create(user=user)
client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)
def create_restaurant(subdomain=None, user=None):
if user is None:
user = User.objects.create_user(random_username(), 'test@example.com', 'password')
if subdomain is None:
subdomain = random_restaurant_name()
restaurant = Restaurant(name=subdomain, subdomain=subdomain, owner=user,
address='10 Rockefeller Plaza', postal_code=10020,
city='New York City', phone_number='+358 50505050',
email=subdomain + '@fud.fi')
restaurant.save()
return restaurant, user
def create_menu(restaurant, title=None, content=None):
if title is None:
title = random_title()
if content is None:
content = MENU_CONTENT
menu = Menu(title=title, content=content, restaurant=restaurant)
menu.save()
return menu
def signup_data(username='test-user', email='test@example.com', password='password'):
return {
'username': username,
'email': email,
'password': password
}
def restaurant_data(name='Test Restaurant', subdomain='test-restaurant', address='',
postal_code='', city='', phone_number='', email=''):
return {
'name': name,
'subdomain': subdomain,
'address': address,
'postal_code': postal_code,
'city': city,
'phone_number': phone_number,
'email': email
}
MENU_CONTENT = [
{
"name": "Starters",
"items": [
{
"name": "Carrot on a Stick",
"price": "1.50 β¬",
"description": "Unsafe for consumption.",
"allergens": ["V", "C"]
}
]
},
{
'name': 'Burgers',
'items': [
{
'name': 'Seitan Burger',
'price': '4.50 β¬',
'description': 'Seitan, whole wheat, lettuce',
'allergens': ['V']
}
]
}
]
def menu_data(title='Test Menu', content=None):
if content is None:
content = MENU_CONTENT
return {
'title': title,
'content': content
}
def in_travis():
return 'TRAVIS' in os.environ
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,836
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/admin.py
|
from django.contrib import admin
from restaurants import models
# Register your models here.
class RestaurantAdmin(admin.ModelAdmin):
list_display = ('name', 'subdomain', 'owner')
pass
class MenuAdmin(admin.ModelAdmin):
list_display = ('title', 'restaurant')
pass
admin.site.register(models.Restaurant, RestaurantAdmin)
admin.site.register(models.Menu, MenuAdmin)
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,837
|
mjuopperi/fud
|
refs/heads/master
|
/fud/urls/api.py
|
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('restaurants.urls.api', namespace='restaurants')),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,838
|
mjuopperi/fud
|
refs/heads/master
|
/fud/util/middleware.py
|
from django.http import HttpResponsePermanentRedirect
class LocalhostRedirectionMiddleware(object):
def process_request(self, request):
"""
Redirects requests to localhost to fud.localhost
"""
path = request.get_raw_uri()
if 'localhost' in path and 'fud' not in path:
path = path.replace('localhost', 'fud.localhost')
return HttpResponsePermanentRedirect(path)
else:
pass
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,839
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_restaurant.py
|
import time
from restaurants.tests.functional.selenium_spec import SeleniumSpec
from restaurants.tests.util import *
User = get_user_model()
class RestaurantSpec(SeleniumSpec):
def setUp(self):
self.selenium.delete_all_cookies()
def tearDown(self):
User.objects.all().delete()
Restaurant.objects.all().delete()
def test_render_restaurant(self):
restaurant = self.create_restaurant()
self.selenium.get(self.live_server_subdomain_url(restaurant.subdomain))
self.will_have_text('.info h1', restaurant.name)
self.assertFalse(self.element_exists('button.switch-mode'))
self.assertEqual(self.selenium.find_element_by_css_selector('h3.address').text, restaurant.address)
self.assertEqual(self.selenium.find_element_by_css_selector('h3.city').text, '%d %s' % (restaurant.postal_code, restaurant.city))
self.assertEqual(self.selenium.find_element_by_css_selector('h3.phone').text, restaurant.phone_number)
self.assertEqual(self.selenium.find_element_by_css_selector('h3.email').text, restaurant.email)
def test_change_restaurant_name(self):
user = User.objects.create_user('test-user', 'test-user@example.com', 'password')
restaurant = self.create_restaurant(user=user)
self.login()
self.selenium.get(self.live_server_subdomain_url(restaurant.subdomain))
self.will_have_text('.info h1', restaurant.name)
self.switch_mode()
self.selenium.find_element_by_css_selector('.info button.change').click()
name_input = self.selenium.find_element_by_css_selector('input[name="name"]')
name_input.clear()
name_input.send_keys('Changed')
self.selenium.find_element_by_css_selector('.info button.save').click()
self.assertTrue(self.will_be_visible('.info .success'))
self.assertEqual(Restaurant.objects.get(subdomain=restaurant.subdomain).name, 'Changed')
def test_change_restaurant_location(self):
user = User.objects.create_user('test-user', 'test-user@example.com', 'password')
restaurant = self.create_restaurant(user=user)
self.login()
self.selenium.get(self.live_server_subdomain_url(restaurant.subdomain))
self.will_have_text('.info h1', restaurant.name)
self.switch_mode()
self.selenium.find_element_by_css_selector('.address button.change').click()
address_input = self.selenium.find_element_by_css_selector('input[name="address"]')
address_input.clear()
address_input.send_keys('M.2')
postal_code_input = self.selenium.find_element_by_css_selector('input[name="postal_code"]')
postal_code_input.clear()
city_input = self.selenium.find_element_by_css_selector('input[name="city"]')
city_input.clear()
city_input.send_keys('Koh Mook')
self.selenium.find_element_by_css_selector('.address button.save').click()
self.assertTrue(self.will_be_visible('.address .success'))
changed = Restaurant.objects.get(subdomain=restaurant.subdomain)
self.assertEqual(changed.address, 'M.2')
self.assertEqual(changed.postal_code, '')
self.assertEqual(changed.city, 'Koh Mook')
def test_change_restaurant_contact_info(self):
user = User.objects.create_user('test-user', 'test-user@example.com', 'password')
restaurant = self.create_restaurant(user=user)
self.login()
self.selenium.get(self.live_server_subdomain_url(restaurant.subdomain))
self.will_have_text('.info h1', restaurant.name)
self.switch_mode()
self.selenium.find_element_by_css_selector('.contact button.change').click()
phone_number_input = self.selenium.find_element_by_css_selector('input[name="phone_number"]')
phone_number_input.clear()
phone_number_input.send_keys('+358 666 666')
email_input = self.selenium.find_element_by_css_selector('input[name="email"]')
email_input.clear()
email_input.send_keys('changed@fud.fi')
self.selenium.find_element_by_css_selector('.contact button.save').click()
self.assertTrue(self.will_be_visible('.contact .success'))
changed = Restaurant.objects.get(subdomain=restaurant.subdomain)
self.assertEqual(changed.phone_number, '+358 666 666')
self.assertEqual(changed.email, 'changed@fud.fi')
def switch_mode(self):
self.assertTrue(self.element_exists('button.switch-mode'))
self.selenium.find_element_by_css_selector('button.switch-mode').click()
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,840
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/selenium_spec.py
|
from operator import mod
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.test import override_settings
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
import selenium.webdriver.support.ui as ui
from restaurants.tests.util import *
@override_settings(BASE_DOMAIN='fud.localhost')
class SeleniumSpec(StaticLiveServerTestCase):
DEFAULT_TIMEOUT = 10
SUBDOMAIN_INDEX = 0
RESTAURANT_SUBDOMAINS = [
'restaurant-0',
'restaurant-1',
'restaurant-2',
'restaurant-3',
'restaurant-4',
'restaurant-5',
'restaurant-6',
'restaurant-7',
'restaurant-8',
'restaurant-9',
]
@classmethod
def setUpClass(cls):
super(SeleniumSpec, cls).setUpClass()
if in_travis():
cls.selenium = webdriver.Firefox()
else:
cls.selenium = webdriver.PhantomJS()
cls.selenium.set_window_size(1024, 768)
cls.selenium.implicitly_wait(2)
@classmethod
def tearDownClass(cls):
cls.selenium.quit()
super(SeleniumSpec, cls).tearDownClass()
def will_be_visible(self, locator, timeout=DEFAULT_TIMEOUT):
try:
ui.WebDriverWait(self.selenium, timeout).until(EC.visibility_of_element_located((By.CSS_SELECTOR, locator)))
return True
except TimeoutException:
return False
def title_will_be(self, title, timeout=DEFAULT_TIMEOUT):
try:
ui.WebDriverWait(self.selenium, timeout).until(EC.title_is(title))
return True
except TimeoutException:
return False
def will_have_text(self, locator, text, timeout=DEFAULT_TIMEOUT):
try:
ui.WebDriverWait(self.selenium, timeout).until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, locator), text))
return True
except TimeoutException:
return False
def element_exists(self, locator):
try:
self.selenium.find_element_by_css_selector(locator)
return True
except NoSuchElementException:
return False
def login(self):
self.selenium.get('%s%s' % (self.server_url(), "/login"))
username = self.selenium.find_element_by_name("username")
username.send_keys("test-user")
password = self.selenium.find_element_by_name("password")
password.send_keys("password")
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
self.title_will_be('Profile')
self.assertTrue(self.will_have_text('.user h2 a', 'test-user'))
def server_url(self):
protocol, url = self.live_server_url.split('//', 1)
return protocol + '//fud.' + url
def live_server_subdomain_url(self, subdomain):
protocol, url = self.server_url().split('//', 1)
return protocol + '//' + subdomain + '.' + url
def create_restaurant(self, subdomain=None, user=None):
if in_travis():
subdomain = self.RESTAURANT_SUBDOMAINS[SeleniumSpec.SUBDOMAIN_INDEX]
SeleniumSpec.SUBDOMAIN_INDEX = mod(SeleniumSpec.SUBDOMAIN_INDEX + 1, 10)
return create_restaurant(subdomain, user)[0]
else:
return create_restaurant(subdomain, user)[0]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,841
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/tests/functional/test_signup.py
|
import djoser.utils
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.tokens import default_token_generator
from restaurants.tests.functional.selenium_spec import SeleniumSpec
User = get_user_model()
class SignupSpec(SeleniumSpec):
def setUp(self):
User.objects.create_user('existing-user', 'existing@example.com', 'password')
settings.EMAIL_SENDER.sentEmails = []
def tearDown(self):
User.objects.all().delete()
def test_signup_with_valid_input(self):
self.sign_up('test-user', 'test-user@example.com', 'password')
self.title_will_be('Account Activation')
self.will_have_text('section h1', 'Almost done!')
self.assertTrue(User.objects.filter(username='test-user').exists())
self.assertEqual(len(settings.EMAIL_SENDER.sentEmails), 1)
def test_signup_with_existing_username(self):
self.sign_up('existing-user', 'test-user@example.com', 'password')
self.will_be_visible('#username-error')
self.will_have_text('#username-error', 'Username is already in use.')
def test_signup_without_username(self):
self.sign_up('', 'test-user@example.com', 'password')
self.will_be_visible('#username-error')
self.will_have_text('#username-error', 'This field is required.')
def test_signup_without_email(self):
self.sign_up('test-user', '', 'password')
self.will_be_visible('#email-error')
self.will_have_text('#email-error', 'This field is required.')
def test_signup_with_invalid_email(self):
self.sign_up('test-user', 'invalid', 'password')
self.will_be_visible('#email-error')
self.will_have_text('#email-error', 'Please enter a valid email address.')
def test_signup_without_password(self):
self.sign_up('test-user', 'test-user@example.com', '')
self.will_be_visible('#password-error')
self.will_have_text('#password-error', 'This field is required.')
def test_signup_and_activate(self):
self.sign_up('test-user', 'test-user@example.com', 'password')
self.title_will_be('Account Activation')
self.assertTrue(User.objects.filter(username='test-user').exists())
user = User.objects.get(username='test-user')
uid = djoser.utils.encode_uid(user.pk)
token = default_token_generator.make_token(user)
path = "/activate/%s/%s" % (uid, token)
self.assertEqual(len(settings.EMAIL_SENDER.sentEmails), 1)
self.assertTrue(path in settings.EMAIL_SENDER.sentEmails[0].body)
self.selenium.get('%s%s' % (self.server_url(), path))
self.will_be_visible('#activate-account')
self.selenium.find_element_by_css_selector('#activate-account').click()
self.will_be_visible('.success')
self.title_will_be('Login')
self.assertTrue(User.objects.get(username='test-user').is_active)
def sign_up(self, username, email, password):
self.selenium.get('%s%s' % (self.server_url(), "/signup"))
username_input = self.selenium.find_element_by_name("username")
username_input.send_keys(username)
email_input = self.selenium.find_element_by_name("email")
email_input.send_keys(email)
password_input = self.selenium.find_element_by_name("password")
password_input.send_keys(password)
self.selenium.find_element_by_xpath('//button[@type="submit"]').click()
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,842
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/forms.py
|
from django import forms
from restaurants import models
class RegistrationForm(forms.ModelForm):
class Meta:
model = models.Restaurant
exclude = ['owner']
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,843
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/views.py
|
import time
from django.conf import settings
from django.http import Http404
from django.contrib.auth import get_user_model
from django.shortcuts import render, get_object_or_404
from djoser.views import RegistrationView, PasswordResetView
from rest_framework import permissions, mixins, generics
from rest_framework.exceptions import PermissionDenied, ValidationError
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from fud.util.auth import TokenAuthenticatedView
from restaurants import forms
from restaurants.models import Restaurant, Menu
from restaurants.permissions import IsOwnerOrReadOnly, RestaurantPermission
from restaurants.serializers import RestaurantSerializer, MenuSerializer
User = get_user_model()
def index(request):
return render(request, 'restaurants/index.html')
def signup(request):
return render(request, 'restaurants/signup.html')
def login(request):
return render(request, 'restaurants/login.html')
def forgot(request):
return render(request, 'restaurants/forgot.html')
def reset(request, uid, token):
return render(request, 'restaurants/reset.html', {
'uid': uid,
'token': token
})
def register(request):
form = forms.RegistrationForm()
context = {
'form': form,
}
return render(request, 'restaurants/register.html', context)
def activation(request):
return render(request, 'restaurants/activation.html')
def activate(request, uid, token):
return render(request, 'restaurants/activate.html', {
'uid': uid,
'token': token
})
def profile(request):
return render(request, 'restaurants/profile.html')
class RestaurantIndexView(TokenAuthenticatedView):
def get(self, request):
restaurant = Restaurant.objects.filter(subdomain=request.subdomain).first()
if restaurant is not None:
return render(request, 'restaurants/restaurant.html', {
'name': restaurant.name,
'is_admin': self.is_owner(restaurant)
})
else:
raise Http404('Not found')
class RestaurantMenuView(TokenAuthenticatedView):
def get(self, request):
restaurant = Restaurant.objects.filter(subdomain=request.subdomain).first()
if restaurant is not None:
return render(request, 'restaurants/menu.html', {
"title": restaurant.name,
"name": restaurant.name,
'is_admin': self.is_owner(restaurant),
})
else:
raise Http404('Not found')
class CustomRegistrationView(RegistrationView):
def send_email(self, *args, **kwargs):
kwargs['subject_template_name'] = 'activation_email_subject.txt'
kwargs['plain_body_template_name'] = 'activation_email_body.txt'
settings.EMAIL_SENDER.send_email(*args, **kwargs)
class CustomPasswordResetView(PasswordResetView):
def send_email(self, *args, **kwargs):
kwargs['subject_template_name'] = 'password_reset_email_subject.txt'
kwargs['plain_body_template_name'] = 'password_reset_email_body.txt'
settings.EMAIL_SENDER.send_email(*args, **kwargs)
class UsernameValidationView(APIView):
renderer_classes = (JSONRenderer, )
permission_classes = (permissions.AllowAny,)
def get(self, request, format=None):
if User.objects.filter(username=self.request.GET.get('username')).exists():
return Response('Username is already in use.')
else:
return Response('true')
class SubdomainValidationView(APIView):
renderer_classes = (JSONRenderer, )
permission_classes = (permissions.AllowAny,)
def get(self, request, format=None):
if Restaurant.objects.filter(subdomain=self.request.GET.get('subdomain')).exists():
return Response('Subdomain is already in use.')
else:
return Response('true')
class RestaurantList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
"""
List all restaurants or create a new one
"""
queryset = Restaurant.objects.all()
serializer_class = RestaurantSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class RestaurantDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
"""
Update or delete restaurants
"""
queryset = Restaurant.objects.all()
serializer_class = RestaurantSerializer
lookup_field = 'subdomain'
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
IsOwnerOrReadOnly,
)
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
class UserRestaurantList(generics.ListAPIView):
serializer_class = RestaurantSerializer
permission_classes = (permissions.IsAuthenticated, )
def get_queryset(self):
return Restaurant.objects.filter(owner=self.request.user)
class MenuList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
"""
List all menus of a restaurant or create a new one
"""
queryset = Menu.objects.all()
serializer_class = MenuSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
)
def perform_create(self, serializer):
serializer.save(restaurant=Restaurant.objects.get(subdomain=self.kwargs['subdomain']))
def get(self, request, subdomain):
restaurant = Restaurant.objects.get(subdomain=subdomain)
menus = Menu.objects.filter(restaurant=restaurant)
serializer = MenuSerializer(menus, many=True)
return Response({
'menus': serializer.data
})
def post(self, request, *args, **kwargs):
if not Restaurant.objects.filter(subdomain=kwargs['subdomain']).exists():
raise ValidationError('Restaurant does not exist.')
elif RestaurantPermission.has_permission(request, kwargs['subdomain']):
return self.create(request, *args, **kwargs)
else:
raise PermissionDenied()
def put(self, request, *args, **kwargs):
restaurant = Restaurant.objects.get(subdomain=kwargs['subdomain'])
if restaurant is None:
raise ValidationError('Restaurant does not exist.')
elif RestaurantPermission.has_permission(request, kwargs['subdomain']):
if not isinstance(request.data, list):
raise ValidationError('Data must be a list.')
else:
return self.update_menus(request.data, restaurant)
else:
raise PermissionDenied()
def update_menus(self, data, restaurant):
updated = []
for item in data:
serializer = MenuSerializer(data=item)
if serializer.is_valid():
if Menu.objects.filter(id=item['id'], restaurant=restaurant).exists():
serializer.update(Menu.objects.get(id=item['id']), serializer.validated_data)
else:
self.perform_create(serializer)
updated.append(serializer.data)
return Response({
'menus': updated
})
class MenuDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
"""
Update or delete restaurants
"""
queryset = Menu.objects.all()
serializer_class = MenuSerializer
permission_classes = (
permissions.IsAuthenticatedOrReadOnly,
)
def get_object(self):
queryset = self.get_queryset()
restaurant = Restaurant.objects.get(subdomain=self.kwargs['subdomain'])
filter = {'restaurant': restaurant, 'id': self.kwargs['id']}
menu = get_object_or_404(queryset, **filter)
self.check_object_permissions(self.request, restaurant)
return menu
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
if RestaurantPermission.has_permission(request, kwargs['subdomain']):
return self.update(request, *args, **kwargs)
else:
raise PermissionDenied()
def delete(self, request, *args, **kwargs):
if RestaurantPermission.has_permission(request, kwargs['subdomain']):
return self.destroy(request, *args, **kwargs)
else:
raise PermissionDenied()
class StatusCheck(APIView):
permission_classes = (permissions.AllowAny,)
def get(self, request, format=None):
return Response({'server_time': int(time.time() * 1000)})
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,844
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/migrations/0001_initial.py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-14 21:58
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import restaurants.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Menu',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.TextField()),
('content', django.contrib.postgres.fields.jsonb.JSONField()),
],
options={
'db_table': 'menu',
},
),
migrations.CreateModel(
name='Restaurant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.TextField()),
('subdomain', models.TextField(db_index=True, unique=True, validators=[restaurants.models.validate_subdomain])),
('address', models.TextField(blank=True, default=None, null=True)),
('postal_code', models.TextField(blank=True, default=None, null=True)),
('city', models.TextField(blank=True, default=None, null=True)),
('phone_number', models.TextField(blank=True, default=None, null=True)),
('email', models.TextField(blank=True, default=None, null=True)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'restaurant',
},
),
migrations.AddField(
model_name='menu',
name='restaurant',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='restaurants.Restaurant'),
),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,845
|
mjuopperi/fud
|
refs/heads/master
|
/restaurants/urls/restaurants.py
|
from django.conf.urls import url
from restaurants import views
app_name = 'restaurants'
urlpatterns = [
url(r'^$', views.RestaurantIndexView.as_view(), name='home'),
#url(r'^menu/?$', views.restaurant_menu, name='menu'),
url(r'^menu/?$', views.RestaurantMenuView.as_view(), name='menu'),
]
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,846
|
mjuopperi/fud
|
refs/heads/master
|
/fabfile.py
|
from fabric.api import *
from fabric.contrib import django, files, console
django.project('fud')
server_root = '/home/fud/'
server_dir = server_root + 'server'
virtualenv_dir = server_root + 'env/'
virtualenv = virtualenv_dir + 'bin/activate'
conf_dir = server_dir + '/tools/deploy/conf/'
server_package = 'fud.tar.gz'
project_files = [
'fud/',
'restaurants/',
'manage.py',
'manage.sh',
'requirements.txt',
'tools/deploy/conf/',
]
excluded_files = [
'fud/lib/',
'fud/settings/dev.py',
'fud/settings/test.py',
'fud/settings/travis.py',
'fud/settings/secrets.py.example',
'restaurants/static/src/',
'__pycache__',
'*.pyc',
]
def server_target():
git_hash = local('git rev-parse --short HEAD', capture=True)
return server_root + 'versions/server_{}'.format(git_hash)
def python_command(args):
run('source {} && {}'.format(virtualenv, args))
def django_command(args):
python_command('python manage.py {} --settings=fud.settings.prod'.format(args))
def init_dir(dir, clear=False):
if not files.exists(dir):
run('mkdir -p ' + dir)
elif clear:
if files.exists(dir):
run('rm -rf ' + dir)
run('mkdir -p ' + dir)
def create_link(source, target):
if files.exists(target):
run('rm -f ' + target)
run('ln -s {} {}'.format(source, target))
def check_deployed_version():
if files.exists(server_target()):
return console.confirm('Current version is already deployed, continue anyway?')
return True
def gulp():
local('gulp clean && gulp build')
def pack():
included = ' '.join(project_files)
excluded = ' '.join(map(lambda file: '--exclude \'' + file + '\'', excluded_files))
local('tar zcf {} {} {}'.format(server_package, excluded, included))
def send_files():
put(server_package, server_root)
def unpack():
init_dir(server_target(), clear=True)
run('tar zxf {} -C {}'.format(server_root + server_package, server_target()))
create_link(server_target(), server_dir)
run('rm ' + server_root + server_package)
def create_virtualenv():
init_dir(virtualenv_dir, clear=True)
run('virtualenv -p python3 ' + virtualenv_dir)
def setup_server():
create_virtualenv()
with cd(server_dir):
python_command('pip install -r requirements.txt --quiet')
python_command('pip install gunicorn')
django_command('migrate')
django_command('collectstatic -v0 --noinput')
sudo('mv {} {}'.format(conf_dir + 'fud.service', '/etc/systemd/system/'), shell=False)
sudo('chmod 755 /etc/systemd/system/fud.service')
sudo('mv {} {}'.format(conf_dir + 'nginx.conf', '/etc/nginx/'), shell=False)
sudo('chown nginx:nginx /etc/nginx/nginx.conf', shell=False)
sudo('chown nginx:nginx /etc/nginx/fud/*', shell=False)
def enable_service():
sudo('systemctl restart fud', shell=False)
sudo('systemctl enable fud', shell=False)
sudo('systemctl restart nginx', shell=False)
sudo('systemctl enable nginx', shell=False)
def clean():
local('rm ' + server_package)
def deploy():
if check_deployed_version():
gulp()
pack()
send_files()
unpack()
setup_server()
enable_service()
clean()
|
{"/fud/settings/prod.py": ["/fud/util/email.py", "/fud/settings/base.py"], "/restaurants/tests/functional/test_register.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_menus.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/serializers.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_menus.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/restaurants/apps.py": ["/restaurants/signals/handlers.py"], "/restaurants/tests/functional/test_login.py": ["/restaurants/tests/functional/selenium_spec.py"], "/fud/settings/base.py": ["/fud/util/email.py"], "/restaurants/permissions.py": ["/restaurants/models.py"], "/restaurants/tests/api/test_users.py": ["/restaurants/tests/util.py"], "/restaurants/tests/api/test_restaurants.py": ["/restaurants/serializers.py", "/restaurants/tests/util.py"], "/fud/settings/test.py": ["/fud/settings/base.py"], "/fud/settings/dev.py": ["/fud/settings/base.py"], "/restaurants/tests/functional/test_profile.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/test_forgot_password.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/tests/util.py": ["/restaurants/models.py"], "/restaurants/tests/functional/test_restaurant.py": ["/restaurants/tests/functional/selenium_spec.py", "/restaurants/tests/util.py"], "/restaurants/tests/functional/selenium_spec.py": ["/restaurants/tests/util.py"], "/restaurants/tests/functional/test_signup.py": ["/restaurants/tests/functional/selenium_spec.py"], "/restaurants/views.py": ["/fud/util/auth.py", "/restaurants/models.py", "/restaurants/permissions.py", "/restaurants/serializers.py"], "/restaurants/migrations/0001_initial.py": ["/restaurants/models.py"]}
|
33,875
|
tristenallgaier2023/bikers
|
refs/heads/master
|
/experiments/proj.py
|
from src.models import Bike_Classifier
from src.run_model import run_model
from data.load_data import load_proj_data
from data.my_dataset import MyDataset
import matplotlib.pyplot as plt
import numpy as np
import csv
import os
print("started")
# train_count = number of training samples
# test_count = number of testing samples
trainX, testX, trainY, testY = load_proj_data(train_count, test_count)
train_set = MyDataset(trainX, trainY)
test_set = MyDataset(testX, testY)
model = Bike_Classifier()
model, loss, acc = run_model(model,'train',train_set,batch_size=50,learning_rate=1e-4,n_epochs=10)
test_loss, test_accuracy = run_model(model,'test',test_set=test_set,batch_size=50)
print(acc['train'])
epochs = len(loss['train'])
plt.figure()
plt.title('Training Loss by Epoch')
plt.plot(np.arange(epochs), loss['train'])
plt.show()
plt.figure()
plt.title('Training Accuracy by Epoch')
plt.plot(np.arange(epochs), acc['train'])
plt.show()
print("test loss: ", test_loss, "test accuracy: ", test_accuracy)
|
{"/experiments/proj.py": ["/src/models.py", "/src/run_model.py", "/data/load_data.py"]}
|
33,876
|
tristenallgaier2023/bikers
|
refs/heads/master
|
/data/load_data.py
|
import numpy as np
import os
import csv
def load_proj_helper(count, path):
"""
helper for load_proj_data
Arguments:
count - (int) The number of samples to load.
path - (string) The path to the csv file to load from.
Returns:
X - (np.array) An Nxd array where N is count and d is the number of features
Y - (np.array) A 1D array of targets of size N
"""
X = np.empty((count, 3))
Y = np.empty(count)
with open(path, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
i = 0
for line in csv_reader:
if i >= count:
break
X[i, 0] = line[0]
X[i, 1] = line[3]
X[i, 2] = line[5]
if line[8] == "Casual":
Y[i] = 0
else:
Y[i] = 1
i += 1
return X, Y
def load_proj_data(train_count, test_count, base_folder='data'):
"""
Loads biker data
Arguments:
train_count - (int) The number of training samples to load.
test_count - (int) The number of testing samples to load.
base_folder - (string) path to dataset.
Returns:
trainX - (np.array) An Nxd array of features, where N is train_count and
d is the number of features.
testX - (np.array) An Mxd array of features, where M is test_count and
d is the number of features.
trainY - (np.array) A 1D array of targets of size N.
testY - (np.array) A 1D array of targets of size M.
"""
train_path = os.path.join(base_folder, '2017Q1-capitalbikeshare-tripdata.csv')
test_path = os.path.join(base_folder, '2017Q2-capitalbikeshare-tripdata.csv')
trainX, trainY = load_proj_helper(train_count, train_path)
testX, testY = load_proj_helper(test_count, test_path)
return trainX, testX, trainY, testY
|
{"/experiments/proj.py": ["/src/models.py", "/src/run_model.py", "/data/load_data.py"]}
|
33,877
|
tristenallgaier2023/bikers
|
refs/heads/master
|
/src/run_model.py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import numpy as np
def run_model(model,running_mode='train', train_set=None, valid_set=None, test_set=None,
batch_size=1, learning_rate=0.01, n_epochs=1, stop_thr=1e-4, shuffle=True):
"""
This function either trains or evaluates a model.
training mode: the model is trained and evaluated on a validation set, if provided.
If no validation set is provided, the training is performed for a fixed
number of epochs.
Otherwise, the model should be evaluted on the validation set
at the end of each epoch and the training should be stopped based on one
of these two conditions (whichever happens first):
1. The validation loss stops improving.
2. The maximum number of epochs is reached.
testing mode: the trained model is evaluated on the testing set
Inputs:
model: the neural network to be trained or evaluated
running_mode: string, 'train' or 'test'
train_set: the training dataset object generated using the class MyDataset
valid_set: the validation dataset object generated using the class MyDataset
test_set: the testing dataset object generated using the class MyDataset
batch_size: number of training samples fed to the model at each training step
learning_rate: determines the step size in moving towards a local minimum
n_epochs: maximum number of epoch for training the model
stop_thr: if the validation loss from one epoch to the next is less than this
value, stop training
shuffle: determines if the shuffle property of the DataLoader is on/off
Outputs when running_mode == 'train':
model: the trained model
loss: dictionary with keys 'train' and 'valid'
The value of each key is a list of loss values. Each loss value is the average
of training/validation loss over one epoch.
If the validation set is not provided just return an empty list.
acc: dictionary with keys 'train' and 'valid'
The value of each key is a list of accuracies (percentage of correctly classified
samples in the dataset). Each accuracy value is the average of training/validation
accuracies over one epoch.
If the validation set is not provided just return an empty list.
Outputs when running_mode == 'test':
loss: the average loss value over the testing set.
accuracy: percentage of correctly classified samples in the testing set.
Summary of the operations this function should perform:
1. Use the DataLoader class to generate trainin, validation, or test data loaders
2. In the training mode:
- define an optimizer (we use SGD in this homework)
- call the train function (see below) for a number of epochs untill a stopping
criterion is met
- call the test function (see below) with the validation data loader at each epoch
if the validation set is provided
3. In the testing mode:
- call the test function (see below) with the test data loader and return the results
"""
if(running_mode=='test'):
test_loader = DataLoader(test_set, batch_size, shuffle)
test_loss, test_accuracy = _test(model, test_loader)
return test_loss, test_accuracy
if(running_mode=='train'):
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
train_loader = DataLoader(train_set, batch_size, shuffle)
if(valid_set != None):
valid_loader = DataLoader(valid_set, batch_size, shuffle)
train_losses = []
train_accurs = []
val_losses = []
val_accurs = []
prev_val_loss = -1
i = 0
while i < n_epochs:
model, train_loss, train_accur = _train(model,train_loader,optimizer)
train_losses.append(train_loss)
train_accurs.append(train_accur)
if(valid_set != None):
val_loss, val_accur = _test(model,valid_loader)
val_losses.append(val_loss)
val_accurs.append(val_accur)
if(abs(prev_val_loss - val_loss) < stop_thr):
break
prev_val_loss = val_loss
i += 1
return model,{'train':train_losses,'valid':val_losses},{'train':train_accurs,'valid':val_accurs}
def _train(model,data_loader,optimizer,device=torch.device('cpu')):
"""
This function implements ONE EPOCH of training a neural network on a given dataset.
Example: training the Digit_Classifier on the MNIST dataset
Inputs:
model: the neural network to be trained
data_loader: for loading the netowrk input and targets from the training dataset
optimizer: the optimiztion method, e.g., SGD
device: we run everything on CPU in this homework
Outputs:
model: the trained model
train_loss: average loss value on the entire training dataset
train_accuracy: average accuracy on the entire training dataset
"""
correct = 0
total = 0
lossArr = []
lossF = nn.CrossEntropyLoss()
for batch in data_loader:
X, y = batch
model.zero_grad()
output = model(X.float())
# Adds to correct and total counts for accuracy
for i, j in enumerate(output):
if torch.argmax(j) == y[i]:
correct += 1
total += 1
# Find loss and take step
loss = lossF(output, y.long())
loss.backward()
optimizer.step()
lossArr.append(loss.item())
return model, sum(lossArr) / len(lossArr), 100 * correct / total
def _test(model, data_loader, device=torch.device('cpu')):
"""
This function evaluates a trained neural network on a validation set
or a testing set.
Inputs:
model: trained neural network
data_loader: for loading the netowrk input and targets from the validation or testing dataset
device: we run everything on CPU in this homework
Output:
test_loss: average loss value on the entire validation or testing dataset
test_accuracy: percentage of correctly classified samples in the validation or testing dataset
"""
correct = 0
total = 0
lossArr = []
lossF = nn.CrossEntropyLoss()
with torch.no_grad():
for batch in data_loader:
X, y = batch
output = model(X.float())
# Adds to correct and total counts for accuracy
for i, j in enumerate(output):
if torch.argmax(j) == y[i]:
correct += 1
total += 1
# Find loss
loss = lossF(output, y.long())
lossArr.append(loss.item())
return sum(lossArr) / len(lossArr), 100 * correct / total
|
{"/experiments/proj.py": ["/src/models.py", "/src/run_model.py", "/data/load_data.py"]}
|
33,878
|
tristenallgaier2023/bikers
|
refs/heads/master
|
/src/models.py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Bike_Classifier(nn.Module):
"""
This class creates a neural network for classifying bikers as casual(0) or
member(1).
Network architecture:
- Input layer
- First hidden layer: fully connected layer of size 2 nodes
- Second hidden layer: fully connected layer of size 3 nodes
- Output layer: a linear layer with one node per class (so 2 nodes)
ReLU activation function for both hidden layers
"""
def __init__(self):
super(Bike_Classifier, self).__init__()
self.fc1 = nn.Linear(3, 2)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(2, 3)
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(3, 2)
def forward(self, input):
x = self.fc1(input)
x = self.relu1(x)
x = self.fc2(x)
x = self.relu2(x)
x = self.fc3(x)
return x
|
{"/experiments/proj.py": ["/src/models.py", "/src/run_model.py", "/data/load_data.py"]}
|
33,897
|
vlraik/Language-classification-using-boosted-decision-trees
|
refs/heads/master
|
/utils.py
|
from features import *
from classifiers import *
import pickle
def traininginput(input_file):
"""
A function to read the training dataset from the file.
:param input_file: The name of the input file.
:return: The training dataset, along with the english and dutch dataset.
"""
data = open(input_file, encoding="utf8").read().splitlines()
englishdata, dutchdata = [], []
maindata = []
for i in data:
maindata.append(i.lower())
if i.startswith("nl|"):
dutchdata.append(i[3:].lower())
elif i.startswith("en|"):
englishdata.append(i[3:].lower())
return englishdata, dutchdata, data
def testinput(test_file):
"""
A function to read the test dataset from the file.
:param test_file: The name of the test file.
:return: The test dataset as a list.
"""
return open(test_file).read().splitlines()
def train(input_file, model_output, classifier):
"""
Train the dataset based on the input parameters and also get the feautures from the training
document corpus dataset.
:param input_file: The input training file.
:param model_output: The output file to store the model.
:param classifier: The name of the classifier to use.
"""
global english, dutch, tree, dt, ada
english, dutch, data = traininginput(input_file)
feature1 = np.asarray(lengthofwords(english, dutch, data))
feature2 = np.asarray(freqoflettersinsentence(english, dutch, data))
feature3 = np.asarray(uncommontopletters(english, dutch, data))
feature4 = np.asarray(worduniqueness(english, dutch, data))
feature5 = np.asarray(tfidf(english, dutch, data))
feature6 = np.asarray(uniquewordsinsentence(english, dutch, data))
feature7 = np.asarray(uniquelettersinasentence(english, dutch, data))
feature8 = np.asarray(bigram(english, dutch, data))
feature9 = np.asarray(trigram(english, dutch, data))
feature10 = np.asarray(wordswithrepeatingletters(english, dutch, data))
X_train = np.column_stack(
(feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10))
y = []
for i in data:
if i[:3] == 'nl|':
y.append(0)
elif i[:3] == 'en|':
y.append(1)
y = np.asarray(y)
X_train = np.column_stack((X_train, y))
if classifier == 'dt':
tree = DecisionTree(X_train, y, maxdepth=5)
dt = tree.build_tree(X_train)
tree.rootnode(dt)
file = open(model_output+'.obj','wb')
pickle.dump(tree,file)
elif classifier == 'ada':
ada = Adaboost(X_train, y, 2)
#print(type(ada))
file = open(model_output+'.obj','wb')
pickle.dump(ada,file)
file.close()
ada.train(X_train)
#ada.classify(X_train)
#a=pickle.load(open('out.obj','rb'))
#print(type(a) is Adaboost)
# savemodel(model_output)
def predict(model_name, test_file):
"""
A function to classify the test dataset.
:param model_name: The file name to load the model from
:param test_file: The test file dataset.
"""
# data = testinput(test_file)
# loadmodel(model_name)
data = testinput(model_name)
model = pickle.load(open(test_file+'.obj','rb'))
feature1 = np.asarray(lengthofwords(english, dutch, data))
feature2 = np.asarray(freqoflettersinsentence(english, dutch, data))
feature3 = np.asarray(uncommontopletters(english, dutch, data))
feature4 = np.asarray(worduniqueness(english, dutch, data))
feature5 = np.asarray(tfidf(english, dutch, data))
feature6 = np.asarray(uniquewordsinsentence(english, dutch, data))
feature7 = np.asarray(uniquelettersinasentence(english, dutch, data))
feature8 = np.asarray(bigram(english, dutch, data))
feature9 = np.asarray(trigram(english, dutch, data))
feature10 = np.asarray(wordswithrepeatingletters(english, dutch, data))
X_train = np.column_stack(
(feature1, feature2, feature3, feature4, feature5, feature6, feature7, feature8, feature9, feature10))
if type(model) is Adaboost:
ada.classify(X_train)
elif type(model) is DecisionTree:
for i in X_train:
# print(tree.classify(i,dt))
answer = model.classify(i, model.dt)
if 0 in answer:
print("nl")
elif 1 in answer:
print("en")
|
{"/utils.py": ["/features.py", "/classifiers.py"], "/classify.py": ["/utils.py"]}
|
33,898
|
vlraik/Language-classification-using-boosted-decision-trees
|
refs/heads/master
|
/features.py
|
from collections import Counter
def lengthofwords(english, dutch, data):
"""
A function to calculate the average length of words in each of the language.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature1 = []
englishaverage = 0
dutchaverage = 0
for i in english:
for j in i.split():
englishaverage += len(j)
englishaverage = englishaverage / (15 * len(english))
for i in dutch:
for j in i.split():
dutchaverage += len(j)
dutchaverage = dutchaverage / (15 * len(dutch))
threshold = (englishaverage + dutchaverage) / 2
for i in data:
i = i[3:]
total = 0
for j in i.split():
total += len(j)
total = total / 15
if total > threshold:
feature1.append(0)
else:
feature1.append(1)
# returns a boolean feature column based on length of words feature.
return feature1
def freqoflettersinsentence(english, dutch, data):
"""
A feature based on the frequency of letters in each of the languages
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
english = ' '.join(english)
dutch = ' '.join(dutch)
englishcounter = Counter(english)
englishcounter.pop(' ')
dutchcounter = Counter(dutch)
dutchcounter.pop(' ')
englishfeatures = []
dutchfeatures = []
for i in range(10):
englishfeatures.append(max(englishcounter, key=englishcounter.get))
englishcounter.pop(max(englishcounter, key=englishcounter.get))
dutchfeatures.append(max(dutchcounter, key=dutchcounter.get))
dutchcounter.pop(max(dutchcounter, key=dutchcounter.get))
for i in data:
i = i[3:]
datacounter = Counter(i)
datacounter.pop(' ')
datafeatures = []
for j in range(10):
datafeatures.append(max(datacounter, key=datacounter.get))
datacounter.pop(max(datacounter, key=datacounter.get))
englishfault = 0
dutchfault = 0
for a, b, c in zip(datafeatures, englishfeatures, dutchfeatures):
if a != b:
englishfault += 1
if a != c:
dutchfault += 1
if englishfault > dutchfault:
feature.append(0)
else:
feature.append(1)
return feature
def uncommontopletters(english, dutch, data):
"""
A feature based on the most infrequent common letters in both the language. If more of those language
exist in a particular language corpes, we can predict that it's a sentence from that language.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
english = ' '.join(english)
dutch = ' '.join(dutch)
englishcounter = Counter(english)
englishcounter.pop(' ')
dutchcounter = Counter(dutch)
dutchcounter.pop(' ')
englishfeatures = []
dutchfeatures = []
for i in range(10):
englishfeatures.append(max(englishcounter, key=englishcounter.get))
englishcounter.pop(max(englishcounter, key=englishcounter.get))
dutchfeatures.append(max(dutchcounter, key=dutchcounter.get))
dutchcounter.pop(max(dutchcounter, key=dutchcounter.get))
englishset = set(englishfeatures) - set(dutchfeatures)
dutchset = set(dutchfeatures) - set(englishfeatures)
for i in data:
i = i[3:]
datacounter = Counter(i)
datacounter.pop(' ')
datafeatures = []
for j in range(10):
datafeatures.append(max(datacounter, key=datacounter.get))
datacounter.pop(max(datacounter, key=datacounter.get))
englishscore = 0
dutchscore = 0
for j in datafeatures:
if j in englishset:
englishscore += 1
elif j in dutchset:
dutchscore += 1
if englishscore > dutchscore:
feature.append(0)
else:
feature.append(1)
return feature
def worduniqueness(english, dutch, data):
"""
A feature to get how many unique letters are used apart from the commonly occuring letters of the language
in the corpus.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
english = ' '.join(english)
dutch = ' '.join(dutch)
englishcounter = Counter(english)
englishcounter.pop(' ')
dutchcounter = Counter(dutch)
dutchcounter.pop(' ')
englishfeatures = []
dutchfeatures = []
for i in range(10):
englishfeatures.append(max(englishcounter, key=englishcounter.get))
englishcounter.pop(max(englishcounter, key=englishcounter.get))
dutchfeatures.append(max(dutchcounter, key=dutchcounter.get))
dutchcounter.pop(max(dutchcounter, key=dutchcounter.get))
for i in data:
i = i[3:]
englishuniqueletters = 0
dutchuniqueletters = 0
for j in i:
letters = set(j)
englishuniqueletters += len(letters - set(englishfeatures)) / len(letters)
dutchuniqueletters += len(letters - set(dutchfeatures)) / len(letters)
if englishuniqueletters > dutchuniqueletters:
feature.append(0)
else:
feature.append(1)
return feature
def tfidf(english, dutch, data):
"""
A feature to get the most common words from each of the language and check if they exist in the document corpus.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
englishconcat = ' '.join(english)
dutchconcat = ' '.join(dutch)
englishcommon = Counter(englishconcat.split()).most_common()
dutchcommon = Counter(dutchconcat.split()).most_common()
englishcommon = englishcommon[:3]
dutchcommon = dutchcommon[:3]
englishcommon = [i[0] for i in englishcommon]
dutchcommon = [i[0] for i in dutchcommon]
for i in data:
englishscore = 0
dutchscore = 0
i = i[3:]
datawords = i.split()
for j in datawords:
if j in englishcommon:
englishscore += 1
elif j in dutchcommon:
dutchscore += 1
if englishscore > dutchscore:
feature.append(0)
else:
feature.append(1)
return feature
#return [0,0,0,0,0,0,0,0,0,0]
def uniquewordsinsentence(english, dutch, data):
"""
A feature to count the number of unqiue words in a sentence on average.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
englishaverage = 0
for i in english:
englishunique = set(i)
englishaverage += len(englishunique)
dutchaverage = 0
for i in dutch:
dutchunique = set(i)
dutchaverage += len(dutchunique)
englishaverage = englishaverage / len(english)
dutchaverage = dutchaverage / len(dutch)
threshold = (englishaverage + dutchaverage) / 2
for i in data:
i = i[3:]
dataunique = set(i)
dataaverage = len(dataunique)
if dataaverage > threshold:
feature.append(0)
else:
feature.append(1)
return feature
def uniquelettersinasentence(english, dutch, data):
"""
A feature to get the number of unique letters in the document corpus.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
englishaverage = 0
englishunique = set(list(' '.join(english)))
englishunique.remove(' ')
notalpha=[]
for i in englishunique:
if i.isalpha():
continue
else:
notalpha.append(i)
for i in notalpha:
englishunique.remove(i)
englishaverage = len(englishunique)
dutchaverage = 0
dutchunique = set(list(' '.join(dutch)))
dutchunique.remove(' ')
notalpha=[]
for i in dutchunique:
if i.isalpha():
continue
else:
notalpha.append(i)
for i in notalpha:
dutchunique.remove(i)
dutchaverage = len(dutchunique)
threshold = (englishaverage + dutchaverage) / 2
for i in data:
i = i[3:]
dataunique = set(list(' '.join(i)))
dataunique.remove(' ')
dataaverage = len(dataunique)
if dataaverage > threshold:
feature.append(0)
else:
feature.append(1)
return feature
def bigram(english, dutch, data):
"""
A feature to calculate the total number of bigrams in the document corpus.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
englishcounter = 0
for i in english:
for j in i.split():
if len(j) == 2:
englishcounter += 1
englishcounter = englishcounter / len(english)
dutchcounter = 0
for i in dutch:
for j in i.split():
if len(j) == 2:
dutchcounter += 1
dutchcounter = dutchcounter / len(dutch)
threshold = (englishcounter + dutchcounter) / 2
for i in data:
i = i[3:]
datacounter = 0
for j in i.split():
if len(j) == 2:
datacounter += 1
if datacounter > threshold:
feature.append(0)
else:
feature.append(1)
return feature
def trigram(english, dutch, data):
"""
A feature to calculate the total number of trigrams in the document corpus.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
englishcounter = 0
for i in english:
for j in i.split():
if len(j) == 3:
englishcounter += 1
englishcounter = englishcounter / 15
dutchcounter = 0
for i in dutch:
for j in i.split():
if len(j) == 3:
dutchcounter += 1
dutchcounter = dutchcounter / 15
threshold = (englishcounter + dutchcounter) / 2
for i in data:
i = i[3:]
datacounter = 0
for j in i.split():
if len(j) == 3:
datacounter += 1
if datacounter > threshold:
feature.append(0)
else:
feature.append(1)
return feature
def wordswithrepeatingletters(english, dutch, data):
"""
A feauture to count the total number of words with repeating letters.
:param english: English language dataset
:param dutch: Dutch language dataset.
:param data: The entire training data
:return: The feature for each of the samples.
"""
feature = []
englishcount = 0
for i in english:
for j in i.split():
englishset = set(j)
if len(j)-len(englishset) >= 1:
englishcount += 1
#englishcount=englishcount/len(i.split())
englishcount=englishcount/len(english)
dutchcount = 0
for i in dutch:
for j in i.split():
dutchset = set(j)
if len(j)-len(dutchset) >= 1:
dutchcount += 1
#dutchcount=dutchcount/len(i.split())
dutchcount=dutchcount/len(dutch)
threshold = (englishcount + dutchcount) / 2
for i in data:
i = i[3:]
datacounter = 0
for j in i.split():
if len(j)-len(set(j)) >= 1:
datacounter += 1
#datacounter=datacounter/len(i.split())
if datacounter > threshold:
feature.append(0)
else:
feature.append(1)
return feature
#return [0,0,0,0,0,0,0,0,0,0]
|
{"/utils.py": ["/features.py", "/classifiers.py"], "/classify.py": ["/utils.py"]}
|
33,899
|
vlraik/Language-classification-using-boosted-decision-trees
|
refs/heads/master
|
/classify.py
|
from utils import train, predict
def main():
"""
The main function to get the user input.
"""
train('train.dat','out','dt')
predict('test.dat','out')
while(True):
command=input("Enter the option you want to use, type exit to quit: ").split()
if command[0] == 'exit':
exit()
elif command[0] == 'train':
examples = command[1]
hypothesisOut = command[2]
learning_type = command[3]
print("Starting training...")
train(examples, hypothesisOut, learning_type)
print("Training is done.")
elif command[0] == 'predict':
hypothesis = command[1]
file = command[2]
print("Starting to predict...")
print("The predictions are: ")
predictions = predict(hypothesis, file)
if __name__ == '__main__':
main()
|
{"/utils.py": ["/features.py", "/classifiers.py"], "/classify.py": ["/utils.py"]}
|
33,900
|
vlraik/Language-classification-using-boosted-decision-trees
|
refs/heads/master
|
/classifiers.py
|
import numpy as np
class Node:
def __init__(self, question, englishbranch, dutchbranch):
"""
Node intialisation of the decision tree.
:param question: Stores the node information.
:param englishbranch: Datasets splitting into the English Branch
:param dutchbranch: Datasets splitting into the Dutch Branch
"""
self.question = question
self.englishbranch = englishbranch
self.dutchbranch = dutchbranch
class Leaf:
def __init__(self, d, x):
"""
Leaf node initialisation.
:param d: Decision tree object
:param x: Prediction
"""
self.pred = DecisionTree.classcount(d, x)
class DecisionTree:
def __init__(self, X_train, y, maxdepth=5):
"""
Decision tree object intialisation.
:param X_train: Dataset used for training
:param y: The target value for the training dateset.
:param maxdepth: The maximum depth of the decision tree
"""
self.X_train = X_train[:, -1]
self.y = y
self.totaldutch = 0
self.totalenglish = 0
self.maxdepth = maxdepth
self.dt = None
# self.data = np.column_stack((self.X_train, self.y))
def rootnode(self, dt):
"""
A function to declare the rootnode the the decision tree attribute.
:param dt: The root node
"""
self.dt = dt
def build_tree(self, x, depth=5):
"""
A function to build the tree based on the training set.
:param x: Training set
:param depth: Depth of the recursion
:return: The parent node at that level of the decision tree.
"""
gain, question = self.find_best_split(x)
# print(question.val)
# print(question.col)
# print(question)
if gain != 0:
englishrows = []
dutchrows = []
for k in x:
if question.match(k) == False:
dutchrows.append(k)
else:
englishrows.append(k)
englishbranch, dutchbranch = np.asarray(englishrows), np.asarray(dutchrows)
# englishbranch, dutchbranch = self.partition(x, question)
# print(englishbranch)
# print(dutchbranch)
if depth <= self.maxdepth:
depth -= 1
englishbranch = self.build_tree(englishbranch, depth)
dutchbranch = self.build_tree(dutchbranch, depth)
elif gain == 0:
return Leaf(self, x)
return Node(question, englishbranch, dutchbranch)
def classify(self, x, node):
"""
A function for classifying the data based on the decision tree.
:param x: Testing example.
:param node: The root node of the decision tree
:return: The prediction.
"""
if isinstance(node, Leaf):
return node.pred
if node.question.match(x):
return self.classify(x, node.englishbranch)
else:
return self.classify(x, node.dutchbranch)
def classcount(self, x):
"""
A function to get the count of the different labels in the dataset
:param x: The branch of the dataset in which we want to count.
:return: Number of counts.
"""
counts = {}
for i in range(len(x)):
if x[i, -1] in counts:
counts[x[i, -1]] += 1
else:
counts[x[i, -1]] = 1
return counts
def gini(self, x):
"""
A function to get the gini impurity of the dataset.
:param x: The dataset
:return: Gini Impurity
"""
counts = self.classcount(x)
impurity = 1
for i in counts:
prob = counts[i] / float(len(x))
impurity -= prob ** 2
return impurity
def info_gain(self, startnode, left, right):
"""
A function to get the information gain at each node of the decision tree.
:param startnode: The node at which we want to get the information gain.
:param left: The left branch from the node.
:param right: The right branch from the node.
:return: The information gain at that node.
"""
p = float(len(left) / (len(right) + len(left)))
gain = self.gini(startnode) - p * self.gini(left) - (1 - p) * self.gini(right)
return gain
def find_best_split(self, x):
"""
A function to find the based node based on the gini impurity and information gain of node.
:param x: The training dataset.
:return: The gain and the node which we find best divides the dataset.
"""
gain, question = 0, None
for i in range(10):
values = [0, 1]
for j in values:
# print(i,j)
currentquestion = PartitionMatch(i, j)
englishrows = []
dutchrows = []
for k in x:
if currentquestion.match(k) == False:
dutchrows.append(k)
else:
englishrows.append(k)
englishsplit, dutchsplit = np.asarray(englishrows), np.asarray(dutchrows)
if len(englishsplit) == 0 or len(dutchsplit) == 0:
continue
currentgain = self.info_gain(x, englishsplit, dutchsplit)
# print()
if currentgain < gain:
continue
else:
gain = currentgain
question = currentquestion
return gain, question
class PartitionMatch:
def __init__(self, col, val):
"""
Class initialisation to store the structure of the tree.
:param col: The feature which is at the node.
:param val: The value which it predicts.
"""
self.col = col
self.val = val
def match(self, sample):
"""
A function to get what a particular node predicts.
:param sample: The value of the feature.
:return: Binary, the prediction.
"""
return sample[self.col] == self.val
class Adaboost():
def __init__(self, X_train, y, n_trees=2):
"""
Initialisation of the adaboost class.
:param X_train: The training dataset.
:param y: The target value
:param n_trees: Number of decision stump inside the adaboost.
"""
self.n_trees = n_trees
self.y = y
self.X_train = X_train
def train(self, X_train):
"""
A function to train the dataset on adaboost.
:param X_train: The training dataset.
"""
exampleweight = [1 / len(X_train)] * len(X_train)
modelweight = [0.5] * self.n_trees
models = [None] * self.n_trees
dt = [None] * self.n_trees
for epoch in range(20):
for i in range(self.n_trees):
randomsamplesindex = [i for i in range(len(X_train))]
index = np.random.choice(randomsamplesindex, len(X_train) // self.n_trees, p=exampleweight)
randomsamples = [X_train[i] for i in index]
randomsamples = np.asarray(randomsamples)
models[i] = DecisionTree(randomsamples, randomsamples[:, -1], maxdepth=5)
dt[i] = models[i].build_tree(randomsamples)
answers = []
for j in X_train:
if 0 in models[i].classify(j, dt[i]):
answers.append("nl|")
elif 1 in models[i].classify(j, dt[i]):
answers.append("en|")
accuracy = 0
for j in range(len(answers)):
if answers[j] == self.y[j]:
accuracy += 1
# exampleweight[j]-=exampleweight[j]/2
elif answers[j] != self.y[i]:
# exampleweight[j]=1/(len(X_train)-0.2*len(X_train))
pass
for j in range(len(answers)):
if accuracy != 0:
for j in range(len(answers)):
if answers[j] == self.y[j]:
exampleweight[j] = 1 / (accuracy / 0.4)
elif answers[j] != self.y[j]:
exampleweight[j] = 1 / ((len(X_train) - accuracy) / 0.6)
accuracy = accuracy / len(answers)
if accuracy == 0.5:
modelweight[i] = 0
elif accuracy > 0.5:
modelweight[i] = 1
elif accuracy < 0.5:
modelweight[i] = -1
self.modelweight = modelweight
self.models = models
self.dt = dt
def classify(self, X_train):
"""
A function to classify a test example based on the adaboost training.
:param X_train: The test example dataset.
"""
modelweight = self.modelweight
models = self.models
dt = self.dt
finalresults = [None] * self.n_trees
for i in range(self.n_trees):
answers = []
for j in X_train:
answers.append(models[i].classify(j, dt[i]))
finalresults[i] = answers
averageresult = [0] * len(self.y)
for j in range(len(self.y)):
for i in range(len(finalresults)):
for k in finalresults[i][j]:
if 0 == k:
averageresult[j] += modelweight[i] * 0
elif 1 == k:
averageresult[j] += modelweight[i] * 1
averageresult[j] = averageresult[j] / sum(modelweight)
for i in averageresult:
if i > 0.5:
print("en")
else:
print("nl")
|
{"/utils.py": ["/features.py", "/classifiers.py"], "/classify.py": ["/utils.py"]}
|
33,902
|
msomierick/chempy
|
refs/heads/master
|
/chempy/printing/numbers.py
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ..util.parsing import _unicode_sup
def roman(num):
"""
Examples
--------
>>> roman(4)
'IV'
>>> roman(17)
'XVII'
"""
tokens = 'M CM D CD C XC L XL X IX V IV I'.split()
values = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
result = ''
for t, v in zip(tokens, values):
cnt = num//v
result += t*cnt
num -= v*cnt
return result
def number_to_scientific_latex(number, fmt='%.3g'):
r"""
Examples
--------
>>> number_to_scientific_latex(3.14) == '3.14'
True
>>> number_to_scientific_latex(3.14159265e-7)
'3.14\\cdot 10^{-7}'
>>> import quantities as pq
>>> number_to_scientific_latex(2**0.5 * pq.m / pq.s)
'1.41 \\mathrm{\\frac{m}{s}}'
"""
try:
unit = ' ' + number.dimensionality.latex.strip('$')
number = number.magnitude
except AttributeError:
unit = ''
s = fmt % number
if 'e' in s:
prefix, suffix = s.split('e')
if prefix in ('1', '1.0'):
result = '10^{%s}'
else:
result = prefix + r'\cdot 10^{%s}'
return result % str(int(suffix)) + unit
else:
return s + unit
def number_to_scientific_unicode(number, fmt='%.3g'):
u"""
Examples
--------
>>> number_to_scientific_unicode(3.14) == u'3.14'
True
>>> number_to_scientific_unicode(3.14159265e-7) == u'3.14Β·10β»β·'
True
>>> import quantities as pq
>>> number_to_scientific_unicode(2**0.5 * pq.m / pq.s)
'1.41 m/s'
"""
try:
unit = ' ' + number.dimensionality.unicode
number = number.magnitude
except AttributeError:
unit = ''
s = fmt % number
if 'e' in s:
prefix, suffix = s.split('e')
if prefix in ('1', '1.0'):
result = u'10'
else:
result = prefix + u'Β·10'
return result + u''.join(map(_unicode_sup.get, str(int(suffix)))) + unit
else:
return s + unit
def number_to_scientific_html(number, fmt='%.3g'):
"""
Examples
--------
>>> number_to_scientific_html(3.14) == '3.14'
True
>>> number_to_scientific_html(3.14159265e-7)
'3.14⋅10<sup>-7</sup>'
>>> number_to_scientific_html(1e13)
'10<sup>13</sup>'
>>> import quantities as pq
>>> number_to_scientific_html(2**0.5 * pq.m / pq.s)
'1.41 m/s'
"""
try:
unit = ' ' + str(number.dimensionality)
number = number.magnitude
except AttributeError:
unit = ''
s = fmt % number
if 'e' in s:
prefix, suffix = s.split('e')
if prefix in ('1', '1.0'):
result = '10<sup>'
else:
result = prefix + '⋅10<sup>'
return result + str(int(suffix)) + '</sup>' + unit
else:
return s + unit
|
{"/chempy/printing/tests/test_numbers.py": ["/chempy/printing/numbers.py"]}
|
33,903
|
msomierick/chempy
|
refs/heads/master
|
/setup.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import shutil
from setuptools import setup
pkg_name = "chempy"
RELEASE_VERSION = os.environ.get('CHEMPY_RELEASE_VERSION', '')
# http://conda.pydata.org/docs/build.html#environment-variables-set-during-the-build-process
if os.environ.get('CONDA_BUILD', '0') == '1':
try:
RELEASE_VERSION = 'v' + io.open(
'__conda_version__.txt', 'rt', encoding='utf-8'
).readline().rstrip()
except IOError:
pass
def _path_under_setup(*args):
return os.path.join(os.path.dirname(__file__), *args)
release_py_path = _path_under_setup(pkg_name, '_release.py')
if (len(RELEASE_VERSION) > 1 and RELEASE_VERSION[0] == 'v'):
TAGGED_RELEASE = True
__version__ = RELEASE_VERSION[1:]
else:
TAGGED_RELEASE = False
# read __version__ attribute from _release.py:
exec(io.open(release_py_path, encoding='utf-8').read())
submodules = [
'chempy.kinetics',
'chempy.properties',
'chempy.util',
'chempy.electrochemistry',
'chempy.printing',
]
tests = [
'chempy.tests',
'chempy.kinetics.tests',
'chempy.properties.tests',
'chempy.util.tests',
'chempy.electrochemistry.tests',
'chempy.printing.tests',
]
classifiers = [
"Development Status :: 3 - Alpha",
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
with io.open(_path_under_setup(pkg_name, '__init__.py'), 'rt',
encoding='utf-8') as f:
short_description = f.read().split('"""')[1].split('\n')[1]
assert 10 < len(short_description) < 255
long_descr = io.open(_path_under_setup('README.rst'), encoding='utf-8').read()
assert len(long_descr) > 100
setup_kwargs = {
'name': pkg_name,
'version': __version__,
'description': short_description,
'long_description': long_descr,
'author': 'BjΓΆrn Dahlgren',
'author_email': 'bjodah@DELETEMEgmail.com',
'license': 'BSD',
'keywords': ("chemistry", "water properties", "physical chemistry"),
'url': 'https://github.com/bjodah/' + pkg_name,
'packages': [pkg_name] + submodules + tests,
'classifiers': classifiers,
'install_requires': [
'numpy>1.7', 'scipy>=0.16.1', 'matplotlib>=1.3.1',
'sympy>=0.7.6.1', 'quantities>=0.11.1', 'pyneqsys>=0.3.0',
'pyodesys>=0.5.0', 'pyparsing>=2.0.3'
# 'dot2tex>=2.9.0'
],
'extras_require': {
'all': ['argh', 'pycvodes', 'pygslodeiv2', 'pyodeint', 'pykinsol',
'pytest>=2.8.1', 'pytest-pep8>=1.0.6', 'bokeh>=0.11.1']}
}
if __name__ == '__main__':
try:
if TAGGED_RELEASE:
# Same commit should generate different sdist
# depending on tagged version (set CHEMPY_RELEASE_VERSION)
# this will ensure source distributions contain the correct version
shutil.move(release_py_path, release_py_path+'__temp__')
open(release_py_path, 'wt').write(
"__version__ = '{}'\n".format(__version__))
setup(**setup_kwargs)
finally:
if TAGGED_RELEASE:
shutil.move(release_py_path+'__temp__', release_py_path)
|
{"/chempy/printing/tests/test_numbers.py": ["/chempy/printing/numbers.py"]}
|
33,904
|
msomierick/chempy
|
refs/heads/master
|
/chempy/util/regression.py
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
try:
import numpy as np
except ImportError:
np = None
import warnings
def least_squares(x, y, w=1): # w == 1 => OLS, w != 1 => WLS
""" Least-squares (w or w/o weights) fit to data series.
Linear regression (unweighted or weighted).
Parameters
----------
x : array_like
y : array_like
w : array_like, optional
Returns
-------
length 2 tuple : pair of parameter estimates (intercept and slope)
2x2 array : variance-covariance matrix
float : R-squared (goodness of fit)
Examples
--------
>>> beta, vcv, R2 = least_squares([0, 1, 2], [1, 3, 5])
>>> all(abs(beta - [1, 2]) < 1e-14), R2 == 1, (abs(vcv) < 1e-14).all()
(True, True, True)
>>> b1, v1, r2_1 = least_squares([1, 2, 3], [0, 1, 4], [1, 1, 1])
>>> b2, v2, r2_2 = least_squares([1, 2, 3], [0, 1, 4], [1, 1, .2])
>>> abs(b2[1] - 1) < abs(b1[1] - 1)
True
References
----------
Wikipedia & standard texts on least sqaures method.
Comment regarding R2 in WLS:
Willett, John B., and Judith D. Singer. "Another cautionary note about R 2:
Its use in weighted least-squares regression analysis."
The American Statistician 42.3 (1988): 236-238.
"""
sqrtw = np.sqrt(w)
y = np.asarray(y) * sqrtw
x = np.asarray(x)
X = np.ones((x.size, 2))
X[:, 1] = x
if hasattr(sqrtw, 'ndim') and sqrtw.ndim == 1:
sqrtw = sqrtw.reshape((sqrtw.size, 1))
X *= sqrtw
beta = np.linalg.lstsq(X, y)[0]
eps = X.dot(beta) - y
SSR = eps.T.dot(eps) # sum of squared residuals
vcv = SSR/(x.size - 2)*np.linalg.inv(X.T.dot(X))
TSS = np.sum(np.square(y - np.mean(y))) # total sum of squares
R2 = 1 - SSR/TSS
return beta, vcv, float(R2)
def irls(x, y, w_cb=lambda x, y, b, c: x**0, itermax=16, rmsdwtol=1e-8, full_output=False):
""" Iteratively reweighted least squares
Parameters
----------
x : array_like
y : array_like
w_cb : callbable
signature (x, y, beta, cov) -> weight
itermax : int
rmsdwtol : float
full_output : bool
Returns
-------
beta : length-2 array
parameters
cov : 2x2 array
variance-covariance matrix
info : dict
if ``full_output == True``, keys:
- weights
- niter
"""
if itermax < 1:
raise ValueError("intermax must be >= 1")
weights = []
w = np.ones_like(x)
rmsdw = np.inf
ii = 0
while rmsdw > rmsdwtol and ii < itermax:
weights.append(w)
beta, cov, r2 = least_squares(x, y, w)
old_w = w.copy()
w = w_cb(x, y, beta, cov)
rmsdw = np.sqrt(np.mean(np.square(w - old_w)))
ii += 1
if ii == itermax:
warnings.warn('itermax reached')
if full_output:
return beta, cov, {'weights': weights, 'niter': ii, 'success': ii < itermax}
else:
return beta, cov
irls.ones = lambda x, y, b, c: 1
if np is not None:
irls.exp = lambda x, y, b, c: np.exp(b[1]*x)
irls.gaussian = lambda x, y, b, c: np.exp(-(b[1]*x)**2) # guassian weighting
irls.abs_residuals = lambda x, y, b, c: np.abs(np.exp(b[0] + b[1]*x) - np.exp(y))
def plot_fit(x, y, beta, kw_data=None, kw_fit=None):
import matplotlib.pyplot as plt
kw_data, kw_fit = kw_data or {}, kw_fit or {}
plt.plot(x, y, linestyle='None', **kw_data)
plt.plot(x[[0, -1]], beta[0] + beta[1]*x[[0, -1]], marker='None', **kw_fit)
def avg_params(opt_params, cov_params, label_cb=None, plot=False):
var_beta = np.vstack((cov_params[:, 0, 0], cov_params[:, 1, 1])).T
avg_beta, sum_of_weights = np.average(opt_params, axis=0, weights=1/var_beta, returned=True)
var_avg_beta = np.sum(np.square(opt_params - avg_beta)/var_beta, axis=0)/((avg_beta.shape[0] - 1) * sum_of_weights)
if plot:
import matplotlib.pyplot as plt
if label_cb is not None:
lbl = label_cb(avg_beta, var_avg_beta)
else:
lbl = None
plt.errorbar(opt_params[:, 0], opt_params[:, 1], marker='s', ls='None',
xerr=var_beta[:, 0]**0.5, yerr=var_beta[:, 1]**0.5)
plt.xlabel(r'$\beta_0$')
plt.ylabel(r'$\beta_1$')
plt.title(r'$y(x) = \beta_0 + \beta_1 \cdot x$')
plt.errorbar(avg_beta[0], avg_beta[1], xerr=var_avg_beta[0]**0.5, yerr=var_avg_beta[1]**0.5, marker='o', c='r',
linewidth=2, markersize=10, label=lbl)
plt.legend(numpoints=1)
return avg_beta, var_avg_beta
|
{"/chempy/printing/tests/test_numbers.py": ["/chempy/printing/numbers.py"]}
|
33,905
|
msomierick/chempy
|
refs/heads/master
|
/chempy/printing/tests/test_numbers.py
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from ..numbers import roman, number_to_scientific_html, number_to_scientific_latex, number_to_scientific_unicode
def test_roman():
assert roman(4) == 'IV'
assert roman(20) == 'XX'
assert roman(94) == 'XCIV'
assert roman(501) == 'DI'
def test_number_to_scientific_html():
assert number_to_scientific_html(2e-17) == '2⋅10<sup>-17</sup>'
assert number_to_scientific_html(1e-17) == '10<sup>-17</sup>'
def test_number_to_scientific_latex():
assert number_to_scientific_latex(2e-17) == r'2\cdot 10^{-17}'
assert number_to_scientific_latex(1e-17) == '10^{-17}'
def test_number_to_scientific_unicode():
assert number_to_scientific_unicode(2e-17) == u'2Β·10β»ΒΉβ·'
assert number_to_scientific_unicode(1e-17) == u'10β»ΒΉβ·'
|
{"/chempy/printing/tests/test_numbers.py": ["/chempy/printing/numbers.py"]}
|
33,906
|
msomierick/chempy
|
refs/heads/master
|
/chempy/util/_aqueous.py
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from itertools import chain
from .periodic import groups, symbols, names
_anions = {
'F-': 'fluoride',
'Cl-': 'chloride',
'Br-': 'bromide',
'I-': 'iodide',
'OH-': 'hydroxide',
'CN-': 'cyanide',
'SCN-': 'thiocyanate',
'SO4-2': 'sulphate',
'HSO4-': 'hydrogensulphate',
'PO4-3': 'phospahte',
'HPO4-2': 'hydrogenphospahte',
'H2PO4-': 'dihydrogenphospahte',
'NO3-': 'nitrate',
'NO2-': 'nitrite',
'ClO-': 'hypochlorite',
'ClO2-': 'chlorite',
'ClO3-': 'chlorate',
'ClO4-': 'perchlorate',
}
_alkali = [
(symbols[n]+'+', names[n].lower()) for n in groups[1]
]
_alkaline_earth = [
(symbols[n]+'+2', names[n].lower()) for n in groups[2]
]
_all_names = dict(chain(_alkali, _alkaline_earth, _anions.items()))
def name(ion):
return _all_names[ion]
|
{"/chempy/printing/tests/test_numbers.py": ["/chempy/printing/numbers.py"]}
|
33,930
|
lvaka/photoportfolio
|
refs/heads/master
|
/portfolio/folio/urls.py
|
from django.conf.urls import url, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from . import views
urlpatterns = [
url(r'^$', views.main_page, name='main_page'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
{"/portfolio/folio/admin.py": ["/portfolio/folio/models.py"], "/portfolio/folio/views.py": ["/portfolio/folio/models.py"]}
|
33,931
|
lvaka/photoportfolio
|
refs/heads/master
|
/portfolio/folio/admin.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import Picture
# Register your models here.
admin.site.register(Picture)
|
{"/portfolio/folio/admin.py": ["/portfolio/folio/models.py"], "/portfolio/folio/views.py": ["/portfolio/folio/models.py"]}
|
33,932
|
lvaka/photoportfolio
|
refs/heads/master
|
/portfolio/folio/models.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Picture(models.Model):
name = models.CharField(max_length=40)
image = models.ImageField(upload_to="image/")
def __str__(self):
return self.name
|
{"/portfolio/folio/admin.py": ["/portfolio/folio/models.py"], "/portfolio/folio/views.py": ["/portfolio/folio/models.py"]}
|
33,933
|
lvaka/photoportfolio
|
refs/heads/master
|
/portfolio/folio/views.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.utils import timezone
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.conf import settings
from django.http import HttpResponse
from .models import Picture
from .forms import PictureForm
# Create your views here.
def main_page(request):
if request.method == "POST":
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
form.save()
HttpResponse('image upload success')
form = PictureForm()
return redirect('main_page')
else:
return HttpResponse('image upload failed')
else:
form = PictureForm()
pics = Picture.objects.order_by('-pk')
return render(request, 'folio/main.html', {'form': form, 'pics' : pics})
|
{"/portfolio/folio/admin.py": ["/portfolio/folio/models.py"], "/portfolio/folio/views.py": ["/portfolio/folio/models.py"]}
|
33,961
|
aleksandr-kazakov/testukas
|
refs/heads/master
|
/app1/models.py
|
from django.db import models
class Question(models.Model):
Q = models.TextField()
A1 = models.TextField()
A2 = models.TextField()
A3 = models.TextField()
A4 = models.TextField()
A5 = models.TextField()
A6 = models.TextField()
QType = models.TextField()
RightAnswer = models.CharField(max_length = 6)
Source = models.URLField()
Comment = models.TextField()
|
{"/app1/views.py": ["/app1/models.py"]}
|
33,962
|
aleksandr-kazakov/testukas
|
refs/heads/master
|
/testukas/urls.py
|
from django.conf.urls import include, url
from django.contrib import admin
from app1 import views
urlpatterns = [
# Examples:
# url(r'^$', 'testukas.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^question/(?P<id>\d+)/', views.question_detail, name='question_detail'),
url(r'^$', views.index, name='index'),
]
|
{"/app1/views.py": ["/app1/models.py"]}
|
33,963
|
aleksandr-kazakov/testukas
|
refs/heads/master
|
/app1/views.py
|
from django.shortcuts import render
from django.http import Http404
from app1.models import Question
# Create your views here.
def index(request):
questions = Question.objects.all()
return render(request, 'app1/index.html', {
'questions': questions,
})
def question_detail(request, id):
try:
question = Question.objects.get(id=id)
except Question.DoesNotExist:
raise Http404('This question does not exist')
return render(request, 'app1/question_detail.html', {
'question': question,
})
|
{"/app1/views.py": ["/app1/models.py"]}
|
33,978
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/tests/test_usecase1.py
|
import unittest
from unittest import TestCase
import os
from unittest.mock import MagicMock
import openeo
import requests_mock
POST_DATA = '{"process_id": "filter_daterange", "args": { "imagery": { "product_id": "landsat7_ndvi"}, "from": "2014-01-01", "to": "2014-06-01"}}'
@requests_mock.mock()
class TestUsecase1(TestCase):
def setUp(self):
# configuration phase: define username, endpoint, parameters?
self.endpoint = "http://localhost:8000/api"
self.uiser_id = "174367998144"
self.auth_id = "test"
self.auth_pwd = "test"
self.data_id= "sentinel2_subset"
self.process_id = "calculate_ndvi"
self.output_file = "/home/berni/test.gtiff"
def test_user_login(self, m):
m.get("http://localhost:8000/api/auth/login", json={"token": "blabla"})
session = openeo.session(self.uiser_id, endpoint=self.endpoint)
token = session.auth(self.auth_id, self.auth_pwd)
self.assertNotEqual(token, None)
def test_viewing_userjobs(self, m):
m.get("http://localhost:8000/api/auth/login", json={"token": "blabla"})
m.get("http://localhost:8000/api/users/%s/jobs" % self.uiser_id, json=[{"job_id": "748df7caa8c84a7ff6e"}])
session = openeo.session(self.uiser_id, endpoint=self.endpoint)
session.auth(self.auth_id, self.auth_pwd)
userjobs = session.user_jobs()
self.assertGreater(len(userjobs), 0)
def test_viewing_data(self, m):
m.get("http://localhost:8000/api/data", json=[{"product_id": "sentinel2_subset"}])
m.get("http://localhost:8000/api/data/sentinel2_subset", json={"product_id": "sentinel2_subset"})
session = openeo.session(self.uiser_id, endpoint=self.endpoint)
data = session.list_collections()
self.assertGreater(str(data).find(self.data_id), -1)
data_info = session.get_collection(self.data_id)
self.assertEqual(data_info["product_id"], self.data_id)
def test_viewing_processes(self, m):
m.get("http://localhost:8000/api/processes", json=[{"process_id": "calculate_ndvi"}])
m.get("http://localhost:8000/api/processes/calculate_ndvi", json={"process_id": "calculate_ndvi"})
session = openeo.session(self.uiser_id, endpoint=self.endpoint)
processes = session.get_all_processes()
self.assertGreater(str(processes).find(self.process_id), -1)
process_info = session.get_process(self.process_id)
self.assertEqual(process_info["process_id"], self.process_id)
def test_job_creation(self, m):
m.get("http://localhost:8000/api/auth/login", json={"token": "blabla"})
m.post("http://localhost:8000/api/jobs?evaluate=lazy", json={"job_id": "748df7caa8c84a7ff6e"})
session = openeo.session(self.uiser_id, endpoint=self.endpoint)
session.auth(self.auth_id, self.auth_pwd)
job_id = session.create_job(POST_DATA)
self.assertIsNotNone(job_id)
#session.download_image(job_id, self.output_file,"image/gtiff")
# self.assertTrue(os.path.isfile(self.output_file))
if __name__ == '__main__':
unittest.main()
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,979
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/openeo/job.py
|
from abc import ABC
class Job(ABC):
"""Represents the result of creating a new Job out of a process graph. Jobs are stored in the
backend and can be executed directly (in batch), or evaluated lazily."""
def __init__(self, job_id: str):
self.job_id = job_id
def download(self, outputfile: str, outputformat: str):
""" Download the result as a raster."""
pass
# TODO: Maybe add a job status class.
def status(self):
""" Returns the status of the job."""
pass
def queue(self):
""" Queues the job. """
pass
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,980
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/tests/test_rest_session.py
|
# -*- coding: utf-8 -*-
import openeo
from unittest import TestCase
import tempfile
import os
import json
import requests_mock
@requests_mock.mock()
class TestUserFiles(TestCase):
def setUp(self):
# configuration phase: define username, endpoint, parameters?
self.endpoint = "http://localhost:8000/api"
self.user_id = "174367998144"
self.auth_id = "test"
self.auth_pwd = "test"
self.upload_remote_fname = 'polygon.json'
self.upload_local_fname = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'polygon.json')
def match_uploaded_file(self, request):
with open(self.upload_local_fname, 'r') as uploaded_file:
content = uploaded_file.read()
assert request.json() == json.loads(content)
return True
def test_user_upload_file(self, m):
upload_url ="http://localhost:8000/api/users/{}/files/{}".format(self.user_id,
self.upload_remote_fname)
m.register_uri('PUT', upload_url,
additional_matcher=self.match_uploaded_file)
session = openeo.session(self.user_id, endpoint=self.endpoint)
session.auth(self.auth_id, self.auth_pwd)
status = session.user_upload_file(self.upload_local_fname,
remote_path=self.upload_remote_fname)
assert status
def test_user_download_file(self, m):
download_url ="http://localhost:8000/api/users/{}/files/{}".format(self.user_id,
self.upload_remote_fname)
with open(self.upload_local_fname, 'rb') as response_file:
content = response_file.read()
m.get(download_url, content=content)
session = openeo.session(self.user_id, endpoint=self.endpoint)
session.auth(self.auth_id, self.auth_pwd)
local_output_fname = tempfile.NamedTemporaryFile()
status = session.user_download_file(self.upload_remote_fname,
local_output_fname.name)
assert status
with open(local_output_fname.name, 'rb') as downloaded_file:
downloaded_content = downloaded_file.read()
assert content == downloaded_content
def test_user_delete_file(self, m):
delete_url ="http://localhost:8000/api/users/{}/files/{}".format(self.user_id,
self.upload_remote_fname)
m.register_uri('DELETE', delete_url)
session = openeo.session(self.user_id, endpoint=self.endpoint)
session.auth(self.auth_id, self.auth_pwd)
status = session.user_delete_file(self.upload_remote_fname)
assert status
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,981
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/setup.py
|
import re
from setuptools import setup, find_packages
from sphinx.setup_command import BuildDoc
test_requirements = ['requests','mock']
cmdclass = {'build_sphinx': BuildDoc}
with open('openeo/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
name = 'openeo-api'
setup(name=name,
version=version,
author='Jeroen Dries',
author_email='jeroen.dries@vito.be',
description='Client API for OpenEO',
packages=find_packages(include=['openeo*']),
test_requirements=['requests-mock'],
install_requires=['requests','shapely==1.6.4'],
)
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,982
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/openeo/rest/job.py
|
from openeo.rest.rest_session import RESTSession
from ..job import Job
class ClientJob(Job):
def __init__(self, job_id: str, session:RESTSession):
super().__init__(job_id)
self.session = session
def download(self, outputfile:str, outputformat=None):
""" Download the result as a raster."""
try:
return self.session.download_job(self.job_id, outputfile, outputformat)
except ConnectionAbortedError as e:
return print(str(e))
def status(self):
""" Returns the status of the job."""
return self.session.job_status(self.job_id)
def queue(self):
""" Queues the job. """
return self.session.queue_job(self.job_id)
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,983
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/openeo/rest/rest_session.py
|
import datetime
import shutil
import os
import requests
from ..auth.auth_none import NoneAuth
import json
from ..sessions import Session
"""
openeo.sessions
~~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings when interacting with the OpenEO API.
"""
class RESTSession(Session):
def __init__(self,userid, endpoint):
# TODO: Maybe in future only the endpoint is needed, because of some kind of User object inside of the session.
"""
Constructor of RESTSession
:param userid: String User login credential
:param endpoint: String Backend endpoint url
"""
self.userid = userid
self.endpoint = endpoint
self.root = ""
self.authent = NoneAuth("none", "none", endpoint)
def auth(self, username, password, auth_class=NoneAuth) -> bool:
"""
Authenticates a user to the backend using auth class.
:param username: String Username credential of the user
:param password: String Password credential of the user
:param auth_class: Auth instance of the abstract Auth class
:return: token: String Bearer token
"""
self.authent = auth_class(username, password, self.endpoint)
status = self.authent.login()
return status
def user_jobs(self) -> dict:
#TODO: Create a kind of User class to abstract the information (e.g. userid, username, password from the session.
"""
Loads all jobs of the current user.
:return: jobs: Dict All jobs of the user
"""
jobs = self.get(self.root + '/users/{}/jobs'.format(self.userid))
return self.parse_json_response(jobs)
def list_collections(self) -> dict:
"""
Loads all available imagecollections types.
:return: data_dict: Dict All available data types
"""
data = self.get(self.root + '/data', auth=False)
return self.parse_json_response(data)
def list_capabilities(self) -> dict:
"""
Loads all available capabilities.
:return: data_dict: Dict All available data types
"""
data = self.get(self.root + '/capabilities', auth=False)
return self.parse_json_response(data)
def get_outputformats(self) -> dict:
"""
Loads all available output formats.
:return: data_dict: Dict All available output formats
"""
data = self.get(self.root + '/capabilities/output_formats', auth=False)
return self.parse_json_response(data)
def get_collection(self, col_id) -> dict:
# TODO: Maybe create some kind of Data class.
"""
Loads detailed information of a specific image collection.
:param col_id: String Id of the collection
:return: data_dict: Dict Detailed information about the collection
"""
if col_id:
data_info = self.get(self.root + '/data/{}'.format(col_id), auth=False)
return self.parse_json_response(data_info)
else:
raise ValueError("Invalid argument col_id: "+ str(col_id))
def get_all_processes(self) -> dict:
# TODO: Maybe format the result dictionary so that the process_id is the key of the dictionary.
"""
Loads all available processes of the back end.
:return: processes_dict: Dict All available processes of the back end.
"""
processes = self.get('/processes', auth=False)
return self.parse_json_response(processes)
def get_process(self, process_id) -> dict:
# TODO: Maybe create some kind of Process class.
"""
Get detailed information about a specifig process.
:param process_id: String Process identifier
:return: processes_dict: Dict with the detail information about the
process
"""
if process_id:
process_info = self.get('/processes/{}'.format(process_id), auth=False)
processes_dict = self.parse_json_response(process_info)
else:
processes_dict = None
return processes_dict
def create_job(self, post_data, evaluation="lazy") -> str:
# TODO: Create a Job class or something for the creation of a nested process execution...
"""
Posts a job to the back end including the evaluation information.
:param post_data: String data of the job (e.g. process graph)
:param evaluation: String Option for the evaluation of the job
:return: job_id: String Job id of the new created job
"""
job_status = self.post("/jobs?evaluate={}".format(evaluation), post_data)
if job_status.status_code == 200:
job_info = json.loads(job_status.text)
if 'job_id' in job_info:
job_id = job_info['job_id']
else:
job_id = None
return job_id
def imagecollection(self, image_collection_id) -> 'ImageCollection':
"""
Get imagecollection by id.
:param image_collection_id: String image collection identifier
:return: collection: RestImageCollection the imagecollection with the id
"""
from .imagery import RestImagery
collection = RestImagery({'collection_id': image_collection_id}, self)
# read and format extent, band and date availability information
data_info = self.get_collection(image_collection_id)
collection.bands = []
if data_info:
if "bands" in data_info:
for band in data_info['bands']: collection.bands.append(band['band_id'])
if "time" in data_info:
collection.dates = data_info['time']
if "extent" in data_info:
collection.extent = data_info['extent']
else:
collection.bands = ['not specified']
collection.dates = ['not specified']
collection.extent = ['not specified']
return collection
def image(self, image_product_id) -> 'ImageCollection':
"""
Get imagery by id.
:param image_collection_id: String image collection identifier
:return: collection: RestImagery the imagery with the id
"""
from .imagery import RestImagery
image = RestImagery({'product_id': image_product_id}, self)
# read and format extent, band and date availability information
data_info = self.get_collection(image_product_id)
image.bands = []
if data_info:
for band in data_info['bands']: image.bands.append(band['band_id'])
image.dates = data_info['time']
image.extent = data_info['extent']
else:
image.bands = ['not specified']
image.dates = ['not specified']
image.extent = ['not specified']
return image
def point_timeseries(self, graph, x, y, srs):
"""Compute a timeseries for a given point location."""
return self.post(self.root + "/timeseries/point?x={}&y={}&srs={}".format(x,y,srs),graph)
def tiled_viewing_service(self,graph):
return self.parse_json_response(self.post(self.root + "/tile_service",graph))
def queue_job(self, job_id):
"""
Queue the job with a specific id.
:param job_id: String job identifier
:return: status_code: Integer Rest Response status code
"""
request = self.patch("/jobs/{}/queue".format(job_id))
return request.status_code
def job_status(self, job_id):
# TODO: Maybe add a JobStatus class.
"""
Get status of a specific job.
:param job_id: String job identifier
:return: status: Dict Status JSON of the job
"""
request = self.get("/jobs/{}".format(job_id))
return self.parse_json_response(request)
def user_download_file(self, file_path, output_file):
"""
Downloads a user file to the back end.
:param file_path: remote path to the file that should be downloaded.
:param output_file: local path, where the file should be saved.
:return: status: True if it was successful, False otherwise
"""
path = "/users/{}/files/{}".format(self.userid, file_path)
resp = self.get(path, stream=True)
if resp.status_code == 200:
with open(output_file, 'wb') as f:
shutil.copyfileobj(resp.raw, f)
return True
else:
return False
def user_upload_file(self, file_path, remote_path=None):
"""
Uploads a user file to the back end.
:param file_path: Local path to the file that should be uploaded.
:param remote_path: Remote path of the file where it should be uploaded.
:return: status: True if it was successful, False otherwise
"""
if not os.path.isfile(file_path):
return False
if not remote_path:
remote_path = os.path.basename(file_path)
input_file = open(file_path, 'rb').read()
path = "/users/{}/files/{}".format(self.userid, remote_path)
content_type = {'Content-Type': 'application/octet-stream'}
resp = self.put(path=path, header=content_type, data=input_file)
if resp.status_code == 200:
return True
else:
return False
def user_delete_file(self, file_path):
"""
Deletes a user file in the back end.
:param file_path: remote path to the file that should be deleted.
:return: status: True if it was successful, False otherwise
"""
path = "/users/{}/files/{}".format(self.userid, file_path)
resp = self.delete(path)
if resp.status_code == 200:
return True
else:
return False
def user_list_files(self):
"""
Lists all files that the logged in user uploaded.
:return: file_list: List of the user uploaded files.
"""
files = self.get('/users/{}/files'.format(self.userid))
return self.parse_json_response(files)
# TODO: Maybe rename to execute and merge with execute().
# Depricated function, use download_job instead.
def download(self, graph, time, outputfile, format_options):
"""
Downloads a result of a process graph synchronously.
:param graph: Dict representing a process graph
:param time: dba
:param outputfile: output file
:param format_options: formating options
:return: job_id: String
"""
download_url = self.endpoint + self.root + "/execute"
request = {
"process_graph": graph,
"output": format_options
}
r = requests.post(download_url, json=request, stream = True, timeout=1000 )
if r.status_code == 200:
with open(outputfile, 'wb') as f:
shutil.copyfileobj(r.raw, f)
else:
raise IOError("Received an exception from the server for url: {} and POST message: {}".format(download_url,json.dumps( request ) ) + r.text)
return
def download_job(self, job_id, outputfile, outputformat=None):
"""
Download an executed job.
:param job_id: String job identifier
:param outputfile: String destination path of the resulting file.
:param outputformat: String format of the resulting file
:return: status: Dict Status JSON of the resulting job
"""
if outputformat:
download_url = "/jobs/{}/download?format={}".format(job_id,outputformat)
else:
download_url = "/jobs/{}/download".format(job_id)
r = self.get(download_url, stream = True)
if r.status_code == 200:
url = r.json()
download_url = url[0]
auth_header = self.authent.get_header()
with open(outputfile, 'wb') as handle:
response = requests.get(download_url, stream=True, headers=auth_header)
if not response.ok:
print (response)
for block in response.iter_content(1024):
if not block:
break
handle.write(block)
else:
raise ConnectionAbortedError(r.text)
return r.status_code
def execute(self, graph):
"""
Execute a process graph synchronously.
:param graph: Dict representing a process graph
:return: job_id: String
"""
response = self.post(self.root + "/execute", graph)
return self.parse_json_response(response)
def job(self, graph):
"""
Submits a new job to the back-end.
:param graph: Dict representing a process graph
:return: job_id: String
"""
response = self.post(self.root + "/jobs", graph)
return self.parse_json_response(response).get("job_id","")
def parse_json_response(self, response: requests.Response):
"""
Parses json response, if an error occurs it raises an Exception.
:param response: Response of a RESTful request
:return: response: JSON Response
"""
if response.status_code == 200:
return response.json()
elif response.status_code == 502:
from requests.exceptions import ProxyError
return ProxyError("The proxy returned an error, this could be due to a timeout.")
else:
raise ConnectionAbortedError(response.text)
def post(self, path, postdata):
"""
Makes a RESTful POST request to the back end.
:param path: URL of the request (without root URL e.g. "/data")
:param postdata: Data of the post request
:return: response: Response
"""
auth_header = self.authent.get_header()
return requests.post(self.endpoint+path, json=postdata, headers=auth_header)
def patch(self, path):
"""
Makes a RESTful PATCH request to the back end.
:param path: URL of the request (without root URL e.g. "/data")
:return: response: Response
"""
auth_header = self.authent.get_header()
return requests.patch(self.endpoint+path, headers=auth_header)
def put(self, path, header={}, data=None):
"""
Makes a RESTful PUT request to the back end.
:param path: URL of the request (without root URL e.g. "/data")
:param header: header that gets added to the request.
:param data: data that gets added to the request.
:return: response: Response
"""
auth_header = self.authent.get_header()
# Merge headers
head = auth_header.copy()
head.update(header)
if data:
return requests.put(self.endpoint+path, headers=head, data=data)
else:
return requests.put(self.endpoint+path, headers=head)
def get(self,path, stream=False, auth=True):
"""
Makes a RESTful GET request to the back end.
:param path: URL of the request (without root URL e.g. "/data")
:param stream: True if the get request should be streamed, else False
:param auth: True if the get request should be authenticated, else False
:return: response: Response
"""
if auth:
auth_header = self.authent.get_header()
else:
auth_header = {}
return requests.get(self.endpoint+path, headers=auth_header, stream=stream)
def delete(self, path):
"""
Makes a RESTful DELETE request to the backend
:param path: URL of the request relative to endpoint url
"""
auth_header = self.authent.get_header()
return requests.delete(self.endpoint+path, headers=auth_header)
def session(userid=None,endpoint:str="https://openeo.org/openeo"):
"""
This method is the entry point to OpenEO. You typically create one session object in your script or application, per back-end.
and re-use it for all calls to that backend.
If the backend requires authentication, you should set pass your credentials.
:param endpoint: The http url of an OpenEO endpoint.
:rtype: openeo.sessions.Session
"""
return RESTSession(userid,endpoint)
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,984
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/openeo/imagecollection.py
|
from abc import ABC
from typing import List, Dict, Union
from datetime import datetime,date
from openeo.job import Job
from shapely.geometry import Polygon, MultiPolygon
class ImageCollection(ABC):
"""Class representing an Image Collection. """
def __init__(self):
pass
def date_range_filter(self,start_date:Union[str,datetime,date],end_date:Union[str,datetime,date]) -> 'ImageCollection':
"""
Specifies a date range filter to be applied on the ImageCollection
:param start_date: Start date of the filter, inclusive, format: "YYYY-MM-DD".
:param end_date: End date of the filter, exclusive, format e.g.: "2018-01-13".
:return: An ImageCollection filtered by date.
"""
pass
def bbox_filter(self,left:float,right:float,top:float,bottom:float,srs:str) -> 'ImageCollection':
"""
Specifies a bounding box to filter input image collections.
:param left:
:param right:
:param top:
:param bottom:
:param srs:
:return: An image collection cropped to the specified bounding box.
"""
pass
def apply_pixel(self, bands: List, bandfunction) -> 'ImageCollection':
"""Apply a function to the given set of bands in this image collection.
This type applies a simple function to one pixel of the input image or image collection.
The function gets the value of one pixel (including all bands) as input and produces a single scalar or tuple output.
The result has the same schema as the input image (collection) but different bands.
Examples include the computation of vegetation indexes or filtering cloudy pixels.
:param imagecollection: Imagecollection to apply the process, Instance of ImageCollection
:param bands: Bands to be used
:param bandfunction: Band function to be used
:return: An image collection with the pixel applied function.
"""
pass
def apply_tiles(self, code: str) -> 'ImageCollection':
"""Apply a function to the tiles of an image collection.
This type applies a simple function to one pixel of the input image or image collection.
The function gets the value of one pixel (including all bands) as input and produces a single scalar or tuple output.
The result has the same schema as the input image (collection) but different bands.
Examples include the computation of vegetation indexes or filtering cloudy pixels.
:param code: Code to apply to the ImageCollection
:return: An image collection with the tiles applied function.
"""
pass
def aggregate_time(self, temporal_window, aggregationfunction) -> 'ImageCollection' :
""" Applies a windowed reduction to a timeseries by applying a user defined function.
:param temporal_window: The time window to group by
:param aggregationfunction: The function to apply to each time window. Takes a pandas Timeseries as input.
:return: An ImageCollection containing a result for each time window
"""
pass
def reduce_time(self, aggregationfunction) -> 'ImageCollection' :
""" Applies a windowed reduction to a timeseries by applying a user defined function.
:param aggregationfunction: The function to apply to each time window. Takes a pandas Timeseries as input.
:return: An ImageCollection without a time dimension
"""
pass
def min_time(self) -> 'ImageCollection':
"""
Finds the minimum value of time series for all bands of the input dataset.
:return: An ImageCollection without a time dimension.
"""
pass
def max_time(self) -> 'ImageCollection':
"""
Finds the maximum value of time series for all bands of the input dataset.
:return: An ImageCollection without a time dimension.
"""
pass
def mean_time(self) -> 'ImageCollection':
"""
Finds the mean value of time series for all bands of the input dataset.
:return: An ImageCollection without a time dimension.
"""
pass
def median_time(self) -> 'ImageCollection':
"""
Finds the median value of time series for all bands of the input dataset.
:return: An ImageCollection without a time dimension.
"""
pass
def count_time(self) -> 'ImageCollection':
"""
Counts the number of images with a valid mask in a time series for all bands of the input dataset.
:return: An ImageCollection without a time dimension.
"""
pass
def ndvi(self, red, nir) -> 'ImageCollection':
""" NDVI
:param red: Reference to the red band
:param nir: Reference to the nir band
:return An ImageCollection instance
"""
pass
def stretch_colors(self, min, max) -> 'ImageCollection':
""" Color stretching
:param min: Minimum value
:param max: Maximum value
:return An ImageCollection instance
"""
pass
def band_filter(self, bands) -> 'ImageCollection':
"""Filter the imagecollection by the given bands
:param bands: List of band names or single band name as a string.
:return An ImageCollection instance
"""
pass
####VIEW methods #######
def timeseries(self, x, y, srs="EPSG:4326") -> Dict:
"""
Extract a time series for the given point location.
:param x: The x coordinate of the point
:param y: The y coordinate of the point
:param srs: The spatial reference system of the coordinates, by default this is 'EPSG:4326', where x=longitude and y=latitude.
:return: Dict: A timeseries
"""
pass
def zonal_statistics(self, regions, func, scale=1000, interval="day") -> 'Dict':
"""
Calculates statistics for each zone specified in a file.
:param regions: GeoJSON or a path to a GeoJSON file containing the
regions. For paths you must specify the path to a
user-uploaded file without the user id in the path.
:param func: Statistical function to calculate for the specified
zones. example values: min, max, mean, median, mode
:param scale: A nominal scale in meters of the projection to work
in. Defaults to 1000.
:param interval: Interval to group the time series. Allowed values:
day, wee, month, year. Defaults to day.
:return A timeseries
"""
pass
def polygonal_mean_timeseries(self, polygon: Union[Polygon, MultiPolygon]) -> Dict:
"""
Extract a mean time series for the given (multi)polygon. Its points are expected to be in the EPSG:4326 coordinate
reference system.
:param polygon: The (multi)polygon
:return: Dict: A timeseries
"""
pass
def tiled_viewing_service(self) -> Dict:
"""
Returns metadata for a tiled viewing service that visualizes this layer.
:return: A dictionary object containing the viewing service metadata, such as the connection 'url'.
"""
pass
def download(self,outputfile:str, bbox="", time="",**format_options):
"""Extracts a binary raster from this image collection."""
pass
def send_job(self) -> Job:
"""Sends the current process to the backend, for batch processing.
:return: Job: A job object that can be used to query the processing status.
"""
pass
def graph_add_process(self, process_id, args) -> 'ImageCollection':
"""
Returns a new imagecollection with an added process with the given process
id and a dictionary of arguments
:param process_id: String, Process Id of the added process.
:param args: Dict, Arguments of the process.
:return: imagecollection: Instance of the ImageCollection class
"""
pass
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,985
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/tests/test_imagery.py
|
from unittest import TestCase
from openeo.rest.imagery import RestImagery
class TestImagery(TestCase):
def setUp(self):
self.imagery = RestImagery({}, None)
def test_date_range_filter(self):
new_imagery = self.imagery.date_range_filter("2016-01-01", "2016-03-10")
graph = new_imagery.graph
self.assertEqual(graph["process_id"],"filter_daterange")
self.assertEqual(graph["args"]["imagery"], {})
self.assertEqual(graph["args"]["from"], "2016-01-01")
self.assertEqual(graph["args"]["to"], "2016-03-10")
def test_bbox_filter(self):
new_imagery = self.imagery.bbox_filter(left=652000, right=672000,
top=5161000, bottom=5181000,
srs="EPSG:32632")
graph = new_imagery.graph
self.assertEqual(graph["process_id"],"filter_bbox")
self.assertEqual(graph["args"]["imagery"], {})
self.assertEqual(graph["args"]["left"], 652000)
self.assertEqual(graph["args"]["right"], 672000)
self.assertEqual(graph["args"]["top"], 5161000)
self.assertEqual(graph["args"]["bottom"], 5181000)
self.assertEqual(graph["args"]["srs"], "EPSG:32632")
def test_apply_pixel(self):
bandFunction = lambda cells,nodata: (cells[3]-cells[2])/(cells[3]+cells[2])
new_imagery = self.imagery.apply_pixel([], bandFunction)
graph = new_imagery.graph
self.assertEqual(graph["process_id"],"apply_pixel")
self.assertEqual(graph["args"]["imagery"], {})
self.assertEqual(graph["args"]["bands"], [])
self.assertIsNotNone(graph["args"]["function"])
def test_min_time(self):
new_imagery = self.imagery.min_time()
graph = new_imagery.graph
self.assertEqual(graph["process_id"], "min_time")
self.assertEqual(graph["args"]["imagery"], {})
def test_max_time(self):
new_imagery = self.imagery.max_time()
graph = new_imagery.graph
self.assertEqual(graph["process_id"], "max_time")
self.assertEqual(graph["args"]["imagery"], {})
def test_ndvi(self):
new_imagery = self.imagery.ndvi("B04", "B8A")
graph = new_imagery.graph
self.assertEqual(graph["process_id"], "NDVI")
self.assertEqual(graph["args"]["imagery"], {})
self.assertEqual(graph["args"]["red"], "B04")
self.assertEqual(graph["args"]["nir"], "B8A")
def test_strech_colors(self):
new_imagery = self.imagery.stretch_colors(-1, 1)
graph = new_imagery.graph
self.assertEqual(graph["process_id"], "stretch_colors")
self.assertEqual(graph["args"]["imagery"], {})
self.assertEqual(graph["args"]["min"], -1)
self.assertEqual(graph["args"]["max"], 1)
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
33,986
|
AlenaDos/openeo-python-client
|
refs/heads/master
|
/examples/gee_example.py
|
import openeo
import logging
import time
logging.basicConfig(level=logging.DEBUG)
GEE_DRIVER_URL = "http://127.0.0.1:8080"
OUTPUT_FILE = "/tmp/openeo_gee_output.png"
#connect with GEE backend
session = openeo.session("nobody", GEE_DRIVER_URL)
#retrieve the list of available collections
coperincus_s2_image = session.image("COPERNICUS/S2")
logging.debug(coperincus_s2_image.graph)
timeseries = coperincus_s2_image.bbox_filter(left=9.0, right=9.1, top=12.1,
bottom=12.0, srs="EPSG:4326")
logging.debug(timeseries.graph)
timeseries = timeseries.date_range_filter("2017-01-01", "2017-01-31")
logging.debug(timeseries.graph)
timeseries = timeseries.ndvi("B4", "B8")
logging.debug(timeseries.graph)
timeseries = timeseries.min_time()
logging.debug(timeseries.graph)
timeseries = timeseries.stretch_colors(-1, 1)
logging.debug(timeseries.graph)
client_job = timeseries.send_job(out_format="png")
logging.debug(client_job.job_id)
client_job.download(OUTPUT_FILE)
# PoC JSON:
# {
# "process_graph":{
# "process_id":"stretch_colors",
# "args":{
# "imagery":{
# "process_id":"min_time",
# "args":{
# "imagery":{
# "process_id":"NDVI",
# "args":{
# "imagery":{
# "process_id":"filter_daterange",
# "args":{
# "imagery":{
# "process_id":"filter_bbox",
# "args":{
# "imagery":{
# "product_id":"COPERNICUS/S2"
# },
# "left":9.0,
# "right":9.1,
# "top":12.1,
# "bottom":12.0,
# "srs":"EPSG:4326"
# }
# },
# "from":"2017-01-01",
# "to":"2017-01-31"
# }
# },
# "red":"B4",
# "nir":"B8"
# }
# }
# }
# },
# "min": -1,
# "max": 1
# }
# },
# "output":{
# "format":"png"
# }
# }
|
{"/tests/test_usecase1.py": ["/openeo/__init__.py"], "/tests/test_rest_session.py": ["/openeo/__init__.py"], "/openeo/rest/job.py": ["/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/rest/rest_session.py": ["/openeo/sessions.py"], "/openeo/imagecollection.py": ["/openeo/job.py"], "/examples/gee_example.py": ["/openeo/__init__.py"], "/openeo/__init__.py": ["/openeo/imagecollection.py", "/openeo/rest/rest_session.py", "/openeo/job.py"], "/openeo/sessions.py": ["/openeo/imagecollection.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.