index int64 | repo_name string | branch_name string | path string | content string | import_graph string |
|---|---|---|---|---|---|
53,270 | alexdy2007/reidentification_hacky | refs/heads/master | /webserver/person/person.py | from flask_restful import Resource
from db_connection.PeopleDB import PeopleDB
from flask import jsonify, request
crud = PeopleDB()
class Person(Resource):
def get(self, role=None, name=None):
query = {}
if name:
query["name"] = name
query["role"] = role
people = crud.get_person(query)
for p in people:
if "encoded_face" in p: del p["encoded_face"]
del p["_id"]
return jsonify(people)
def post(self):
data = request.get_json()
if not data:
data = {"response": "ERROR"}
return jsonify(data)
elif "name" in data:
crud.insert_person(data)
return {"data":"Added"}
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,271 | alexdy2007/reidentification_hacky | refs/heads/master | /tests/model_tests/test_get_encoding_list.py | from unittest import TestCase
from db_connection.Crud import Crud
import os
from model.get_feature_encoded_list import get_feature_encoding_list
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep
class TestGetEncodedListOfKnownPeople(TestCase):
def test_list_of_known_people(self):
feature_list = get_feature_encoding_list()
self.assertTrue(len(feature_list)==2)
feature_with_name = tuple(zip(feature_list[0],feature_list[1]))
self.assertTrue(len(feature_with_name)>40)
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,272 | alexdy2007/reidentification_hacky | refs/heads/master | /pre_processing/insert_test_data.py | from db_connection.Crud import Crud
import os
import random
from shutil import copyfile
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "webface" + os.sep + "src" + os.sep + "assets" + os.sep + "pictures" + os.sep
DATA_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep
ROLES = ["BI", "Dev", "Tester", "Discovery", "Product Owner", "Director", "Lab Manager"]
def insert_test_faces_into_db():
crud = Crud()
crud.delete_all_people()
for person in os.listdir(DATA_DIR):
person_dir = DATA_DIR + person + os.sep
for pic in os.listdir(person_dir):
if "0001.jpg" in pic:
name = " ".join(person.split("_"))
role = ROLES[random.randint(0,6)]
person_data_pic = DATA_DIR + person + os.sep + pic
person_target_dir = PICTURE_DIR + person
person_target_pic = person_target_dir + os.sep + person + ".jpg"
if not os.path.exists(person_target_dir):
os.makedirs(person_target_dir)
copyfile(person_data_pic, person_target_pic)
person_data = {
"name":name,
"role":role,
"photo_location" : PICTURE_DIR + person + os.sep + person + ".jpg",
"has_encodings" : False
}
crud.insert_person(person_data)
insert_test_faces_into_db()
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,273 | alexdy2007/reidentification_hacky | refs/heads/master | /webserver/take_pictures/take_pictures.py | from model.compare_single_to_known_faces import compare_face_to_known
from model.get_feature_encoded_list import get_feature_encoding_list
from model.montage.create_montage_from_photos import create_montage
from PIL import Image
import os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = CURRENT_DIR + os.sep + ".." + os.sep + "static" + os.sep + "tmp" +os.sep
TEMP_FILE = UPLOAD_FOLDER + "tmpstream.jpg"
def take_pictures(sc, crud, montage, make_montage=False):
picture = sc.get_picture()
known_faces = get_feature_encoding_list()
people_similar = compare_face_to_known(picture, known_faces, True)
if people_similar is not None:
for p in people_similar:
print("{}:found".format(p["name"]))
crud.person_seen_db_insert(p)
if make_montage:
im = Image.fromarray(picture)
im.save(TEMP_FILE)
photos = montage.get_all_photos_with_person_in(TEMP_FILE)
create_montage(photos)
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,274 | alexdy2007/reidentification_hacky | refs/heads/master | /db_connection/Crud.py | import os
from pymongo import MongoClient
from tests.db_tests.test_data import TEST_DATA
from datetime import datetime, timedelta
#mongo -u ian -p secretPassword 123.45.67.89/cool_db
class Crud(object):
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep
def __init__(self, remote=False):
if remote:
self.URI_CONNTECTION_STRING = "mongodb://localhost:27017/"
else:
self.URI_CONNTECTION_STRING = "mongodb://localhost:27017/"
self.client = MongoClient(self.URI_CONNTECTION_STRING)
self.db = self.client.facialrecdb
def person_seen_db_insert(self, person):
new_person = {}
person_seen_db = self.db.personSeen
new_person["name"] = person["name"]
new_person["time_seen"] = datetime.now()
if "encoded_face" in person:
del person["encoded_face"]
person_seen_db.insert(new_person)
def find_someone_seen_in_last_x_seconds(self, seconds):
person_seen_db = self.db.personSeen
dt_x_second_ago = datetime.now() - timedelta(seconds=seconds)
query = {"time_seen":{'$gt':dt_x_second_ago}}
limit_to_fields = {"name":1}
people_seen = person_seen_db.find(query, limit_to_fields).distinct("name")
return people_seen
def __del__(self):
self.client.close()
if __name__ == "__main__":
crud = Crud()
crud.insert_test_data()
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,275 | alexdy2007/reidentification_hacky | refs/heads/master | /model/encode_image.py |
import face_recognition
import numpy as np
def encode_image(image):
"""
:param image: srt file location or np.array
:return: [[int,int,..],[int,int,...],...]
"""
if isinstance(image, str):
loaded_image = face_recognition.load_image_file(image)
else:
loaded_image = np.array(image)
people_encoding = face_recognition.face_encodings(loaded_image)
if len(people_encoding)>0:
return people_encoding
else:
return [] | {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,276 | alexdy2007/reidentification_hacky | refs/heads/master | /tests/model_tests/montage/test_match_all_photos.py | from model.montage.montage import Montage
from unittest import TestCase
import os
from model.montage.create_montage_from_photos import create_montage
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_TEST_DIR = CURRENT_DIR + os.sep + ".." + os.sep + ".." + os.sep + ".." + os.sep + "data" + os.sep + "MontageTestData" + os.sep
class TestMontage(TestCase):
def setUp(self):
self.montage = Montage()
def test_add_to_montage_db(self):
self.montage.delete_all()
self.montage.insert_batch_data_set_from_file(PICTURE_TEST_DIR)
pics = self.montage.get_all()
self.assertEquals(len(pics), 16)
def test_mat_returns_2_pics(self):
matt_pic_file = CURRENT_DIR + os.sep + "Matt_glasses.jpg"
photos = self.montage.get_all_photos_with_person_in(matt_pic_file)
print(photos)
self.assertEquals(len(photos), 4)
def test_create_montage_matt(self):
matt_pic_file = CURRENT_DIR + os.sep + "Matt_glasses.jpg"
photos = self.montage.get_all_photos_with_person_in(matt_pic_file)
print(photos)
create_montage(photos)
def test_create_montage_frank(self):
frank_pic_file = CURRENT_DIR + os.sep + "frank2.jpg"
photos = self.montage.get_all_photos_with_person_in(frank_pic_file)
print(photos)
create_montage(photos)
def test_create_montage_alex(self):
alex_pic_file = CURRENT_DIR + os.sep + "alex.jpg"
photos = self.montage.get_all_photos_with_person_in(alex_pic_file)
print(photos)
create_montage(photos) | {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,277 | alexdy2007/reidentification_hacky | refs/heads/master | /tests/socket/test_picsocket.py | from unittest import TestCase
from sockets.PictureRecSocket import SocketClient
from db_connection.Crud import Crud
from model.compare_single_to_known_faces import compare_face_to_known
from model.crop_face_from_image import crop_face_from_image
from model.get_feature_encoded_list import get_feature_encoding_list
import os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep
class TestPictureIdentification(TestCase):
"""
Inorder for test to pass, must have sight of raspberry pi with facial socket server running
Alex needs to be standing infont of camera
"""
def setUp(self):
self.sc = SocketClient()
def test_identify_alex(self):
picture = self.sc.get_picture()
face = crop_face_from_image(picture)
known_faces = get_feature_encoding_list()
people_similar = compare_face_to_known(face, known_faces)
most_similar = people_similar[0]
self.assertEqual(most_similar["name"], "Alex Young")
def test_no_person_found(self):
picture = self.sc.get_picture()
face = crop_face_from_image(picture)
if face is not None:
known_faces = get_feature_encoding_list()
people_similar = compare_face_to_known(face, known_faces)
if len(people_similar) != []:
most_similar = people_similar[0]
self.assertEqual(face, None)
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,278 | alexdy2007/reidentification_hacky | refs/heads/master | /model/montage/montage.py | from db_connection.MontageDB import MontageDB
from model.encode_image import encode_image
from model.montage.check_person_in_photo import is_in_photo
import os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
SAVE_FILE = CURRENT_DIR
class Montage():
def __init__(self):
self.montageDB = MontageDB()
self.all_picture_data = self.montageDB.get_all()
self.save_file = SAVE_FILE
def add_picture(self, photo_location):
face_encodings = encode_image(photo_location)
print("people found {}".format(len(face_encodings)))
if len(face_encodings) > 0:
data = {"photo_location": photo_location,
"face_encodings": face_encodings}
self.all_picture_data.append(data)
self.montageDB.insert_new_picture(photo_location, face_encodings)
return data
else:
return []
def insert_batch_data_set_from_file(self, picture_file):
for pic_file in os.listdir(picture_file):
print("adding {}".format(pic_file))
pic_abs_path = picture_file + pic_file
self.add_picture(pic_abs_path)
def get_all_photos_with_person_in(self, picture_file):
list_of_photos_in = []
person_encoding = encode_image(picture_file)
if len(person_encoding)>0:
#use first person identified in photo
person_encoding = person_encoding[0]
for pic in self.all_picture_data:
pic_face_encodings_list = pic["face_encodings"]
distance_of_person = is_in_photo(person_encoding, pic_face_encodings_list)
if distance_of_person:
list_of_photos_in.append(pic["photo_location"])
return list_of_photos_in
else:
return []
def delete_all(self):
self.montageDB.delete_all()
def get_all(self):
return self.montageDB.get_all()
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,279 | alexdy2007/reidentification_hacky | refs/heads/master | /model/montage/create_montage_from_photos.py | from imutils import build_montages
import math
import random
import os
import cv2
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
TMP_DIR = CURRENT_DIR + os.sep + ".." + os.sep + ".." + os.sep \
+ "webserver" + os.sep + "static" + os.sep + "tmp" + os.sep
TMP_MONTAGE_FILE0 = TMP_DIR + "montage0.jpg"
TMP_MONTAGE_FILE1 = TMP_DIR + "montage1.jpg"
def create_montage(image_list, samples=10):
samples = min(len(image_list), samples)
imagePaths = image_list
random.shuffle(imagePaths)
imagePaths = imagePaths[:samples]
# initialize the list of images
images = []
# loop over the list of image paths
for imagePath in imagePaths:
# load the image and update the list of images
image = cv2.imread(imagePath)
images.append(image)
# construct the montages for the images
h = math.ceil(round(samples/2))
w = 2
print(len(images))
if len(images) == 1:
resized_img = cv2.resize(images[0], (256,256), interpolation=cv2.INTER_AREA)
montages = [resized_img]
elif len(images) > 1:
montages = build_montages(images, (256, 256), (w, h))
else:
montages =[]
if len(montages)>0:
montage = montages[0]
cv2.imwrite(TMP_MONTAGE_FILE0, montage)
cv2.imwrite(TMP_MONTAGE_FILE1, montage) | {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,280 | alexdy2007/reidentification_hacky | refs/heads/master | /sockets/PictureRecSocket.py | import socket
import pickle
import numpy as np
import atexit
class SocketClient(object):
def __init__(self):
#host = '192.168.0.48'
host = '10.42.0.192'
port = 5560
self.soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.soc.connect((host, port))
def get_picture(self):
self.soc.sendall(str.encode("length"))
pic_length = self.soc.recv(1024)
pic_length = int(pic_length.decode("utf-8"))
self.soc.sendall(str.encode("picture"))
picture = self._recvall(self.soc,pic_length)
picture_array = pickle.loads(picture)
return picture_array
def kill_server(self):
self.soc.send(str.encode("kill"))
def exit_server(self):
self.soc.send(str.encode("exit"))
def listen_for_pictures(self, conn):
while True:
with conn:
length = self._recvall(conn, 16)
pic_data = self._recvall(conn, int(length))
print(pic_data[1:10])
def _recvall(self, soc, count):
buf = b''
while count:
newbuf = soc.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
def __del__(self):
self.kill_socket()
def kill_socket(self):
self.soc.close()
if __name__ == "__main__":
ss = SocketClient()
ss.get_picture()
ss.exit_server()
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,281 | alexdy2007/reidentification_hacky | refs/heads/master | /tests/model_tests/test_encode_image.py | from unittest import TestCase
from db_connection.Crud import Crud
import os
from model.crop_face_from_image import crop_face_from_image
from model.encode_image import encode_image
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep
MONTAGE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + ".." + os.sep + "data" + os.sep + "MontageTestData" + os.sep
class TestEncodeImage(TestCase):
# def test_crop_image(self):
# image_path = PICTURE_DIR + "Alex_Young/Alex_Young.jpg"
# image = crop_face_from_image(image_path)
# image.save("test.jpg", "JPEG", quality=80, optimize=True, progressive=True)
def test_encode_2_face_in_pic(self):
pic = MONTAGE_DIR + "stephen_and_laurance.jpg"
encodings = encode_image(pic)
print("here")
def test_1_encode_face_in_pic(self):
pic = MONTAGE_DIR + "mohit.jpg"
encodings = encode_image(pic)
print("HERE")
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,282 | alexdy2007/reidentification_hacky | refs/heads/master | /db_connection/MontageDB.py | from db_connection.Crud import Crud
import numpy as np
from bson.binary import Binary
import pickle
class MontageDB(Crud):
def __init__(self):
super().__init__()
self.target_db = self.db.montagephotos
def insert_new_picture(self, photo_location, face_encodings):
"""
:param photo_location: path
:param face_encodings: [[face encodings],[face encodings],...]
"""
face_encodings_bin = Binary(pickle.dumps(face_encodings, pickle.HIGHEST_PROTOCOL))
if len(face_encodings) > 0:
data = {"photo_location":photo_location,
"face_encodings" : face_encodings_bin}
self.target_db.insert(data)
def get_all(self):
data = [x for x in self.target_db.find({})]
for d in data:
d["face_encodings"] = pickle.loads(d["face_encodings"], )
return data
def delete_all(self):
self.target_db.remove({})
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,283 | alexdy2007/reidentification_hacky | refs/heads/master | /tests/model_tests/test_crop_image.py | from unittest import TestCase
import os
from model.crop_face_from_image import crop_face_from_image
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + ".." + os.sep + "pictures" + os.sep
class TestCropImage(TestCase):
def test_crop_image(self):
image_path = PICTURE_DIR + "Alex_Young/Alex_Young.jpg"
image = crop_face_from_image(image_path)
image.save("test.jpg", "JPEG", quality=80, optimize=True, progressive=True)
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,284 | alexdy2007/reidentification_hacky | refs/heads/master | /tests/preprocessing_tests/test_encode_test_images.py | from unittest import TestCase
from model.crop_face_from_image import crop_face_from_image
from pre_processing.insert_test_data import insert_test_faces_into_db
from pre_processing.encode_test_data import encode_all_people_in_db
from db_connection.Crud import Crud
import os
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
PICTURE_DIR = CURRENT_DIR + os.sep + ".." + os.sep + "pictures" + os.sep
class TestEncodeTestImages(TestCase):
def setUp(self):
insert_test_faces_into_db()
self.crud = Crud()
def test_encode_images(self):
encode_all_people_in_db()
person = self.crud.get_person({"name":"AJ Cook"})
self.assertTrue("encoded_face" in person[0])
self.assertTrue(len(person[0]["encoded_face"]) > 2)
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,285 | alexdy2007/reidentification_hacky | refs/heads/master | /pre_processing/encode_test_data.py | from db_connection.Crud import Crud
from model.encode_image import encode_image
def encode_all_people_in_db():
crud = Crud()
people = crud.get_person({})
for person in people:
image_location = person["photo_location"]
image_encoding = encode_image(image_location)
if len(image_encoding) > 1:
image_encoding = image_encoding[0]
if len(image_encoding)>0:
crud.update_person(person, {"encoded_face":list(image_encoding), "has_encodings":True})
if __name__ == "__main__":
encode_all_people_in_db() | {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,286 | alexdy2007/reidentification_hacky | refs/heads/master | /model/get_feature_encoded_list.py | from db_connection.PeopleDB import PeopleDB
def get_feature_encoding_list():
crud = PeopleDB()
people = crud.get_person({"has_encodings":True})
encoding_list = []
name_list = []
for person in people:
name_list.append(person["name"])
encoding_list.append(person["encoded_face"])
return [name_list, encoding_list]
| {"/tests/db_tests/crud_test.py": ["/db_connection/PeopleDB.py"], "/tests/db_tests/test_insert_person_seen_from_camera.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py"], "/webserver/main.py": ["/webserver/person/person.py", "/webserver/take_pictures/take_pictures.py", "/db_connection/PeopleDB.py", "/db_connection/MontageDB.py", "/webserver/apis/montage_api.py", "/sockets/PictureRecSocket.py", "/model/montage/montage.py"], "/webserver/apis/montage_api.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/model/compare_single_to_known_faces.py": ["/model/encode_image.py", "/db_connection/Crud.py"], "/tests/model_tests/test_match_person.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py", "/model/compare_single_to_known_faces.py"], "/db_connection/PeopleDB.py": ["/db_connection/Crud.py"], "/webserver/person/person.py": ["/db_connection/PeopleDB.py"], "/tests/model_tests/test_get_encoding_list.py": ["/db_connection/Crud.py", "/model/get_feature_encoded_list.py"], "/pre_processing/insert_test_data.py": ["/db_connection/Crud.py"], "/webserver/take_pictures/take_pictures.py": ["/model/compare_single_to_known_faces.py", "/model/get_feature_encoded_list.py", "/model/montage/create_montage_from_photos.py"], "/db_connection/Crud.py": ["/tests/db_tests/test_data.py"], "/tests/model_tests/montage/test_match_all_photos.py": ["/model/montage/montage.py", "/model/montage/create_montage_from_photos.py"], "/tests/socket/test_picsocket.py": ["/sockets/PictureRecSocket.py", "/db_connection/Crud.py", "/model/compare_single_to_known_faces.py", "/model/crop_face_from_image.py", "/model/get_feature_encoded_list.py"], "/model/montage/montage.py": ["/db_connection/MontageDB.py", "/model/encode_image.py", "/model/montage/check_person_in_photo.py"], "/tests/model_tests/test_encode_image.py": ["/db_connection/Crud.py", "/model/crop_face_from_image.py", "/model/encode_image.py"], "/db_connection/MontageDB.py": ["/db_connection/Crud.py"], "/tests/model_tests/test_crop_image.py": ["/model/crop_face_from_image.py"], "/tests/preprocessing_tests/test_encode_test_images.py": ["/model/crop_face_from_image.py", "/pre_processing/insert_test_data.py", "/pre_processing/encode_test_data.py", "/db_connection/Crud.py"], "/pre_processing/encode_test_data.py": ["/db_connection/Crud.py", "/model/encode_image.py"], "/model/get_feature_encoded_list.py": ["/db_connection/PeopleDB.py"]} |
53,288 | ggnight82/netflix | refs/heads/master | /account/serializers.py | from rest_framework import serializers
from .models import User
class UserRegistrationSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields = ['email', 'username','rating','first_name','last_name',
'password', 'password2',]
extra_kwargs = {
'password': {
'write_only':True
}
}
def save(self):
user = User(
email=self.validated_data['email'],
username=self.validated_data['username'],
rating=self.validated_data['rating'],
first_name=self.validated_data['first_name'],
last_name=self.validated_data['last_name'],
is_tutor=self.validated_data['is_tutor'],
is_student=self.validated_data['is_student'],
)
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({'password':'Passwords must match.'})
user.set_password(password)
user.save()
return user | {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,289 | ggnight82/netflix | refs/heads/master | /browse/serializers.py | from rest_framework import serializers
from . import models
class ContentsSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Contents
fields = '__all__'
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,290 | ggnight82/netflix | refs/heads/master | /my_database_setting.py | DATABASES = {
'default' : {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'netflix',
'USER': 'root',
'HOST': 'localhost',
'PORT': '3306',
}
}
SECRET_KEY = 'za1m@ag$s@(&@ulxy(tz7x0_muo^bsyq!y&q(h!=sdk@kxd8tj'
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,291 | ggnight82/netflix | refs/heads/master | /browse/models.py | from django.db import models
# Create your models here.
class Genres(models.Model):
genre_genre = models.CharField(max_length=20)
def __str__(self):
return self.genre_genre
class Actors(models.Model):
actor_name = models.CharField(max_length=20)
def __str__(self):
return self.actor_name
class Productions(models.Model):
productions_name = models.CharField(max_length=20)
def __str__(self):
return self.productions_name
class Contents(models.Model):
contents_id = models.BigAutoField(help_text="CONTENTS ID", primary_key=True)
contents_title = models.CharField(max_length=50)
contents_description = models.TextField()
contents_created_at = models.DateTimeField(auto_now_add=True)
contents_updated_at = models.DateTimeField(auto_now=True)
contents_genre = models.ManyToManyField(Genres)
contents_actor = models.ManyToManyField(Actors)
contents_productions = models.OneToOneField(Productions,on_delete=models.CASCADE)
def __str__(self):
return self.contents_title
class Videos(models.Model):
video_season = models.IntegerField(default=0)
video_episode = models.IntegerField(default=0)
video_id = models.BigAutoField(help_text="VIDEO ID", primary_key=True)
video_file = models.FileField(upload_to="../MEDIA",null=True)
contents_id = models.ForeignKey(Contents, related_name="content", on_delete=models.CASCADE, db_column="post_id")
def __str__(self):
return self.contents
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,292 | ggnight82/netflix | refs/heads/master | /UserAccount/migrations/0001_initial.py | # Generated by Django 3.1.7 on 2021-03-09 15:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('id', models.BigAutoField(help_text='User Id', primary_key=True, serialize=False)),
('email', models.EmailField(max_length=60, unique=True, verbose_name='email')),
('username', models.CharField(max_length=30, unique=True)),
('date_joined', models.DateField(auto_now_add=True, verbose_name='date joined')),
('last_login', models.DateField(auto_now=True, verbose_name='last login')),
('is_admin', models.BooleanField(default=False)),
('is_active', models.BooleanField(default=True)),
('is_superuser', models.BooleanField(default=False)),
('rating', models.FloatField(choices=[('1', 'All'), ('2', '7+'), ('3', '12+'), ('4', '15+'), ('5', 'Rated-R'), ('6', '19+')], max_length=1)),
('first_name', models.CharField(max_length=30, verbose_name='first_name')),
('last_name', models.CharField(max_length=30, verbose_name='last_name')),
],
options={
'abstract': False,
},
),
]
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,293 | ggnight82/netflix | refs/heads/master | /account/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager, AbstractBaseUser
class MyUserManager(BaseUserManager):
def create_user(self,email,username,rating,first_name,last_name,password=None):
user = self.model(
email=self.normalize_email(email),
username=username,
rating=rating,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self,email,username,password,rating,first_name,last_name,is_admin,is_superuser):
user = self.model(
email=self.normalize_email(email),
username=username,
rating=rating,
first_name = first_name,
last_name = last_name,
password = password
)
user.is_admin = True
user.is_superuser = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
RATING = (
('1','All'),
('2', '7+'),
('3', '12+'),
('4', '15+'),
('5','Rated-R'),
('6','19+')
)
id = models.BigAutoField(help_text="User Id", primary_key=True)
email = models.EmailField(verbose_name='email', max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
date_joined = models.DateField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_superuser = models.BooleanField(default=False)
rating = models.FloatField(max_length=1,choices=RATING)
first_name = models.CharField(verbose_name='first_name', max_length=30)
last_name = models.CharField(verbose_name='last_name', max_length=30)
REQUIRED_FIELDS = ['username','first_name','last_name','rating']
USERNAME_FIELD = 'email'
objects = MyUserManager()
def __str__(self):
return self.first_name + ' ' + self.last_name + ' ' + self.username | {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,294 | ggnight82/netflix | refs/heads/master | /browse/views.py | from django.shortcuts import render
# Create your views here.
from rest_framework import generics
from .models import Genres, Actors, Contents, Videos
from .serializers import ContentsSerializer
class contents_list(generics.ListCreateAPIView):
queryset = Contents.objects.all()
serializer_class = ContentsSerializer
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,295 | ggnight82/netflix | refs/heads/master | /browse/migrations/0002_auto_20210314_1902.py | # Generated by Django 3.1.7 on 2021-03-14 10:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('browse', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Productions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('productions_name', models.CharField(max_length=20)),
],
),
migrations.RenameModel(
old_name='actor',
new_name='Actors',
),
migrations.RenameModel(
old_name='genre',
new_name='Genres',
),
migrations.RenameModel(
old_name='video',
new_name='Videos',
),
migrations.AddField(
model_name='contents',
name='contents_productions',
field=models.OneToOneField(default=1, on_delete=django.db.models.deletion.CASCADE, to='browse.productions'),
preserve_default=False,
),
]
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,296 | ggnight82/netflix | refs/heads/master | /browse/migrations/0001_initial.py | # Generated by Django 3.1.7 on 2021-03-09 15:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='actor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('actor_name', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='contents',
fields=[
('contents_id', models.BigAutoField(help_text='CONTENTS ID', primary_key=True, serialize=False)),
('contents_title', models.CharField(max_length=50)),
('contents_description', models.TextField()),
('contents_created_at', models.DateTimeField(auto_now_add=True)),
('contents_updated_at', models.DateTimeField(auto_now=True)),
('contents_actor', models.ManyToManyField(to='browse.actor')),
],
),
migrations.CreateModel(
name='genre',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('genre_genre', models.CharField(max_length=20)),
],
),
migrations.CreateModel(
name='video',
fields=[
('video_season', models.IntegerField(default=0)),
('video_episode', models.IntegerField(default=0)),
('video_id', models.BigAutoField(help_text='VIDEO ID', primary_key=True, serialize=False)),
('video_file', models.FileField(null=True, upload_to='../MEDIA')),
('contents_id', models.ForeignKey(db_column='post_id', on_delete=django.db.models.deletion.CASCADE, related_name='content', to='browse.contents')),
],
),
migrations.AddField(
model_name='contents',
name='contents_genre',
field=models.ManyToManyField(to='browse.genre'),
),
]
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,297 | ggnight82/netflix | refs/heads/master | /UserAccount/serializers.py | from rest_framework import serializers
from . models import User
class UserAccountRegistrationSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(style={'input_type':'password'}, write_only=True)
class Meta:
model = User
fields = ['email', 'username','rating','first_name','last_name',
'password', 'password2',]
extra_kwargs = {
'password': {
'write_only':True
}
}
def save(self,user):
user = User(
email=self.validated_data['email'],
username=self.validated_data['username'],
rating=self.validated_data['rating'],
first_name=self.validated_data['first_name'],
last_name=self.validated_data['last_name'],
#is_admin=self.validated_data['is_admin'],
#is_active=self.validated_data['is_active'],
#is_staff=self.validated_data['is_staff'],
#is_superuser=self.validated_data['is_superuser']
)
password = self.validated_data['password']
password2 = self.validated_data['password2']
if password != password2:
raise serializers.ValidationError({'password':'Passwords must match.'})
user.set_password(password)
user.save()
return user
#class LoginSerializers(serializers.Serializer):
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,298 | ggnight82/netflix | refs/heads/master | /UserAccount/migrations/0002_auto_20210310_1649.py | # Generated by Django 3.1.7 on 2021-03-10 07:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UserAccount', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='rating',
field=models.CharField(choices=[('1', 'All'), ('2', '7+'), ('3', '12+'), ('4', '15+'), ('5', 'Rated-R'), ('6', '19+')], max_length=1),
),
]
| {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,299 | ggnight82/netflix | refs/heads/master | /browse/admin.py |
# Register your models here.
from django.contrib import admin
from . models import Contents,Genres,Actors
# Register your models here.
admin.site.register(Contents)
admin.site.register(Genres)
admin.site.register(Actors) | {"/account/serializers.py": ["/account/models.py"], "/browse/views.py": ["/browse/models.py", "/browse/serializers.py"], "/browse/admin.py": ["/browse/models.py"]} |
53,300 | madison08/dog-rental | refs/heads/main | /dogrental/routers/user.py | from fastapi import APIRouter, Depends, status, HTTPException
from .. import database, models, schemas, hashing, oauth2
from sqlalchemy.orm import Session
router = APIRouter(
prefix='/user',
tags=['users 👨']
)
get_db = database.get_db
@router.get('')
def all_users(db:Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
users = db.query(models.User).all()
return users
@router.post('')
def create_user(request: schemas.User, db: Session = Depends(get_db)):
# , current_user: schemas.User = Depends(oauth2.get_current_user)
hashedPassword = hashing.Hash.bcrypt(request.password)
newUser = models.User(firstname=request.firstname, lastname=request.lastname, username=request.username, email=request.email, password = hashedPassword)
db.add(newUser)
db.commit()
db.refresh(newUser)
return newUser
@router.get('/{id}')
def show_user(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
user = db.query(models.User).filter(models.User.id == id).first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"l'utilisateur {id} n'existe pas"
)
return user
@router.delete('/{id}')
def delete_user(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
user = db.query(models.User).filter(models.User.id == id)
if not user.first():
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"l'utilisateur {id} n'existe pas"
)
user.delete(synchronize_session=False)
db.commit()
return {'detail': 'deleted'}
@router.put('/{id}')
def update_user(id: int,request: schemas.User, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
user = db.query(models.User).filter(models.User.id == id)
if not user.first():
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"l'utilisateur {id} n'existe pas"
)
user.update(request.dict())
db.commit()
return {'detail': 'updated'}
| {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,301 | madison08/dog-rental | refs/heads/main | /dogrental/schemas.py | from pydantic import BaseModel
from typing import Optional
class User(BaseModel):
firstname: str
lastname: str
username: str
email: str
password: str
class Config():
orm_mode = True
class Tenant(BaseModel):
firstname: str
lastname: str
email: str
adress: str
class Dog(BaseModel):
name: str
race: str
class Login(BaseModel):
username: str
password: str
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None | {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,302 | madison08/dog-rental | refs/heads/main | /dogrental/main.py | from fastapi import FastAPI
from . import models
from .database import engine
from .routers import user, tenant, dog, auth
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(title="dog rental API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
models.Base.metadata.create_all(engine)
app.include_router(auth.router)
app.include_router(user.router)
app.include_router(tenant.router)
app.include_router(dog.router) | {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,303 | madison08/dog-rental | refs/heads/main | /dogrental/database.py | from sqlalchemy import create_engine, engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = 'sqlite:///./dogrent.db'
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
sesionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Base = declarative_base()
def get_db():
db = sesionLocal()
try:
yield db
finally:
db.close() | {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,304 | madison08/dog-rental | refs/heads/main | /dogrental/routers/dog.py | from fastapi import APIRouter, Depends, status, HTTPException
from .. import database, models, schemas, oauth2
from sqlalchemy.orm import Session
router = APIRouter(
prefix='/dog',
tags=['dogs 🐕']
)
get_db = database.get_db
@router.get('')
def all_dog(db:Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user) ):
dogs = db.query(models.Dog).all()
return dogs
@router.post('')
def create_dog(request: schemas.Dog, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
newDog = models.Dog(name=request.name, race=request.race, tenant_id = 1)
db.add(newDog)
db.commit()
db.refresh(newDog)
return newDog
@router.get('/{id}')
def show_dog(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
dog = db.query(models.Dog).filter(models.Dog.id == id).first()
if not dog:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"le chien {id} n'existe pas"
)
return dog
@router.delete('/{id}')
def delete_dog(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
dog = db.query(models.Dog).filter(models.Dog.id == id)
if not dog.first():
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"le chien {id} n'existe pas"
)
dog.delete(synchronize_session=False)
db.commit()
return {'detail': 'deleted'}
@router.put('/{id}')
def update_dog(id: int,request: schemas.Dog, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
dog = db.query(models.Dog).filter(models.Dog.id == id)
if not dog.first():
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"le chien {id} n'existe pas"
)
dog.update(request.dict())
db.commit()
return {'detail': 'updated'}
| {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,305 | madison08/dog-rental | refs/heads/main | /dogrental/routers/tenant.py | from fastapi import APIRouter, Depends, status, HTTPException
from .. import database, models, schemas, oauth2
from sqlalchemy.orm import Session
router = APIRouter(
prefix='/tenant',
tags=['tenants 👤']
)
get_db = database.get_db
@router.get('')
def all_tenant(db:Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
tenants = db.query(models.Tenant).all()
return tenants
@router.post('')
def create_tenant(request: schemas.Tenant, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
newTenant = models.Tenant(firstname=request.firstname, lastname=request.lastname, email=request.email, adress=request.adress, user_id=1)
db.add(newTenant)
db.commit()
db.refresh(newTenant)
return newTenant
@router.get('/{id}')
def show_tenant(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
tenant = db.query(models.Tenant).filter(models.Tenant.id == id).first()
if not tenant:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"le proprietaire {id} n'existe pas"
)
return tenant
@router.delete('/{id}')
def delete_tenant(id: int, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
tenant = db.query(models.Tenant).filter(models.Tenant.id == id)
if not tenant.first():
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"le proprietaire {id} n'existe pas"
)
tenant.delete(synchronize_session=False)
db.commit()
return {'detail': 'deleted'}
@router.put('/{id}')
def update_tenant(id: int,request: schemas.Tenant, db: Session = Depends(get_db), current_user: schemas.User = Depends(oauth2.get_current_user)):
tenant = db.query(models.Tenant).filter(models.Tenant.id == id)
if not tenant.first():
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"le proprietaire {id} n'existe pas"
)
tenant.update(request.dict())
db.commit()
return {'detail': 'updated'}
| {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,306 | madison08/dog-rental | refs/heads/main | /dogrental/models.py | from sqlalchemy import Column, Integer, String, ForeignKey
from .database import Base
from sqlalchemy.orm import relationship
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, index=True)
firstname = Column(String)
lastname = Column(String)
username = Column(String, unique=True)
email = Column(String)
password = Column(String)
tenants = relationship("Tenant", back_populates="creator")
class Dog(Base):
__tablename__ = 'dogs'
id = Column(Integer, primary_key=True, index=True)
name = Column(String)
race = Column(String, default="unknown")
tenant_id = Column(Integer, ForeignKey('tenants.id'))
owner = relationship("Tenant", back_populates="dogs")
class Tenant(Base):
__tablename__ = 'tenants'
id = Column(Integer, primary_key=True, index=True)
firstname = Column(String)
lastname = Column(String)
email = Column(String)
adress = Column(String)
user_id = Column(Integer, ForeignKey('users.id'))
creator = relationship("User", back_populates="tenants")
dogs = relationship("Dog", back_populates="owner")
| {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,307 | madison08/dog-rental | refs/heads/main | /dogrental/routers/auth.py | # from ..token import ACCESS_TOKEN_EXPIRE_MINUTES, create_access_token
# from datetime import timedelta
from .. import models
from fastapi import APIRouter, Depends, status, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from .. import schemas, database, models, hashing, token
from sqlalchemy.orm import Session
router = APIRouter(tags=['Authentication 🔑'])
get_db = database.get_db
@router.post('/login')
def login(request: OAuth2PasswordRequestForm= Depends(), db: Session = Depends(get_db)):
user = db.query(models.User).filter(models.User.username == request.username).first()
if not user:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Invalid Credentials')
if not hashing.Hash.verify(user.password, request.password):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f'Incorrect pasword')
# access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = token.create_access_token(
data={"sub": user.username}
)
#, expires_delta=access_token_expires
return {"access_token": access_token, "token_type": "bearer"}
| {"/dogrental/main.py": ["/dogrental/database.py"], "/dogrental/models.py": ["/dogrental/database.py"]} |
53,308 | stevecshanks/pipenv-and-pyenv | refs/heads/main | /main.py | from flask import Flask
app = Flask(__name__)
@app.route("/hello/<name>")
def hello_world(name):
return {"message": f"Hello, {name.title()}!"}
| {"/test_main.py": ["/main.py"]} |
53,309 | stevecshanks/pipenv-and-pyenv | refs/heads/main | /test_main.py | from main import app
def test_hello_world():
with app.test_client() as client:
response = client.get("/hello/your%20name")
assert response.status_code == 200
assert response.json == {"message": "Hello, Your Name!"}
| {"/test_main.py": ["/main.py"]} |
53,310 | CavemanIV/service-capacity-modeling | refs/heads/main | /tests/netflix/test_crdb.py | from service_capacity_modeling.capacity_planner import planner
from service_capacity_modeling.interface import CapacityDesires
from service_capacity_modeling.interface import DataShape
from service_capacity_modeling.interface import Interval
from service_capacity_modeling.interface import QueryPattern
def test_crdb_basic():
basic = CapacityDesires(
service_tier=1,
query_pattern=QueryPattern(
estimated_read_per_second=Interval(
low=100, mid=1000, high=10000, confidence=0.98
),
estimated_write_per_second=Interval(
low=100, mid=1000, high=10000, confidence=0.98
),
),
data_shape=DataShape(
estimated_state_size_gib=Interval(
low=10, mid=100, high=1000, confidence=0.98
),
),
)
plan = planner.plan(
model_name="org.netflix.cockroachdb",
region="us-east-1",
desires=basic,
)
lr = plan.least_regret[0]
lr_cluster = lr.candidate_clusters.zonal[0]
# Resulting cluster should not be too expensive
assert 2000 < lr.candidate_clusters.total_annual_cost < 10_000
# Should have enough disk space for around 80GiB of data in a single
# replica (compression). Also that drive should be ephemeral
assert lr_cluster.instance.drive is not None
assert lr_cluster.count * lr_cluster.instance.drive.size_gib > 80
# Should have enough CPU to handle 1000 QPS
assert lr_cluster.count * lr_cluster.instance.cpu > 4
def test_crdb_footprint():
space = CapacityDesires(
service_tier=1,
query_pattern=QueryPattern(
estimated_read_per_second=Interval(
low=100, mid=1000, high=10000, confidence=0.98
),
estimated_write_per_second=Interval(
low=100, mid=1000, high=10000, confidence=0.98
),
),
data_shape=DataShape(
estimated_state_size_gib=Interval(
low=100, mid=1000, high=10000, confidence=0.98
),
),
)
plan = planner.plan(
model_name="org.netflix.cockroachdb",
region="us-east-1",
desires=space,
)
lr = plan.least_regret[0]
lr_cluster = lr.candidate_clusters.zonal[0]
# Resulting cluster should not be too expensive
assert 4000 < lr.candidate_clusters.total_annual_cost < 12_000
# Should have enough disk space for around 80GiB of data in a single
# replica (compression). Also that drive should be ephemeral
assert lr_cluster.instance.drive is not None
assert lr_cluster.count * lr_cluster.instance.drive.size_gib > 800
# Should have enough CPU to handle 1000 QPS
assert lr_cluster.count * lr_cluster.instance.cpu >= 8
| {"/service_capacity_modeling/models/org/netflix/crdb.py": ["/service_capacity_modeling/models/common.py"], "/service_capacity_modeling/models/org/netflix/__init__.py": ["/service_capacity_modeling/models/org/netflix/crdb.py"]} |
53,311 | CavemanIV/service-capacity-modeling | refs/heads/main | /tests/test_reproducible.py | from service_capacity_modeling.capacity_planner import planner
from service_capacity_modeling.interface import CapacityDesires
from service_capacity_modeling.interface import DataShape
from service_capacity_modeling.interface import Interval
from service_capacity_modeling.interface import QueryPattern
uncertain_mid = CapacityDesires(
service_tier=1,
query_pattern=QueryPattern(
estimated_read_per_second=Interval(
low=1000, mid=10000, high=100000, confidence=0.98
),
estimated_write_per_second=Interval(
low=1000, mid=10000, high=100000, confidence=0.98
),
),
data_shape=DataShape(
estimated_state_size_gib=Interval(low=100, mid=500, high=1000, confidence=0.98),
),
)
def test_repeated_plans():
results = []
for _ in range(5):
results.append(
planner.plan(
model_name="org.netflix.cassandra",
region="us-east-1",
desires=uncertain_mid,
).json()
)
a = [hash(x) for x in results]
# We should end up with consistent results
assert all(i == a[0] for i in a)
def test_compositional():
direct_result = planner.plan(
model_name="org.netflix.cassandra",
region="us-east-1",
desires=uncertain_mid,
num_results=4,
explain=True,
)
composed_result = planner.plan(
model_name="org.netflix.key-value",
region="us-east-1",
desires=uncertain_mid,
num_results=4,
explain=True,
)
for i in range(4):
direct_cluster = direct_result.least_regret[i].candidate_clusters.zonal[0]
composed_cluster = composed_result.least_regret[i].candidate_clusters.zonal[0]
assert direct_cluster == composed_cluster
java = composed_result.least_regret[i].candidate_clusters.regional[0]
assert java.cluster_type == "dgwkv"
# usually like 15 * 4 = ~50
assert 100 > java.count * java.instance.cpu > 20
def test_multiple_options():
result = planner.plan(
model_name="org.netflix.cassandra",
region="us-east-1",
desires=uncertain_mid,
num_results=4,
simulations=6,
)
least_regret = result.least_regret
# With only 128 simulations we have < 4 instance families
assert len(least_regret) < 4
families = [lr.candidate_clusters.zonal[0].instance.family for lr in least_regret]
for f in families:
assert f in set(("i3en", "m5d", "m5"))
# With 1024 simulations we get a 4th instance family (r5)
result = planner.plan(
model_name="org.netflix.cassandra",
region="us-east-1",
desires=uncertain_mid,
num_results=4,
simulations=1024,
)
least_regret = result.least_regret
assert len(least_regret) == 4
families = [lr.candidate_clusters.zonal[0].instance.family for lr in least_regret]
assert set(families) == set(("r5", "i3en", "m5d", "m5"))
| {"/service_capacity_modeling/models/org/netflix/crdb.py": ["/service_capacity_modeling/models/common.py"], "/service_capacity_modeling/models/org/netflix/__init__.py": ["/service_capacity_modeling/models/org/netflix/crdb.py"]} |
53,312 | CavemanIV/service-capacity-modeling | refs/heads/main | /service_capacity_modeling/models/common.py | import logging
import math
import random
from typing import Callable
from typing import Optional
from service_capacity_modeling.interface import AVG_ITEM_SIZE_BYTES
from service_capacity_modeling.interface import CapacityDesires
from service_capacity_modeling.interface import CapacityPlan
from service_capacity_modeling.interface import certain_float
from service_capacity_modeling.interface import certain_int
from service_capacity_modeling.interface import Clusters
from service_capacity_modeling.interface import Drive
from service_capacity_modeling.interface import Instance
from service_capacity_modeling.interface import Interval
from service_capacity_modeling.interface import RegionClusterCapacity
from service_capacity_modeling.interface import Requirements
from service_capacity_modeling.interface import ZoneClusterCapacity
from service_capacity_modeling.models import utils
logger = logging.getLogger(__name__)
# In square root staffing we have to take into account the QOS parameter
# Which is related to the probability that a user queues. On low tier clusters
# (aka critical clusters) we want a lower probability of queueing
def _QOS(tier: int) -> float:
# Halfin-Whitt delay function
# P(queue) ~= [1 + B * normal_cdf(B) / normal_pdf(B)] ^ -1
#
# P(queue) ~= 0.01
if tier == 0:
return 2.375
# P(queue) ~= 0.05
elif tier == 1:
return 1.761
# P(queue) ~= 0.2
elif tier == 2:
return 1.16
# P(queue) ~= 0.29 ~= 0.3
else:
return 1
def _sqrt_staffed_cores(rps: float, latency_s: float, qos: float) -> int:
# Square root staffing
# s = a + Q*sqrt(a)
return int(math.ceil((rps * latency_s) + qos * math.sqrt(rps * latency_s)))
def sqrt_staffed_cores(desires: CapacityDesires) -> int:
"""Computes cores given a sqrt staffing model"""
qos = _QOS(desires.service_tier)
read_rps, read_lat = (
desires.query_pattern.estimated_read_per_second.mid,
desires.query_pattern.estimated_mean_read_latency_ms.mid / 1000.0,
)
write_rps, write_lat = (
desires.query_pattern.estimated_write_per_second.mid,
desires.query_pattern.estimated_mean_write_latency_ms.mid / 1000.0,
)
read_cores = _sqrt_staffed_cores(read_rps, read_lat, qos)
write_cores = _sqrt_staffed_cores(write_rps, write_lat, qos)
return read_cores + write_cores
def simple_network_mbps(desires: CapacityDesires) -> int:
"""Computes network mbps with a simple model"""
read_bytes_per_second = (
desires.query_pattern.estimated_read_per_second.mid
* desires.query_pattern.estimated_mean_read_size_bytes.mid
)
write_bytes_per_second = (
desires.query_pattern.estimated_write_per_second.mid
* desires.query_pattern.estimated_mean_write_size_bytes.mid
)
net_bytes_per_sec = read_bytes_per_second + write_bytes_per_second
return int(max(1, math.ceil(net_bytes_per_sec / 125000)))
def compute_stateless_region(
instance: Instance,
needed_cores: int,
needed_memory_gib: float,
needed_network_mbps: float,
# Faster CPUs can execute operations faster
core_reference_ghz: float,
num_zones: int = 3,
) -> RegionClusterCapacity:
"""Computes a regional cluster of a stateless app
Basically just takes into cpu, memory, and network
returns: (count of instances, annual cost in dollars)
"""
# Stateless apps basically just use CPU resources and network
needed_cores = math.ceil(
max(1, needed_cores // (instance.cpu_ghz / core_reference_ghz))
)
count = max(2, math.ceil(needed_cores / instance.cpu))
# Now take into account the network bandwidth
count = max(count, math.ceil(needed_network_mbps / instance.net_mbps))
# Now take into account the needed memory
count = max(count, math.ceil(needed_memory_gib / instance.ram_gib))
# Try to keep zones balanced
count = utils.next_n(count, num_zones)
return RegionClusterCapacity(
cluster_type="stateless-app",
count=count,
instance=instance,
annual_cost=count * instance.annual_cost,
)
# pylint: disable=too-many-locals
def compute_stateful_zone(
instance: Instance,
drive: Drive,
needed_cores: int,
needed_disk_gib: float,
needed_memory_gib: float,
needed_network_mbps: float,
# Faster CPUs can execute operations faster
core_reference_ghz: float,
# EBS may need to scale for IOs, and datastores might need more
# or less IOs for a given data size as well as space
required_disk_ios: Callable[[float], float] = lambda x: 0,
required_disk_space: Callable[[float], float] = lambda x: x,
# The maximum amount of state we can hold per node in the database
# typically you don't want stateful systems going much higher than a
# few TiB so that recovery functions properly
max_local_disk_gib: float = 2048,
# Some stateful clusters have sidecars that take memory
reserve_memory: Callable[[float], float] = lambda x: 0,
# How much write buffer we get per instance (usually a percentage of
# the reserved memory, e.g. for buffering writes in heap)
write_buffer: Callable[[float], float] = lambda x: 0,
required_write_buffer_gib: float = 0,
# Some stateful clusters have preferences on per zone sizing
cluster_size: Callable[[int], int] = lambda x: x,
min_count: int = 0,
) -> ZoneClusterCapacity:
# Normalize the cores of this instance type to the latency reference
needed_cores = math.ceil(
max(1, needed_cores // (instance.cpu_ghz / core_reference_ghz))
)
# Datastores often require disk headroom for e.g. compaction and such
if instance.drive is not None:
needed_disk_gib = math.ceil(required_disk_space(needed_disk_gib))
# How many instances do we need for the CPU
count = math.ceil(needed_cores / instance.cpu)
# How many instances do we need for the ram, taking into account
# reserved memory for the application and system
count = max(
count,
math.ceil(
needed_memory_gib / (instance.ram_gib - reserve_memory(instance.ram_gib))
),
)
# Account for if the stateful service needs a certain amount of reserved
# memory for a given throughput.
if write_buffer(instance.ram_gib) > 0:
count = max(
count,
math.ceil(required_write_buffer_gib / (write_buffer(instance.ram_gib))),
)
# How many instances do we need for the network
count = max(count, math.ceil(needed_network_mbps / instance.net_mbps))
# How many instances do we need for the disk
if instance.drive is not None and instance.drive.size_gib > 0:
disk_per_node = min(max_local_disk_gib, instance.drive.size_gib)
count = max(count, math.ceil(needed_disk_gib / disk_per_node))
count = max(cluster_size(count), min_count)
cost = count * instance.annual_cost
attached_drives = []
if instance.drive is None and required_disk_space(needed_disk_gib) > 0:
# If we don't have disks attach GP2 in at 50% space overprovision
# because we can only (as of 2020-10-31) scale EBS once per 6 hours
# Note that ebs is provisioned _per node_ and must be chosen for
# the max of space and IOS
space_gib = max(1, math.ceil((needed_disk_gib * 2) / count))
io_gib = gp2_gib_for_io(required_disk_ios(needed_disk_gib / count))
# Provision EBS in increments of 200 GiB
ebs_gib = utils.next_n(max(1, max(io_gib, space_gib)), n=200)
attached_drive = drive.copy()
attached_drive.size_gib = ebs_gib
# TODO: appropriately handle RAID setups for throughput requirements
attached_drives.append(attached_drive)
cost = cost + attached_drive.annual_cost
logger.debug(
"For (cpu, memory_gib, disk_gib) = (%s, %s, %s) need (%s, %s, %s, %s)",
needed_cores,
needed_memory_gib,
needed_disk_gib,
count,
instance.name,
attached_drives,
cost,
)
return ZoneClusterCapacity(
cluster_type="stateful-cluster",
count=count,
instance=instance,
attached_drives=attached_drives,
annual_cost=cost,
)
# AWS GP2 gives 3 IOS / gb stored.
def gp2_gib_for_io(read_ios) -> int:
return int(max(1, read_ios // 3))
class WorkingSetEstimator:
def __init__(self):
self._cache = {}
def working_set_percent(
self,
# latency distributions of the read SLOs versus the drives
# expressed as scipy rv_continuous objects
drive_read_latency_dist,
read_slo_latency_dist,
# what percentile of disk latency should we target for keeping in
# memory. Not as this is _increased_ more memory will be reserved
target_percentile: float = 0.90,
min_working_set: float = 0.01,
) -> Interval:
# random cache eviction
if len(self._cache) >= 100:
self._cache.pop(random.choice(tuple(self._cache.keys())))
cache_key = (
id(drive_read_latency_dist),
id(read_slo_latency_dist),
target_percentile,
)
# Cached because ppf in particular is _really_ slow
if cache_key not in self._cache:
# How fast is the drive at the target percentile
minimum_drive_latency = drive_read_latency_dist.ppf(target_percentile)
# How much of the read latency SLO lies below the minimum
# drive latency. So for example if EBS's 99% is 1.7ms and we
# 45% of our read SLO lies below that then we need at least 45%
# of our data to be stored in memory.
required_percent = float(read_slo_latency_dist.cdf(minimum_drive_latency))
self._cache[cache_key] = certain_float(
max(required_percent, min_working_set)
)
return self._cache[cache_key]
_working_set_estimator = WorkingSetEstimator()
def working_set_from_drive_and_slo(
# latency distributions of the read SLOs versus the drives
# expressed as scipy rv_continuous objects
drive_read_latency_dist,
read_slo_latency_dist,
estimated_working_set: Optional[Interval] = None,
# what percentile of disk latency should we target for keeping in
# memory. Not as this is _increased_ more memory will be reserved
target_percentile: float = 0.90,
min_working_set: float = 0.01,
) -> Interval:
if estimated_working_set is not None:
return estimated_working_set
return _working_set_estimator.working_set_percent(
drive_read_latency_dist=drive_read_latency_dist,
read_slo_latency_dist=read_slo_latency_dist,
target_percentile=target_percentile,
min_working_set=min_working_set,
)
def item_count_from_state(
estimated_state_size_gib: Interval,
estimated_state_item_count: Optional[Interval] = None,
) -> Interval:
if estimated_state_item_count is not None:
return estimated_state_item_count
return certain_int(
int(estimated_state_size_gib.mid * 1024 * 1024 * 1024) // AVG_ITEM_SIZE_BYTES
)
def _add_optional_float(
left: Optional[float], right: Optional[float]
) -> Optional[float]:
if left is None and right is None:
return None
if left is None:
return right
if right is None:
return left
return left + right
def _add_interval(left: Interval, right: Interval) -> Interval:
return Interval(
low=(left.low + right.low),
mid=(left.mid + right.mid),
high=(left.high + right.high),
confidence=min(left.confidence, right.confidence),
model_with=left.model_with,
minimum_value=_add_optional_float(left.minimum_value, right.minimum_value),
maximum_value=_add_optional_float(left.maximum_value, right.maximum_value),
)
def _noop_zone(x: ZoneClusterCapacity) -> ZoneClusterCapacity:
return x
def _noop_region(x: RegionClusterCapacity) -> RegionClusterCapacity:
return x
def merge_requirements(
left_req: Requirements,
right_req: Requirements,
) -> Requirements:
merged_zonal, merged_regional = [], []
for req in list(left_req.zonal) + list(right_req.zonal):
merged_zonal.append(req)
for req in list(left_req.regional) + list(right_req.regional):
merged_regional.append(req)
merged_regrets = set(left_req.regrets) | set(right_req.regrets)
return Requirements(
zonal=merged_zonal, regional=merged_regional, regrets=tuple(merged_regrets)
)
def merge_plan(
left: Optional[CapacityPlan],
right: Optional[CapacityPlan],
zonal_transform: Callable[[ZoneClusterCapacity], ZoneClusterCapacity] = _noop_zone,
regional_transform: Callable[
[RegionClusterCapacity], RegionClusterCapacity
] = _noop_region,
) -> Optional[CapacityPlan]:
if left is None or right is None:
return None
merged_requirements = merge_requirements(left.requirements, right.requirements)
left_cluster = left.candidate_clusters
right_cluster = right.candidate_clusters
merged_clusters = Clusters(
total_annual_cost=(
left_cluster.total_annual_cost + right_cluster.total_annual_cost
),
zonal=(
[zonal_transform(z) for z in left_cluster.zonal]
+ [zonal_transform(z) for z in right_cluster.zonal]
),
regional=(
[regional_transform(z) for z in left_cluster.regional]
+ [regional_transform(z) for z in right_cluster.regional]
),
)
return CapacityPlan(
requirements=merged_requirements, candidate_clusters=merged_clusters
)
| {"/service_capacity_modeling/models/org/netflix/crdb.py": ["/service_capacity_modeling/models/common.py"], "/service_capacity_modeling/models/org/netflix/__init__.py": ["/service_capacity_modeling/models/org/netflix/crdb.py"]} |
53,313 | CavemanIV/service-capacity-modeling | refs/heads/main | /service_capacity_modeling/models/org/netflix/crdb.py | import logging
import math
from decimal import Decimal
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from service_capacity_modeling.interface import AccessConsistency
from service_capacity_modeling.interface import AccessPattern
from service_capacity_modeling.interface import CapacityDesires
from service_capacity_modeling.interface import CapacityPlan
from service_capacity_modeling.interface import CapacityRequirement
from service_capacity_modeling.interface import certain_float
from service_capacity_modeling.interface import certain_int
from service_capacity_modeling.interface import Clusters
from service_capacity_modeling.interface import Consistency
from service_capacity_modeling.interface import DataShape
from service_capacity_modeling.interface import Drive
from service_capacity_modeling.interface import FixedInterval
from service_capacity_modeling.interface import GlobalConsistency
from service_capacity_modeling.interface import Instance
from service_capacity_modeling.interface import Interval
from service_capacity_modeling.interface import QueryPattern
from service_capacity_modeling.interface import RegionContext
from service_capacity_modeling.interface import Requirements
from service_capacity_modeling.models import CapacityModel
from service_capacity_modeling.models.common import compute_stateful_zone
from service_capacity_modeling.models.common import simple_network_mbps
from service_capacity_modeling.models.common import sqrt_staffed_cores
from service_capacity_modeling.models.common import working_set_from_drive_and_slo
from service_capacity_modeling.stats import dist_for_interval
logger = logging.getLogger(__name__)
# Pebble does Leveled compaction with tieres of size??
# (FIXME) What does pebble actually do
def _crdb_io_per_read(node_size_gib, sstable_size_mb=1000):
gb = node_size_gib * 1024
sstables = max(1, gb // sstable_size_mb)
# 10 sstables per level, plus 1 for L0 (avg)
levels = 1 + int(math.ceil(math.log(sstables, 10)))
return levels
def _estimate_cockroachdb_requirement(
instance: Instance,
desires: CapacityDesires,
working_set: float,
reads_per_second: float,
max_rps_to_disk: int,
zones_per_region: int = 3,
copies_per_region: int = 3,
) -> CapacityRequirement:
"""Estimate the capacity required for one zone given a regional desire
The input desires should be the **regional** desire, and this function will
return the zonal capacity requirement
"""
# Keep half of the cores free for background work (compaction, backup, repair)
needed_cores = sqrt_staffed_cores(desires) * 2
# Keep half of the bandwidth available for backup
needed_network_mbps = simple_network_mbps(desires) * 2
needed_disk = math.ceil(
(1.0 / desires.data_shape.estimated_compression_ratio.mid)
* desires.data_shape.estimated_state_size_gib.mid
* copies_per_region
)
# Rough estimate of how many instances we would need just for the the CPU
# Note that this is a lower bound, we might end up with more.
needed_cores = math.ceil(
max(1, needed_cores // (instance.cpu_ghz / desires.core_reference_ghz))
)
rough_count = math.ceil(needed_cores / instance.cpu)
# Generally speaking we want fewer than some number of reads per second
# hitting disk per instance. If we don't have many reads we don't need to
# hold much data in memory.
instance_rps = max(1, reads_per_second // rough_count)
disk_rps = instance_rps * _crdb_io_per_read(max(1, needed_disk // rough_count))
rps_working_set = min(1.0, disk_rps / max_rps_to_disk)
# If disk RPS will be smaller than our target because there are no
# reads, we don't need to hold as much data in memory
needed_memory = min(working_set, rps_working_set) * needed_disk
# Now convert to per zone
needed_cores = max(1, needed_cores // zones_per_region)
needed_disk = max(1, needed_disk // zones_per_region)
needed_memory = max(1, int(needed_memory // zones_per_region))
logger.debug(
"Need (cpu, mem, disk, working) = (%s, %s, %s, %f)",
needed_cores,
needed_memory,
needed_disk,
working_set,
)
return CapacityRequirement(
requirement_type="crdb-zonal",
core_reference_ghz=desires.core_reference_ghz,
cpu_cores=certain_int(needed_cores),
mem_gib=certain_float(needed_memory),
disk_gib=certain_float(needed_disk),
network_mbps=certain_float(needed_network_mbps),
context={
"working_set": min(working_set, rps_working_set),
"rps_working_set": rps_working_set,
"disk_slo_working_set": working_set,
"replication_factor": copies_per_region,
"compression_ratio": round(
1.0 / desires.data_shape.estimated_compression_ratio.mid, 2
),
"read_per_second": reads_per_second,
},
)
def _upsert_params(cluster, params):
if cluster.cluster_params:
cluster.cluster_params.update(params)
else:
cluster.cluster_params = params
# pylint: disable=too-many-locals
def _estimate_cockroachdb_cluster_zonal(
instance: Instance,
drive: Drive,
desires: CapacityDesires,
zones_per_region: int = 3,
copies_per_region: int = 3,
max_local_disk_gib: int = 2048,
max_regional_size: int = 288,
max_rps_to_disk: int = 500,
) -> Optional[CapacityPlan]:
# cockroachdb doesn't like to deploy on small cpu instances
if instance.cpu < 8:
return None
# Right now CRDB doesn't deploy to cloud drives, just adding this
# here and leaving the capability to handle cloud drives for the future
if instance.drive is None:
return None
rps = desires.query_pattern.estimated_read_per_second.mid // zones_per_region
# Based on the disk latency and the read latency SLOs we adjust our
# working set to keep more or less data in RAM. Faster drives need
# less fronting RAM.
ws_drive = instance.drive or drive
working_set = working_set_from_drive_and_slo(
drive_read_latency_dist=dist_for_interval(ws_drive.read_io_latency_ms),
read_slo_latency_dist=dist_for_interval(
desires.query_pattern.read_latency_slo_ms
),
estimated_working_set=desires.data_shape.estimated_working_set_percent,
# CRDB has looser latency SLOs but we still want a lot of the data
# hot in cache. Target the 95th percentile of disk latency to
# keep in RAM.
target_percentile=0.95,
).mid
requirement = _estimate_cockroachdb_requirement(
instance=instance,
desires=desires,
working_set=working_set,
reads_per_second=rps,
zones_per_region=zones_per_region,
copies_per_region=copies_per_region,
max_rps_to_disk=max_rps_to_disk,
)
base_mem = (
desires.data_shape.reserved_instance_app_mem_gib
+ desires.data_shape.reserved_instance_system_mem_gib
)
cluster = compute_stateful_zone(
instance=instance,
drive=drive,
needed_cores=int(requirement.cpu_cores.mid),
needed_disk_gib=requirement.disk_gib.mid,
needed_memory_gib=requirement.mem_gib.mid,
needed_network_mbps=requirement.network_mbps.mid,
core_reference_ghz=requirement.core_reference_ghz,
# Assume that by provisioning enough memory we'll get
# a 90% hit rate, but take into account the reads per read
# from the per node dataset using leveled compaction
# FIXME: I feel like this can be improved
required_disk_ios=lambda x: _crdb_io_per_read(x) * math.ceil(0.1 * rps),
# CRDB requires ephemeral disks to be 80% full because leveled
# compaction can make progress as long as there is some headroom
required_disk_space=lambda x: x * 1.2,
max_local_disk_gib=max_local_disk_gib,
# cockroachdb clusters will autobalance across available nodes
cluster_size=lambda x: x,
min_count=1,
# Sidecars/System takes away memory from cockroachdb
# cockroachdb by default uses --max-sql-memory of 25% of system memory
# that cannot be used for caching
reserve_memory=lambda x: base_mem + 0.25 * x,
# TODO: Figure out how much memory CRDB needs to buffer writes
# in memtables in order to only flush occasionally
# write_buffer=...
# required_write_buffer_gib=...
)
# Communicate to the actual provision that if we want reduced RF
params = {"cockroachdb.copies": copies_per_region}
_upsert_params(cluster, params)
# cockroachdb clusters generally should try to stay under some total number
# of nodes. Orgs do this for all kinds of reasons such as
# * Security group limits. Since you must have < 500 rules if you're
# ingressing public ips)
# * Maintenance. If your restart script does one node at a time you want
# smaller clusters so your restarts don't take months.
# * NxN network issues. Sometimes smaller clusters of bigger nodes
# are better for network propagation
if cluster.count > (max_regional_size // zones_per_region):
return None
ec2_cost = zones_per_region * cluster.annual_cost
cluster.cluster_type = "cockroachdb"
clusters = Clusters(
total_annual_cost=round(Decimal(ec2_cost), 2),
zonal=[cluster] * zones_per_region,
regional=[],
)
return CapacityPlan(
requirements=Requirements(zonal=[requirement] * zones_per_region),
candidate_clusters=clusters,
)
class NflxCockroachDBCapacityModel(CapacityModel):
@staticmethod
def capacity_plan(
instance: Instance,
drive: Drive,
context: RegionContext,
desires: CapacityDesires,
extra_model_arguments: Dict[str, Any],
) -> Optional[CapacityPlan]:
# (FIXME): Need crdb input
# TODO: Use read requirements to compute RF.
copies_per_region: int = extra_model_arguments.get("copies_per_region", 3)
max_regional_size: int = extra_model_arguments.get("max_regional_size", 500)
max_rps_to_disk: int = extra_model_arguments.get("max_rps_to_disk", 500)
# Very large nodes are hard to recover
max_local_disk_gib: int = extra_model_arguments.get("max_local_disk_gib", 2048)
return _estimate_cockroachdb_cluster_zonal(
instance=instance,
drive=drive,
desires=desires,
zones_per_region=context.zones_in_region,
copies_per_region=copies_per_region,
max_regional_size=max_regional_size,
max_local_disk_gib=max_local_disk_gib,
max_rps_to_disk=max_rps_to_disk,
)
@staticmethod
def description():
return "Netflix Streaming CockroachDB Model"
@staticmethod
def extra_model_arguments() -> Sequence[Tuple[str, str, str]]:
return (
(
"copies_per_region",
"int = 3",
"How many copies of the data will exist e.g. RF=3. If unsupplied"
" this will be deduced from durability and consistency desires",
),
(
"max_regional_size",
"int = 288",
"What is the maximum size of a cluster in this region",
),
(
"max_local_disk_gib",
"int = 2048",
"The maximum amount of data we store per machine",
),
(
"max_rps_to_disk",
"int = 500",
"How many disk IOs should be allowed to hit disk per instance",
),
)
@staticmethod
def default_desires(user_desires, extra_model_arguments: Dict[str, Any]):
acceptable_consistency = set(
(
None,
AccessConsistency.linearizable,
AccessConsistency.linearizable_stale,
AccessConsistency.serializable,
AccessConsistency.serializable_stale,
AccessConsistency.never,
)
)
for key, value in user_desires.query_pattern.access_consistency:
if value.target_consistency not in acceptable_consistency:
raise ValueError(
f"CockroachDB can only provide {acceptable_consistency} access."
f"User asked for {key}={value}"
)
if user_desires.query_pattern.access_pattern == AccessPattern.latency:
return CapacityDesires(
query_pattern=QueryPattern(
access_pattern=AccessPattern.latency,
access_consistency=GlobalConsistency(
same_region=Consistency(
target_consistency=AccessConsistency.serializable,
),
cross_region=Consistency(
target_consistency=AccessConsistency.serializable,
),
),
estimated_mean_read_size_bytes=Interval(
low=128, mid=1024, high=65536, confidence=0.95
),
estimated_mean_write_size_bytes=Interval(
low=128, mid=1024, high=65536, confidence=0.95
),
# (FIXME): Need crdb input
# CockroachDB reads and writes can take CPU time as
# JOINs and such can be hard to predict.
estimated_mean_read_latency_ms=Interval(
low=1, mid=2, high=100, confidence=0.98
),
# Writes typically involve transactions which can be
# expensive, but it's rare for it to have a huge tail
estimated_mean_write_latency_ms=Interval(
low=1, mid=4, high=200, confidence=0.98
),
# Assume point queries "Single digit millisecond SLO"
read_latency_slo_ms=FixedInterval(
minimum_value=1,
maximum_value=100,
low=1,
mid=10,
high=20,
confidence=0.98,
),
write_latency_slo_ms=FixedInterval(
minimum_value=1,
maximum_value=100,
low=1,
mid=10,
high=20,
confidence=0.98,
),
),
# Most latency sensitive cockroachdb clusters are in the
# < 100GiB range
data_shape=DataShape(
estimated_state_size_gib=Interval(
low=10, mid=20, high=100, confidence=0.98
),
# Pebble compresses with Snappy by default
estimated_compression_ratio=Interval(
minimum_value=1.1,
maximum_value=8,
low=1.5,
mid=2.4,
high=4,
confidence=0.98,
),
# CRDB doesn't have a sidecar, but it does have data
# gateway taking about 1 MiB of memory
reserved_instance_app_mem_gib=0.001,
),
)
else:
return CapacityDesires(
# (FIXME): Need to pair with crdb folks on the exact values
query_pattern=QueryPattern(
access_pattern=AccessPattern.throughput,
access_consistency=GlobalConsistency(
same_region=Consistency(
target_consistency=AccessConsistency.serializable,
),
cross_region=Consistency(
target_consistency=AccessConsistency.serializable,
),
),
estimated_mean_read_size_bytes=Interval(
low=128, mid=4096, high=65536, confidence=0.95
),
estimated_mean_write_size_bytes=Interval(
low=128, mid=4096, high=65536, confidence=0.95
),
# (FIXME): Need crdb input
# CockroachDB analytics reads probably take extra time
# as they are full table scanning or doing complex JOINs
estimated_mean_read_latency_ms=Interval(
low=1, mid=20, high=100, confidence=0.98
),
# Throughput writes typically involve large transactions
# which can be expensive, but it's rare for it to have a
# huge tail
estimated_mean_write_latency_ms=Interval(
low=1, mid=20, high=100, confidence=0.98
),
# Assume scan queries "Tens of millisecond SLO"
read_latency_slo_ms=FixedInterval(
minimum_value=1,
maximum_value=100,
low=10,
mid=20,
high=99,
confidence=0.98,
),
write_latency_slo_ms=FixedInterval(
minimum_value=1,
maximum_value=100,
low=10,
mid=20,
high=99,
confidence=0.98,
),
),
# Most throughput sensitive cockroachdb clusters are in the
# < 100GiB range
data_shape=DataShape(
estimated_state_size_gib=Interval(
low=10, mid=20, high=100, confidence=0.98
),
# Pebble compresses with Snappy by default
estimated_compression_ratio=Interval(
minimum_value=1.1,
maximum_value=8,
low=1.5,
mid=2.4,
high=4,
confidence=0.98,
),
# CRDB doesn't have a sidecar, but it does have data
# gateway taking about 1 MiB of memory
reserved_instance_app_mem_gib=0.001,
),
)
nflx_cockroachdb_capacity_model = NflxCockroachDBCapacityModel()
| {"/service_capacity_modeling/models/org/netflix/crdb.py": ["/service_capacity_modeling/models/common.py"], "/service_capacity_modeling/models/org/netflix/__init__.py": ["/service_capacity_modeling/models/org/netflix/crdb.py"]} |
53,314 | CavemanIV/service-capacity-modeling | refs/heads/main | /service_capacity_modeling/models/org/netflix/__init__.py | from .cassandra import nflx_cassandra_capacity_model
from .crdb import nflx_cockroachdb_capacity_model
from .elasticsearch import nflx_elasticsearch_capacity_model
from .entity import nflx_entity_capacity_model
from .evcache import nflx_evcache_capacity_model
from .key_value import nflx_key_value_capacity_model
from .rds import nflx_rds_capacity_model
from .stateless_java import nflx_java_app_capacity_model
from .time_series import nflx_time_series_capacity_model
from .zookeeper import nflx_zookeeper_capacity_model
def models():
return {
"org.netflix.cassandra": nflx_cassandra_capacity_model,
"org.netflix.stateless-java": nflx_java_app_capacity_model,
"org.netflix.key-value": nflx_key_value_capacity_model,
"org.netflix.time-series": nflx_time_series_capacity_model,
"org.netflix.zookeeper": nflx_zookeeper_capacity_model,
"org.netflix.evcache": nflx_evcache_capacity_model,
"org.netflix.rds": nflx_rds_capacity_model,
"org.netflix.elasticsearch": nflx_elasticsearch_capacity_model,
"org.netflix.entity": nflx_entity_capacity_model,
"org.netflix.cockroachdb": nflx_cockroachdb_capacity_model,
}
| {"/service_capacity_modeling/models/org/netflix/crdb.py": ["/service_capacity_modeling/models/common.py"], "/service_capacity_modeling/models/org/netflix/__init__.py": ["/service_capacity_modeling/models/org/netflix/crdb.py"]} |
53,315 | iesmirnoff/whiteshadoofs | refs/heads/master | /whiteshadoofs/views.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
import whiteshadoofs.models as models
def main(request):
if request.method == 'GET' and request.META['QUERY_STRING']:
return HttpResponse(request.META['QUERY_STRING'])
else:
return render_to_response('index.html')
def objects_search(request):
"""Функция осуществляет поиск соответствующих get-запросу
объектов в бд, передает их шаблону в качестве контекста.
"""
nothing_found = "Ничего не нашлось..."
empty_title = 'Поле "Название" является обязательным.'
if not request.GET['title']: return HttpResponse(empty_title)
in_desc = True if request.GET['in_desc'] == 'true' else False
if request.GET['country']:
in_country = models.Object.objects.filter(
address__locality__region__country__title__icontains=request.GET['country']
)
else:
in_country = models.Object.objects.all()
if request.GET['region']:
in_region = in_country.filter(
address__locality__region__title__icontains=request.GET['region']
)
else:
in_region = in_country
if request.GET['city']:
in_locality = in_region.filter(
address__locality__title__icontains=request.GET['locality']
)
else:
in_locality = in_region
if request.GET['street']:
in_street = in_locality.filter(
address__street__icontains=request.GET['street']
)
else:
in_street = in_locality
result = in_street.filter(title__icontains=request.GET['title'])
result = list(result)
if in_desc:
result += in_street.filter(description__icontains=request.GET['title'])
if not result: return HttpResponse(nothing_found)
return render_to_response('search_result.html', {'result': result})
| {"/whiteshadoofs/views.py": ["/whiteshadoofs/models.py"], "/whiteshadoofs/admin.py": ["/whiteshadoofs/models.py"]} |
53,316 | iesmirnoff/whiteshadoofs | refs/heads/master | /whiteshadoofs/models.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
"""Models for db 'ws' """
"""
"""
from django.db import models
class Role(models.Model):
"""Соответствует таблице role"""
title = models.CharField(max_length=45)
def __unicode__(self):
return self.title
class User(models.Model):
"""Соответствует таблице user, зарегистр-му пользователю сервиса"""
name = models.CharField(max_length=45)
soc_network = models.CharField(max_length=45, blank=True)
soc_network_id = models.CharField(max_length=45, blank=True)
nick = models.CharField(max_length=45, blank=True)
role = models.ForeignKey(Role)
def __unicode__(self):
return self.name
class Image(models.Model):
"""TO DO"""
pass
def __unicode__(self):
pass
class Country(models.Model):
"""Соответствует таблице country, стране, в кот. находится объект"""
title = models.CharField(max_length=30)
def __unicode__(self):
return self.title
class Region(models.Model):
"""Соответствует таблице region, региону, в кот. находится объект"""
title = models.CharField(max_length=45,)
country = models.ForeignKey(Country)
def __unicode__(self):
return u"{0}, {1}".format( self.title, self.country )
class Locality(models.Model):
"""Соответствует таблице Locality, насел. пункту, в кот. находится объект"""
title = models.CharField(max_length=45)
region = models.ForeignKey(Region)
def __unicode__(self):
return u"{0}, {1}".format( self.title, self.region )
class Address(models.Model):
"""Соответствует таблице address, полному адресу объекта"""
street = models.CharField(max_length=45)
latitude = models.FloatField()
longitude = models.FloatField()
locality = models.ForeignKey(Locality)
def __unicode__(self):
return u"{0}, {1}".format( self.street, self.locality )
class Mem_event(models.Model):
"""Соответствует таблице mem_event, ист. событию, связанному с объектом"""
title = models.CharField(max_length=45)
description = models.TextField(blank=True)
def __unicode__(self):
return self.title
class Object(models.Model):
state = models.CommaSeparatedIntegerField(max_length=5)
title = models.CharField(max_length=255)
category = models.CommaSeparatedIntegerField(max_length=10)
adding_date = models.DateField(auto_now_add=True)
description = models.TextField(blank=True)
user = models.ForeignKey(User)
mem_event = models.ForeignKey(Mem_event)
address = models.ForeignKey(Address)
def __unicode__(self):
return self.title
| {"/whiteshadoofs/views.py": ["/whiteshadoofs/models.py"], "/whiteshadoofs/admin.py": ["/whiteshadoofs/models.py"]} |
53,317 | iesmirnoff/whiteshadoofs | refs/heads/master | /whiteshadoofs/admin.py | #!/usr/bin/env python
#-*-coding:utf-8-*-
"""Classes for administrator's interface"""
from django.contrib import admin
from whiteshadoofs.models import *
admin.site.register(Role)
admin.site.register(User)
admin.site.register(Country)
admin.site.register(Region)
admin.site.register(Locality)
admin.site.register(Address)
admin.site.register(Mem_event)
admin.site.register(Object)
| {"/whiteshadoofs/views.py": ["/whiteshadoofs/models.py"], "/whiteshadoofs/admin.py": ["/whiteshadoofs/models.py"]} |
53,319 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/forms.py | from FoodApp.models import ReviewModel
from django import forms
class CreateReviewForm(forms.ModelForm):
class Meta:
model = ReviewModel
fields=['rate','text'] | {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,320 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/models.py | from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import User
RATE_CHOICES = [
('Poor','Poor'),
('Average','Average'),
('Good','Good'),
('Excellent','Excellent')
]
DIET_CHOICES = [
(1,'BreakFast'),
(2,'Lunch'),
(3,'Snacks'),
(4,'Dinner')
]
class FoodModel(models.Model):
item_name = models.CharField(max_length=200,null=False,blank=False)
item_image = models.ImageField(null=False,blank=True,upload_to='static/images/')
item_desc = models.CharField(max_length = 200,null=False,blank = False)
createdon = models.DateTimeField(default=now, editable=True)
diet = models.SmallIntegerField(choices =DIET_CHOICES,null=False,blank=False)
def __str__(self):
return self.item_name
class Meta:
ordering = ('-createdon',)
class ReviewModel(models.Model):
student = models.ForeignKey(User,on_delete=models.CASCADE)
foodmodel = models.ForeignKey(FoodModel,on_delete=models.CASCADE)
createdon = models.DateTimeField(default=now, editable=True)
text = models.CharField(max_length = 600 , null=False,blank=True)
rate = models.CharField(max_length=100,choices=RATE_CHOICES,default="Excellent")
def __str__(self):
return self.student.username
| {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,321 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/migrations/0002_auto_20210206_1420.py | # Generated by Django 3.0.4 on 2021-02-06 08:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('FoodApp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='foodmodel',
name='diet',
field=models.SmallIntegerField(choices=[(1, 'BreakFast'), (2, 'Lunch'), (3, 'Snacks'), (4, 'Dinner')]),
),
]
| {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,322 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/views.py | from django.shortcuts import render,redirect
from FoodApp.models import FoodModel,ReviewModel
from FoodApp.forms import CreateReviewForm
from django.contrib.auth import login,logout,authenticate
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.forms import AuthenticationForm
import datetime
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
def Home(request):
today = datetime.date.today()
itemlist = FoodModel.objects.filter(createdon__year=today.year, createdon__month=today.month, createdon__day=today.day)
context = {
"itemlist" : itemlist
}
return render(request,'FoodApp/home.html',context)
@login_required(login_url="login")
def createReview(request,pk):
usernameg = None
if request.user.is_authenticated:
usernameg = request.user.get_username()
userinstance =User.objects.get(username=usernameg)
foodmodelinstance = FoodModel.objects.get(id=pk)
if request.method =='POST':
form = CreateReviewForm(request.POST)
if form.is_valid():
rate = form.cleaned_data['rate']
text = form.cleaned_data['text']
obj = ReviewModel(student=userinstance,foodmodel=foodmodelinstance,rate=rate,text=text)
obj.save()
return redirect('home')
form = CreateReviewForm()
context={
'form':form,
'objid' : pk
}
return render(request,'FoodApp/create_review.html',context)
def LogOut(request):
logout(request)
return redirect('home')
def LogIn(request):
form = AuthenticationForm
if request.method == 'POST':
print('I am in post')
form = AuthenticationForm(request,data = request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username,password=password)
if user is not None:
login(request,user)
return redirect('home')
context= {
'form':form
}
return render(request,'FoodApp/login.html',context)
def register(request):
form = UserCreationForm
if request.method=='POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
context = {
"form" : form
}
return render(request,'FoodApp/register.html',context)
@login_required(login_url="login")
def AllReviews(request):
objs = ReviewModel.objects.all()
context={
'objs' : objs
}
return render(request,'FoodApp/allreviews.html',context) | {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,323 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/urls.py | from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from FoodApp.views import Home,createReview,LogOut,LogIn,register,AllReviews
from django.views.static import serve
from django.conf.urls.static import static
from django.conf.urls import url
urlpatterns=[
path('',Home,name='home'),
path('create/<str:pk>/',createReview,name='review'),
path('login/',LogIn,name='login'),
path('logout/',LogOut,name='logout'),
path('register/',register,name='register'),
path('allreviews/',AllReviews,name='allreviews'),
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}),
]
urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) | {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,324 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/migrations/0003_auto_20210206_1422.py | # Generated by Django 3.0.4 on 2021-02-06 08:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('FoodApp', '0002_auto_20210206_1420'),
]
operations = [
migrations.AlterField(
model_name='reviewmodel',
name='rate',
field=models.SmallIntegerField(choices=[('Poor', 'Poor'), ('Average', 'Average'), ('Good', 'Good'), ('Excellent', 'Excellent')], default=1),
),
]
| {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,325 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/migrations/0001_initial.py | # Generated by Django 3.0.4 on 2021-02-06 08:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='FoodModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('item_name', models.CharField(max_length=200)),
('item_image', models.ImageField(blank=True, upload_to='static/images/')),
('item_desc', models.CharField(max_length=200)),
('createdon', models.DateTimeField(default=django.utils.timezone.now)),
('diet', models.CharField(choices=[('BreakFast', 'BreakFast'), ('Lunch', 'Lunch'), ('Snacks', 'Snacks'), ('Snacks', 'Dinner')], max_length=100)),
],
options={
'ordering': ('-createdon',),
},
),
migrations.CreateModel(
name='ReviewModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('createdon', models.DateTimeField(default=django.utils.timezone.now)),
('text', models.CharField(blank=True, max_length=600)),
('rate', models.SmallIntegerField(choices=[('Poor', 'Poor'), ('Average', 'Average'), ('Good', 'Good'), ('Excellent', 'Excellent')], default='Excellent')),
('foodmodel', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='FoodApp.FoodModel')),
('student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,326 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/admin.py | from django.contrib import admin
from FoodApp.models import FoodModel,ReviewModel
# Register your models here.
admin.site.register(FoodModel)
admin.site.register(ReviewModel)
| {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,327 | pradeepvarma22/Food_Review | refs/heads/master | /FoodApp/migrations/0004_auto_20210206_1426.py | # Generated by Django 3.0.4 on 2021-02-06 08:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('FoodApp', '0003_auto_20210206_1422'),
]
operations = [
migrations.AlterField(
model_name='reviewmodel',
name='rate',
field=models.CharField(choices=[('Poor', 'Poor'), ('Average', 'Average'), ('Good', 'Good'), ('Excellent', 'Excellent')], default='Dinner', max_length=100),
),
]
| {"/FoodApp/forms.py": ["/FoodApp/models.py"], "/FoodApp/views.py": ["/FoodApp/models.py", "/FoodApp/forms.py"], "/FoodApp/urls.py": ["/FoodApp/views.py"], "/FoodApp/admin.py": ["/FoodApp/models.py"]} |
53,332 | hollsmarie/Python_Deployment | refs/heads/master | /apps/examThree/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
import pytz
from django.utils import timezone
from time import strptime,strftime
from datetime import datetime, date, time
import datetime
from ..loginReg.models import User
class TripManager(models.Manager):
def validate(self, postData):
errors = {}
now = timezone.now()
currentDate = unicode(datetime.datetime.now().date())
startDate = unicode(postData['startDate'])
endDate = unicode(postData['endDate'])
if len(postData['destination']) < 1:
errors["Destination"] = "Destination name cannot be empty"
if len(postData['description']) < 1:
errors["Description"] = "Description cannot be empty"
if len(str(postData["startDate"])) < 1:
errors["Start Date"] = "Date cannot be empty"
if len(str(postData["endDate"])) < 1:
errors["End Date"] = "Date cannot be empty"
if startDate < currentDate:
errors["Start Date"] = "Time travel isn't real."
if endDate < startDate:
errors["End Date"] = "Trip cannot end before it begins, party pooper!"
return errors
class Trip(models.Model):
destination = models.CharField(max_length=50)
description = models.CharField(max_length=255)
startDate = models.DateField(auto_now=False, auto_now_add=False, null=True)
endDate = models.DateField(auto_now=False, auto_now_add=False, null=True)
favorites = models.ManyToManyField(User, related_name="userFaves")
userAdded = models.ForeignKey(User, related_name="userAdds")
objects = TripManager() | {"/apps/examThree/models.py": ["/apps/loginReg/models.py"], "/apps/examThree/views.py": ["/apps/examThree/models.py", "/apps/loginReg/models.py"]} |
53,333 | hollsmarie/Python_Deployment | refs/heads/master | /apps/examThree/migrations/0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-01 18:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('loginReg', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Trip',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('destination', models.CharField(max_length=50)),
('description', models.CharField(max_length=255)),
('startDate', models.DateField(null=True)),
('endDate', models.DateField(null=True)),
('favorites', models.ManyToManyField(related_name='userFaves', to='loginReg.User')),
('userAdded', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='userAdds', to='loginReg.User')),
],
),
]
| {"/apps/examThree/models.py": ["/apps/loginReg/models.py"], "/apps/examThree/views.py": ["/apps/examThree/models.py", "/apps/loginReg/models.py"]} |
53,334 | hollsmarie/Python_Deployment | refs/heads/master | /apps/examThree/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.contrib import messages
from datetime import date, time, datetime
import datetime
from .models import *
from ..loginReg.models import User
from django.shortcuts import render, HttpResponse, redirect
def index(request ):
currentUser = User.objects.get(id=request.session['userid'])
trips = currentUser.userFaves.all()
othersTrips = Trip.objects.exclude(favorites=currentUser)
context = {
"trips" : trips,
"othersTrips": othersTrips,
}
return render(request,'examThree/index.html', context)
def add(request):
return render(request,'examThree/add.html')
def update(request):
currentUser = User.objects.get(id=request.session['userid'])
errors = Trip.objects.validate(request.POST)
if len(errors) > 0:
for error in errors.iteritems():
messages.error(request, error)
return redirect('examThree:add')
else:
Trip.objects.create(description=request.POST["description"], destination=request.POST["destination"], startDate=request.POST["startDate"], endDate=request.POST["endDate"], userAdded = currentUser)
return redirect(reverse('examThree:index'))
def show(request, id):
trip = Trip.objects.get(id=id)
context = {
"trip": trip
}
return render(request,'examThree/show.html', context)
def addfave(request, id):
currentUser = User.objects.get(id=request.session['userid'])
fave = Trip.objects.get(id=id)
fave.favorites.add(currentUser)
fave.save()
return redirect(reverse('examThree:index'))
def remove(request, id):
currentUser = User.objects.get(id=request.session['userid'])
fave = Trip.objects.get(id=id)
fave.favorites.remove(currentUser)
fave.save()
return redirect(reverse('examThree:index')) | {"/apps/examThree/models.py": ["/apps/loginReg/models.py"], "/apps/examThree/views.py": ["/apps/examThree/models.py", "/apps/loginReg/models.py"]} |
53,335 | hollsmarie/Python_Deployment | refs/heads/master | /apps/loginReg/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
import bcrypt
import re
NAME_REGEX = re.compile(r"^[-a-zA-Z']+$")
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
class UserManager(models.Manager):
def validate(self, postData): #declare a controller of validation for the registration checker and create an empty dictionary of errors. Checks for errors below
errors = {}
if len(postData['first']) < 2:
errors["First name cannot be blank!"] = "First"
if not NAME_REGEX.match(postData['first']):
errors["First name contains invalid characters or spaces."] = "First"
if not NAME_REGEX.match(postData['last']):
errors["Last name contains invalid characters or spaces."] = "Last"
if len(postData['last']) < 2:
errors["Last name cannot be blank!"] = "Last"
if len(postData['email']) < 2:
errors["Email cannot be blank!"] = "Email"
if (User.objects.filter(email=postData["email"])):
errors["Email already in use"] = "Email"
if not EMAIL_REGEX.match(postData['email']):
errors["Invalid Email Address!"] = "Email"
elif User.objects.filter(email = postData["email"]).count() > 0:
errors["Email address already exists in database!"] = "Email"
if len(postData['password']) < 8:
errors["Password much be at least 8 characters long"] = "PasswordEmail"
if (postData['password']) != (postData['confirm']):
errors["Passwords must match."] = "Password"
return errors
def loginvalidate(self, postData): #declare a controller to check for errors in your login process
errors = {}
if User.objects.filter(email=postData["email"]): #if the email the user enters matches
currentUser = User.objects.get(email=postData["email"]) #creates a variable called current user and sets the object equal to it
tempPW = currentUser.password #sets the temporary PW to be the CurrentUser's pw
if not bcrypt.checkpw(postData["password"].encode(), tempPW.encode()): #encrypts the password
errors["Invalid password"] = "password."
else:
errors["Email address does not exist in database."] = "Email"
return errors
class User(models.Model):
first = models.CharField(max_length=30)
last = models.CharField(max_length=30)
email = models.CharField(max_length=30)
password = models.CharField(max_length=30)
objects = UserManager()
| {"/apps/examThree/models.py": ["/apps/loginReg/models.py"], "/apps/examThree/views.py": ["/apps/examThree/models.py", "/apps/loginReg/models.py"]} |
53,336 | hollsmarie/Python_Deployment | refs/heads/master | /apps/loginReg/views.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse, redirect
from django.contrib import messages #imports messages for errors
from .models import * #imports everything from models
def index(request):
if "userid" in request.session: # if a session id is present
print "userid in session" #print in the terminal to tell me
return render(request,'success.html')
else: #if there is no user in session
print "no user in session" #print it in the terminal
return render (request, 'index.html') #and take the person back to the homepage
def register(request): #never renders a page, it only processes the registration
errors = User.objects.validate(request.POST) #creates a variable and assigns the validate object to it, which contains everything in request.post
if len(errors) > 0: #if there are any errors (which is determined in models)
for error in errors: #for each error in the list of errors
messages.error(request,error) #print messages of the error
return redirect ('/')
pwhash= bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt()) #hashing password and setting a variable for it
newUser = User.objects.create(first=request.POST['first'], last=request.POST['last'], email= request.POST['email'], password = pwhash) #create a user out of the information passed in the registration form and set it to a variable of newUser
request.session["userid"] = newUser.id #set session id to newuser id
request.session["first"] = newUser.first #set the first name attached to the session to the newUser's first name
return redirect('/success')
def login(request): #never renders a page, it only processes the login
errors = User.objects.loginvalidate(request.POST) #setting a variable of errors equal to all of the errors gathered from the models page
if len(errors) > 0: #if there are any errors present
for error in errors:
messages.error(request,error) #tell us with the messages function
return redirect ('/')
else:
print "got here"
user = User.objects.filter(email=request.POST['email'])[0] #run query to filter for email equal to one in the databast. A list is returned. [0] calls that place in the list. Then you need to use key/value for dictionary
request.session["userid"] = user.id #set session id to be the userid
request.session["first"] = user.first
return redirect("/success")
def logout(request, methods='POST'):
request.session.clear() #clears session
return redirect('/')
def success(request):
user = request.session["userid"] #gets the user from the database
return render(request,'success.html') | {"/apps/examThree/models.py": ["/apps/loginReg/models.py"], "/apps/examThree/views.py": ["/apps/examThree/models.py", "/apps/loginReg/models.py"]} |
53,337 | hollsmarie/Python_Deployment | refs/heads/master | /apps/examThree/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^add$', views.add, name='add'),
url(r'^update$', views.update, name='update'),
url(r'^(?P<id>\d+)/remove$', views.remove, name='remove'),
url(r'^(?P<id>\d+)/show$', views.show, name='show'),
url(r'^(?P<id>\d+)/addfave$', views.addfave, name='addfave'),
] | {"/apps/examThree/models.py": ["/apps/loginReg/models.py"], "/apps/examThree/views.py": ["/apps/examThree/models.py", "/apps/loginReg/models.py"]} |
53,340 | flychensc/apple | refs/heads/master | /app_exp_val.py | """
绘制期望值
"""
import dash
import dash_html_components as html
import dash_core_components as dcc
from lottery import get_history, expected_value
codes = ['双色球', '七乐彩', '3D', '大乐透', '排列三', '排列五', '七星彩']
count = 20
datas = []
for c in codes:
print('Get %s data...' % c)
try:
his = get_history(c, count)
except AttributeError:
print('Fail to get history')
continue
exp = expected_value(his)
data={'type':'line', 'name':c}
data['x'] = [d for (d, e) in exp]
data['y'] = [e for (d, e) in exp]
datas.append(data)
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='期望值对比'),
html.Div(children='''
最近%d期
''' % count),
dcc.Graph(
id='exp-value-graph',
figure={
'data':datas,
'layout':{
'title':'期望值'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,341 | flychensc/apple | refs/heads/master | /lottery/__init__.py | from .ticket import get_history
from .utilities import expected_value, similar, is_winning, iter_history
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,342 | flychensc/apple | refs/heads/master | /coll_plw.py | """
排列五的概率输出
"""
from lottery import get_history
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
CODE = '排列五'
MIN = 1
COUNT = 200
def _calc_prob(num, datas):
"""
计算num在datas里的概率
e.g.:
num = 1
data = [[2,3],[1,7],[3,6]]
retunr 1/3
"""
count = datas.count(num)
# count/len(datas)
return round(count/len(datas)*100)
def calc_loc(historys, loc):
"""
{
0: [0.16, 0.16, 0.15, ...],
1: [0.16, 0.16, 0.22, ...],
...
9: [0.16, 0.16, 0.02, ...],
}
"""
history_numbers = [history['result'][loc-1] for history in historys]
result = dict()
for num in range(0,10): #0-9
# result.setdefault(num, [])
prob_list = list()
size = len(history_numbers)
while size >= MIN:
prob_list.append(_calc_prob(num, history_numbers[:size]))
size -= 1
result[num] = prob_list
return result
def gen_xls(historys):
with pd.ExcelWriter('排列五.xlsx') as writer:
for loc in range(1,5+1):
cols1 = ["近%d期" % i for i in range(len(historys), MIN-1, -1)]
data1 = calc_loc(historys, loc)
df1 = pd.DataFrame.from_dict(data1, orient='index', columns=cols1)
df1.to_excel(writer, sheet_name=f"第{loc}位")
def gen_html(historys):
children = [
html.H1(children='排列五分析'),
html.Div(children='数学期望值趋势'),
]
for loc in range(1,5+1):
cols = ["近%d期" % i for i in range(len(historys), MIN-1, -1)]
datas = []
for k,v in calc_loc(historys, loc).items():
data={'type':'line', 'name':k}
data['x'] = cols
data['y'] = v
datas.append(data)
children.append(dcc.Graph(
id=f'{loc}-exp-val-graph',
figure={
'data':datas,
'layout':{
'title':f'第{loc}位趋势'
}
}
))
app = dash.Dash()
app.layout = html.Div(children=children)
app.run_server(debug=True)
if __name__ == '__main__':
historys = get_history(CODE, COUNT)
#gen_xls(historys)
gen_html(historys)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,343 | flychensc/apple | refs/heads/master | /rand_select.py | """
机选,
从以往count期结果里,随机k个抽选号码,随机选择一份
"""
import random
from lottery import get_history, similar, is_winning, iter_history
def _rand_select_list(results):
pools = {}
for result in results:
for idx, value in enumerate(result):
# 【排列】按位区分,放入历史每位的数据
pools.setdefault(idx, list())
pools[idx].append(value)
result = []
for sequence in pools.values():
random.shuffle(sequence)
result.append(random.choice(sequence))
return result
def _rand_select_dict(results):
pools = {}
for result in results:
for position, sequence in result.items():
if type(sequence) is not list:
sequence = [sequence]
# 【组合】按颜色区分,放入历史每个颜色的数据,以及数量
pools.setdefault(position, (list(), len(sequence)))
pools[position][0].extend(sequence)
result = {}
for position, (sequence, size) in pools.items():
random.shuffle(sequence)
if size != 1:
while 1:
result[position] = random.choices(sequence, k=size)
if len(result[position]) == len(set(result[position])):
break
else:
result[position] = random.choice(sequence)
return result
def _rand_select(code, historys, k=10):
_select_func = {
'七星彩': _rand_select_list,
'大乐透': _rand_select_dict,
'排列五': _rand_select_list,
'排列三': _rand_select_list,
'双色球': _rand_select_dict,
'七乐彩': _rand_select_dict,
'3D': _rand_select_list,
}
_ref_range = {
'七星彩': (5, 14),
'大乐透': (12, 18),
'排列五': (6, 12),
'排列三': (4, 16),
'双色球': (12, 20),
'七乐彩': (16, 24),
'3D': (5, 15),
}
# only result
results = [history['result'] for history in historys]
# random selection
(s_min, s_max) = _ref_range[code]
rs = []
while 1:
r = _select_func[code](results)
s = similar(r, results)
if s_min < s*100 < s_max:
rs.append((r, s))
if len(rs) == k:
break
return random.choice(rs)
def rand_select(code, count=30):
# get history
historys = get_history(code, count)
one = _rand_select(code, historys)
print("{0}\r\n {1}\r\n {2:.2f}%\r\n".format(code, one[0], one[1]*100))
def test_rand_select(code, count=30):
def _handler(code, latest, past):
my = _rand_select(code, past)[0]
result = latest['result']
if is_winning(code, my, result):
return my
period = 70
out = iter_history(code, _handler, count, period)
probability = len(out)/period
print("{0}概率为{1:.2f}%".format(code, probability*100))
if __name__ == "__main__":
codes = ['双色球', '排列三', '排列五', '七星彩']
for code in codes:
test_rand_select(code)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,344 | flychensc/apple | refs/heads/master | /app_sim_val.py | """
绘制相似度
"""
import dash
import dash_html_components as html
import dash_core_components as dcc
from lottery import get_history, similar, iter_history
codes = ['双色球', '七乐彩', '3D', '大乐透', '排列三', '排列五', '七星彩']
count = 30
datas = []
for c in codes:
print('Get %s data...' % c)
try:
his = get_history(c, count*2)
except AttributeError:
print('Fail to get history')
continue
sim = []
date = []
def _collecter(code, latest, past):
sim.append(similar(latest['result'], [one['result'] for one in past])*100)
date.append(latest['date'])
iter_history(c, _collecter)
data={'type':'line', 'name':c}
data['x'] = date
data['y'] = sim
datas.append(data)
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='相似度对比'),
html.Div(children='''
最近%d期
''' % count),
dcc.Graph(
id='exp-value-graph',
figure={
'data':datas,
'layout':{
'title':'相似度'
}
}
)
])
if __name__ == '__main__':
app.run_server(debug=True)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,345 | flychensc/apple | refs/heads/master | /lottery/utilities.py | """
expected_value 计算彩票期望值
similar 计算相似度,【排列】判断对于位的数值相同与否。【组合】判断每个颜色相同的数值数量。
"""
from numpy import mean
from lottery import get_history
def _expected_value(his_one):
"""
(每级获奖数量/销售数量)*每级奖金的汇总
"""
return sum([grade['money']*(grade['num']/his_one['total']) for grade in his_one['grades']])
def expected_value(history):
if type(history) is list:
return [(one['date'], _expected_value(one)) for one in history]
else:
return [(history['date'], _expected_value(history))]
def _similar(data, sample):
"""
data与sample匹配的位(个)数/总位(个)数
"""
if type(sample) is list:
matched = 0
size = len(sample)
for p in range(size):
if data[p] == sample[p]:
matched += 1
return matched/size
elif type(sample) is dict:
matched = 0
size = 0
for k, v in sample.items():
if type(v) is list:
size += len(v)
for d in data[k]:
if d in v:
matched += 1
else:
size += 1
if v == data[k]:
matched += 1
return matched/size
def similar(data, samples):
if type(samples) is list:
values = [_similar(data, sample) for sample in samples]
else:
values = [_similar(data, samples)]
return round(mean(values), 4)
def _is_permutation_winning(my, result, count):
"""判断是否匹配(排列方式)
my: 排列数1
result: 排列数2
count: 匹配的位数
e.g.:
my = [9,9,8,5,6,3,8]
result = [2,0,3,5,6,4,9]
count = 2
return is True
"""
s, e = 0, count #逐个切片
while e <= len(result):
if my[s:e] == result[s:e]:
return True
s += 1
e += 1
return False
def _is_combination_winning(my, result, count):
"""判断是否匹配(组合方式)
my: 组合数1
result: 组合数2
count: 匹配的个数
e.g.:
my = [1,3,8,15,16,23]
result = [2,3,6,15,20,23]
count = 3
return is True
"""
check = set(result)
for m in my:
check.add(m)
if (len(check) - len(result)) == (len(result) - count):
return True
return False
def is_winning(code, my, result):
"""判断是否中奖
code: 彩票类别
my: 投注号码
result: 开奖结果
e.g.:
code = '排列三'
my = [1,3,8]
result = [1,8,2]
return is False
"""
if code in ['排列五', '排列三']:
return my == result
if code in ['七星彩']:
if _is_permutation_winning(my, result, 7):
return True
if _is_permutation_winning(my, result, 6):
return True
if _is_permutation_winning(my, result, 5):
return True
if _is_permutation_winning(my, result, 4):
return True
if _is_permutation_winning(my, result, 3):
return True
if _is_permutation_winning(my, result, 2):
return True
if code in ['双色球']:
if my['blue'] == result['blue'] and _is_combination_winning(my['red'], result['red'], 6):
return True
if _is_combination_winning(my['red'], result['red'], 6):
return True
if my['blue'] == result['blue'] and _is_combination_winning(my['red'], result['red'], 5):
return True
if my['blue'] == result['blue'] and _is_combination_winning(my['red'], result['red'], 4) or _is_combination_winning(my['red'], result['red'], 5):
return True
if my['blue'] == result['blue'] and _is_combination_winning(my['red'], result['red'], 3) or _is_combination_winning(my['red'], result['red'], 4):
return True
if my['blue'] == result['blue']:
return True
return False
def iter_history(code, handler, count=30, period=30):
"""判断是否中奖
code: 彩票类别
handler: 处理函数
count: 每个待处理数据的数量
period: 处理多长时间的数据
e.g.:
historys = [[1,2],[1,3],[2,3],[2,4],[3,5],[4,5]]
count = 3, period = 2
1st:
latest = [1,2]
past = [[1,3],[2,3],[2,4]]
2nd:
latest = [1,3]
past = [[2,3],[2,4],[3,5]]
3rd:
latest = [2,3]
past = [[2,4],[3,5],[4,5]]
"""
history = get_history(code, count+period)
assert(len(history) == (count+period))
out = list()
idx = 0
while idx < period:
latest = history[idx]
past = history[idx+1:idx+1+count]
idx += 1
ret = handler(code, latest, past)
if ret:
out.append(ret)
return out
if __name__ == "__main__":
from ticket import get_history
data = get_history('3D', count=10)
exp = expected_value(data)
print(exp)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,346 | flychensc/apple | refs/heads/master | /coll_dlt.py | """
大乐透的概率输出
"""
from lottery import get_history
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
CODE = '大乐透'
RED_MIN = 1
BLUE_MIN = 1
COUNT = 200
def _calc_prob(num, datas):
"""
计算num在datas里的概率
e.g.:
num = 1
data = [[2,3],[1,7],[3,6]]
retunr 1/3
"""
match = 0
for data in datas:
if num in data:
match += 1
# match/len(datas)
return round(match/len(datas)*100)
def calc_red(historys):
"""
{
1: [0.16, 0.16, 0.15, ...],
2: [0.16, 0.16, 0.22, ...],
...
35: [0.16, 0.16, 0.02, ...],
}
"""
reds = [history['result']['red'] for history in historys]
result = dict()
for num in range(1,36): #35选5
# result.setdefault(num, [])
prob_list = list()
size = len(reds)
while size >= RED_MIN:
prob_list.append(_calc_prob(num, reds[:size]))
size -= 1
result[num] = prob_list
return result
def calc_blue(historys):
"""
{
1: [0.16, 0.16, 0.15, ...],
2: [0.16, 0.16, 0.22, ...],
...
12: [0.16, 0.16, 0.3, ...],
}
"""
blues = [history['result']['blue'] for history in historys]
result = dict()
for num in range(1,13): #12选2
# result.setdefault(num, [])
prob_list = list()
size = len(blues)
while size >= BLUE_MIN:
prob_list.append(_calc_prob(num, blues[:size]))
size -= 1
result[num] = prob_list
return result
def gen_xls(historys):
cols1 = ["近%d期" % i for i in range(len(historys), RED_MIN-1, -1)]
data1 = calc_red(historys)
df1 = pd.DataFrame.from_dict(data1, orient='index', columns=cols1)
cols2 = ["近%d期" % i for i in range(len(historys), BLUE_MIN-1, -1)]
data2 = calc_blue(historys)
df2 = pd.DataFrame.from_dict(data2, orient='index', columns=cols2)
with pd.ExcelWriter('大乐透.xlsx') as writer:
df1.to_excel(writer, sheet_name="红球")
df2.to_excel(writer, sheet_name="蓝球")
def gen_html(historys):
cols1 = ["近%d期" % i for i in range(len(historys), RED_MIN-1, -1)]
datas1 = []
for k,v in calc_red(historys).items():
data={'type':'line', 'name':k}
data['x'] = cols1
data['y'] = v
datas1.append(data)
cols2 = ["近%d期" % i for i in range(len(historys), BLUE_MIN-1, -1)]
datas2 = []
for k,v in calc_blue(historys).items():
data={'type':'line', 'name':k}
data['x'] = cols2
data['y'] = v
datas2.append(data)
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='大乐透分析'),
html.Div(children='数学期望值趋势'),
dcc.Graph(
id='red-exp-val-graph',
figure={
'data':datas1,
'layout':{
'title':'红球趋势'
}
}
),
dcc.Graph(
id='blue-exp-val-graph',
figure={
'data':datas2,
'layout':{
'title':'蓝球趋势'
}
}
),
])
app.run_server(debug=True)
if __name__ == '__main__':
historys = get_history(CODE, COUNT)
#gen_xls(historys)
gen_html(historys)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,347 | flychensc/apple | refs/heads/master | /lottery/ticket.py | """
用法:
print(get_history('双色球', count=1))
输出格式大致如下,差异在result部分,要么为dict,要么为list
[
{
'date': datetime.date(2018, 7, 12),
'result': {
'red': [4,7,13,20,29,33],
'blue': 3
},
'grades': [
{'num': 6, 'money': 8230212},
{'num': 128, 'money': 189270},
{'num': 1015, 'money': 3000},
{'num': 56290, 'money': 200},
{'num': 1090402, 'money': 10},
{'num': 7457743, 'money': 5},
{'num': 0, 'money': 0}
]
}
]
"""
import requests
import datetime
from bs4 import BeautifulSoup
_str2date = lambda s,f: datetime.datetime.strptime(s, f).date()
def _get_cwl_history(_type, count=30):
name = {'3D':'3d', '双色球':'ssq', '七乐彩':'qlc'}
if _type not in name:
raise ValueError
payload = {'name': name[_type]}
if count:
payload["issueCount"] = count
else:
payload["issueCount"] = 30
jkdz = "http://www.cwl.gov.cn/cwl_admin/"
url = jkdz + "kjxx/findDrawNotice"
headers = {
'Accept': 'application/json',
'Referer': 'http://www.cwl.gov.cn/kjxx/',
}
r = requests.get(url=url, params=payload, headers=headers)
historys = []
for one in r.json()['result']:
history = {'date': _str2date(one['date'][:10], '%Y-%m-%d')}
if name[_type] == 'ssq':
red = [int(r) for r in one['red'].split(',')]
blue = int(one['blue'])
history['result'] = {'red': red, 'blue': blue}
elif name[_type] == 'qlc':
red = [int(r) for r in one['red'].split(',')]
blue = int(one['blue'])
history['result'] = {'red': red, 'blue': blue}
elif name[_type] == '3d':
red = [int(r) for r in one['red'].split(',')]
history['result'] = red
history['total'] = int(int(one['sales'])/2)
history['grades'] = []
for prizegrade in one['prizegrades']:
grade = {}
try:
grade['num'] = int(prizegrade['typenum'])
except ValueError:
grade['num'] = 0
try:
grade['money'] = int(prizegrade['typemoney'])
if name[_type] == '3d' and grade['num'] !=0:
grade['money'] = int(grade['money']/grade['num'])
except ValueError:
grade['money'] = 0
history['grades'].append(grade)
historys.append(history)
return historys
def _get_lottery_history(_type, count=30):
name = {'七星彩':'04', '大乐透':'85', '排列五':'350133', '排列三':'35'}
if _type not in name:
raise ValueError
payload = {'gameNo': name[_type], 'provinceId':'0'}
if count:
payload["pageSize"] = count
else:
payload["pageSize"] = 30
"""
GET https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry?gameNo=04&provinceId=0&pageSize=30&isVerify=1&pageNo=1 HTTP/1.1
Host: webapi.sporttery.cn
Connection: keep-alive
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.50
Origin: https://static.sporttery.cn
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://static.sporttery.cn/
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6
"""
url = 'https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry'
r = requests.get(url=url, params=payload)
result = r.json()
historys = []
if result['errorCode'] == '0':
for data in result['value']['list']:
history = {'date': data['lotteryDrawTime']}
if _type == '大乐透':
num_result = [int(i) for i in data['lotteryDrawResult'].split()]
red = num_result[:-2]
blue = num_result[-2:]
history['result'] = {'red': red, 'blue': blue}
else:
history['result'] = [int(i) for i in data['lotteryDrawResult'].split()]
history['total'] = int(int(data['totalSaleAmount'].replace(",",""))/2)
history['grades'] = []
for prizeLevel in data['prizeLevelList']:
grade = {}
grade['num'] = int(prizeLevel['stakeCount'].replace(",",""))
grade['money'] = int(float(prizeLevel['stakeAmount'].replace(",","")))
history['grades'].append(grade)
historys.append(history)
return historys
def get_history(_type, count=30):
if _type in ['双色球', '七乐彩', '3D']:
return _get_cwl_history(_type, count)
elif _type in ['大乐透', '排列三', '排列五', '七星彩']:
return _get_lottery_history(_type, count)
else:
raise ValueError
if __name__ == "__main__":
data = get_history('双色球', count=1)
print(data)
| {"/app_exp_val.py": ["/lottery/__init__.py"], "/lottery/__init__.py": ["/lottery/ticket.py", "/lottery/utilities.py"], "/coll_plw.py": ["/lottery/__init__.py"], "/rand_select.py": ["/lottery/__init__.py"], "/app_sim_val.py": ["/lottery/__init__.py"], "/lottery/utilities.py": ["/lottery/__init__.py"], "/coll_dlt.py": ["/lottery/__init__.py"]} |
53,361 | rnels12/sorting-algos | refs/heads/main | /main.py | #!/usr/bin/env python3
"""
File name : main.py
Author : Ryky Nelson
Created Date : October 2021
Python Version: Python 3.6.9
Main function:
- to produce a list of random numbers
- to call a sorting algorithm
- to display the orignal and sorted lists
"""
import random
import sort
if __name__ == "__main__":
nn = 15
random.seed()
A = random.sample( range(0, nn*5), nn)
print("Unsorted:", A)
B = sort.Bubble(A)
# C = sort.Quick(A)
# D = sort.Merge(A)
# E = sort.Selection(A)
# F = sort.Insertion(A)
print("Sorted:", B)
# print("Sorted:", C)
# print("Sorted:", D)
# print("Sorted:", E)
# print("Sorted:", F)
| {"/main.py": ["/sort.py"]} |
53,362 | rnels12/sorting-algos | refs/heads/main | /sort.py | #!/usr/bin/env python3
"""
File name : sort.py
Author : Ryky Nelson
Created Date : October 2021
Python Version: Python 3.6.9
Description:
a list of simple implementations of sorting algorithms
"""
def Bubble(A):
nn = len(A)
if len(A) < 2 : return A
for i in range(nn - 1):
swap = False
for j in range( nn - 1 - i):
if A[j] > A[j+1]:
A[j], A[j+1] = A[j+1], A[j]
swap = True
if not swap: break
return A
def Quick(A):
nn = len(A)
if len(A) < 2 : return A
p, s = nn - 1, 0
while s < p:
if A[s] > A[p]:
A[s], A[p-1] = A[p-1], A[s]
A[p-1], A[p] = A[p], A[p-1]
p -= 1
else: s += 1
return Quick(A[:p]) + [A[p]] + Quick(A[p+1:])
def Merge(A):
nn = len(A)
if len(A) < 2 : return A
mid = nn // 2
L, R = Merge(A[:mid]), Merge(A[mid:])
ll, lr = len(L), len(R)
B = []
lidx, ridx = 0, 0
while lidx < ll and ridx < lr:
if L[lidx] < R[ridx]:
B.append( L[lidx] )
lidx += 1
else:
B.append( R[ridx] )
ridx += 1
if lidx < ll: B += L[lidx:]
elif ridx < lr: B += R[ridx:]
return B
def Selection(A):
nn = len(A)
if len(A) < 2 : return A
for i in range(nn):
imin = i
cmin = A[imin]
for j in range(i,nn):
if A[j] < cmin:
cmin, imin = A[j], j
if i != imin: A[i], A[imin] = A[imin], A[i]
return A
def Insertion(A):
nn = len(A)
if len(A) < 2 : return A
for i in range(1,nn):
j = i - 1
while j >= 0 and A[i] < A[j]: j -= 1
A = A[:j+1] + [A[i]] + A[j+1:i] + A[i+1:]
return A
| {"/main.py": ["/sort.py"]} |
53,367 | mfuentesg/luhnpy | refs/heads/master | /test.py | import unittest
import luhnpy
class LuhnTest(unittest.TestCase):
def test_digit_invalid_argument(self):
with self.assertRaises(ValueError):
luhnpy.digit('00x')
def test_digit_hexadecimal_string(self):
with self.assertRaises(ValueError):
luhnpy.digit('0xff000000')
def test_complete_invalid_argument(self):
with self.assertRaises(ValueError):
luhnpy.digit('')
def test_rand_invalid_argument(self):
with self.assertRaises(ValueError):
luhnpy.digit('123a1_')
def test_verify_invalid_argument(self):
with self.assertRaises(ValueError):
luhnpy.digit('_')
def test_digit(self):
tests = [('7', 5), ('0', 0), ('383', 0), ('101099877719', 5)]
for test, expected in tests:
self.assertEqual(luhnpy.digit(test), expected)
def test_verify_wrong_cases(self):
tests = ['73', '01', '3836', '1010998777197', '1']
for test in tests:
self.assertFalse(luhnpy.verify(test))
def test_verify_success_cases(self):
tests = ['75', '00', '3830', '1010998777195', '18']
for test in tests:
self.assertTrue(luhnpy.verify(test))
def test_complete(self):
tests = [('7', '75'), ('0', '00'), ('383', '3830'), ('101099877719', '1010998777195'), ('1', '18')]
for test, expected in tests:
self.assertEqual(luhnpy.complete(test), expected)
def test_random_length(self):
rand_str = luhnpy.rand(10)
self.assertEqual(len(rand_str), 10)
def test_valid_random_digit(self):
rand_str = luhnpy.rand(10)
self.assertEqual(int(rand_str[-1]), luhnpy.digit(rand_str[:-1]))
def test_success_random(self):
self.assertTrue(luhnpy.verify(luhnpy.rand()))
def test_success_random_complete(self):
rand_str = luhnpy.rand()
self.assertEqual(luhnpy.complete(rand_str[:-1]), rand_str)
if __name__ == '__main__':
unittest.main()
| {"/test.py": ["/luhnpy.py"]} |
53,368 | mfuentesg/luhnpy | refs/heads/master | /luhnpy.py | __version__ = '1.0.0'
from random import randint
from functools import wraps
def _digit_validator(fun):
@wraps(fun)
def digit_wrapper(*args, **kwargs):
for arg in args:
if not str(arg).isdigit():
raise ValueError('The given argument must be a string a digits')
return fun(*args, **kwargs)
return digit_wrapper
@_digit_validator
def _checksum(string):
"""Calculates the luhn checksum of the given string of digits."""
doubled = [int(n)*2 if i % 2 != 0 else int(n) for i, n in enumerate(string[::-1])]
return sum(map(lambda n: (n % 10 + 1) if n > 9 else n, doubled)) % 10
def rand(length=16):
"""Create a random valid luhn string of digits"""
if length < 1:
raise ValueError('The `length` attribute must be greater than 1')
ran_str = ''.join(([str(randint(1, 9))] + [str(randint(0, 9)) for _ in range(length-2)]))
return '{}{}'.format(ran_str, digit(ran_str))
@_digit_validator
def verify(string):
"""Check if the provided string complies with the Luhn Algorithm"""
return _checksum(string) % 10 == 0
@_digit_validator
def digit(string):
"""Generate the luhn check digit for the provided string of digits"""
return (10 - _checksum(string + '0')) % 10
@_digit_validator
def complete(string):
"""Append the luhn check digit to the provided string of digits"""
return '{}{}'.format(string, digit(string))
| {"/test.py": ["/luhnpy.py"]} |
53,369 | mfuentesg/luhnpy | refs/heads/master | /setup.py | from distutils.core import setup
setup(
name='luhnpy',
py_modules=['luhnpy'],
version='1.0.0',
description='A minimalistic implementation of Luhn algorithm',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author='Marcelo Fuentes',
author_email='marceloe.fuentes@gmail.com',
url='https://github.com/mfuentesg/luhnpy',
download_url='https://github.com/mfuentesg/luhnpy/archive/1.0.0.tar.gz',
keywords=['luhn', 'algorithm'],
classifiers=[]
)
| {"/test.py": ["/luhnpy.py"]} |
53,376 | jonesclarence37/pomace | refs/heads/main | /pomace/__init__.py | from pkg_resources import (
DistributionNotFound as _DistributionNotFound,
get_distribution as _get_distribution,
)
from .api import *
try:
__version__ = _get_distribution("pomace").version
except _DistributionNotFound:
__version__ = "(local)"
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,377 | jonesclarence37/pomace | refs/heads/main | /pomace/tests/test_models.py | # pylint: disable=expression-not-assigned,unused-variable,redefined-outer-name,unused-argument
import pytest
import requests
from ..models import Action, Locator, Page
@pytest.fixture
def locator():
return Locator("name", "email")
@pytest.fixture
def action():
return Action("fill", "email")
@pytest.fixture
def page(mockbrowser):
return Page("example.com", "/foo/bar")
def describe_locator():
def describe_bool():
def it_is_false_when_placeholder(expect, locator):
expect(bool(locator)) == True
locator.value = ""
expect(bool(locator)) == False
def describe_sort():
def it_orders_by_uses(expect):
locators = [
Locator("name", "bbb", uses=5),
Locator("name", "aaa", uses=6),
Locator("name", "BBB", uses=6),
Locator("name", "AAA", uses=7),
Locator("name", "zzz", uses=8),
]
expect(sorted(locators)) == locators
def describe_find():
def it_returns_callable(expect, mockbrowser, locator):
expect(locator.find()) == "mockelement:name=email"
def it_can_find_links_by_partial_text(expect, mockbrowser, locator):
locator.mode = "text (partial)"
expect(locator.find()) == "mockelement:links.partial_text=email"
def it_can_find_links_by_aria_label(expect, mockbrowser, locator):
locator.mode = "aria-label"
expect(locator.find()) == 'mockelement:css=[aria-label="email"]'
def describe_score():
def it_updates_uses(expect, locator):
expect(locator.score(+1)) == True
expect(locator.uses) == 1
def it_tops_out_at_max_value(expect, locator):
locator.score(+99)
expect(locator.score(+1)) == False
expect(locator.uses) == 99
def it_bottoms_out_at_min_value(expect, locator):
locator.score(-1)
expect(locator.score(-1)) == False
expect(locator.uses) == -1
def describe_action():
def describe_str():
def it_includes_the_verb_and_name(expect, action):
expect(str(action)) == "fill_email"
def describe_humanized():
def it_describes_the_action(expect, action):
expect(action.humanized) == "Filling email"
def describe_sorted_locators():
def it_orders_by_use(expect, action):
action.locators = [
Locator("id", "email", uses=-2),
Locator("name", "email", uses=-3),
Locator("value", "email", uses=-1),
]
modes = [locator.mode for locator in action.sorted_locators]
expect(modes) == ["value", "id", "name"]
def it_tries_new_locators_first(expect, action):
action.locators = [
Locator("name", "email", uses=-1),
Locator("id", "email", uses=0),
]
expect(len(action.sorted_locators)) == 1
expect(action.locator.mode) == "id"
def it_only_includes_invalid_locators_when_no_other_options(expect, action):
action.locators = [
Locator("id", "email", uses=2),
Locator("name", "email", uses=3),
Locator("value", "email", uses=-1),
]
modes = [locator.mode for locator in action.sorted_locators]
expect(modes) == ["name", "id"]
def describe_locator():
def it_returns_placeholder_when_no_locators_defined(expect, action):
action.locators = []
expect(action.locator.value) == "placeholder"
def describe_bool():
def it_is_false_when_placeholder(expect, action):
expect(bool(action)) == True
action.name = ""
expect(bool(action)) == False
def describe_clean():
def it_removes_unused_locators(expect, action):
previous_count = len(action.locators)
action.locators[0].uses = -1
action.locators[1].uses = 99
expect(action.clean("<page>")) == previous_count - 1
expect(len(action.locators)) == 1
def it_requires_one_locator_to_exceed_usage_threshold(expect, action):
previous_count = len(action.locators)
action.locators[0].uses = 98
expect(action.clean("<page>")) == 0
expect(len(action.locators)) == previous_count
def it_can_be_forced(expect, action):
previous_count = len(action.locators)
action.locators[0].uses = 1
expect(action.clean("<page>", force=True)) == previous_count - 1
expect(len(action.locators)) == 1
def it_keeps_used_locators(expect, action):
action.locators = [Locator("mode", "value", uses=1)]
expect(action.clean("<page>", force=True)) == 0
expect(len(action.locators)) == 1
def describe_page():
def describe_repr():
def it_includes_the_url(expect, page):
expect(repr(page)) == "Page.at('https://example.com/foo/bar')"
def it_includes_the_variant_when_set(expect, page):
page.variant = "qux"
expect(
repr(page)
) == "Page.at('https://example.com/foo/bar', variant='qux')"
def describe_str():
def it_returns_the_url(expect, page):
expect(str(page)) == "https://example.com/foo/bar"
def it_includes_the_variant_when_set(expect, page):
page.variant = "qux"
expect(str(page)) == "https://example.com/foo/bar (qux)"
def describe_dir():
def it_lists_valid_actions(expect, page, action):
page.actions = []
expect(dir(page)) == []
page.actions.append(action)
expect(dir(page)) == ["fill_email"]
def describe_getattr():
def it_returns_matching_action(expect, page, action):
page.actions = [action]
expect(getattr(page, "fill_email")) == action
def it_adds_missing_actions(expect, page, monkeypatch):
page.actions = []
new_action = getattr(page, "fill_password")
expect(new_action.verb) == "fill"
expect(new_action.name) == "password"
expect(len(new_action.locators)) > 1
def it_rejects_invalid_actions(expect, page):
with expect.raises(AttributeError):
getattr(page, "mash_password")
def it_rejects_missing_attributes(expect, page):
with expect.raises(AttributeError):
getattr(page, "foobar")
def describe_contains():
def it_matches_partial_html(expect, page, mockbrowser):
expect(page).contains("world")
def describe_clean():
def it_removes_unused_locators(expect, page):
page.locators.inclusions = [
Locator("id", "foo", uses=0),
Locator("id", "bar", uses=-1),
Locator("id", "qux", uses=99),
]
page.locators.exclusions = [
Locator("id", "foo", uses=0),
Locator("id", "bar", uses=-1),
Locator("id", "qux", uses=99),
]
expect(page.clean()) == 4
expect(len(page.locators.inclusions)) == 1
expect(len(page.locators.exclusions)) == 1
def describe_properties():
@pytest.mark.vcr()
def it_computes_values_based_on_the_html(expect, page, mockbrowser):
mockbrowser.html = requests.get("http://example.com").text
expect(page.text) == (
"Example Domain\n"
"Example Domain\n"
"This domain is for use in illustrative examples in documents. You may use this\n"
"domain in literature without prior coordination or asking for permission.\n"
"More information..."
)
expect(page.identity) == 19078
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,378 | jonesclarence37/pomace | refs/heads/main | /tests/test_sites.py | # pylint: disable=unused-argument,expression-not-assigned
from contextlib import suppress
from pomace import shared
from pomace.models import Page
def test_locator_uses_are_persisted(expect, browser):
page = Page.at("https://www.wikipedia.org")
page.actions = []
page.datafile.save()
page.fill_search("foobar")
page = Page.at("https://www.wikipedia.org")
locators = sorted(page.fill_search.locators)
good_locator = locators[-1]
bad_locator = locators[0]
expect(good_locator.uses) > 0
expect(bad_locator.uses) <= 0
def test_type_actions_are_supported(expect, browser):
page = Page.at("https://www.wikipedia.org")
page.fill_search("foobar")
page.type_enter()
expect(shared.browser.url) == "https://en.wikipedia.org/wiki/Foobar"
def test_modifier_keys_are_supported(expect, browser):
page = Page.at("https://www.wikipedia.org")
page.fill_search("foobar")
page.type_tab()
page.type_shift_tab()
page.type_enter()
expect(shared.browser.url) == "https://en.wikipedia.org/wiki/Foobar"
def test_unused_actions_are_removed_on_forced_cleanup(expect, browser):
page = Page.at("https://www.wikipedia.org")
page.click_foobar()
previous_count = len(page.actions)
page.clean(force=True)
expect(len(page.actions)) < previous_count
def test_multiple_indices_are_tried(expect, browser):
page = Page.at("https://www.mtggoldfish.com/metagame/standard#paper")
with suppress(AttributeError):
page.click_gruul_adventures.locators = []
page.datafile.save()
page.click_gruul_adventures()
expect(page.click_gruul_adventures.sorted_locators[0].index) == 1
def test_links_are_opened_in_the_same_window(expect, browser):
page = Page.at("https://share.michiganelections.io/elections/41/precincts/1209/")
with suppress(AttributeError):
page.click_official_ballot.locators = []
page.datafile.save()
page = page.click_official_ballot()
expect(page.url) == "https://mvic.sos.state.mi.us/Voter/GetMvicBallot/1828/683/"
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,379 | jonesclarence37/pomace | refs/heads/main | /notebooks/profile_default/startup/ipython_startup.py | # pylint: disable=unused-import,import-outside-toplevel
import pomace
from pomace import prompts as _prompts, utils as _utils
from pomace.config import settings
from pomace.models import Page, auto
from pomace.shared import browser
def _configure_logging():
import log
log.reset()
log.init(debug=True)
log.silence("datafiles")
def _display_settings():
from pomace.config import settings
line = ""
if settings.browser.name:
line += settings.browser.name.capitalize()
if settings.browser.headless:
line += " (headless)"
if line and settings.url:
line += f" -- {settings.url}"
if line:
print(line)
_prompts.linebreak(force=True)
if __name__ == "__main__":
_configure_logging()
_display_settings()
_prompts.browser_if_unset()
_prompts.url_if_unset()
_utils.launch_browser()
page = auto()
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,380 | jonesclarence37/pomace | refs/heads/main | /pomace/server.py | from urllib.parse import unquote
from flask import redirect, request, url_for
from flask_api import FlaskAPI
from . import models, utils
app = FlaskAPI("Pomace")
@app.route("/")
def index():
return redirect("/sites?url=http://example.com")
@app.route("/sites")
def pomace():
if "url" not in request.args:
return redirect("/")
utils.launch_browser(restore_previous_url=False)
url = request.args.get("url")
page = models.Page.at(url) # type: ignore
for action, value in request.args.items():
if "_" in action:
page, _updated = page.perform(action, value, _logger=app.logger)
data = {
"id": page.identity,
"url": page.url,
"title": page.title,
"html": page.html.prettify(),
"text": page.text,
"_next": unquote(url_for(".pomace", url=page.url, _external=True)),
"_actions": dir(page),
}
if not app.debug:
utils.quit_browser()
return data
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,381 | jonesclarence37/pomace | refs/heads/main | /pomace/cli.py | # pylint: disable=no-self-use
import os
from importlib import reload
import log
from cleo import Application, Command
from . import models, prompts, server, utils
from .config import settings
class BaseCommand(Command): # pragma: no cover
def handle(self):
self.configure_logging()
self.set_directory()
self.update_settings()
prompts.browser_if_unset()
domains = list(set(p.domain for p in models.Page.objects.all()))
prompts.url_if_unset(domains)
utils.launch_browser()
utils.locate_models()
try:
self.run()
finally:
utils.quit_browser()
prompts.linebreak()
def configure_logging(self):
log.reset()
shift = 2 if self._command.name == "exec" else 1
log.init(verbosity=self.io.verbosity + shift)
log.silence("datafiles", allow_warning=True)
log.silence("urllib3.connectionpool", allow_error=True)
def set_directory(self):
if self.option("root"):
os.chdir(self.option("root"))
def update_settings(self):
if self.option("browser"):
settings.browser.name = self.option("browser").lower()
settings.browser.headless = self.option("headless")
if self.argument("domain"):
if "://" in self.argument("domain"):
settings.url = self.argument("domain")
else:
settings.url = "http://" + self.argument("domain")
class CleanCommand(BaseCommand):
"""
Remove unused actions in local site definitions
clean
{domain? : Limit cleaning to a single domain}
{--r|root= : Path to directory to containing models}
"""
def handle(self):
self.configure_logging()
self.set_directory()
utils.locate_models()
if self.argument("domain"):
pages = models.Page.objects.filter(domain=self.argument("domain"))
else:
pages = models.Page.objects.all()
for page in pages:
page.clean(force=True)
class CloneCommand(BaseCommand):
"""
Download site definitions from a git repository
clone
{url : Git repository URL containing pomace models}
{domain? : Name of sites directory for this repository}
{--f|force : Overwrite uncommitted changes in cloned repositories}
{--r|root= : Path to directory to containing models}
"""
def handle(self):
self.configure_logging()
self.set_directory()
utils.locate_models()
utils.clone_models(
self.argument("url"),
domain=self.argument("domain"),
force=self.option("force"),
)
class ExecCommand(BaseCommand): # pragma: no cover
"""
Run a Python script
exec
{script : Path to a Python script}
{--b|browser= : Browser to use for automation}
{--d|headless : Run the specified browser in a headless mode}
{--r|root= : Path to directory to containing models}
"""
def update_settings(self):
if self.option("browser"):
settings.browser.name = self.option("browser").lower()
settings.browser.headless = self.option("headless")
def run(self):
utils.run_script(self.argument("script"))
class RunCommand(BaseCommand): # pragma: no cover
"""
Start the command-line interface
run
{domain? : Starting domain for the automation}
{--b|browser= : Browser to use for automation}
{--d|headless : Run the specified browser in a headless mode}
{--p|prompt=* : Prompt for secrets before running}
{--r|root= : Path to directory to containing models}
"""
def run(self):
for name in self.option("prompt"):
prompts.secret_if_unset(name)
self.clear_screen()
page = models.auto()
self.display_url(page)
while True:
action = prompts.action(page)
if action:
page, transitioned = page.perform(action)
if transitioned:
self.clear_screen()
self.display_url(page)
else:
reload(models)
self.clear_screen()
page = models.auto()
self.display_url(page)
def clear_screen(self):
os.system("cls" if os.name == "nt" else "clear")
def display_url(self, page):
self.line(f"<fg=white;options=bold>{page}</>")
prompts.linebreak(force=True)
class ShellCommand(BaseCommand): # pragma: no cover
"""
Launch an interactive shell
shell
{domain? : Starting domain for the automation}
{--b|browser= : Browser to use for automation}
{--d|headless : Run the specified browser in a headless mode}
{--r|root= : Path to directory to containing models}
"""
def run(self):
prompts.shell()
class ServeCommand(BaseCommand):
"""
Start the web API interaface
serve
{domain? : Starting domain for the automation}
{--b|browser= : Browser to use for automation}
{--d|headless : Run the specified browser in a headless mode}
{--p|prompt=* : Prompt for secrets before running}
{--r|root= : Path to directory to containing models}
{--debug : Run the server in debug mode}
"""
def handle(self):
self.configure_logging()
self.set_directory()
self.update_settings()
prompts.bullet = None
utils.locate_models()
try:
server.app.run(debug=self.option("debug"))
finally:
utils.quit_browser()
application = Application()
application.add(CleanCommand())
application.add(CloneCommand())
application.add(ExecCommand())
application.add(RunCommand())
application.add(ServeCommand())
application.add(ShellCommand())
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,382 | jonesclarence37/pomace | refs/heads/main | /pomace/tests/test_types.py | # pylint: disable=expression-not-assigned,unused-variable,redefined-outer-name,unused-argument
import log
import pytest
from ..types import URL, Fake
@pytest.fixture
def url():
return URL("http://www.example.com/foo/bar")
def describe_url():
def describe_init():
def with_url(expect, url):
expect(url.value) == "http://www.example.com/foo/bar"
def with_url_and_trailing_slash(expect):
url = URL("http://example.com/login/error/")
expect(url.value) == "http://example.com/login/error"
def with_path(expect):
url = URL("example.com", "login")
expect(url.value) == "https://example.com/login"
def with_path_at_root(expect):
url = URL("example.com", "@")
expect(url.value) == "https://example.com"
def with_path_and_extra_slashes(expect):
url = URL("example.com", "/login/error/")
expect(url.value) == "https://example.com/login/error"
def describe_str():
def it_returns_the_value(expect, url):
expect(str(url)) == "http://www.example.com/foo/bar"
def describe_eq():
def it_compares_domain_and_path(expect, url):
expect(url) == URL("https://www.example.com/foo/bar/")
expect(url) != URL("http://example.com/foo/bar")
def it_matches_patterns(expect):
pattern = URL("http://example.com/p/{name}")
expect(pattern) == URL("http://example.com/p/foobar")
expect(pattern) != URL("http://example.com/")
expect(pattern) != URL("http://example.com/p")
expect(pattern) != URL("http://example.com/p/foo/bar")
def it_does_not_match_root_placeholder(expect):
pattern = URL("http://example.com/{value}")
expect(pattern) != URL("http://example.com")
def it_can_be_compared_to_str(expect, url):
expect(url) == str(url)
expect(url) == str(url) + "/"
expect(url) != str(url) + "_extra"
def describe_contains():
def it_checks_url_contents(expect, url):
expect(url).contains("foo/bar")
expect(url).excludes("qux")
def describe_path():
def when_root(expect, url):
url = URL("http://example.com")
expect(url.path) == "@"
def when_single(expect, url):
url = URL("http://example.com/login")
expect(url.path) == "login"
def when_trailing_slash(expect, url):
url = URL("http://example.com/login/error/")
expect(url.path) == "login/error"
def describe_fragment():
def when_default(expect, url):
expect(url.fragment) == ""
def when_provided(expect, url):
url = URL("http://example.com/signup/#step1")
expect(url.fragment) == "step1"
def when_containing_slashes(expect, url):
url = URL("http://example.com/signup/#/step/2/")
expect(url.fragment) == "step_2"
def describe_fake():
@pytest.fixture
def fake():
return Fake()
@pytest.mark.parametrize(
"name",
[
"email_address",
"zip_code",
],
)
def it_maps_aliases(expect, fake, name):
value = getattr(fake, name)
expect(value).isinstance(str)
def it_handles_missing_attributes(expect, fake):
with expect.raises(AttributeError):
getattr(fake, "foobar")
def describe_person():
@pytest.fixture
def person():
return Fake().person
def it_includes_email_in_str(expect, person):
expect(str(person)).contains("<")
expect(str(person)).contains("@")
def it_includes_name_in_email(expect, person):
expect(person.email).icontains(person.last_name)
def it_includes_state_name_and_abbr(expect, person):
log.info(f"State: {person.state} ({person.state_abbr})")
expect(len(person.state)) >= 4
expect(len(person.state_abbr)) == 2
@pytest.mark.parametrize(
"name",
[
"address",
"birthday",
"cell_phone",
"county",
"email",
"honorific",
"phone",
"prefix",
"street_address",
"zip",
],
)
def it_maps_aliases(expect, person, name):
value = getattr(person, name)
expect(value).isinstance(str)
def it_handles_missing_attributes(expect, person):
with expect.raises(AttributeError):
getattr(person, "foobar")
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,383 | jonesclarence37/pomace | refs/heads/main | /pomace/types.py | import random
from dataclasses import dataclass
from typing import Optional
from urllib.parse import urlparse
import faker
import log
import us
import zipcodes
from parse import parse
__all__ = ["URL"]
class URL:
ROOT = "@"
def __init__(self, url_or_domain: str, path: Optional[str] = None):
if path == self.ROOT:
self.value = f"https://{url_or_domain}"
elif path:
path = ("/" + path).rstrip("/").replace("//", "/")
self.value = f"https://{url_or_domain}" + path
else:
self.value = str(url_or_domain).rstrip("/")
def __repr__(self):
return f"URL({self.value!r})"
def __str__(self):
return self.value
def __eq__(self, other):
if not isinstance(other, self.__class__):
return str(self) == str(other).strip("/")
if self.domain != other.domain:
return False
if self.path == other.path:
return True
result = parse(self.path, other.path)
if not result:
return False
for value in result.named.values():
if value == self.ROOT or "/" in value:
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def __contains__(self, value):
return value in self.value
@property
def domain(self) -> str:
return urlparse(self.value).netloc
@property
def path(self) -> str:
path = urlparse(self.value).path.strip("/")
return path if path else self.ROOT
@property
def fragment(self) -> str:
return urlparse(self.value).fragment.replace("/", "_").strip("_")
ALIASES = {
"birthday": "date_of_birth",
"cell_phone": "phone_number",
"email_address": "email",
"email": "email_address",
"phone": "phone_number",
"prefix": "honorific",
"street_address": "address",
"zip_code": "postcode",
"zip": "zip_code",
}
STREETS = ["First", "Second", "Third", "Fourth", "Park", "Main"]
@dataclass
class Person:
honorific: str
first_name: str
last_name: str
date_of_birth: str
phone_number: str
email_address: str
address: str
city: str
state: str
state_abbr: str
county: str
zip_code: str
@classmethod
def random(cls, fake) -> "Person":
if random.random() > 0.5:
prefix, first_name, last_name = (
fake.prefix_female,
fake.first_name_female,
fake.last_name,
)
else:
prefix, first_name, last_name = (
fake.prefix_male,
fake.first_name_male,
fake.last_name,
)
phone_number = str(random.randint(1000000000, 9999999999))
email_address = f"{first_name}{last_name}@{fake.free_email_domain}".lower()
while True:
place = random.choice(zipcodes.filter_by())
state = us.states.lookup(place["state"])
if state and state.statehood_year:
break
if random.random() < 0.75:
number = random.randint(50, 200)
street = random.choice(STREETS)
place["address"] = f"{number} {street} St."
else:
place["address"] = fake.street_address
return cls(
prefix,
first_name,
last_name,
fake.birthday,
phone_number,
email_address,
place["address"],
place["city"],
state.name,
state.abbr,
place["county"],
place["zip_code"],
)
def __str__(self):
return f"{self.name} <{self.email}>"
def __getattr__(self, name):
try:
alias = ALIASES[name]
except KeyError:
return super().__getattribute__(name)
else:
log.debug(f"Mapped fake attribute {alias!r} to {name!r}")
return getattr(self, alias)
@property
def name(self) -> str:
return f"{self.first_name} {self.last_name}"
class Fake:
def __init__(self):
self._generator = faker.Faker()
def __getattr__(self, name):
try:
method = getattr(self._generator, name)
except AttributeError:
try:
alias = ALIASES[name]
except KeyError:
return super().__getattribute__(name)
else:
log.debug(f"Mapped fake attribute {alias!r} to {name!r}")
method = getattr(self._generator, alias)
return method()
@property
def person(self) -> Person:
return Person.random(self)
@property
def birthday(self) -> str:
return self._generator.date_of_birth(minimum_age=18, maximum_age=80).strftime(
"%m/%d/%Y"
)
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,384 | jonesclarence37/pomace | refs/heads/main | /pomace/config.py | from typing import List, Optional
import log
from datafiles import datafile, field
from . import shared
from .types import URL
log.silence("datafiles", allow_warning=True)
@datafile
class Browser:
name: str = ""
width: int = 1920
height: int = 1080
headless: bool = False
@datafile
class Secret:
name: str
value: str
@datafile
class Site:
domain: str
data: List[Secret] = field(
default_factory=lambda: [Secret("username", ""), Secret("password", "")]
)
@property
def url(self) -> str:
return f"http://{self.domain}"
@datafile("./pomace.yml", defaults=True)
class Settings:
browser: Browser = field(default_factory=Browser)
url: str = ""
secrets: List[Site] = field(default_factory=list)
dev = True
def __getattr__(self, name):
if name.startswith("_"):
return object.__getattribute__(self, name)
return self.get_secret(name) or ""
def get_secret(self, name, *, _log=True) -> Optional[str]:
domain = URL(shared.browser.url).domain
for site in self.secrets:
if site.domain == domain:
for secret in site.data:
if secret.name == name:
return secret.value
if _log:
log.info(f"Secret {name!r} not set for {domain}")
return None
def set_secret(self, name, value):
domain = URL(shared.browser.url).domain
self._ensure_site(domain)
site: Site = self._get_site(domain) # type: ignore
for secret in site.data:
if secret.name == name:
secret.value = value
break
else:
site.data.append(Secret(name, value))
def update_secret(self, name, value):
domain = URL(shared.browser.url).domain
site = self._get_site(domain)
if site:
for secret in site.data:
if secret.name == name:
secret.value = value
return
log.info(f"Secret {name!r} not set for {domain}")
def _get_site(self, domain: str) -> Optional[Site]:
for site in self.secrets:
if site.domain == domain:
return site
return None
def _ensure_site(self, domain: str):
if not self._get_site(domain):
site = Site(domain)
self.secrets.append(site)
settings = Settings()
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,385 | jonesclarence37/pomace | refs/heads/main | /pomace/api.py | import inspect
from typing import Optional
import log
from . import models, prompts, types, utils
from .config import settings
from .models import Page, auto
__all__ = [
"auto",
"clean",
"fake",
"freeze",
"log",
"Page",
"prompt",
"visit",
]
fake = types.Fake()
def visit(
url: str = "",
*,
browser: str = "",
headless: Optional[bool] = None,
delay: float = 0.0,
) -> models.Page:
if url:
settings.url = url
else:
prompts.url_if_unset()
if browser:
settings.browser.name = browser.lower()
else:
prompts.browser_if_unset()
if headless is not None:
settings.browser.headless = headless
utils.launch_browser(delay, silence_logging=True)
utils.locate_models(caller=inspect.currentframe())
return models.auto()
def prompt(*names):
for name in names:
prompts.secret_if_unset(name)
return settings
def freeze():
log.debug("Disabling automatic actions and placeholder locators")
prompts.bullet = None
settings.dev = False
def clean():
utils.locate_models(caller=inspect.currentframe())
for page in models.Page.objects.all():
page.clean(force=True)
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,386 | jonesclarence37/pomace | refs/heads/main | /pomace/browser.py | import sys
import log
from fake_useragent import UserAgent
from splinter import Browser
from splinter.exceptions import DriverNotFoundError
from webdriver_manager import chrome, firefox
from .config import settings
NAMES = ["Firefox", "Chrome"]
WEBDRIVER_MANAGERS = {
"chromedriver": chrome.ChromeDriverManager,
"geckodriver": firefox.GeckoDriverManager,
}
USER_AGENT = "Mozilla/5.0 Gecko/20100101 Firefox/53.0"
def launch() -> Browser:
if not settings.browser.name:
sys.exit("No browser specified")
if settings.browser.name == "open":
settings.browser.name = NAMES[0]
settings.browser.name = settings.browser.name.lower()
log.info(f"Launching browser: {settings.browser.name}")
options = {
"headless": settings.browser.headless,
"user_agent": UserAgent(fallback=USER_AGENT)[settings.browser.name],
"wait_time": 1.0,
}
log.debug(f"Options: {options}")
try:
return Browser(settings.browser.name, **options)
except DriverNotFoundError:
sys.exit(f"Unsupported browser: {settings.browser.name}")
except Exception as e: # pylint: disable=broad-except
log.debug(str(e))
if "exited process" in str(e):
sys.exit("Browser update prevented launch. Please try again.")
for driver, manager in WEBDRIVER_MANAGERS.items():
if driver in str(e).lower():
options["executable_path"] = manager().install()
return Browser(settings.browser.name, **options)
raise e from None
def resize(browser: Browser):
browser.driver.set_window_size(settings.browser.width, settings.browser.height)
browser.driver.set_window_position(0, 0)
size = browser.driver.get_window_size()
log.debug(f"Resized browser: {size}")
def save_url(browser: Browser):
if settings.browser != browser.url:
log.debug(f"Saving last browser URL: {browser.url}")
settings.url = browser.url
def save_size(browser: Browser):
size = browser.driver.get_window_size()
if size != (settings.browser.width, settings.browser.height):
log.debug(f"Saving last browser size: {size}")
settings.browser.width = size["width"]
settings.browser.height = size["height"]
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,387 | jonesclarence37/pomace | refs/heads/main | /pomace/shared.py | from splinter import Browser
browser: Browser = None
linebreak: bool = True
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,388 | jonesclarence37/pomace | refs/heads/main | /pomace/tests/test_enums.py | # pylint: disable=expression-not-assigned,unused-variable,redefined-outer-name,unused-argument
from ..enums import Verb
def describe_verb():
def describe_get_default_locators():
def when_click(expect):
verb = Verb("click")
locators = list(verb.get_default_locators("send_email"))
expect(locators) == [
("text", "Send Email"),
("text", "Send email"),
("text", "send email"),
("value", "Send Email"),
("value", "Send email"),
("value", "send email"),
]
def when_fill(expect):
verb = Verb("fill")
locators = list(verb.get_default_locators("first_name"))
expect(locators) == [
("name", "first_name"),
("name", "first-name"),
("id", "first_name"),
("id", "first-name"),
("aria-label", "First Name"),
("css", '[placeholder="First Name"]'),
("id", "FirstName"),
]
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,389 | jonesclarence37/pomace | refs/heads/main | /tests/conftest.py | """Integration tests configuration file."""
# pylint: disable=unused-argument,redefined-outer-name
import os
import datafiles
import log
import pytest
from pomace import shared, utils
from pomace.config import settings as _settings
def pytest_configure(config):
log.init(debug=True)
log.silence("parse", "faker", "selenium", "urllib3", allow_info=True)
terminal = config.pluginmanager.getplugin("terminal")
terminal.TerminalReporter.showfspath = False
def pytest_runtest_setup(item):
datafiles.settings.HOOKS_ENABLED = True
@pytest.fixture(scope="session", autouse=True)
def settings():
backup = _settings.datafile.text
yield _settings
_settings.datafile.text = backup
@pytest.fixture
def browser(settings):
if "APPVEYOR" in os.environ:
# TODO: https://github.com/jacebrowning/pomace/issues/42
pytest.skip("Launching browsers on AppVeyor causes build timeouts")
settings.browser.name = "chrome"
settings.browser.headless = True
settings.url = "http://example.com"
utils.launch_browser()
return shared.browser
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,390 | jonesclarence37/pomace | refs/heads/main | /pomace/prompts.py | import os
import sys
from functools import wraps
from importlib import import_module
from typing import Optional, Tuple, no_type_check
import log
from IPython import embed
from . import browser, enums, shared
from .config import settings
try:
import bullet
except ImportError:
bullet = None # https://github.com/Mckinsey666/bullet/issues/2
log.warn("Interactive CLI prompts not yet supported on Windows")
if "pytest" in sys.modules:
bullet = None
log.warn("Interactive CLI prompts disabled while testing")
RELOAD_ACTIONS = "<reload actions>"
ADD_ACTION = "<add action>"
CANCEL = "<cancel prompt>"
DEBUG = "<start shell>"
def linebreak(*, force: bool = False):
if not shared.linebreak or force:
print()
shared.linebreak = True
def offset(function):
@wraps(function)
def wrapper(*args, **kwargs):
linebreak()
value = function(*args, **kwargs)
linebreak()
return value
return wrapper
@offset
def browser_if_unset():
if settings.browser.name:
return
if "CI" in os.environ or not bullet:
value = os.getenv("BROWSER") or browser.NAMES[0]
settings.browser.name = value.lower()
return
shared.linebreak = False
command = bullet.Bullet(
prompt="Select a browser for automation: ",
bullet=" ● ",
choices=browser.NAMES,
)
settings.browser.name = command.launch()
@offset
def url_if_unset(domains=None):
if settings.url:
return
if "CI" in os.environ or not bullet:
settings.url = "http://example.com"
return
shared.linebreak = False
if domains:
command = bullet.Bullet(
prompt="Starting domain: ", bullet=" ● ", choices=domains
)
else:
command = bullet.Input(prompt="Starting domain: ", strip=True)
value = command.launch()
settings.url = f"https://{value}"
@offset
def secret_if_unset(name: str):
if settings.get_secret(name, _log=False):
return
if "CI" in os.environ or not bullet:
settings.set_secret(name, "<unset>")
return
value = named_value(name)
settings.set_secret(name, value)
@offset
def action(page) -> Optional[str]:
shared.linebreak = False
choices = [RELOAD_ACTIONS] + dir(page) + [DEBUG, ADD_ACTION]
command = bullet.Bullet(
prompt="Select an action: ",
bullet=" ● ",
choices=choices,
)
value = command.launch()
if value == RELOAD_ACTIONS:
return None
if value == DEBUG:
shell()
return ""
if value == ADD_ACTION:
verb, name = verb_and_name()
if verb and name:
return f"{verb}_{name}"
return ""
return value
@offset
def named_value(name: str) -> Optional[str]:
if not bullet:
return None
shared.linebreak = False
command = bullet.Input(prompt="Value for " + name.replace("_", " ") + ": ")
value = command.launch()
return value
@offset
def verb_and_name() -> Tuple[str, str]:
choices = [CANCEL] + [verb.value for verb in enums.Verb] + [DEBUG]
command = bullet.Bullet(
prompt="Select element verb: ",
bullet=" ● ",
choices=choices,
)
verb = command.launch()
linebreak(force=True)
if verb == CANCEL:
return "", ""
if verb == DEBUG:
shell()
return "", ""
shared.linebreak = False
command = bullet.Input("Name of element: ")
name = command.launch().lower().replace(" ", "_")
return verb, name
@offset
def mode_and_value() -> Tuple[str, str]:
if not bullet:
return "", ""
choices = [CANCEL] + [mode.value for mode in enums.Mode] + [DEBUG]
command = bullet.Bullet(
prompt="Select element locator: ",
bullet=" ● ",
choices=choices,
)
mode = command.launch()
linebreak(force=True)
if mode == CANCEL:
return "", ""
if mode == DEBUG:
shell()
return "", ""
shared.linebreak = False
command = bullet.Input("Value to match: ")
value = command.launch()
return mode, value
@no_type_check
def shell():
try:
get_ipython() # type: ignore
except NameError:
log.debug("Launching IPython")
linebreak()
else:
return
pomace = import_module("pomace")
globals().update(
{name: getattr(pomace.models, name) for name in pomace.models.__all__}
)
globals().update(
{name: getattr(pomace.types, name) for name in pomace.types.__all__}
)
auto = pomace.models.auto
page = auto() # pylint: disable=unused-variable
embed(colors="neutral")
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,391 | jonesclarence37/pomace | refs/heads/main | /tests/test_cli.py | # pylint: disable=unused-variable,redefined-outer-name
from pathlib import Path
import pytest
from cleo import ApplicationTester
from pomace.cli import application
@pytest.fixture
def cli():
return ApplicationTester(application).execute
def describe_clone():
def with_url(cli):
cli("clone https://github.com/jacebrowning/pomace-twitter.com")
assert Path("sites", "twitter.com").is_dir()
def with_url_and_domain(cli):
cli(
"clone https://github.com/jacebrowning/pomace-twitter.com"
" twitter.fake --force"
)
assert Path("sites", "twitter.fake").is_dir()
def describe_clean():
def with_domain(cli):
cli("clean twitter.fake")
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,392 | jonesclarence37/pomace | refs/heads/main | /pomace/tests/conftest.py | # pylint: disable=no-self-use,unused-argument
"""Unit tests configuration file."""
import datafiles
import log
import pytest
from pomace import shared
class MockElement(str):
@property
def outer_html(self):
return f"<mockhtml>{self}</>"
@property
def visible(self):
return True
class MockLinks:
def find_by_partial_text(self, value):
return [MockElement(f"mockelement:links.partial_text={value}")]
class MockBrowser:
url = "http://example.com"
html = "Hello, world!"
def find_by_name(self, value):
return [MockElement(f"mockelement:name={value}")]
def find_by_css(self, value):
return [MockElement(f"mockelement:css={value}")]
links = MockLinks()
@pytest.fixture
def mockbrowser(monkeypatch):
browser = MockBrowser()
monkeypatch.setattr(shared, "browser", browser)
return browser
def pytest_configure(config):
log.init(debug=True)
log.silence("faker", "vcr")
terminal = config.pluginmanager.getplugin("terminal")
terminal.TerminalReporter.showfspath = False
def pytest_runtest_setup(item):
datafiles.settings.HOOKS_ENABLED = False
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,393 | jonesclarence37/pomace | refs/heads/main | /pomace/tests/test_browser.py | # pylint: disable=unused-variable,expression-not-assigned
from pomace import browser
from pomace.config import settings
def describe_launch():
def it_requires_a_browser_to_be_set(expect):
settings.browser.name = ""
with expect.raises(SystemExit):
browser.launch()
def it_rejects_invalid_browsers(expect):
settings.browser.name = "foobar"
with expect.raises(SystemExit):
browser.launch()
def it_forces_lowercase_browser_name(expect, mocker):
settings.browser.name = "Firefox"
mocker.patch.object(browser, "Browser")
browser.launch()
expect(settings.browser.name) == "firefox"
def it_handles_unspecified_browser(expect, mocker):
settings.browser.name = "open"
mocker.patch.object(browser, "Browser")
browser.launch()
expect(settings.browser.name) == "firefox"
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,394 | jonesclarence37/pomace | refs/heads/main | /pomace/utils.py | import atexit
import inspect
import os
import sys
import time
from bdb import BdbQuit
from pathlib import Path
import ipdb
import log
from gitman.decorators import preserve_cwd
from gitman.models import Source
from selenium.common.exceptions import WebDriverException
from urllib3.exceptions import HTTPError
from . import browser, shared
from .config import settings
def launch_browser(
delay: float = 0.0,
*,
silence_logging: bool = False,
restore_previous_url: bool = True,
) -> bool:
did_launch = False
if silence_logging:
log.silence("urllib3.connectionpool")
if shared.browser:
try:
log.debug(f"Current browser windows: {shared.browser.windows}")
log.debug(f"Current browser URL: {shared.browser.url}")
except (WebDriverException, HTTPError) as e:
log.warn(str(e).strip())
shared.browser = None
if not shared.browser:
shared.browser = browser.launch()
atexit.register(quit_browser, silence_logging=silence_logging)
browser.resize(shared.browser)
did_launch = True
if restore_previous_url and settings.url:
shared.browser.visit(settings.url)
time.sleep(delay)
return did_launch
def quit_browser(*, silence_logging: bool = False) -> bool:
did_quit = False
if silence_logging:
log.silence("pomace", "selenium", allow_warning=True)
if shared.browser:
try:
browser.save_url(shared.browser)
browser.save_size(shared.browser)
shared.browser.quit()
except Exception as e:
log.debug(e)
else:
did_quit = True
shared.browser = None
path = Path().resolve()
for _ in range(5):
logfile = path / "geckodriver.log"
if logfile.exists():
log.debug(f"Deleting {logfile}")
logfile.unlink()
path = path.parent
return did_quit
def locate_models(*, caller=None):
cwd = Path.cwd()
if caller:
for frame in inspect.getouterframes(caller):
if "pomace" not in frame.filename or "pomace/tests" in frame.filename:
path = Path(frame.filename)
log.debug(f"Found caller's package directory: {path.parent}")
os.chdir(path.parent)
return
if (cwd / "sites").is_dir():
log.debug(f"Found models in current directory: {cwd}")
return
for path in cwd.iterdir():
if (path / "sites").is_dir():
log.debug(f"Found models in package directory: {path}")
os.chdir(path)
return
@preserve_cwd
def clone_models(url: str, *, domain: str = "", force: bool = False):
repository = url.replace(".git", "").split("/")[-1]
domain = domain or repository.replace("pomace-", "")
directory = Path("sites") / domain
log.info(f"Cloning {url} to {directory}")
assert "." in domain, f"Invalid domain: {domain}"
source = Source(url, directory)
source.update_files(force=force)
def run_script(script: str):
path = Path(script).resolve()
if path.is_file():
log.info(f"Running script: {path}")
else:
log.error(f"Script not found: {path}")
try:
exec(path.read_text()) # pylint: disable=exec-used
except (KeyboardInterrupt, BdbQuit):
pass
except Exception as e:
log.critical(f"Script exception: {e}")
_type, _value, traceback = sys.exc_info()
ipdb.post_mortem(traceback)
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,395 | jonesclarence37/pomace | refs/heads/main | /pomace/models.py | from contextlib import suppress
from copy import copy
from typing import Callable, List, Optional, Tuple
import log
from bs4 import BeautifulSoup
from cached_property import cached_property
from datafiles import datafile, field, mapper
from selenium.common.exceptions import (
ElementNotInteractableException,
WebDriverException,
)
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from splinter import Browser
from splinter.driver.webdriver import WebDriverElement
from splinter.exceptions import ElementDoesNotExist
from . import prompts, shared
from .config import settings
from .enums import Mode, Verb
from .types import URL
__all__ = ["Locator", "Action", "Page", "auto"]
@datafile(order=True)
class Locator:
mode: str = field(default="", compare=False)
value: str = field(default="", compare=False)
index: int = field(default=0, compare=False)
uses: int = field(default=0, compare=True)
def __repr__(self) -> str:
return f"<locator {self.mode}={self.value}[{self.index}]>"
def __bool__(self) -> bool:
return bool(self.mode and self.value)
def find(self) -> Optional[WebDriverElement]:
elements = self._mode.find(self.value)
index = self.index
try:
element = elements[index]
if index == 0 and not element.visible:
log.debug(f"{self} found invisible element: {element.outer_html}")
index += 1
element = elements[index]
except ElementDoesNotExist:
log.debug(f"{self} unable to find element")
return None
else:
self.index = index
log.debug(f"{self} found element: {element.outer_html}")
return element
def score(self, value: int) -> bool:
previous = self.uses
if value > 0:
self.uses = min(99, max(1, self.uses + value))
else:
self.uses = max(-1, self.uses + value)
if self.uses == previous:
return False
result = "Increased" if self.uses > previous else "Decreased"
log.debug(f"{result} {self} uses to {self.uses}")
return True
@property
def _mode(self) -> Mode:
return Mode(self.mode)
@datafile
class Action:
verb: str = ""
name: str = ""
locators: List[Locator] = field(default_factory=lambda: [Locator()])
@property
def humanized(self) -> str:
return self._verb.humanized + " " + self.name.replace("_", " ")
@property
def sorted_locators(self) -> List[Locator]:
locators = [x for x in sorted(self.locators, reverse=True) if x]
if all(locator.uses < 0 for locator in locators):
return locators
if len(locators) > 1 and locators[0].uses == 0 and locators[1].uses < 0:
log.debug("Trying new locator first")
return [locators[0]]
return [locator for locator in locators if locator.uses >= 0]
@property
def locator(self) -> Locator:
try:
return self.sorted_locators[0]
except IndexError:
return Locator("id", "placeholder")
@property
def valid(self) -> bool:
return self.locator.uses >= 0
def __post_init__(self):
if self.verb and self._verb != Verb.TYPE and not self.sorted_locators:
if settings.dev:
log.info(f"Adding placeholder locators for {self}")
for mode, value in self._verb.get_default_locators(self.name):
self.locators.append(Locator(mode, value))
else:
log.debug("Placeholder locators are disabled")
def __str__(self):
return f"{self.verb}_{self.name}"
def __bool__(self) -> bool:
return bool(self.verb and self.name)
def __call__(self, *args, **kwargs) -> "Page":
page = kwargs.pop("_page", None)
page = self._call_method(page, *args, **kwargs)
self.datafile.save()
page.clean()
return page
def _call_method(self, page, *args, **kwargs) -> "Page":
while self._trying_locators(*args, **kwargs):
log.error(f"No locators able to find {self.name!r}")
if prompts.bullet:
shared.linebreak = False
mode, value = prompts.mode_and_value()
if mode and value:
self.locators.append(Locator(mode, value))
else:
break
if page and self._verb.updates:
return page
return auto()
def _trying_locators(self, *args, **kwargs) -> bool:
if self._verb == Verb.TYPE:
if "_" in self.name:
names = self.name.split("_")
assert len(names) == 2, "Multiple modifier keys not supported"
modifier = getattr(Keys, names[0].upper())
key = getattr(Keys, names[-1].upper())
function = (
ActionChains(shared.browser.driver)
.key_down(modifier)
.send_keys(key)
.key_up(modifier)
.perform
)
else:
key = getattr(Keys, self.name.upper())
function = ActionChains(shared.browser.driver).send_keys(key).perform
self._perform_action(function, *args, **kwargs)
return False
for locator in self.sorted_locators:
if locator:
log.debug(f"Using {locator} to find {self.name!r}")
element = locator.find()
if element:
function = getattr(element, self.verb)
if self._perform_action(function, *args, **kwargs):
locator.score(+1)
return False
locator.score(-1)
return True
def _perform_action(self, function: Callable, *args, **kwargs) -> bool:
previous_url = shared.browser.url
delay = kwargs.pop("delay", None)
wait = kwargs.pop("wait", None)
self._verb.pre_action()
try:
function(*args, **kwargs)
except ElementDoesNotExist as e:
log.warn(e)
return False
except ElementNotInteractableException as e:
log.warn(e.msg)
return False
except WebDriverException as e:
log.debug(e)
return False
else:
self._verb.post_action(previous_url, delay, wait)
return True
def clean(self, page, *, force: bool = False) -> int:
unused_locators = []
remove_unused_locators = force
for locator in self.locators:
if locator.uses <= 0:
unused_locators.append(locator)
if locator.uses >= 99:
remove_unused_locators = True
log.debug(f"Found {len(unused_locators)} unused locators for {self} on {page}")
if not remove_unused_locators:
return 0
if unused_locators:
log.info(f"Cleaning up locators for {self} on {page}")
for locator in unused_locators:
log.info(f"Removed unused {locator}")
self.locators.remove(locator)
return len(unused_locators)
@property
def _verb(self) -> Verb:
return Verb(self.verb)
@datafile
class Locators:
inclusions: List[Locator] = field(default_factory=lambda: [Locator()])
exclusions: List[Locator] = field(default_factory=lambda: [Locator()])
@property
def sorted_inclusions(self) -> List[Locator]:
return [x for x in sorted(self.inclusions, reverse=True) if x]
@property
def sorted_exclusions(self) -> List[Locator]:
return [x for x in sorted(self.exclusions, reverse=True) if x]
def clean(self, page, *, force: bool = False) -> int:
unused_inclusion_locators = []
unused_exclusion_locators = []
remove_unused_locators = force
for locator in self.inclusions:
if locator.uses <= 0:
unused_inclusion_locators.append(locator)
if locator.uses >= 99:
remove_unused_locators = True
for locator in self.exclusions:
if locator.uses <= 0:
unused_exclusion_locators.append(locator)
if locator.uses >= 99:
remove_unused_locators = True
count = len(unused_inclusion_locators) + len(unused_exclusion_locators)
log.debug(f"Found {count} unused locators for {page}")
if not remove_unused_locators:
return 0
if unused_inclusion_locators:
log.info(f"Cleaning up inclusion locators for {page}")
for locator in unused_inclusion_locators:
log.info(f"Removed unused {locator}")
self.inclusions.remove(locator)
if unused_exclusion_locators:
log.info(f"Cleaning up exclusion locators for {page}")
for locator in unused_exclusion_locators:
log.info(f"Removed unused {locator}")
self.exclusions.remove(locator)
return len(unused_inclusion_locators) + len(unused_exclusion_locators)
@datafile(
"./sites/{self.domain}/{self.path}/{self.variant}.yml", defaults=True, manual=True
)
class Page:
domain: str
path: str = URL.ROOT
variant: str = "default"
locators: Locators = field(default_factory=Locators)
actions: List[Action] = field(default_factory=lambda: [Action()])
@classmethod
def at(cls, url: str, *, variant: str = "") -> "Page":
if shared.browser.url != url:
log.info(f"Visiting {url}")
shared.browser.visit(url)
if shared.browser.url != url:
log.info(f"Redirected to {url}")
kwargs = {"domain": URL(url).domain, "path": URL(url).path}
variant = variant or URL(url).fragment
if variant:
kwargs["variant"] = variant
page = cls(**kwargs) # type: ignore
log.debug(f"Loaded {page.url}: {page.title} ({page.identity})")
return page
@property
def url_pattern(self) -> URL:
return URL(self.domain, self.path)
@property
def exact(self) -> bool:
return "{" not in self.path
@property
def browser(self) -> Browser:
return shared.browser
@cached_property
def url(self) -> str:
return self.browser.url
@cached_property
def title(self) -> str:
return self.browser.title
@cached_property
def identity(self) -> int:
return sum(ord(c) for c in self.text)
@cached_property
def text(self) -> str:
html = copy(self.html)
for element in html(["script", "style"]):
element.extract()
lines = (line.strip() for line in html.get_text().splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split(" "))
return "\n".join(chunk for chunk in chunks if chunk)
@cached_property
def html(self) -> BeautifulSoup:
return BeautifulSoup(self.browser.html, "html.parser")
@property
def active(self) -> bool:
log.debug(f"Determining if {self!r} is active")
if self.url_pattern != URL(shared.browser.url):
log.debug(f"{self!r} is inactive: URL not matched")
return False
log.debug("Checking that all expected elements can be found")
for locator in self.locators.sorted_inclusions:
if locator.find():
if locator.score(+1):
self.datafile.save()
else:
log.debug(f"{self!r} is inactive: {locator!r} found expected element")
return False
log.debug("Checking that no unexpected elements can be found")
for locator in self.locators.sorted_exclusions:
if locator.find():
if locator.score(+1):
self.datafile.save()
log.debug(f"{self!r} is inactive: {locator!r} found unexpected element")
return False
log.debug(f"{self!r} is active")
return True
def __repr__(self):
if self.variant == "default":
return f"Page.at('{self.url_pattern}')"
return f"Page.at('{self.url_pattern}', variant='{self.variant}')"
def __str__(self):
if self.variant == "default":
return f"{self.url_pattern}"
return f"{self.url_pattern} ({self.variant})"
def __dir__(self):
names = []
add_placeholder = True
for action in self.actions:
if action:
if action.valid:
names.append(str(action))
else:
add_placeholder = False
if add_placeholder:
if settings.dev:
log.info(f"Adding placeholder action for {self}")
self.actions.append(Action())
else:
log.debug("Placeholder actions are disabled")
return names
def __getattr__(self, value: str) -> Action:
if "_" in value:
verb, name = value.split("_", 1)
with suppress(FileNotFoundError):
self.datafile.load()
for action in self.actions:
if action.name == name and action.verb == verb:
return action
if Verb.validate(verb, name):
action = Action(verb, name)
setattr(
action,
"datafile",
mapper.create_mapper(action, root=self.datafile),
)
if settings.dev:
self.actions.append(action)
else:
log.debug("Automatic actions are disabled")
return action
return object.__getattribute__(self, value)
def __contains__(self, value):
return value in self.text
def perform(self, name: str, value: str = "", _logger=None) -> Tuple["Page", bool]:
_logger = _logger or log
action = getattr(self, name)
if action.verb in {"fill", "select"}:
if not value:
value = settings.get_secret(action.name) or prompts.named_value(
action.name
)
settings.update_secret(action.name, value)
_logger.info(f"{action.humanized} with {value!r}")
page = action(value, _page=self)
else:
_logger.info(f"{action.humanized}")
page = action(_page=self)
return page, page != self
def clean(self, *, force: bool = False) -> int:
count = self.locators.clean(self, force=force)
unused_actions = []
remove_unused_actions = force
for action in self.actions:
if all(locator.uses <= 0 for locator in action.locators):
unused_actions.append(action)
log.debug(f"Found {len(unused_actions)} unused actions for {self}")
if unused_actions and remove_unused_actions:
log.info(f"Cleaning up actions for {self}")
for action in unused_actions:
log.info(f"Removed unused {action}")
self.actions.remove(action)
for action in self.actions:
count += action.clean(self, force=force)
if count or force:
self.datafile.save()
return count
def auto() -> Page:
matching_pages = []
found_exact_match = False
for page in Page.objects.filter(domain=URL(shared.browser.url).domain):
if page.active:
matching_pages.append(page)
if page.exact:
found_exact_match = True
if found_exact_match:
log.debug("Removing abstract pages from matches")
matching_pages = [page for page in matching_pages if page.exact]
if matching_pages:
if len(matching_pages) > 1:
for page in matching_pages:
log.warn(f"Multiple pages matched: {page}")
if prompts.bullet:
shared.linebreak = False
return matching_pages[0]
log.info(f"Creating new page: {shared.browser.url}")
page = Page.at(shared.browser.url)
page.datafile.save()
return page
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,396 | jonesclarence37/pomace | refs/heads/main | /pomace/enums.py | import time
from enum import Enum
from typing import Iterator, Optional, Tuple
import inflection
import log
from selenium.webdriver.common.keys import Keys
from . import shared
class Mode(Enum):
NAME = "name"
ID = "id"
TEXT = "text"
PARTIAL_TEXT = "text (partial)" # extended
VALUE = "value"
ARIA_LABEL = "aria-label" # extended
CSS = "css"
TAG = "tag"
XPATH = "xpath"
@property
def finder(self):
if self is self.PARTIAL_TEXT:
return shared.browser.links.find_by_partial_text
if self is self.ARIA_LABEL:
return shared.browser.find_by_css
return getattr(shared.browser, f"find_by_{self.value}")
def find(self, value):
if self is self.ARIA_LABEL:
value = f'[aria-label="{value}"]'
return self.finder(value)
class Verb(Enum):
CLICK = "click"
FILL = "fill"
SELECT = "select"
CHOOSE = "choose"
TYPE = "type"
@property
def humanized(self) -> str:
return (self.value.capitalize() + "ing").replace("eing", "ing")
@classmethod
def validate(cls, value: str, name: str) -> bool:
values = [enum.value for enum in cls]
if value not in values:
return False
# TODO: name should be validated somewhere else
if value == "type" and not all(
hasattr(Keys, n.upper()) for n in name.split("_")
):
return False
return True
@property
def updates(self) -> bool:
return self not in {self.CLICK, self.TYPE}
def get_default_locators(self, name: str) -> Iterator[Tuple[str, str]]:
if self is self.CLICK:
yield Mode.TEXT.value, inflection.titleize(name)
yield Mode.TEXT.value, inflection.humanize(name)
yield Mode.TEXT.value, name.replace("_", " ")
yield Mode.VALUE.value, inflection.titleize(name)
yield Mode.VALUE.value, inflection.humanize(name)
yield Mode.VALUE.value, name.replace("_", " ")
elif self in {self.FILL, self.SELECT}:
yield Mode.NAME.value, name
yield Mode.NAME.value, inflection.dasherize(name)
yield Mode.ID.value, name
yield Mode.ID.value, inflection.dasherize(name)
yield Mode.ARIA_LABEL.value, inflection.titleize(name)
yield Mode.CSS.value, f'[placeholder="{inflection.titleize(name)}"]'
yield Mode.ID.value, inflection.titleize(name).replace(" ", "")
def pre_action(self):
if self is self.CLICK:
shared.browser.execute_script(
"""
Array.from(document.querySelectorAll('a[target="_blank"]'))
.forEach(link => link.removeAttribute('target'));
"""
)
def post_action(
self,
previous_url: str,
delay: float = 0.0,
wait: Optional[float] = None,
):
if delay:
log.debug(f"Waiting {delay} seconds before continuing")
time.sleep(delay)
if wait is None:
wait = 0.0 if self.updates else 5.0
if wait:
log.debug(f"Waiting {wait} seconds for URL to change: {previous_url}")
elapsed = 0.0
start = time.time()
while elapsed < wait:
time.sleep(0.1)
elapsed = round(time.time() - start, 1)
current_url = shared.browser.url
if current_url != previous_url:
log.debug(f"URL changed after {elapsed} seconds: {current_url}")
time.sleep(delay or 0.5)
break
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,397 | jonesclarence37/pomace | refs/heads/main | /pomace/tests/test_prompts.py | # pylint: disable=expression-not-assigned,unused-variable,redefined-outer-name,unused-argument
from .. import config, prompts
def describe_browser_if_unset():
def when_ci(expect, monkeypatch):
monkeypatch.setenv("CI", "true")
config.settings.browser.name = ""
prompts.browser_if_unset()
expect(config.settings.browser.name) == "firefox"
def when_ci_and_override(expect, monkeypatch):
monkeypatch.setenv("CI", "true")
monkeypatch.setenv("BROWSER", "chrome")
config.settings.browser.name = ""
prompts.browser_if_unset()
expect(config.settings.browser.name) == "chrome"
def describe_url_if_unset():
def when_ci(expect, monkeypatch, mockbrowser):
monkeypatch.setenv("CI", "true")
config.settings.url = ""
prompts.url_if_unset()
expect(config.settings.url) == "http://example.com"
def describe_secret_if_unset():
def when_ci(expect, monkeypatch, mockbrowser):
monkeypatch.setenv("CI", "true")
prompts.secret_if_unset("foobar")
expect(config.settings.get_secret("foobar")) == "<unset>"
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,398 | jonesclarence37/pomace | refs/heads/main | /pomace/__main__.py | #!/usr/bin/env python
"""Package entry point."""
from pomace.cli import application
if __name__ == "__main__": # pragma: no cover
application.run()
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,399 | jonesclarence37/pomace | refs/heads/main | /tests/test_api.py | # pylint: disable=unused-variable,expression-not-assigned
import os
from pathlib import Path
import pytest
import pomace
from pomace.config import settings
def test_package_contents(expect):
names = [name for name in dir(pomace) if not name.startswith("_")]
expect(names).contains("auto")
expect(names).contains("Page")
expect(names).contains("visit")
expect(names).excludes("get_distribution")
def describe_visit():
def it_launches_a_browser(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
expect(page).contains("Example Domain")
@pytest.mark.skipif(os.name == "nt", reason="Path differs on Windows")
def it_saves_data_relative_to_caller(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
path = Path(__file__).parent / "sites" / "example.com" / "@" / "default.yml"
expect(page.datafile.path) == path
def describe_freeze():
def it_disables_automatic_actions(expect):
page = pomace.visit("http://example.com", browser="chrome", headless=True)
page.actions = []
page.datafile.save()
pomace.freeze()
try:
page.click_foobar()
expect(dir(page)).excludes("click_foobar")
finally:
settings.dev = True
| {"/pomace/__init__.py": ["/pomace/api.py"], "/pomace/tests/test_models.py": ["/pomace/models.py"], "/tests/test_sites.py": ["/pomace/__init__.py", "/pomace/models.py"], "/notebooks/profile_default/startup/ipython_startup.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py", "/pomace/shared.py"], "/pomace/server.py": ["/pomace/__init__.py"], "/pomace/cli.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/tests/test_types.py": ["/pomace/types.py"], "/pomace/config.py": ["/pomace/__init__.py", "/pomace/types.py"], "/pomace/api.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/models.py"], "/pomace/browser.py": ["/pomace/config.py"], "/pomace/tests/test_enums.py": ["/pomace/enums.py"], "/tests/conftest.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/prompts.py": ["/pomace/__init__.py", "/pomace/config.py"], "/tests/test_cli.py": ["/pomace/cli.py"], "/pomace/tests/conftest.py": ["/pomace/__init__.py"], "/pomace/tests/test_browser.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/utils.py": ["/pomace/__init__.py", "/pomace/config.py"], "/pomace/models.py": ["/pomace/__init__.py", "/pomace/config.py", "/pomace/enums.py", "/pomace/types.py"], "/pomace/enums.py": ["/pomace/__init__.py"], "/pomace/tests/test_prompts.py": ["/pomace/__init__.py"], "/pomace/__main__.py": ["/pomace/cli.py"], "/tests/test_api.py": ["/pomace/__init__.py", "/pomace/config.py"]} |
53,401 | akarishiraj/Voice-Controlled-Game-Space-Invader | refs/heads/master | /game_logic.py | # seperated logic
def game_over_text():
over_text = over_font.render("GAME OVER", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y)) # blit means draw
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x + 16, y + 10)) # 16 is added so that bullet look at the center of spaceship
def isCollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt(math.pow(enemyX - bulletX, 2) + (math.pow(enemyY - bulletY, 2)))
if distance < 25:
return True
else:
return False
| {"/keyboard_game.py": ["/configuration.py"]} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.