index
int64 | repo_name
string | branch_name
string | path
string | content
string | import_graph
string |
|---|---|---|---|---|---|
1,025
|
Tadaboody/good_smell
|
refs/heads/master
|
/good_smell/smells/filter.py
|
from typing import TypeVar
import ast
from typing import cast
from good_smell import AstSmell, LoggingTransformer
class NameReplacer(ast.NodeTransformer):
def __init__(self, old: ast.Name, new: ast.AST):
self.old = old
self.new = new
def visit_Name(self, node: ast.Name) -> ast.AST:
if node.id == self.old.id:
return self.new
return node
T = TypeVar("T", bound=ast.AST)
def replace_name_with_node(node: T, old_val: ast.Name, new_val: ast.AST) -> T:
"""Returns `node` with all occurences of `old_val` (a variable) replaced with `new_val` (an expression)"""
return NameReplacer(old_val, new_val).visit(node)
class FilterTransformer(LoggingTransformer):
"""Bumps the filter to the iterator"""
def visit_For(self, node: ast.For) -> ast.For:
if_node: ast.If = node.body[0]
filter_condition: ast.Expr = if_node.test
if not isinstance(node.iter, ast.GeneratorExp):
# Create a generator expression if it doesn't exist
GEN_ELT_NAME = "x"
gen_exp: ast.GeneratorExp = cast(
ast.GeneratorExp,
ast_node(f"({GEN_ELT_NAME} for {GEN_ELT_NAME} in seq)").value,
)
gen_target = ast_node(GEN_ELT_NAME).value
iter_comprehension = gen_exp.generators[0]
iter_comprehension.iter = replace_name_with_node(
node.iter, node.target, gen_target
)
else:
gen_exp = node.iter
iter_comprehension = gen_exp.generators[0]
gen_target = gen_exp.elt
iter_comprehension.ifs.append(
replace_name_with_node(filter_condition, node.target, gen_target)
)
node.iter = gen_exp
node.body = if_node.body
return node
def is_smelly(self, node: ast.AST):
"""Check if the node is only a nested for"""
return (
isinstance(node, ast.For)
and len(node.body) == 1
and isinstance(node.body[0], ast.If)
)
class FilterIterator(AstSmell):
"""Checks for adjacent nested fors and replaces them with itertools.product"""
@property
def transformer_class(self):
return FilterTransformer
@property
def warning_message(self):
return "Consider using itertools.product instead of a nested for"
@property
def symbol(self) -> str:
return "filter-iterator"
def ast_node(expr: str) -> ast.AST:
"""Helper function to parse a string denoting an expression into an AST node"""
# ast.parse returns "Module(body=[Node])"
return ast.parse(expr).body[0]
|
{"/good_smell/__init__.py": ["/good_smell/smell_warning.py", "/good_smell/lint_smell.py", "/good_smell/ast_smell.py", "/good_smell/smells/__init__.py", "/good_smell/main.py", "/good_smell/flake8_ext.py"], "/good_smell/smells/range_len_fix.py": ["/good_smell/__init__.py"], "/docs/generate_smell_doc.py": ["/tests/test_collection.py"], "/good_smell/ast_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/__init__.py": ["/good_smell/smells/filter.py", "/good_smell/smells/join_literal.py", "/good_smell/smells/nested_for.py", "/good_smell/smells/range_len_fix.py", "/good_smell/smells/yield_from.py"], "/good_smell/main.py": ["/good_smell/__init__.py"], "/good_smell/smells/yield_from.py": ["/good_smell/__init__.py"], "/tests/test_collection.py": ["/good_smell/__init__.py"], "/good_smell/lint_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/nested_for.py": ["/good_smell/__init__.py"], "/good_smell/smells/join_literal.py": ["/good_smell/__init__.py"], "/tests/test_no_transform.py": ["/good_smell/smells/__init__.py"], "/good_smell/smells/filter.py": ["/good_smell/__init__.py"], "/good_smell/flake8_ext.py": ["/good_smell/__init__.py"], "/tests/test_enumerate_fix.py": ["/good_smell/__init__.py"]}
|
1,026
|
Tadaboody/good_smell
|
refs/heads/master
|
/good_smell/flake8_ext.py
|
import ast
from typing import Generator, Tuple
from good_smell import SmellWarning, implemented_smells, __version__
class LintingFlake8:
"""Entry point good smell to be used as a flake8 linting plugin"""
name = "good-smell"
version = __version__
def __init__(self, tree: ast.AST, filename: str):
""""http://flake8.pycqa.org/en/latest/plugin-development/plugin-parameters.html"""
self.tree = tree
self.filename = filename
def run(self) -> Generator[Tuple[int, int, str, str], None, None]:
for num, smell in enumerate(implemented_smells):
warnings = smell(
transform=False, tree=self.tree, path=self.filename
).check_for_smell()
warning: SmellWarning
yield from (
(
warning.row,
warning.col,
f"SML{str(num).zfill(3)} {warning.msg}",
"GoodSmell",
)
for warning in warnings
)
|
{"/good_smell/__init__.py": ["/good_smell/smell_warning.py", "/good_smell/lint_smell.py", "/good_smell/ast_smell.py", "/good_smell/smells/__init__.py", "/good_smell/main.py", "/good_smell/flake8_ext.py"], "/good_smell/smells/range_len_fix.py": ["/good_smell/__init__.py"], "/docs/generate_smell_doc.py": ["/tests/test_collection.py"], "/good_smell/ast_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/__init__.py": ["/good_smell/smells/filter.py", "/good_smell/smells/join_literal.py", "/good_smell/smells/nested_for.py", "/good_smell/smells/range_len_fix.py", "/good_smell/smells/yield_from.py"], "/good_smell/main.py": ["/good_smell/__init__.py"], "/good_smell/smells/yield_from.py": ["/good_smell/__init__.py"], "/tests/test_collection.py": ["/good_smell/__init__.py"], "/good_smell/lint_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/nested_for.py": ["/good_smell/__init__.py"], "/good_smell/smells/join_literal.py": ["/good_smell/__init__.py"], "/tests/test_no_transform.py": ["/good_smell/smells/__init__.py"], "/good_smell/smells/filter.py": ["/good_smell/__init__.py"], "/good_smell/flake8_ext.py": ["/good_smell/__init__.py"], "/tests/test_enumerate_fix.py": ["/good_smell/__init__.py"]}
|
1,027
|
Tadaboody/good_smell
|
refs/heads/master
|
/tests/examples/filter.py
|
#: Move if to iterator
# filter-iterator
for i in range(10):
if i == 2:
print(1)
print(2)
# ==>
for i in (x for x in range(10) if x == 2):
print(1)
print(2)
# END
#: Don't move if there's code before
# None
for i in range(10):
print(1)
if pred(i):
print(2)
# ==>
for i in range(10):
print(1)
if pred(i):
print(2)
# END
#: don't move if there's code after
# None
for i in range(10):
if pred(i):
print(1)
print(2)
# ==>
for i in range(10):
if pred(i):
print(1)
print(2)
# END
#: Merge into existing expr
# filter-iterator
for i in (a * 2 for a in range(2)):
if pred(i):
pass
# ==>
for i in (a * 2 for a in range(2) if pred(a * 2)):
pass
# END
#: Merge into existing complex expr
# filter-iterator
for i in (f(a) * 2 for a in range(2)):
if pred(i):
pass
# ==>
for i in (f(a) * 2 for a in range(2) if pred(f(a) * 2)):
pass
# END
|
{"/good_smell/__init__.py": ["/good_smell/smell_warning.py", "/good_smell/lint_smell.py", "/good_smell/ast_smell.py", "/good_smell/smells/__init__.py", "/good_smell/main.py", "/good_smell/flake8_ext.py"], "/good_smell/smells/range_len_fix.py": ["/good_smell/__init__.py"], "/docs/generate_smell_doc.py": ["/tests/test_collection.py"], "/good_smell/ast_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/__init__.py": ["/good_smell/smells/filter.py", "/good_smell/smells/join_literal.py", "/good_smell/smells/nested_for.py", "/good_smell/smells/range_len_fix.py", "/good_smell/smells/yield_from.py"], "/good_smell/main.py": ["/good_smell/__init__.py"], "/good_smell/smells/yield_from.py": ["/good_smell/__init__.py"], "/tests/test_collection.py": ["/good_smell/__init__.py"], "/good_smell/lint_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/nested_for.py": ["/good_smell/__init__.py"], "/good_smell/smells/join_literal.py": ["/good_smell/__init__.py"], "/tests/test_no_transform.py": ["/good_smell/smells/__init__.py"], "/good_smell/smells/filter.py": ["/good_smell/__init__.py"], "/good_smell/flake8_ext.py": ["/good_smell/__init__.py"], "/tests/test_enumerate_fix.py": ["/good_smell/__init__.py"]}
|
1,028
|
Tadaboody/good_smell
|
refs/heads/master
|
/tests/test_enumerate_fix.py
|
from good_smell import fix_smell
from re import match
import pytest
valid_sources = ["""
a = [0]
for i in range(len(a)):
print(a[i])
""",
"""
b = [1]
for i in range(len(a + b)):
print(i)
"""]
@pytest.mark.parametrize("source", valid_sources)
def test_range_len_fix(source):
assert not match(r'for \w+ in range\(len\(.+\)\):',
fix_smell(source))
|
{"/good_smell/__init__.py": ["/good_smell/smell_warning.py", "/good_smell/lint_smell.py", "/good_smell/ast_smell.py", "/good_smell/smells/__init__.py", "/good_smell/main.py", "/good_smell/flake8_ext.py"], "/good_smell/smells/range_len_fix.py": ["/good_smell/__init__.py"], "/docs/generate_smell_doc.py": ["/tests/test_collection.py"], "/good_smell/ast_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/__init__.py": ["/good_smell/smells/filter.py", "/good_smell/smells/join_literal.py", "/good_smell/smells/nested_for.py", "/good_smell/smells/range_len_fix.py", "/good_smell/smells/yield_from.py"], "/good_smell/main.py": ["/good_smell/__init__.py"], "/good_smell/smells/yield_from.py": ["/good_smell/__init__.py"], "/tests/test_collection.py": ["/good_smell/__init__.py"], "/good_smell/lint_smell.py": ["/good_smell/__init__.py"], "/good_smell/smells/nested_for.py": ["/good_smell/__init__.py"], "/good_smell/smells/join_literal.py": ["/good_smell/__init__.py"], "/tests/test_no_transform.py": ["/good_smell/smells/__init__.py"], "/good_smell/smells/filter.py": ["/good_smell/__init__.py"], "/good_smell/flake8_ext.py": ["/good_smell/__init__.py"], "/tests/test_enumerate_fix.py": ["/good_smell/__init__.py"]}
|
1,031
|
tagplay/django-uuid-pk
|
refs/heads/master
|
/django_uuid_pk/tests/settings.py
|
import os
SITE_ID = 1
STATIC_URL = '/static/'
SECRET_KEY =';pkj;lkj;lkjh;lkj;oi'
db = os.environ.get('DBENGINE', None)
if db == 'pg':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django_uuid_pk',
'HOST': '127.0.0.1',
'PORT': '',
'USER': 'postgres',
'PASSWORD': '',
'OPTIONS': {
'autocommit': True, # same value for all versions of django (is the default in 1.6)
}}}
elif db == 'mysql':
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_uuid_pk',
'HOST': '127.0.0.1',
'PORT': '',
'USER': 'aa',
'PASSWORD': ''}}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'django_uuid_pk.sqlite',
'HOST': '',
'PORT': ''}}
INSTALLED_APPS = ('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django_uuid_pk.tests')
ALLOWED_HOSTS = ('127.0.0.1',)
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(levelname)-8s: %(asctime)s %(name)10s: %(funcName)40s %(message)s'
}
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
}
|
{"/django_uuid_pk/tests/tests.py": ["/django_uuid_pk/tests/models.py"]}
|
1,032
|
tagplay/django-uuid-pk
|
refs/heads/master
|
/conftest.py
|
import os
import sys
from django.conf import settings
def pytest_configure(config):
if not settings.configured:
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_uuid_pk.tests.settings'
def runtests(args=None):
import pytest
if not args:
args = []
if not any(a for a in args[1:] if not a.startswith('-')):
args.append('django_uuid_pk/tests')
sys.exit(pytest.main(args))
if __name__ == '__main__':
runtests(sys.argv)
|
{"/django_uuid_pk/tests/tests.py": ["/django_uuid_pk/tests/models.py"]}
|
1,033
|
tagplay/django-uuid-pk
|
refs/heads/master
|
/django_uuid_pk/tests/__init__.py
|
# from __future__ import absolute_import
# from .tests import *
# from .models import *
|
{"/django_uuid_pk/tests/tests.py": ["/django_uuid_pk/tests/models.py"]}
|
1,034
|
tagplay/django-uuid-pk
|
refs/heads/master
|
/django_uuid_pk/tests/models.py
|
import uuid
from django.db import models
from django_uuid_pk.fields import UUIDField
class ModelUUIDField(models.Model):
uuid1 = UUIDField(version=1, auto=True)
uuid3 = UUIDField(namespace=uuid.NAMESPACE_URL, version=3, auto=True)
uuid4 = UUIDField(version=4, auto=True)
uuid5 = UUIDField(namespace=uuid.NAMESPACE_URL, version=5, auto=True)
class AutoUUIDFieldModel(models.Model):
uuid = UUIDField(auto=True)
class ManualUUIDFieldModel(models.Model):
uuid = UUIDField(auto=False)
class NamespaceUUIDFieldModel(models.Model):
uuid = UUIDField(auto=True, namespace=uuid.NAMESPACE_URL, version=5)
class BrokenNamespaceUUIDFieldModel(models.Model):
uuid = UUIDField(auto=True, namespace='lala', version=5)
class PrimaryKeyUUIDFieldModel(models.Model):
uuid = UUIDField(primary_key=True)
#char = models.CharField(max_length=10, null=True)
class BrokenPrimaryKeyUUIDFieldModel(models.Model):
uuid = UUIDField(primary_key=True)
unique = models.IntegerField(unique=True)
def __repr__(self):
return {}
|
{"/django_uuid_pk/tests/tests.py": ["/django_uuid_pk/tests/models.py"]}
|
1,035
|
tagplay/django-uuid-pk
|
refs/heads/master
|
/django_uuid_pk/tests/tests.py
|
import json
import uuid
from django.core.serializers import serialize
from django.db import IntegrityError
from django.test import TestCase
import pytest
from django_uuid_pk.fields import StringUUID
from django_uuid_pk.tests.models import (AutoUUIDFieldModel, ManualUUIDFieldModel, NamespaceUUIDFieldModel,
BrokenNamespaceUUIDFieldModel, PrimaryKeyUUIDFieldModel,
BrokenPrimaryKeyUUIDFieldModel, ModelUUIDField)
def assertJSON(data):
try:
json.loads(data)
except ValueError:
raise
@pytest.mark.django_db
class UUIDFieldTestCase(TestCase):
def test_protocols(self):
obj = ModelUUIDField.objects.create()
self.assertTrue(isinstance(obj.uuid1, uuid.UUID))
self.assertTrue(isinstance(obj.uuid3, uuid.UUID))
self.assertTrue(isinstance(obj.uuid4, uuid.UUID))
self.assertTrue(isinstance(obj.uuid5, uuid.UUID))
def test_auto_uuid4(self):
obj = AutoUUIDFieldModel.objects.create()
self.assertTrue(obj.uuid)
self.assertEquals(len(obj.uuid), 32)
#self.assertTrue(isinstance(obj.uuid, uuid.UUID))
self.assertEquals(obj.uuid.version, 4)
def test_raises_exception(self):
self.assertRaises(IntegrityError, ManualUUIDFieldModel.objects.create)
def test_manual(self):
obj = ManualUUIDFieldModel.objects.create(uuid=uuid.uuid4())
self.assertTrue(obj)
self.assertEquals(len(obj.uuid), 32)
#self.assertTrue(isinstance(obj.uuid, uuid.UUID))
self.assertEquals(obj.uuid.version, 4)
def test_namespace(self):
obj = NamespaceUUIDFieldModel.objects.create()
self.assertTrue(obj)
self.assertEquals(len(obj.uuid), 32)
#self.assertTrue(isinstance(obj.uuid, uuid.UUID))
self.assertEquals(obj.uuid.version, 5)
def test_broken_namespace(self):
self.assertRaises(ValueError, BrokenNamespaceUUIDFieldModel.objects.create)
def test_wrongvalue(self):
obj = PrimaryKeyUUIDFieldModel.objects.create()
with pytest.raises(ValueError):
obj.uuid = 1
def test_assign1(self):
obj = PrimaryKeyUUIDFieldModel.objects.create()
obj.uuid = uuid.UUID('5b27d1bd-e7c3-46f3-aaf2-11e4d32f60d4')
obj.save()
assert str(obj.uuid) == '5b27d1bde7c346f3aaf211e4d32f60d4'
#assert obj.uuid == '5b27d1bd-e7c3-46f3-aaf2-11e4d32f60d4'
assert obj.uuid == uuid.UUID('5b27d1bd-e7c3-46f3-aaf2-11e4d32f60d4')
def test_assign2(self):
obj = PrimaryKeyUUIDFieldModel.objects.create()
obj.uuid = '5b27d1bd-e7c3-46f3-aaf2-11e4d32f60d4'
obj.save()
assert str(obj.uuid) == '5b27d1bde7c346f3aaf211e4d32f60d4'
def test_primary_key(self):
obj = PrimaryKeyUUIDFieldModel.objects.create()
assert obj.pk
obj = PrimaryKeyUUIDFieldModel()
assert not obj.pk
# reset primary key if save() fails
BrokenPrimaryKeyUUIDFieldModel.objects.create(unique=1)
obj = BrokenPrimaryKeyUUIDFieldModel(unique=1)
with pytest.raises(IntegrityError):
obj.save()
assert not obj.pk
def test_serialize(self):
obj = PrimaryKeyUUIDFieldModel.objects.create()
obj.uuid = uuid.UUID("2e9280cfdc8e42bdbf0afa3043acaa7e")
obj.save()
serialized = serialize('json', PrimaryKeyUUIDFieldModel.objects.all())
assertJSON(serialized)
#def test_json(self):
# obj = PrimaryKeyUUIDFieldModel.objects.create()
# obj.save()
# serialized = json.dumps(obj)
# assertJSON(serialized)
#deserialized = json.loads(serialized, object_hook=registry.object_hook)
#
#print 111, deserialized
#
#assert PrimaryKeyUUIDField(**deserialized).uuid == obj.uuid
|
{"/django_uuid_pk/tests/tests.py": ["/django_uuid_pk/tests/models.py"]}
|
1,036
|
ddward/ansible
|
refs/heads/master
|
/user.py
|
from db import insert, exists, select_one, update
from werkzeug.security import check_password_hash, generate_password_hash
import logging
import traceback
def create_user(username,password):
try:
formattedUsername = format_username(username)
hashedPassword = generate_password_hash(password)
insert( 'user', ('username', 'password'), (formattedUsername, hashedPassword))
except Exception as e:
logging.error(traceback.format_exc())
def user_exists(username):
try:
formattedUsername = format_username(username)
return exists('user','username',formattedUsername)
except Exception as e:
logging.error(traceback.format_exc())
print("User existence check failed")
def get_user(username):
try:
formattedUsername = format_username(username)
return select_one('user',('username','password'), 'username',formattedUsername)
except Exception as e:
logging.error(traceback.format_exc())
print("Failed to get user")
def update_user(username,password,new_password):
try:
formattedUsername = format_username(username)
user = get_user(formattedUsername)
user_password = user[1]
if(user is not None):
if(check_password_hash(user_password,password)):
newHashedPassword = generate_password_hash(new_password)
update('user',{'password':newHashedPassword},'username',formattedUsername)
except:
logging.error(traceback.format_exc())
def gen_default_user():
while(True):
password = getpass(prompt='Create a password, at least 8 characters: ')
password2 = getpass(prompt='Confirm password: ')
if password == password2:
if len(password) < 8:
print('Password must be at least 8 characters.')
else:
break
else:
print('Passwords do not match')
try:
create_user('default',password)
except:
logging.error(traceback.format_exc())
def format_username(username):
return username.lower()
|
{"/user.py": ["/db.py"], "/app.py": ["/build_dir.py", "/sanitize_path.py", "/db.py", "/user.py"]}
|
1,037
|
ddward/ansible
|
refs/heads/master
|
/sanitize_path.py
|
import re
def sanitize(path):
# escape nasty double-dots
path = re.sub(r'\.\.', '', path)
# then remove any duplicate slashes
path = re.sub(r'(/)\1+', r'\1', path)
# then remove any leading slashes and dots
while(path and (path[0] == '/' or path[0] == '.')):
path = path[1:]
return path
|
{"/user.py": ["/db.py"], "/app.py": ["/build_dir.py", "/sanitize_path.py", "/db.py", "/user.py"]}
|
1,038
|
ddward/ansible
|
refs/heads/master
|
/penetrationTesting.py
|
from bs4 import BeautifulSoup
import getpass
import requests
import os
def pTest(attack_string, attack_url, password):
payload = {'password': password}
with requests.Session() as s:
p = s.post(attack_url + 'login', data=payload)
r = requests.Request('GET', attack_url)
prepared = s.prepare_request(r)
prepared.url += attack_string
response = s.send(prepared)
print('Sending request with url:', prepared.url)
#print('Request successful:', response.ok)
if response.ok:
soup = BeautifulSoup(response.text, 'html.parser')
safeResponse = s.get(attack_url)
soup2 = BeautifulSoup(safeResponse.text, 'html.parser')
if (response.text == safeResponse.text):
print("Attack Failed - Attack Led to Top Directory")
else:
print("Attack may have succeded")
print("Attack response tags:")
for link in soup.find_all('a'):
print(link.get('href'))
print('')
print('Safe Output')
print('')
for link in soup2.find_all('a'):
print(link.get('href'))
else:
print('Attack Failed - No Such Directory')
def pWrap(attack_string):
pTest(attack_string=attack_string, attack_url=ATTACK_URL, password=PASSWORD)
PASSWORD = os.getenv('PWRD')
ATTACK_URL ='http://127.0.0.1:5050/'
ATTACK_STRINGS = [
'../../../..',
'test/../.././.../',
'..',
'level1/../..',
'level1/../../',
'pwd'
]
if __name__ == '__main__':
if not PASSWORD:
PASSWORD = print('First set environment variable PWRD. (export PWRD=YOUR_PASSWORD)')
else:
for attack in ATTACK_STRINGS:
pWrap(attack)
|
{"/user.py": ["/db.py"], "/app.py": ["/build_dir.py", "/sanitize_path.py", "/db.py", "/user.py"]}
|
1,039
|
ddward/ansible
|
refs/heads/master
|
/build_dir.py
|
# build_dir.py
import os
def build_dir(curPath):
directoryDict = {}
with os.scandir(curPath) as directory:
for entry in directory:
#dont include shortcuts and hidden files
if not entry.name.startswith('.'):
#stat dict reference:
#https://docs.python.org/2/library/stat.html
fileStats = entry.stat()
directoryDict[entry.name] = {"is_dir" : entry.is_dir(),
"size" : fileStats.st_size}
return directoryDict
|
{"/user.py": ["/db.py"], "/app.py": ["/build_dir.py", "/sanitize_path.py", "/db.py", "/user.py"]}
|
1,040
|
ddward/ansible
|
refs/heads/master
|
/db.py
|
from getpass import getpass
import os
import sqlite3
from werkzeug.security import generate_password_hash
from flask import g
import traceback
import logging
path = os.getcwd()
DATABASE = os.path.join(path, 'ansible.db')
def init_db():
with app.app_context():
db = sqlite3.connect(DATABASE)
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db(app):
with app.app_context():
if 'db' not in g:
g.db = sqlite3.connect(
DATABASE,
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def insert(table,columnTuple,valueTuple):
try:
dbConnection = sqlite3.connect(DATABASE)
columnTupleString = ', '.join(columnTuple)
dbConnection.execute(
'INSERT INTO ' + table + ' (' + columnTupleString + ') VALUES (?, ?)',
(valueTuple)
)
dbConnection.commit()
except Exception as e:
logging.error(traceback.format_exc())
def select_one(table, return_columns, query_column, value):
try:
dbConnection = sqlite3.connect(DATABASE)
result = (dbConnection.execute(
'SELECT ' + ', '.join(return_columns) + ' FROM ' + table + ' WHERE ' + query_column + '= (?) Limit 1',
(value,)
).fetchone())
return result
except Exception as e:
logging.error(traceback.format_exc())
print("User existence check failed")
def exists(table,column,value):
try:
dbConnection = sqlite3.connect(DATABASE)
result = dbConnection.execute(
'SELECT CASE WHEN EXISTS( SELECT 1 FROM ' + table + ' WHERE ' + column + '= (?)) THEN 1 ELSE 0 END',
(value,)
).fetchone()
if result[0] == 1:
return True
else:
return False
except Exception as e:
logging.error(traceback.format_exc())
def update(table, update_dict, query_column, query_value):
try:
dbConnection = sqlite3.connect(DATABASE)
result = (dbConnection.execute(
'UPDATE ' + table + ' SET ' + build_set_statement(update_dict) + ' WHERE ' + query_column + '= (?)',
(query_value,)
).fetchone())
dbConnection.commit()
return result
except Exception as e:
logging.error(traceback.format_exc())
def build_set_statement(updated_field_dict):
setItems = []
for field in updated_field_dict:
setItems.append(field + ' = \'' + updated_field_dict[field] + '\'')
setFields = ', '.join(setItems)
return setFields
|
{"/user.py": ["/db.py"], "/app.py": ["/build_dir.py", "/sanitize_path.py", "/db.py", "/user.py"]}
|
1,041
|
ddward/ansible
|
refs/heads/master
|
/app.py
|
from cryptography.fernet import Fernet
import datetime
from flask import (flash, Flask, g, Markup, redirect, render_template, request,
send_from_directory, session, url_for)
import functools
import logging
import os
from secrets import token_urlsafe
import sqlite3
import sys
from werkzeug.utils import secure_filename
from werkzeug.security import check_password_hash, generate_password_hash
from build_dir import build_dir
import sanitize_path
from db import get_db
from user import create_user, user_exists, gen_default_user, get_user, update_user
import html
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(256) # TODO: change to environemnt variable
app.config["CRYPTO_KEY"] = Fernet.generate_key() # TODO put this somewhere where it wont update often possibly environmnet analize impact of changing.
path = os.getcwd()
database = os.path.join(path, 'ansible.db')
db = get_db(app)
def login_required(view):
@functools.wraps(view)
def wrapped_view(**kwargs):
if 'authenticated' not in session:
return redirect(url_for('login'))
return view(**kwargs)
return wrapped_view
@app.route('/', defaults={'loc': ""}, methods=('GET',))
@app.route('/<path:loc>', methods=('GET',))
@login_required
def ansible(loc):
logging.debug('made it here')
sanitize_path.sanitize(loc)
# TODO: if loc is empty return the home directory for the node
# possible security concern - could ask for a higher level node
# TODO: for future addition of link sending - store encrypted version
# of top level directory in session can possibly use a werkzeug module
# TODO: check if input is an encrypted link (use a /share/ or something to indicate)
# TODO: process encrypted link
# TODO: process a normal link
# TODO: get the the home directory
# TODO: authenticate the requested directory
logging.debug(loc)
currentDir = os.path.join('cloud-drive', loc) #update to be maliable for sharing
currentPath = os.path.join(path, currentDir)
logging.debug(os.path.splitext(currentPath)[1])
logging.debug(currentDir)
logging.debug(path)
logging.debug(currentPath)
logging.debug(loc)
fileExtension = os.path.splitext(currentPath)[1]
if fileExtension:
splitUrl = currentPath.rsplit('/', 1)
localDir = splitUrl[0]
filename = splitUrl[1]
absPath = os.path.join(path, 'cloud-drive', localDir)
return send_from_directory(directory=absPath, filename=filename)
directoryDict = build_dir(currentPath)
return render_template('index-alt.html', directory=directoryDict, curDir=loc)
@app.route("/login", methods=('GET', 'POST'))
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
error = None
user = get_user(username)
if user is not None:
user_password = user[1]
if not check_password_hash(user_password, password):
error = 'Incorrect password, please try again.'
else:
error = 'User not found'
if error is None:
session.clear()
session['authenticated'] = 'true'
session['user_id'] = token_urlsafe()
return redirect(url_for('ansible'))
flash(error)
return render_template('login.html')
@app.route("/signup", methods=('GET','POST'))
def signup():
if request.method == 'POST':
username = request.form['name']
password = request.form['password']
error = None
if not user_exists(username):
create_user(username,password)
else:
error = 'Username already exists.'
if error is None:
return redirect(url_for('login'))
flash(error)
return render_template('signup.html')
@app.route("/updatepassword", methods=('GET','POST'))
def update_password():
if request.method == 'POST':
username = request.form['username']
prev_password = request.form['password']
new_password = request.form['new_password']
verified_new_password = request.form['verify_new_password']
error = None
if(new_password == verified_new_password):
if user_exists(username):
update_user(username,prev_password,new_password)
else:
error = 'User doesnt exist.'
else:
error = 'Passwords do not match'
if error is None:
return redirect(url_for('login'))
flash(error)
return render_template('update-password.html')
@app.route("/logout", methods=('GET',))
def logout():
del session['authenticated']
return redirect(url_for('login'))
|
{"/user.py": ["/db.py"], "/app.py": ["/build_dir.py", "/sanitize_path.py", "/db.py", "/user.py"]}
|
1,070
|
DSGDSR/pykedex
|
refs/heads/master
|
/main.py
|
import sys, requests, json
from io import BytesIO
from PIL import Image
from pycolors import *
from funcs import *
print( pycol.BOLD + pycol.HEADER + "Welcome to the pokedex, ask for a pokemon: " + pycol.ENDC, end="" )
pokemon = input()
while True:
response = getPokemon(pokemon)
if response.status_code == 404:
print( "This pokemon name is not valid, try again: ", end="" )
pokemon = input()
continue
data = response.json()
#############################################################
########################### IMAGE ###########################
#############################################################
#imgburl = "https://assets.pokemon.com/assets/cms2/img/pokedex/full/" + str(data["id"]) + ".png"
imgburl = "https://img.pokemondb.net/artwork/" + str(data["name"]) + ".jpg"
imgr = requests.get(imgburl)
img = Image.open(BytesIO(imgr.content))
w, h = img.size
img.resize((w, h)).show()
#############################################################
######################### BASE INFO #########################
#############################################################
print( "\n" + pycol.BOLD + pycol.UNDERLINE + data["name"].capitalize() + pycol.ENDC + " (ID: " + str(data["id"]) + ")" + "\n" +
"Weight: " + str(data["weight"]/10) + "kg\n" +
"Height: " + str(data["height"]/10) + "m\n" +
"Base experience: " + str(data["base_experience"]) )
########################### TYPES ###########################
types, abilities = [], []
for t in data["types"]:
types.append(t["type"]["name"])
print( "Types: " + ', '.join(types) )
######################### ABILITIES #########################
for a in data["abilities"]:
ab = a["ability"]["name"]
if a["is_hidden"]:
ab = ab + " (hidden ab.)"
abilities.append(ab)
print( "Abilities: " )
for ab in abilities:
print( " - " + ab.capitalize() )
########################### STATS ###########################
print( "Stats: " )
for s in data["stats"]:
print(getStrBar((s["stat"]["name"] + ":").ljust(17), s["base_stat"]))
######################## EVOL CHAIN #########################
print("Evolutions:\n" + " " + getEvolChain(data["id"]))
print()
#############################################################
#############################################################
######################## END OF LOOP ########################
#############################################################
print( "Do you wanna ask for another pokemon? (Y/n) ", end="" )
answer = input()
if answer == 'n':
break
else:
print( "Enter the pokemon name: ", end="" )
pokemon = input()
|
{"/main.py": ["/funcs.py"]}
|
1,071
|
DSGDSR/pykedex
|
refs/heads/master
|
/funcs.py
|
import requests, math
def getPokemon(pokemon):
return requests.get("http://pokeapi.co/api/v2/pokemon/"+pokemon)
def getEvolChain(id):
url = "http://pokeapi.co/api/v2/pokemon-species/" + str(id)
resp = requests.get(url)
data = resp.json()
evol = requests.get(data["evolution_chain"]["url"]).json()["chain"]
evols = evol["species"]["name"].capitalize()
while evol["evolves_to"]:
evol = evol["evolves_to"][0]
evols = evols + " -> " + evol["species"]["name"].capitalize()
return evols
def getStrBar(stat, base):
# ▓▓▓▓▓▓▓▓░░░░░░░
num = math.ceil(base/20)
stat = stat.capitalize()
statStr = " - " + stat + "▓" * num + "░" * (10-num) + " " + str(base)
return statStr
if __name__ == "__main__":
print(getStrBar("speed", 90))
#print(getPokemon("pikachu"))
|
{"/main.py": ["/funcs.py"]}
|
1,127
|
Terfno/tdd_challenge
|
refs/heads/master
|
/test/calc_price.py
|
import sys
import io
import unittest
from calc_price import Calc_price
from di_sample import SomeKVSUsingDynamoDB
class TestCalculatePrice(unittest.TestCase):
def test_calculater_price(self):
calc_price = Calc_price()
assert 24 == calc_price.calculater_price([10, 12])
assert 62 == calc_price.calculater_price([40, 16])
assert 160 == calc_price.calculater_price([100, 45])
assert 171 == calc_price.calculater_price([50, 50, 55])
assert 1100 == calc_price.calculater_price([1000])
assert 66 == calc_price.calculater_price([20,40])
assert 198 == calc_price.calculater_price([30,60,90])
assert 40 == calc_price.calculater_price([11,12,13])
def test_input_to_data(self):
calc_price = Calc_price()
input = io.StringIO('10,12,3\n40,16\n100,45\n')
calc_price.input_to_data(input)
input = io.StringIO('1,25,3\n40,16\n\n100,45\n')
calc_price.input_to_data(input)
def test_calculater(self):
calc_price = Calc_price()
self.assertEqual(calc_price.calculater(io.StringIO('1,25,3\n40,16\n\n100,45\n')),[32,62,0,160])
|
{"/test/calc_price.py": ["/calc_price.py"], "/test/stack.py": ["/stack.py"]}
|
1,128
|
Terfno/tdd_challenge
|
refs/heads/master
|
/stack.py
|
class STACK():
def isEmpty(self):
return True
def top(self):
return 1
|
{"/test/calc_price.py": ["/calc_price.py"], "/test/stack.py": ["/stack.py"]}
|
1,129
|
Terfno/tdd_challenge
|
refs/heads/master
|
/calc_price.py
|
import sys
class Calc_price():
def calculater_price(self, values):
round=lambda x:(x*2+1)//2
sum = 0
for value in values:
sum += int(value)
ans = sum * 1.1
ans = int(round(ans))
return ans
def input_to_data(self, input):
result = []
lines = []
input = input.read()
input = input.split('\n')
for i in input:
i = i.split(',')
lines.append(i)
lines.pop(-1)
for i in lines:
if i == [''] :
result.append([])
continue
result.append(list(map(lambda x: int(x), i)))
return result
def calculater(self,input):
result = []
input = self.input_to_data(input)
for i in input:
result.append(self.calculater_price(i))
return result
if __name__ == '__main__':
calc_price = Calc_price()
print(calc_price.calculater(sys.stdin))
|
{"/test/calc_price.py": ["/calc_price.py"], "/test/stack.py": ["/stack.py"]}
|
1,130
|
Terfno/tdd_challenge
|
refs/heads/master
|
/test/stack.py
|
import unittest
from stack import STACK
class TestSTACK(unittest.TestCase):
@classmethod
def setUpClass(cls):
stack=STACK()
def test_isEmpty(self):
self.assertEqual(stack.isEmpty(), True)
def test_push_top(self):
self.assertEqual(stack.top(),1)
|
{"/test/calc_price.py": ["/calc_price.py"], "/test/stack.py": ["/stack.py"]}
|
1,133
|
paolapilar/juegos
|
refs/heads/master
|
/collectables.py
|
import pygame
import base
class Apple( base.Entity ) :
def __init__( self, i, j, cellSize, canvasWidth, canvasHeight ) :
super( Apple, self ).__init__( i, j, 1, 1, cellSize, canvasWidth, canvasHeight )
self._color = ( 255, 255, 0 )
self._alive = True
def draw( self, canvas ) :
_xleft = self._x - 0.5 * self._cellSize
_ytop = self._y - 0.5 * self._cellSize
pygame.draw.rect( canvas,
self._color,
(_xleft, _ytop, self._w, self._h) )
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,134
|
paolapilar/juegos
|
refs/heads/master
|
/snake.py
|
import pygame
import base
from collections import deque
class SnakePart( base.Entity ) :
def __init__( self, i, j, color, cellSize, canvasWidth, canvasHeight ) :
super( SnakePart, self ).__init__( i, j, 1, 1, cellSize, canvasWidth, canvasHeight )
self.color = color
self.lasti = i
self.lastj = j
def draw( self, canvas ) :
_xleft = self._x - 0.5 * self._cellSize
_ytop = self._y - 0.5 * self._cellSize
pygame.draw.rect( canvas,
self.color,
(_xleft, _ytop, self._w, self._h) )
class Snake( base.Entity ) :
def __init__( self, i, j, cellSize, canvasWidth, canvasHeight ) :
super( Snake, self ).__init__( i, j, 1, 1, cellSize, canvasWidth, canvasHeight )
self._bodyParts = [ SnakePart( i, j, ( 50, 50, 50 ), cellSize, canvasWidth, canvasHeight ) ]
self._speed = 800.
self._direction = 'left'
self._displacement = 0.0
self._frameTime = 0.001
self._nx = int( canvasWidth / cellSize )
self._ny = int( canvasHeight / cellSize )
self._alive = True
def alive( self ) :
return self._alive
def head( self ) :
return self._bodyParts[0]
def tail( self ) :
return self._bodyParts[-1]
def setDirection( self, direction ) :
if len( self._bodyParts ) > 1 :
# chequear si quieren ir a la direccion contraria
if ( self._direction == 'left' and direction == 'right' or
self._direction == 'right' and direction == 'left' or
self._direction == 'up' and direction == 'down' or
self._direction == 'down' and direction == 'up' ) :
# mantener la misma direccion
self._direction = self._direction
else :
# cambiar la direction
self._direction = direction
else :
self._direction = direction
def grow( self ) :
_i = self.tail().lasti
_j = self.tail().lastj
_newPart = SnakePart( _i, _j,
( 50, 50, 50 ),
self._cellSize,
self._canvasWidth,
self._canvasHeight )
self._bodyParts.append( _newPart )
def update( self ) :
self._displacement = self._displacement + self._speed * self._frameTime
if self._displacement > self._cellSize :
self.head().lasti = self.head().i
self.head().lastj = self.head().j
# mover una casilla en la direccion adecuada
if self._direction == 'up' :
self.head().j += 1
elif self._direction == 'down' :
self.head().j -= 1
elif self._direction == 'right' :
self.head().i += 1
elif self._direction == 'left' :
self.head().i -= 1
for k in range( 1, len( self._bodyParts ) ) :
self._bodyParts[k].lasti = self._bodyParts[k].i
self._bodyParts[k].lastj = self._bodyParts[k].j
self._bodyParts[k].i = self._bodyParts[k-1].lasti
self._bodyParts[k].j = self._bodyParts[k-1].lastj
# resetear el acumulador
self._displacement = 0.0
if self.head()._x > 800. and self._direction == 'right' :
self.head().i = 0
if self.head()._x < 0. and self._direction == 'left' :
self.head().i = self._nx
if self.head()._y > 600. and self._direction == 'down' :
self.head().j = self._ny
if self.head()._y < 0. and self._direction == 'up' :
self.head().j = 0
for k in range( len( self._bodyParts ) ) :
self._bodyParts[k].update()
for i in range( 1, len( self._bodyParts ) ) :
if self.head().hit( self._bodyParts[i] ):
self._alive = False
def draw( self, canvas ) :
for k in range( len( self._bodyParts ) ) :
self._bodyParts[k].draw( canvas )
## # la misma forma de iterar
## for bodyPart in self._bodyParts :
## bodyPart.draw( canvas )
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,135
|
paolapilar/juegos
|
refs/heads/master
|
/screen.py
|
import pygame
import world
class Text( object ) :
def __init__( self, x, y, message, size, color ) :
super( Text, self).__init__()
self._message = message
self._textFont = pygame.font.Font( None, size )
self._textSurface = self._textFont.render( message, True, color )
self._textRect = self._textSurface.get_rect()
self._textRect.center = ( x, y )
def draw( self, canvas ) :
canvas.blit( self._textSurface, self._textRect )
class Screen( object ) :
def __init__( self, canvas, backgroundColor ) :
super( Screen, self ).__init__()
self._canvas = canvas
self._backgroundColor = backgroundColor
self._texts = []
self._keys = None
def setKeys( self, keys ) :
self._keys = keys
def addText( self, text ) :
self._texts.append( text )
def draw( self ) :
self._canvas.fill( self._backgroundColor )
for i in range( len( self._texts ) ) :
self._texts[i].draw( self._canvas )
def update( self ) :
pass
class MenuScreen( Screen ) :
def __init__( self, canvas ) :
super( MenuScreen, self ).__init__( canvas, ( 255, 255, 0 ) )
self._textTitle = Text( 100, 100, 'SNAKE', 50, ( 0, 0, 0 ) )
self._textPlay = Text( 100, 400, 'PLAY', 40, ( 255, 255, 255 ) )
self.addText( self._textTitle )
self.addText( self._textPlay )
class GameOverScreen( Screen ) :
def __init__( self, canvas ) :
super( GameOverScreen, self ).__init__( canvas, ( 0, 0, 0 ) )
self._textGameOver = Text( 100, 100, 'GAME OVER :(', 50, ( 255, 0, 255 ) )
self._textContinue = Text( 100, 400, 'Continue???', 40, ( 255, 255, 255 ) )
self.addText( self._textGameOver )
self.addText( self._textContinue )
class GameScreen( Screen ) :
def __init__( self, canvas, canvasWidth, canvasHeight ) :
super( GameScreen, self ).__init__( canvas, ( 255, 255, 255 ) )
self._world = world.World( 40, canvasWidth, canvasHeight )
def draw( self ) :
super( GameScreen, self ).draw()
self._world.draw( self._canvas )
def update( self ) :
self._world.setKeys( self._keys )
self._world.update()
def lose( self ) :
return self._world.lose()
def win( self ) :
return self._world.win()
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,136
|
paolapilar/juegos
|
refs/heads/master
|
/world.py
|
import math
import random
import pygame
from base import Entity
from snake import Snake
from collectables import Apple
class Obstacle( Entity ) :
def __init__( self, i, j, di, dj, cellSize, canvasWidth, canvasHeight ) :
super( Obstacle, self ).__init__( i, j, di, dj, cellSize, canvasWidth, canvasHeight )
self._color = ( 255, 0, 0 )
def draw( self, canvas ) :
_xleft = self._x - 0.5 * self._cellSize
_ytop = self._y - 0.5 * self._cellSize
pygame.draw.rect( canvas,
self._color,
(_xleft, _ytop, self._w, self._h) )
class World( object ) :
def __init__( self, cellSize, canvasWidth, canvasHeight, level = 1 ) :
super( World, self ).__init__()
self._cellSize = cellSize
self._canvasWidth = canvasWidth
self._canvasHeight = canvasHeight
self._level = level
self._nx = int( self._canvasWidth / self._cellSize )
self._ny = int( self._canvasHeight / self._cellSize )
self._maxLives = 4
self._numLives = 4
self._snake = Snake( int( self._nx / 2. ),
int( self._ny / 2. ),
self._cellSize,
self._canvasWidth,
self._canvasHeight )
self._gameWin = False
self._gameOver = False
self._keys = None
self._points = 0
self._font = pygame.font.Font( None, 40 )
self._obstacles = []
self._occupied = []
self._apples = []
self._createObstacles()
self._createWalls()
for obstacle in self._obstacles :
self._occupied.append( ( obstacle.i, obstacle.j ) )
self._createApples( 1 )
if self._level == 1 :
self._snake._speed = 800.
elif self._level == 2 :
self._snake._speed = 2100.
elif self._level == 3 :
self._snake._speed = 2100.
def _createObstacles( self ) :
if self._level == 1 :
return
elif self._level == 2 :
while len( self._obstacles ) < 5 :
_i = random.randint(0, self._nx)
_j = random.randint(0, self._ny)
if _i == int( self._nx / 2 ) and _j == int( self._ny / 2 ) :
continue
self._obstacles.append( Obstacle( _i, _j, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
elif self._level == 3 :
while len( self._obstacles ) < 10 :
_i = random.randint(0, self._nx)
_j = random.randint(0, self._ny)
if _i == int( self._nx / 2 ) and _j == int( self._ny / 2 ) :
continue
self._obstacles.append( Obstacle( _i, _j, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
def _createWalls( self ) :
if self._level == 1 :
return
elif self._level == 2 :
for i in range( self._nx ) :
self._obstacles.append( Obstacle( i, 0, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
self._obstacles.append( Obstacle( i, self._ny - 1, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
for j in range( self._ny ) :
self._obstacles.append( Obstacle( 0, j, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
self._obstacles.append( Obstacle( self._nx - 1, j, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
elif self._level == 3 :
for i in range( self._nx ) :
if i == int( self._nx / 2 ) :
continue
self._obstacles.append( Obstacle( i, 0, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
self._obstacles.append( Obstacle( i, self._ny - 1, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
for j in range( self._ny ) :
if j == int( self._ny / 2 ) :
continue
self._obstacles.append( Obstacle( 0, j, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
self._obstacles.append( Obstacle( self._nx - 1, j, 1, 1, self._cellSize, self._canvasWidth, self._canvasHeight ) )
def _createApples( self, maxApples = 20 ) :
while True :
_i = random.randint( 2, self._nx - 2 )
_j = random.randint( 2, self._ny - 2 )
_canCreate = True
for _occupiedPosition in self._occupied :
_ioccupied = _occupiedPosition[0]
_joccupied = _occupiedPosition[1]
if _i == _ioccupied and _j == _joccupied :
_canCreate = False
break
if _canCreate :
self._apples.append( Apple( _i, _j, self._cellSize, self._canvasWidth, self._canvasHeight ) )
if len( self._apples ) >= maxApples :
break
def setKeys( self, keys ) :
self._keys = keys
def restart( self ) :
self._points = 0
self._snake = Snake( int( self._nx / 2. ),
int( self._ny / 2. ),
self._cellSize,
self._canvasWidth,
self._canvasHeight )
if self._level == 1 :
self._snake._speed = 800.
elif self._level == 2 :
self._snake._speed = 2100.
elif self._level == 3 :
self._snake._speed = 2100.
self._apples = []
self._obstacles = []
self._occupied = []
self._createObstacles()
self._createWalls()
for obstacle in self._obstacles :
self._occupied.append( ( obstacle.i, obstacle.j ) )
self._createApples( 1 )
def _drawGrid( self, canvas ) :
for i in range( self._nx ) :
xline = ( i + 1 ) * self._cellSize
pygame.draw.line( canvas,
( 0, 0, 0 ),
( xline, 0 ),
( xline, self._canvasHeight ),
1 )
for j in range( self._ny ) :
yline = ( j + 1 ) * self._cellSize
pygame.draw.line( canvas,
( 0, 0, 0 ),
( 0, yline ),
( self._canvasWidth, yline ),
1 )
def _drawScore( self, canvas ) :
_textSurface = self._font.render( 'Puntaje: %d - Vidas: %d' % ( self._points, self._numLives ),
True,
( 0, 0, 255 ) )
_textSurface.get_rect().center = ( 30, 30 )
canvas.blit( _textSurface, _textSurface.get_rect() )
def draw( self, canvas ) :
self._drawGrid( canvas )
self._snake.draw( canvas )
for obstacle in self._obstacles :
obstacle.draw( canvas )
for apple in self._apples :
apple.draw( canvas )
self._drawScore( canvas )
def update( self ) :
if self._keys :
if self._keys['up'] == True :
self._snake.setDirection( 'up' )
elif self._keys['down'] == True :
self._snake.setDirection( 'down' )
elif self._keys['right'] == True :
self._snake.setDirection( 'right' )
elif self._keys['left'] == True :
self._snake.setDirection( 'left' )
self._snake.update()
for obstacle in self._obstacles :
obstacle.update()
if self._snake.head().hit( obstacle ) :
self._snake._alive = False
if not self._snake.alive() :
self._numLives = self._numLives - 1
if self._numLives >= 1 :
self.restart()
else :
self._gameOver = True
return
for i in range( len( self._apples ) ) :
self._apples[i].update()
if self._snake.head().hit( self._apples[i] ) :
self._apples[i]._alive = False
self._snake.grow()
self._points = self._points + 1
self._createApples( 1 )
if self._level == 1 and self._points >= 5 :
self._level = 2
self._numLives = 4
self._points = 0
self.restart()
elif self._level == 2 and self._points >= 10 :
self._level = 3
self._numLives = 4
self._points = 0
self.restart()
elif self._level == 3 and self._points >= 15 :
self._gameWin = True
return
_newApples = []
for apple in self._apples :
if apple._alive :
_newApples.append( apple )
self._apples = _newApples
def lose( self ) :
return self._gameOver
def win( self ) :
return self._gameWin
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,137
|
paolapilar/juegos
|
refs/heads/master
|
/main.py
|
import pygame
import random
import time
from snake import Snake
from collectables import Apple
import screen
class Game :
def __init__( self ) :
pygame.init()
self._canvasWidth = 800
self._canvasHeight = 600
self._canvas = pygame.display.set_mode( ( self._canvasWidth, self._canvasHeight ) )
self._gameExit = False
self._keys = { 'up' : False,
'down' : False,
'right' : False,
'left' : False,
'enter' : False,
'escape' : False }
self._screen = screen.MenuScreen( self._canvas )
self._screenName = 'menu'
def _getEvents( self ) :
for event in pygame.event.get() :
if event.type == pygame.QUIT :
self._gameExit = True
elif event.type == pygame.KEYDOWN :
if event.key == pygame.K_UP :
self._keys['up'] = True
elif event.key == pygame.K_DOWN :
self._keys['down'] = True
elif event.key == pygame.K_RIGHT :
self._keys['right'] = True
elif event.key == pygame.K_LEFT :
self._keys['left'] = True
elif event.key == pygame.K_RETURN :
self._keys['enter'] = True
elif event.key == pygame.K_ESCAPE :
self._keys['escape'] = True
elif event.type == pygame.KEYUP :
if event.key == pygame.K_UP :
self._keys['up'] = False
elif event.key == pygame.K_DOWN :
self._keys['down'] = False
elif event.key == pygame.K_RIGHT :
self._keys['right'] = False
elif event.key == pygame.K_LEFT :
self._keys['left'] = False
elif event.key == pygame.K_RETURN :
self._keys['enter'] = False
elif event.key == pygame.K_ESCAPE :
self._keys['escape'] = False
def _updateScreen( self ) :
self._screen.setKeys( self._keys )
self._screen.update()
self._screen.draw()
if self._screenName == 'menu' and self._keys['enter'] == True :
self._screen = screen.GameScreen( self._canvas, self._canvasWidth, self._canvasHeight )
self._screenName = 'game'
elif self._screenName == 'game' and self._screen.lose() :
self._screen = screen.GameOverScreen( self._canvas )
self._screenName = 'gameover'
elif self._screenName == 'game' and self._screen.win() :
self._screen = screen.MenuScreen( self._canvas )
self._screenName = 'menu'
elif self._screenName == 'gameover' and self._keys['enter'] == True :
self._screen = screen.GameScreen( self._canvas, self._canvasWidth, self._canvasHeight )
self._screenName = 'game'
elif self._screenName == 'gameover' and self._keys['escape'] == True :
self._screen = screen.MenuScreen( self._canvas )
self._screenName = 'menu'
def run( self ) :
while not self._gameExit :
self._getEvents()
self._updateScreen()
# actualizar el canvas
pygame.display.update()
# esperar un ratito
time.sleep( 0.001 )
if __name__ == '__main__' :
_game = Game()
_game.run()
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,138
|
paolapilar/juegos
|
refs/heads/master
|
/utils.py
|
import math
def grid2screen( i, j, cellSize, canvasWidth, canvasHeight ) :
x = ( i + 0.5 ) * cellSize
y = canvasHeight - ( j + 0.5 ) * cellSize
return x, y
def screen2grid( x, y, cellSize, canvasWidth, canvasHeight ) :
i = math.floor( x / cellSize - 0.5 )
j = math.floor( ( canvasHeight - y ) / cellSize - 0.5 )
return i, j
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,139
|
paolapilar/juegos
|
refs/heads/master
|
/base.py
|
import math
import utils
class Entity( object ) :
def __init__( self, i, j, di, dj, cellSize, canvasWidth, canvasHeight ) :
super( Entity, self ).__init__()
self.i = i
self.j = j
self._cellSize = cellSize
self._canvasWidth = canvasWidth
self._canvasHeight = canvasHeight
self._di = di
self._dj = dj
self._x, self._y = utils.grid2screen( i, j, cellSize, canvasWidth, canvasHeight )
self._w = di * cellSize
self._h = dj * cellSize
self._xc = self._x + self._cellSize * ( math.floor( ( self._di - 1 ) / 2. ) + 0.5 if self._di % 2 == 0 else 0.0 )
self._yc = self._y + self._cellSize * ( math.floor( ( self._dj - 1 ) / 2. ) + 0.5 if self._dj % 2 == 0 else 0.0 )
def x( self ) :
return self._x
def y( self ) :
return self._y
def xc( self ) :
return self._xc
def yc( self ) :
return self._yc
def w( self ) :
return self._w
def h( self ) :
return self._h
def update( self ) :
self._x, self._y = utils.grid2screen( self.i, self.j,
self._cellSize,
self._canvasWidth,
self._canvasHeight )
self._xc = self._x + self._cellSize * ( math.floor( ( self._di - 1 ) / 2. ) + 0.5 if self._di % 2 == 0 else 0.0 )
self._yc = self._y + self._cellSize * ( math.floor( ( self._dj - 1 ) / 2. ) + 0.5 if self._dj % 2 == 0 else 0.0 )
def hit( self, other ) :
_dx = abs( self._xc - other.xc() )
_dy = abs( self._yc - other.yc() )
if ( _dx < ( self._w / 2. ) + ( other.w() / 2. ) and
_dy < ( self._h / 2. ) + ( other.h() / 2. ) ) :
return True
else :
return False
|
{"/collectables.py": ["/base.py"], "/snake.py": ["/base.py"], "/screen.py": ["/world.py"], "/world.py": ["/base.py", "/snake.py", "/collectables.py"], "/main.py": ["/snake.py", "/collectables.py", "/screen.py"], "/base.py": ["/utils.py"]}
|
1,167
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/conteudo/views.py
|
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render, redirect, get_object_or_404
from conteudo.models import Video, Categoria
def exibir_catalogo(request):
categorias = Categoria.objects.all()
return render(request, 'conteudo/catalogo_videos.html', {'categorias': categorias})
def cadastro_video(request):
return render(request, 'conteudo/cadastro_video.html')
def editar_video(request):
return render(request, 'conteudo/editar_video.html')
def lista_categoria(request, id=None):
categorias = Categoria.objects.all()
if id != None:
videos_lista = Video.objects.all().filter(categoria_id=id)
else:
videos_lista = Video.objects.all()
paginator = Paginator(videos_lista, 3)
page = request.GET.get('page',1)
try:
videos = paginator.page(page)
except PageNotAnInteger:
videos = paginator.page(1)
except EmptyPage:
videos = paginator.page(paginator.num_pages)
return render(request, 'conteudo/lista_categoria.html', {'categorias': categorias, 'videos' : videos})
def exibir_video(request, id):
video = get_object_or_404(Video, id= id)
categorias = Categoria.objects.all()
return render(request, 'conteudo/player_video.html', {'video':video, 'categorias':categorias})
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,168
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/conteudo/urls.py
|
from django.urls import path
from conteudo import views
app_name = 'conteudo'
urlpatterns = [
path('', views.exibir_catalogo, name='catalogo'),
path('cadastro_video/', views.cadastro_video, name='cadastro_video'),
path('editar_video/<int:id>/', views.editar_video, name='editar_video'),
path('<int:id>/', views.exibir_video, name='exibir_video'),
path('categoria/', views.lista_categoria, name='listar_todas_categorias'),
path('categoria/<int:id>/', views.lista_categoria, name='lista_categoria'),
]
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,169
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/conteudo/forms.py
|
from django import forms
from conteudo.models import Video, Categoria
class VideoForm(forms.ModelForm):
error_messages = {
'campo invalido' : "Campo inválido"
}
class Meta:
model = Video
fields = ('video_id','categoria', 'nome', 'url', 'capa', 'visualizacao', 'nota', 'sinopse')
video_id = forms.CharField(widget=forms.HiddenInput(), required=False)
categoria = forms.ModelChoiceField(
error_messages={'required': 'Campo obrigatório', },
queryset=Categoria.objects.all().order_by(id),
empty_label='--- Selecionar a Categoria ---',
widget=forms.Select(attrs={'class': 'form-control form-control-sm'}),
required=True
)
nome = forms.CharField(
error_messages = {'required', 'Campo obrigatório',},
widget=forms.TextInput(attrs={'class': 'form-control form-control-sm', 'maxlength': '120'}),
required=True
)
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,170
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/conteudo/models.py
|
from django.db import models
class Categoria(models.Model):
nome = models.CharField(max_length=255, db_index=True)
slug = models.SlugField(max_length=200)
class Meta:
ordering = ('nome',)
verbose_name = 'categoria'
verbose_name_plural = 'categorias'
def __str__(self):
return self.nome
def videosCategoria(self):
return Video.objects.all().filter(categoria_id=self.id).order_by('-id')[:4]
class Video(models.Model):
categoria = models.ForeignKey(Categoria, on_delete=models.DO_NOTHING)
nome = models.CharField(max_length=255)
url = models.FileField(upload_to='conteudo/videos/')
capa = models.FileField(upload_to='conteudo/images/')
visualizacao = models.DecimalField(max_digits=10, decimal_places=1, default=0)
nota = models.FloatField(max_length=20)
sinopse = models.CharField(max_length=500)
class Meta:
ordering = ('nome',)
verbose_name = 'video'
verbose_name_plural = 'videos'
def __str__(self):
return self.nome
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,171
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/projeto/views.py
|
from django.shortcuts import render
def pagina_inicial(request):
return render(request, 'index.html')
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,172
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/login/urls.py
|
from django.urls import path
from login import views
app_name = 'login'
urlpatterns = [
path('', views.pagina_login, name='pagina_login'),
]
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,173
|
MatheusLealAquino/meuCanal
|
refs/heads/master
|
/login/views.py
|
from django.shortcuts import render
def pagina_login(request):
return render(request, 'login/pagina_login.html')
|
{"/conteudo/views.py": ["/conteudo/models.py"], "/conteudo/forms.py": ["/conteudo/models.py"]}
|
1,193
|
Cryptek768/MacGyver-Game
|
refs/heads/master
|
/Maze.py
|
import pygame
import random
from Intel import *
#Classe du Niveau(placement des murs)
class Level:
#Preparation de la classe
def __init__(self, map_pool):
self.map_pool = map_pool
self.map_structure = []
self.position_x = 0
self.position_y = 0
self.sprite_x = int(0 /30)
self.sprite_y = int(0 /30)
self.image_Macgyver = pygame.image.load(MacGyver).convert_alpha()
self.image_Guardian = pygame.image.load(Guardian).convert_alpha()
self.background = pygame.image.load(Background).convert()
#Prépartion de la liste pour le fichier map
def level(self):
with open (self.map_pool, "r") as map_pool:
level_structure = []
for line in map_pool:
line_level = []
for char in line:
if char != '/n':
line_level.append(char)
level_structure.append(line_level)
self.map_structure = level_structure
#Placement des murs
def display_wall (self, screen):
wall = pygame.image.load(Wall).convert_alpha()
screen.blit(self.background, (0, 0))
num_line = 0
for ligne_horiz in self.map_structure:
num_col = 0
for ligne_verti in ligne_horiz:
position_x = num_col * Sprite_Size
position_y = num_line * Sprite_Size
if ligne_verti == str(1):
screen.blit(wall, (position_x, position_y))
num_col +=1
num_line +=1
|
{"/Maze.py": ["/Intel.py"], "/Items.py": ["/Intel.py"], "/Characters.py": ["/Intel.py"], "/Main.py": ["/Maze.py", "/Intel.py", "/Characters.py", "/Items.py"]}
|
1,194
|
Cryptek768/MacGyver-Game
|
refs/heads/master
|
/Items.py
|
import pygame
import random
from Intel import *
#Classe des placements d'objets
class Items:
#Preparation de la classe
def __init__(self, map_pool):
self.item_needle = pygame.image.load(Object_N).convert_alpha()
self.item_ether = pygame.image.load(Object_E).convert_alpha()
self.item_tube = pygame.image.load(Object_T).convert_alpha()
#Méthode de spawn des objets
def items_spawn(self, screen):
while items:
rand_x = random.randint(0, 14)
rand_y = random.randint(0, 14)
if self.map_structure [rand_x][rand_y] == 0:
screen.blit(self.image_(Object_N), (rand_x, rand_y))
|
{"/Maze.py": ["/Intel.py"], "/Items.py": ["/Intel.py"], "/Characters.py": ["/Intel.py"], "/Main.py": ["/Maze.py", "/Intel.py", "/Characters.py", "/Items.py"]}
|
1,195
|
Cryptek768/MacGyver-Game
|
refs/heads/master
|
/Intel.py
|
# Information des variables Global et des images
Sprite_Size_Level = 15
Sprite_Size = 30
Size_Level = Sprite_Size_Level * Sprite_Size
Background = 'images/Background.jpg'
Wall = 'images/Wall.png'
MacGyver = 'images/MacGyver.png'
Guardian = 'images/Guardian.png'
Object_N = 'images/Needle.png'
Object_E = 'images/Ether.png'
Object_T = 'images/Tube.png'
items = ["Object_N","Object_E","Object_T"]
|
{"/Maze.py": ["/Intel.py"], "/Items.py": ["/Intel.py"], "/Characters.py": ["/Intel.py"], "/Main.py": ["/Maze.py", "/Intel.py", "/Characters.py", "/Items.py"]}
|
1,196
|
Cryptek768/MacGyver-Game
|
refs/heads/master
|
/Characters.py
|
import pygame
from Intel import *
class Characters:
def __init__(self, map_pool):
self.map_pool = map_pool
self.position_x = 0
self.position_y = 0
self.sprite_x = int(0 /30)
self.sprite_y = int(0 /30)
self.image_Macgyver = pygame.image.load(MacGyver).convert_alpha()
self.image_Guardian = pygame.image.load(Guardian).convert_alpha()
#Placement du Gardien
def blit_mg(self, screen):
screen.blit(self.image_Macgyver, (self.position_x, self.position_y))
#Placement de Macgyver
def blit_g(self, screen):
num_line = 14
for line in self.map_structure:
num_col = 14
for ligne_verti in line:
position_x = num_col * Sprite_Size
position_y = num_line * Sprite_Size
if ligne_verti == str(3):
screen.blit(self.image_Guardian, (position_x, position_y))
else:
if ligne_verti == str(3):
self.available_tiles.append((num_col, num_line))
#Méthode de déplacement de Macgyver(player)
def move_mg(self, direction, screen):
if direction == 'down':
if self.sprite_y < (Sprite_Size_Level - 1):
if self.map_structure[self.sprite_y+1][self.sprite_x] != '1':
self.position_y += 30
self.sprite_y += 1
elif direction == 'up':
if self.sprite_y > 0:
if self.map_structure[self.sprite_y-1][self.sprite_x] != '1':
self.position_y -= 30
self.sprite_y -= 1
elif direction == 'left':
if self.sprite_x > 0:
if self.map_structure[self.sprite_y][self.sprite_x-1] != '1':
self.position_x -= 30
self.sprite_x -= 1
elif direction == 'right':
if self.sprite_x < (Sprite_Size_Level - 1):
if self.map_structure[self.sprite_y][self.sprite_x+1] != '1':
self.position_x += 30
self.sprite_x += 1
|
{"/Maze.py": ["/Intel.py"], "/Items.py": ["/Intel.py"], "/Characters.py": ["/Intel.py"], "/Main.py": ["/Maze.py", "/Intel.py", "/Characters.py", "/Items.py"]}
|
1,197
|
Cryptek768/MacGyver-Game
|
refs/heads/master
|
/Main.py
|
import pygame
from Maze import *
from Intel import *
from Characters import *
from Items import *
from pygame import K_DOWN, K_UP, K_LEFT, K_RIGHT
#Classe Main du jeux avec gestion des movements et l'affichage
class Master:
def master():
pygame.init()
screen = pygame.display.set_mode((Size_Level, Size_Level))
maze = Level("Map.txt")
maze.level()
#Boucle de rafraichisement
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_DOWN:
Characters.move_mg(maze, 'down', screen)
if event.key == K_UP:
Characters.move_mg(maze, 'up', screen)
if event.key == K_LEFT:
Characters.move_mg(maze, 'left', screen)
if event.key == K_RIGHT:
Characters.move_mg(maze, 'right', screen)
maze.display_wall(screen)
Characters.blit_mg(maze, screen)
Characters.move_mg(maze, 'direction', screen)
Characters.blit_g(maze, screen)
Items. items_spawn(maze, screen)
pygame.display.flip()
if __name__ =="__main__":
master()
|
{"/Maze.py": ["/Intel.py"], "/Items.py": ["/Intel.py"], "/Characters.py": ["/Intel.py"], "/Main.py": ["/Maze.py", "/Intel.py", "/Characters.py", "/Items.py"]}
|
1,198
|
alan-valenzuela93/port-scanner
|
refs/heads/main
|
/port-scanner.py
|
import socket
import argparse
from grabber import banner_grabbing
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--target', help='Enter your target address', required=True)
parser = parser.parse_args()
ports = [21, 22, 25, 53, 66, 80, 88, 110, 139, 443, 445, 8080, 9050] # These are some of the most interesting ports to scan
def get_ip(target):
return str(socket.gethostbyname(target))
def scan(host, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, port))
s.settimeout(0.2) # Increase scanning speed
except:
return False
else:
return True
def main():
for p in ports:
if scan(parser.target, p):
print(banner_grabbing(parser.target, p))
if __name__ == '__main__':
print('TCP/IP scan started at IP ' + get_ip(parser.target))
main()
|
{"/port-scanner.py": ["/grabber.py"]}
|
1,199
|
alan-valenzuela93/port-scanner
|
refs/heads/main
|
/grabber.py
|
import socket
def banner_grabbing(addr, port):
print("Getting service information for open TCP/IP port: ", port + "...")
socket.setdefaulttimeout(10)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((addr, port))
data = ''
headers = \
"GET / HTTP/1.1\r\n" \
f"Host: {addr}\r\n" \
"User-Agent: python-custom-script/2.22.0\r\n" \
"Accept-Encoding: gzip, deflate\r\nAccept: */*\r\n" \
"Connection: keep-alive\r\n\r\n"
print("\n\n" + headers)
cycle = True
try: # If banner can't be reach, print a message
while cycle: # Keep looping until the banner is found
data = str(s.recv(4096))
if data != '':
s.send(headers.encode()) # Send request
cycle = False
s.close()
except:
print("Connection refused... banner unreachable")
return data + '\n'
|
{"/port-scanner.py": ["/grabber.py"]}
|
1,225
|
marioxe301/ParserDR
|
refs/heads/master
|
/Lexer.py
|
from pyparsing import (Regex, White, Literal ,
ZeroOrMore, OneOrMore, Group , Combine ,
Word , alphanums, Suppress)
import sys
class Tokens(object):
def __init__(self,tag,token):
self.tag = tag
self.token = token
#esta clase permitira guardar en la lista
class Lexer(object):
def __init__(self,path):
#TERMINALES
WHITESPACE = White(ws=" \t\r")
LETTER = Regex('[a-zA-Z]')
DIGIT = Regex('[0-9]')
DATE_TYPE = Literal('date')
STRING_TYPE = Literal('String')
REAL_TYPE = Literal('real')
VOID_TYPE = Literal('void')
BOOLEAN_TYPE = Literal('boolean')
ANYTYPE_TYPE = Literal('anytype')
INT_TYPE = Literal('int')
STATIC_TKN = Literal('static')
RETURN = Literal('EXIT')
IF = Literal('if')
WHILE = Literal('while')
#TERMINALES LITERALES
DATE_LITERAL = DIGIT + DIGIT + Literal('/') + DIGIT + DIGIT + Literal('/') + DIGIT + DIGIT + DIGIT + DIGIT
STRING_LITERAL = Combine(Literal('"')+ ZeroOrMore(LETTER | DIGIT | Literal(' ') | Literal('%')|Literal('@')| Literal(',')| Literal('-')|Literal('=')|Literal('(')|Literal(')')|Literal('_')) +Literal('"'))
REAL_LITERAL = Combine(OneOrMore(DIGIT) + Literal('.') + OneOrMore(DIGIT))
INT_LITERAL = Combine(OneOrMore(DIGIT))
TRUE_LITERAL = Literal('true')
FALSE_LITERAL = Literal('false')
BOOLEAN_LITERAL = TRUE_LITERAL | FALSE_LITERAL
INCR = Literal('++')
DDPERIOD = Literal('::')
PAR_OP = Literal('(')
PAR_CL = Literal(')')
SEMICOLON = Literal(';')
COMA = Literal(',')
BRACK_OP = Literal('{')
BRACK_CL = Literal('}')
PERIOD = Literal('.')
ASIG = Literal(':=')
REL_OP = Literal('>') | Literal('<') | Literal('==') | Literal('<=') | Literal('>=')
LOG_OP = Literal('||') | Literal('&&')
MULT_OP = Literal('/') | Literal('*')
ADD_OP = Literal('+') | Literal('-')
ID = Combine((LETTER | Literal('_')) + ZeroOrMore( LETTER | DIGIT ) )
TEXT = ZeroOrMore(Word(alphanums)| WHITESPACE )
COMMENT = Combine((Literal('//')+ TEXT + Literal('\n') ) | (Literal('//')+ TEXT) )
program = ZeroOrMore( Suppress(COMMENT) | Group(DATE_TYPE)("DATE-TY") | Group(STRING_TYPE)("STRING-TY") | Group(REAL_TYPE)("REAL-TY") | Group( VOID_TYPE)("VOID-TY") | Group(BOOLEAN_TYPE)("BOOLEAN-TY") | Group(ANYTYPE_TYPE)("ANY-TY")
| Group(INT_TYPE)("INT-TY") | Group(STATIC_TKN)("STATIC-TY")| Group(RETURN)("RETURN-TOK") | Group(IF)("IF-TOK") | Group(WHILE)("WHILE-TOK") | Group(DATE_LITERAL)("DATE-TOK") | Group(STRING_LITERAL)("STRING-TOK")
| Group(COMA)("COMA-TOK") | Group(REAL_LITERAL)("REAL-TOK") | Group(INT_LITERAL)("INT-TOK") | Group(BOOLEAN_LITERAL)("BOOLEAN-TOK") | Group(INCR)("INCR-TOK") |Group( DDPERIOD)("DDPERIOD-TOK") | Group(PAR_OP)("PAR-OP-TOK") | Group(PAR_CL)("PAR-CL-TOK") | Group(SEMICOLON)("SEMICOLON-TOK")
| Group(BRACK_OP)("BRACK-OP-TOK") | Group(BRACK_CL)("BRACK-CL-TOK") | Group(PERIOD)("PERIOD-TOK") | Group(ASIG)("ASIG-TOK") | Group( REL_OP)("REL-OP-TOK") | Group(LOG_OP)("LOG-OP-TOK") | Group(MULT_OP)("MULT-OP-TOK") | Group( ADD_OP)("ADD-OP-TOK") | Group(ID)("ID-TOK")
)
#manda las palabras reservadas que acepta la gramatica
self.lexer = program
self.tokenList = []
self.path = path
#Divide en Tokens el archivo que se le manda
def tokenFile(self):
try:
return self.lexer.parseFile(self.path)
except Exception:
print("Invalid token found")
sys.exit()
def tokenize(self):
tokenItems = self.tokenFile()
for items in tokenItems:
tok = Tokens(items.getName(),items[0])
self.tokenList.append(tok)
def printAllTokens(self):
for tok in self.tokenList:
print("TAG:",tok.tag," ","TOKEN:",tok.token,"\n")
#lex = Lexer('Program.g4')
#lex.tokenize()
#lex.printAllTokens()
|
{"/ParserSimpleExample.py": ["/Lexer.py"], "/Parser.py": ["/Lexer.py"]}
|
1,226
|
marioxe301/ParserDR
|
refs/heads/master
|
/ParserSimpleExample.py
|
from Lexer import Lexer
from treelib import Node, Tree
#verifica unicamente la declaracion de un int int <ID> := <NUMERO>
class ParserExample(object):
def __init__(self,path):
lex = Lexer(path)
lex.tokenize()
self.TOKENS = lex.tokenList
self.INDEX = 0
tree = Tree()
self.TREE = tree
def nextToken(self):
if self.INDEX < len(self.TOKENS):
x = self.INDEX
self.INDEX+=1
return [True ,self.TOKENS[x]]
else:
#self.INDEX = 0
return [False]
def parseCheck(self):
if self.variable():
print("Gramatica Correcta")
else:
print("Gramatica Incorrecta")
def variable(self):
if self.TYPE():
if self.ID():
if self.ASSIG():
if self.NUMBER():
return True
def TYPE(self):
x = self.nextToken()
if x[0]:
if x[1].tag == "INT-TY":
return True
else:
return False
else:
return False
def ID(self):
x = self.nextToken()
if x[0]:
if x[1].tag == "ID-TOK":
return True
else:
return False
else:
return False
def ASSIG(self):
x = self.nextToken()
if x[0]:
if x[1].tag == "ASIG-TOK":
return True
else:
return False
else:
return False
def NUMBER(self):
x = self.nextToken()
if x[0]:
if x[1].tag == "INT-TOK":
return True
else:
return False
else:
return False
def ImprimirArbol(self):
self.TREE.show()
Par = ParserExample('Program.g4')
Par.parseCheck()
#Par.ImprimirArbol()
|
{"/ParserSimpleExample.py": ["/Lexer.py"], "/Parser.py": ["/Lexer.py"]}
|
1,227
|
marioxe301/ParserDR
|
refs/heads/master
|
/Parser.py
|
from Lexer import Lexer
from treelib import Node, Tree
import re
from termcolor import colored,cprint
class Parser(object):
def __init__(self,path):
lex = Lexer(path)
lex.tokenize()
self.TOKENS = lex.tokenList
self.TYPES= re.compile(".*-TY")
def nextToken(self):
if len(self.TOKENS) != 0:
x = self.TOKENS[0]
self.TOKENS.pop(0)
return [True,x]
else:
return [False]
def seekNextToken(self):
if len(self.TOKENS) > 2:
return [True,self.TOKENS[1]]
else:
return [False]
def seekActualToken(self):
if len(self.TOKENS)!= 0:
return [True,self.TOKENS[0]]
else:
return [False]
def Parse(self):
if self.Program():
cprint("Grammar Correct\n","green",attrs=['bold'])
else:
cprint("Grammar Incorrect\n","red",attrs=['bold'])
def Program(self):
print("Program\n")
if self.Opt_funct_decl():
return True
else:
return False
def Opt_funct_decl(self):
print("Opt_funct_decl\n")
if self.Funct_head():
if self.Body():
return True
else:
return False
else:
return False
def Funct_head(self):
print("Funct_head\n")
if self.Funct_name():
token = self.nextToken()
if token[0] and token[1].tag == 'PAR-OP-TOK':
print("PAREN_OP_TOKEN")
print("Token: ",token[1].token,"\n")
if self.Param_list_opt():
return True
else:
cprint("Expected a ( TOKEN\n","red",attrs=['bold'])
return False
else:
return False
def Funct_name(self):
print("Funct_name\n")
if self.Funct_type():
token = self.nextToken()
if token[0] and token[1].tag == 'ID-TOK':
print("ID_TOKEN")
print("Token: ",token[1].token,"\n")
return True
else:
cprint("Expected a ID TOKEN\n","red",attrs=['bold'])
return False
else:
return False
def Funct_type(self):
print("Funct_type\n")
token = self.nextToken()
if token[0] and token[1].tag == 'STATIC-TY':
print("STATIC_TOKEN")
print("Token: ",token[1].token,"\n")
if self.Decl_type():
return True
else:
cprint("Expected a STATIC TOKEN\n","red",attrs=['bold'])
return False
else:
return False
def Decl_type(self):
print("Decl_type\n")
token = self.nextToken()
if token[0] and self.TYPES.match(token[1].tag) is not None:
print("TYPE_TOKEN")
print("Token: ",token[1].token,"\n")
return True
else:
cprint("Expected a TYPE TOKEN\n","red",attrs=['bold'])
return False
def Param_list_opt(self):
print("Param_list_opt\n")
Token = self.seekActualToken()
if Token[0] and Token[1].tag == 'PAR-CL-TOK':
print("PAREN_CL_TOKEN")
print("Token: ",Token[1].token,"\n")
self.nextToken() # para quitar el parentesis
return True
elif Token[0] and self.TYPES.match(Token[1].tag) is not None:
while True:
if self.Decl_param():
Token = self.seekActualToken()
if Token[0] and Token[1].tag == 'COMA-TOK':
print("COMA_TOKEN")
print("Token: ",Token[1].token,"\n")
self.nextToken() #solo para descartar la coma
continue
elif Token[0] and Token[1].tag == 'PAR-CL-TOK':
print("PAREN_CL_TOKEN")
print("Token: ",Token[1].token,"\n")
self.nextToken() # para descartar el parentesis
return True
else:
cprint("Expected a COMA or ) TOKEN\n","red",attrs=['bold'])
return False
else:
cprint("Expected a ) TOKEN\n","red",attrs=['bold'])
return False
def Decl_param(self):
print("Decl_param\n")
if self.Decl_type():
token = self.nextToken()
if token[0] and token[1].tag == 'ID-TOK':
print("ID_TOKEN")
print("Token: ",token[1].token,"\n")
return True
else:
cprint("Expected a ID TOKEN\n","red",attrs=['bold'])
return False
else:
return False
def Body(self):
print("Body\n")
token = self.nextToken()
if token[0] and token[1].tag == 'BRACK-OP-TOK':
print("BRACK_OP_TOKEN")
print("Token: ",token[1].token,"\n")
if self.Stmt_list():
return True
else:
return False
else:
cprint("Expected a { TOKEN\n","red",attrs=['bold'])
return False
def Stmt_list(self):
print("Stmt_list\n")
if self.Stmts():
return True
else:
return False
def Stmts(self):
print("Stmts\n")
BrackToken = self.seekActualToken()
if BrackToken[0] and BrackToken[1].tag == 'BRACK-CL-TOK':
print("BRACK_CL_TOKEN")
print("Token: ",BrackToken[1].token,"\n")
self.nextToken() # para quitar el braket
return True
else:
while True:
if self.Stmt():
BrackToken = self.seekActualToken()
if BrackToken[0] and BrackToken[1].tag == 'BRACK-CL-TOK':
print("BRACK_CL_TOKEN")
print("Token: ",BrackToken[1].token,"\n")
self.nextToken() # descarta el bracket
return True
else:
continue
else:
cprint("Unexpected TOKEN found\n","red",attrs=['bold'])
return False
def Stmt(self):
print("Stmt\n")
Token = self.seekActualToken()
if Token[0] and Token[1].tag == 'IF-TOK':
if self.If_stmt():
return True
else:
return False
elif Token[0] and Token[1].tag == 'WHILE-TOK' :
if self.While_stmt():
return True
else:
return False
elif Token[0] and Token[1].tag == 'RETURN-TOK':
if self.Return_stmt():
return True
else:
return False
elif Token[0] and self.TYPES.match(Token[1].tag) is not None:
if self.Assign_stmt():
return True
else:
return False
else:
return False
def If_stmt(self):
print("If_stmt\n")
IfToken = self.nextToken()
ParToken = self.nextToken()
if IfToken[0] and IfToken[1].tag == 'IF-TOK' and ParToken[0] and ParToken[1].tag == 'PAR-OP-TOK':
print("IF_TOKEN")
print("Token: ",IfToken[1].token,"\n")
print("PAR_OP_TOKEN")
print("Token: ",ParToken[1].token,"\n")
if self.Bool_expr():
ParToken = self.nextToken()
if ParToken[0] and ParToken[1].tag == 'PAR-CL-TOK':
print("PAR_CL_TOKEN")
print("Token: ",ParToken[1].token,"\n")
if self.Body():
return True
else:
return False
else:
cprint("Expected a ) TOKEN\n","red",attrs=['bold'])
return False
else:
return False
else:
cprint("Expected a IF or ( or TOKEN\n","red",attrs=['bold'])
return False
def Bool_expr(self):
print("Bool_expr\n")
Token = self.seekActualToken()
if Token[0] and Token[1].tag == 'BOOLEAN-TOK':
print("BOOLEAN_TOKEN")
print("Token: ",Token[1].token,"\n")
self.nextToken() #Descartar el token
return True
else:
if self.Constant():
Token = self.nextToken()
if Token[0] and (Token[1].tag == 'REL-OP-TOK' or Token[1].tag == 'LOG-OP-TOK'):
print("LOGICAL_TOKEN")
print("Token: ",Token[1].token,"\n")
if self.Constant():
return True
else:
return False
else:
cprint("Expected a RELATIONAL or LOGICAL TOKEN\n","red",attrs=['bold'])
return False
else:
return False
def Constant(self):
print("Constant\n")
Token = self.nextToken()
if Token[0] and Token[1].tag == 'INT-TOK':
print("INT_TOKEN")
print("Token: ",Token[1].token,"\n")
return True
elif Token[0] and Token[1].tag == 'STRING-TOK':
print("STRING_TOKEN")
print("Token: ",Token[1].token,"\n")
return True
elif Token[0] and Token[1].tag == 'REAL-TOK':
print("REAL_TOKEN")
print("Token: ",Token[1].token,"\n")
return True
elif Token[0] and Token[1].tag == 'DATE-TOK':
print("DATE_TOKEN")
print("Token: ",Token[1].token,"\n")
return True
elif Token[0] and Token[1].tag == 'BOOLEAN-TOK':
print("BOOLEAN_TOKEN")
print("Token: ",Token[1].token,"\n")
return True
else:
cprint("Expected a CONSTANT TOKEN\n","red",attrs=['bold'])
return False
def While_stmt(self):
print("While_stmt\n")
WhileToken = self.nextToken()
ParToken = self.nextToken()
if WhileToken[0] and ParToken[0] and WhileToken[1].tag == 'WHILE-TOK' and ParToken[1].tag == 'PAR-OP-TOK':
print("WHILE_TOKEN")
print("Token: ",WhileToken[1].token,"\n")
print("PAR_OP_TOKEN")
print("Token: ",ParToken[1].token,"\n")
if self.Bool_expr():
ParToken = self.nextToken()
if ParToken[0] and ParToken[1].tag == 'PAR-CL-TOK':
print("PAR_CL_TOKEN")
print("Token: ",ParToken[1].token,"\n")
if self.Body():
return True
else:
return False
else:
return False
else:
return False
else:
cprint("Expected a WHILE or ( TOKEN\n","red",attrs=['bold'])
return False
def Return_stmt(self):
print("Return_stmt\n")
Token = self.nextToken()
if Token[0] and Token[1].tag == 'RETURN-TOK':
print("RETURN_TOKEN")
print("Token: ",Token[1].token,"\n")
Semicolon = self.seekActualToken()
if Semicolon[0] and Semicolon[1].tag == 'SEMICOLON-TOK':
print("SEMICOLON_TOKEN")
print("Token: ",Semicolon[1].token,"\n")
self.nextToken()
return True
else:
if self.Constant():
Semicolon = self.seekActualToken()
if Semicolon[0] and Semicolon[1].tag == 'SEMICOLON-TOK':
print("SEMICOLON_TOKEN")
print("Token: ",Semicolon[1].token,"\n")
self.nextToken()
return True
else:
return False
else:
return False
else:
cprint("Expected a RETURN TOKEN\n","red",attrs=['bold'])
return False
def Assign_stmt(self):
print("Assign_stmt\n")
if self.Decl_type():
Token = self.nextToken()
if Token[0] and Token[1].tag == 'ID-TOK':
print("ID_TOKEN")
print("Token: ",Token[1].token,"\n")
Token = self.nextToken()
if Token[0] and Token[1].tag == 'ASIG-TOK':
print("ASSIGN_TOKEN")
print("Token: ",Token[1].token,"\n")
if self.Constant():
Token = self.nextToken()
if Token[0] and Token[1].tag == 'SEMICOLON-TOK':
print("SEMICOLON_TOKEN")
print("Token: ",Token[1].token,"\n")
return True
else:
cprint("Expected a SEMICOLON TOKEN\n","red",attrs=['bold'])
return False
else:
return False
else:
cprint("Expected a ASSIGN TOKEN\n","red",attrs=['bold'])
return False
else:
cprint("Expected a ID TOKEN\n","red",attrs=['bold'])
return False
Pars = Parser('Program.g4')
Pars.Parse()
|
{"/ParserSimpleExample.py": ["/Lexer.py"], "/Parser.py": ["/Lexer.py"]}
|
1,228
|
flinteller/unit_eleven
|
refs/heads/master
|
/paddle.py
|
import pygame
import random
class Paddle(pygame.sprite.Sprite):
def __init__(self, main_surface, color, height, width):
"""
This function creates creates a surface using each other params
:param main_surface:
:param color:
:param height:
:param width:
"""
# initialize sprite super class
super().__init__()
# finish setting the class variables to the parameters
self.main_surface = main_surface
self.color = color
self.height = height
self.width = width
# Create a surface with the correct height and width
self.image = pygame.Surface((width, height))
# Get the rect coordinates
self.rect = self.image.get_rect()
# Fill the surface with the correct color
self.image.fill(color)
def move_left(self):
"""
This function moves the paddle left and stops the paddle form going off screen
:return:
"""
self.rect.x = self.rect.x - 7
if self.rect.left < 0:
self.rect.x = 1
def move_right(self):
"""
This function moves the paddle right and stops the paddle form going off screen
:return:
"""
self.rect.x = self.rect.x + 7
if self.rect.right > 400:
self.rect.x = 335
def resize(self):
"""
This function creates a new surface with a random size and keeps its color
:return:
"""
self.width = random.randint(20, 100)
self.image = pygame.Surface((self.width, self.height))
self.image.fill(self.color)
|
{"/breakout.py": ["/ball.py", "/paddle.py"]}
|
1,229
|
flinteller/unit_eleven
|
refs/heads/master
|
/ball.py
|
import pygame
class Ball(pygame.sprite.Sprite):
def __init__(self, color, window_width, window_height, radius):
# initialize sprite super class
super().__init__()
# finish setting the class variables to the parameters
self.color = color
self.radius = radius
self.window_width = window_width
self.window_height = window_height
self.speedx = 6
self.speedy = 8
# Create a surface, get the rect coordinates, fill the surface with a white color (or whatever color the
# background of your breakout game will be.
self.image = pygame.image.load("chrome copy.png")
self.rect = self.image.get_rect()
# Add a circle to represent the ball to the surface just created.
def move(self):
"""
This makes the ball move and keeps it on the screen
:return:
"""
self.rect.top += self.speedy
self.rect.left += self.speedx
if self.rect.top < 0:
self.speedy = -self.speedy
elif self.rect.left < 0 or self.rect.right > self.window_width:
self.speedx = -self.speedx
def collide(self, paddle_group, brick_group):
"""
This detects collisions and plays a sound accordingly
:param paddle_group:
:param brick_group:
:return:
"""
if pygame.sprite.spritecollide(self, brick_group, True):
self.speedx = self.speedx
self.speedy = -self.speedy
pygame.mixer.init()
pygame.init()
sound = pygame.mixer.Sound("Bleep-sound.wav")
sound.play()
if pygame.sprite.spritecollide(self, paddle_group, False):
self.speedx = self.speedx
self.speedy = -self.speedy
pygame.mixer.init()
pygame.init()
sound = pygame.mixer.Sound("Paddle_bounce_sound.wav")
sound.play()
|
{"/breakout.py": ["/ball.py", "/paddle.py"]}
|
1,230
|
flinteller/unit_eleven
|
refs/heads/master
|
/breakout.py
|
import pygame
import sys
from pygame.locals import *
import brick
import ball
import paddle
def main():
# Constants that will be used in the program
APPLICATION_WIDTH = 400
APPLICATION_HEIGHT = 600
PADDLE_Y_OFFSET = 30
BRICKS_PER_ROW = 10
BRICK_SEP = 4 # The space between each brick
BRICK_Y_OFFSET = 70
BRICK_WIDTH = (APPLICATION_WIDTH - (BRICKS_PER_ROW -1) * BRICK_SEP) / BRICKS_PER_ROW
BRICK_HEIGHT = 8
PADDLE_HEIGHT = 10
PADDLE_WIDTH = 60
RADIUS_OF_BALL = 10
NUM_TURNS = 3
# Sets up the colors
BLUE = (30, 144, 255)
RED = (255, 48, 48)
YELLOW = (255, 215, 0)
GREEN =(0, 201, 87)
WHITE = (255, 255, 255)
pygame.init()
main_window = pygame.display.set_mode((APPLICATION_WIDTH, APPLICATION_HEIGHT), 32, 0)
pygame.display.set_caption("AD Blocker")
pygame.display.update()
# Step 1: Use loops to draw the rows of bricks. The top row of bricks should be 70 pixels away from the top of
# the screen (BRICK_Y_OFFSET)
brick_group = pygame.sprite.Group()
paddle_group = pygame.sprite.Group()
x_pos = 0
y_pos = BRICK_Y_OFFSET
# Places bricks with correct colors
colors = [BLUE, RED, YELLOW, BLUE, GREEN]
for color in colors:
for y in range(2):
for z in range(10):
my_brick = brick.Brick(BRICK_WIDTH, BRICK_HEIGHT, color)
brick_group.add(my_brick)
my_brick.rect.y = y_pos
my_brick.rect.x = x_pos
main_window.blit(my_brick.image, my_brick.rect)
x_pos += (BRICK_SEP + BRICK_WIDTH)
x_pos = 0
y_pos += BRICK_HEIGHT + BRICK_SEP
# Places ball and passes it parameters
my_ball = ball.Ball(RED, APPLICATION_WIDTH, APPLICATION_HEIGHT, RADIUS_OF_BALL)
my_ball.rect.x = 200
my_ball.rect.y = 200
# Places paddle and passes it parameters
my_paddle = paddle.Paddle(main_window, GREEN, PADDLE_HEIGHT, PADDLE_WIDTH)
paddle_group.add(my_paddle)
my_paddle.rect.x = APPLICATION_WIDTH / 2
my_paddle.rect.y = APPLICATION_HEIGHT - PADDLE_Y_OFFSET
pygame.display.update()
# Event detection loop
while True:
for event in pygame.event.get():
if event == QUIT:
pygame.quit()
sys.exit()
if pygame.key.get_pressed()[K_LEFT]:
my_paddle.move_left()
if pygame.key.get_pressed()[K_RIGHT]:
my_paddle.move_right()
if pygame.key.get_pressed()[K_SPACE]:
my_paddle.resize()
if my_ball.rect.bottom > 590:
NUM_TURNS -= 1
pygame.mixer.init()
pygame.init()
sound = pygame.mixer.Sound("Error_sound.wav")
sound.play()
my_ball.rect.x = 200
my_ball.rect.y = 20
main_window.fill(WHITE)
# Prints number of lives
mouse_font = pygame.font.SysFont("Verdana", 32)
mouse_label = mouse_font.render("Lives: " + str(NUM_TURNS), 1, BLUE)
main_window.blit(mouse_label, (30, 30))
pygame.display.update()
# Prints message if you win
if len(brick_group) == 0:
mouse_font = pygame.font.SysFont("Verdana", 32)
mouse_label = mouse_font.render("You Win!!!", 1, BLUE)
main_window.blit(mouse_label, (135, 200))
pygame.mixer.init()
pygame.init()
sound = pygame.mixer.Sound("Win_sound.wav")
sound.play()
pygame.display.update()
if len(brick_group) == 0:
pygame.time.wait(2000)
break
# Prints message if you loose
if NUM_TURNS == 1 and my_ball.rect.bottom > 585:
mouse_font = pygame.font.SysFont("Verdana", 32)
mouse_label = mouse_font.render("Game Over", 1, RED)
main_window.blit(mouse_label, (135, 200))
pygame.mixer.init()
pygame.init()
sound = pygame.mixer.Sound("Game_over_sound.wav")
sound.play()
pygame.display.update()
if NUM_TURNS == 0:
pygame.time.wait(2000)
break
# Moves and blits ball
my_ball.move()
main_window.blit(my_ball.image, my_ball.rect)
if my_ball.rect.bottom > my_ball.window_height:
NUM_TURNS -= 1
# Blits each brick
for a_brick in brick_group:
main_window.blit(a_brick.image, a_brick.rect)
# Calls collision function
my_ball.collide(paddle_group, brick_group)
# Blits paddle
main_window.blit(my_paddle.image, my_paddle.rect)
pygame.display.update()
main()
|
{"/breakout.py": ["/ball.py", "/paddle.py"]}
|
1,231
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/play_handsfree_GO.py
|
from pynput.mouse import Button, Controller
import cv2
import imageio
import matplotlib.pyplot as plt
import threading
import time
import queue
import os
import numpy as np
import src
frames = queue.Queue(maxsize=10)
class frameGrabber(threading.Thread):
def __init__(self):
# Constructor
threading.Thread.__init__(self)
def run(self):
cam = cv2.VideoCapture(0)
img_counter = 0
while True:
ret, frame = cam.read()
if not ret:
break
img_name = f"images/game_log/opencv_frame_{img_counter}.png"
cv2.imwrite(img_name, frame)
print("{} written!".format(img_name))
frames.put(img_counter)
img_counter += 1
time.sleep(30)
cam.release()
def verify_calibration(x_idx, y_idx, red_scale_th, blue_scale_th, color, i, j):
# Display a message to the user to put a stone
print(f"\nPlease put a {color} stone at {src.convert_physical_board_ij_to_str(i,j)}...")
# Assert the stone with desired color is on the goban at the exact spot
while True:
time.sleep(5)
frame_num = frames.get()
img_name = f"images/game_log/opencv_frame_{frame_num}.png"
rgb = imageio.imread(img_name)
plt.imshow(rgb)
plt.title(f"This board should have a {color} stone at {src.convert_physical_board_ij_to_str(i,j)}.")
plt.show()
ans = input(f"Did you put a {color} stone at {src.convert_physical_board_ij_to_str(i,j)}? [y/n]: ")
if ans is 'y':
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
assert src.is_this_stone_on_the_board(rgb, x_idx, y_idx, \
red_scale_th, blue_scale_th, color, i, j, plot_stuff=True)
remove_this_frame(img_name)
frames.task_done()
remove_unused_frames()
break
else:
remove_this_frame(img_name)
frames.task_done()
def remove_this_frame(img_name):
os.remove(img_name)
print('Frame', img_name, 'removed.')
def remove_unused_frames():
print('Removing unused frames...')
while True:
time.sleep(1)
try:
frame_num = frames.get(False)
except queue.Empty:
# Handle empty queue here
break
else:
# Handle task here and call q.task_done()
frame_num = frames.get()
img_name = f"images/game_log/opencv_frame_{frame_num}.png"
remove_this_frame(img_name)
frames.task_done()
print('Unused frames removed...')
board_corners = []
def onclick(event):
print(event.xdata, event.ydata)
board_corners.append(event.xdata)
board_corners.append(event.ydata)
if __name__ == '__main__':
# Initiate the frame grabber thread for goban pictures
my_frame_grabber = frameGrabber()
# Start running the threads!
my_frame_grabber.start()
print('Frame grabbing has started...')
# MANUAL BOARD EDGE DETECTION FOR THE PYHSICAL BOARD
# Show a plot frames and ask user to input boundaries
while True:
time.sleep(5)
frame_num = frames.get()
img_name = f"images/game_log/opencv_frame_{frame_num}.png"
rgb = imageio.imread(img_name)
fig = plt.figure()
plt.imshow(rgb)
plt.title("Please click on UL-UR-BL-BR corners or close plot...")
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
if not board_corners:
# Skip if nothing is clicked
remove_this_frame(img_name)
frames.task_done()
else:
# Read goban corners
ob = board_corners
assert ob[2] > ob[0] and ob[6] > ob[4] and \
ob[7] > ob[4] and ob[5] > ob[1]
# Remove this filename as it served its purpose and break out of loop
remove_this_frame(img_name)
frames.task_done()
break
# Remove all unused frames at the end
remove_unused_frames()
# Remove non-goban part from the RGB matrix and make it a square matrix
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
# Find the indices of board points in the new square RGB matrix
x_idx, y_idx = src.find_board_points(rgb, plot_stuff=False)
# CALIBRATION OF PYHSICAL BOARD
# Ask the user to put black and white stones on the board
print('\nPlease put black stones on corners and a white stone at center')
bxy, wxy = [(1,1), (19,19), (1,19), (19,1)], [(10,10)]
while True:
time.sleep(5)
frame_num = frames.get()
img_name = f"images/game_log/opencv_frame_{frame_num}.png"
rgb = imageio.imread(img_name)
plt.imshow(rgb)
plt.title('Did you put black on corners and white at center?')
plt.show()
ans = input('Did you put black stones on corners and a white stone at center? [y/n]: ')
if ans is 'y':
# Remove non-goban part from the RGB matrix and make it a square matrix
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
# Calibrate
red_scale_th1, blue_scale_th1 = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
# Refind stones using the above thresholds
bxy_new, wxy_new = src.mark_stones(rgb, x_idx, y_idx, \
red_scale_th1, blue_scale_th1, plot_stuff=False)
remove_this_frame(img_name)
frames.task_done()
remove_unused_frames()
break
else:
remove_this_frame(img_name)
frames.task_done()
print('\nPlease put white stones on corners and a black stone at center')
wxy, bxy = [(1,1), (19,19), (1,19), (19,1)], [(10,10)]
while True:
time.sleep(5)
frame_num = frames.get()
img_name = f"images/game_log/opencv_frame_{frame_num}.png"
rgb = imageio.imread(img_name)
plt.imshow(rgb)
plt.title('Did you put white on corners and black at center?')
plt.show()
ans = input('Did you put white stones on corners and a black stone at center? [y/n]: ')
if ans is 'y':
# Remove non-goban part from the RGB matrix and make it a square matrix
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
# Calibrate
red_scale_th2, blue_scale_th2 = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
# Refind stones using the above thresholds
bxy_new, wxy_new = src.mark_stones(rgb, x_idx, y_idx, \
red_scale_th2, blue_scale_th2, plot_stuff=False)
remove_this_frame(img_name)
frames.task_done()
remove_unused_frames()
break
else:
remove_this_frame(img_name)
frames.task_done()
red_scale_th = 0.5 * (red_scale_th1 + red_scale_th2)
blue_scale_th = 0.5 * (blue_scale_th1 + blue_scale_th2)
# VERIFY CALIBRATION OF PHYSICAL BOARD
print(' [PLEASE KEEP IN MIND THAT YOUR LOWER-LEFT CORNER IS (1,1)]')
verify_calibration(x_idx, y_idx, red_scale_th, blue_scale_th, 'black', 3, 4)
verify_calibration(x_idx, y_idx, red_scale_th, blue_scale_th, 'white', 1, 1)
verify_calibration(x_idx, y_idx, red_scale_th, blue_scale_th, 'black', 10, 10)
verify_calibration(x_idx, y_idx, red_scale_th, blue_scale_th, 'white', 19, 19)
print("CALIBRATION IS VERIFIED\n" + 50*"-")
# DIGITAL BOARD DETECTION
# Ask the user to open a KGS board
print('\n OPEN A KGS BOARD/GAME NOW')
input('ENTER when the digital board is open: ')
# Get the user to click on come corners to get to know the digital board
UL_x, UL_y, goban_step = src.get_goban_corners()
# Test by moving to the star points on the board
for str in ['D16', 'K16', 'Q16', 'D10', 'K10', 'Q10', 'D4', 'K4', 'Q4']:
i, j = src.str_to_integer_coordinates(str)
x, y = src.int_coords_to_screen_coordinates(UL_x, UL_y, i, j, goban_step)
src.make_the_move(mouse, x, y, no_click=True)
# START REPLAYING PYHSICAL BOARD MOVES ON THE DIGITAL BOARD
# Plan - 1) check frames continously until a move is made by you
# 2) check digital board until a move is made by your opponent
# First, remove all unused frames
remove_unused_frames()
# Scan the frames for moves every five seconds
mouse = Controller() # obtain mouse controller
bxy, wxy = [], [] # empty board in the beginning
while True:
time.sleep(5)
frame_num = frames.get()
img_name = f"images/game_log/opencv_frame_{frame_num}.png"
color, i, j = src.scan_next_move(img_name, ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, bxy, wxy)
if color is not None:
# Play the move and update the stone lists
bxy, wxy = src.play_next_move_on_digital_board(mouse, color, \
i, j, bxy, wxy, UL_x, UL_y, goban_step)
# Start checking the digital board for new moves
else:
# Remove this frame and start waiting for the next frame
remove_this_frame(img_name)
frames.task_done()
# Wait for the threads to finish...
my_frame_grabber.join()
print('Main Terminating...')
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,232
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/tests/test_screenshot_actions.py
|
import imageio
import pytest
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src
def test_get_digital_goban_state():
rgb_pix = imageio.imread('images/digital_goban.png')
# Process KGS goban grayscale and find the stones
assert src.get_digital_goban_state(rgb_pix) == \
set([(1,1,1), (1, 1, 14), (2,19,19)])
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,233
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/src/mouse_actions.py
|
from pynput.mouse import Button, Controller
import src
import time
def get_goban_corners():
# Obtain mouse controller
mouse = Controller()
# Ask the user to define goban corners
print('Move cursor to upper-left (A19) corner of Goban and keep it there five seconds')
time.sleep(5)
(UL_x, UL_y) = mouse.position
print(f"Upper-Left: ({UL_x},{UL_y})")
print()
print('Move cursor to bottom-right (T1) corner of Goban and keep it there five seconds')
time.sleep(5)
(BR_x, BR_y) = mouse.position
print(f"Bottom-Right: ({BR_x},{BR_y})")
print()
# Compute goban step sizes
goban_step = 0.5 * (BR_x - UL_x) * 1/18 + 0.5 * (BR_y - UL_y) * 1/18
print(f"Goban-steps is {goban_step}")
return UL_x, UL_y, goban_step
def make_the_move(mouse, x, y, no_click=False):
(cx, cy) = mouse.position
time.sleep(0.5)
mouse.move(x - cx, y - cy)
time.sleep(0.2)
if not no_click:
mouse.click(Button.left, 1)
def int_coords_to_screen_coordinates(UL_x, UL_y, i, j, goban_step):
x = UL_x + (i-1) * goban_step
y = UL_y + (j-1) * goban_step
return x, y
def str_to_integer_coordinates(str):
# Upper-lef corner is 1,1 and Bottom-right corner is 19,19
# Goban boards skip the letter I
j = 19 - int(str[1:3]) + 1
if ord(str[0]) < ord('I'):
i = ord(str[0]) - ord('A') + 1
else:
i = ord(str[0]) - ord('A')
return i,j
def int_coords_to_str(i, j):
# Upper-lef corner is 1,1 and Bottom-right corner is 19,19
# Goban boards skip the letter I
if i <= ord('I') - ord('A'):
return chr(ord('A') + i-1) + f"{20-j}"
else:
return chr(ord('A') + i) + f"{20-j}"
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,234
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/src/cam_actions.py
|
import imageio
def get_pyhsical_goban_state(rgb_pix):
pass
def picture_to_rgb(path):
return misc.imageio(path)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,235
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/make_goban_speak.py
|
import src
import time
UL_x, UL_y, goban_step = src.get_goban_corners()
prev_stone_set = set()
print("Started scanning the board for moves every 5 seconds...")
while True:
# wait between screenshots
time.sleep(5)
# get board screenshot
board_rgb_screenshot = src.KGS_goban_rgb_screenshot(UL_x, UL_y, goban_step)
# find the stones on the board
current_stone_set = src.get_goban_state(board_rgb_screenshot)
# is there a new stone on the board?
if current_stone_set > prev_stone_set:
# find the new stone
stone = current_stone_set - prev_stone_set
# IN THE FUTURE, ALLOW FOR OPPONENT TO MAKE A QUICK MOVE!!!
assert len(stone) == 1
# say the new moves on the board
player = list(stone)[0][0] # 1-black, 2-white
i, j = list(stone)[0][1], list(stone)[0][2]
pos = src.int_coords_to_str(i,j)
if player==1:
update_msg = "Black played at " + pos
elif player==2:
update_msg = "White played at " + pos
print(update_msg)
prev_stone_set = current_stone_set
else:
print("No moves made!")
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,236
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/src/screenshot_actions.py
|
import pyscreeze
import numpy as np
import matplotlib.pyplot as plt
import src
def get_digital_goban_state(rgb_pix, plot_stuff=False):
# RGB of Black = [ 0, 0, 0]
# RGB of White = [255, 255, 255]
# RGB of Orange = [255, 160, 16]
# Use red scale to find out black stones, blue scale to find out white stones
# (1, 1, 1) - Black A1 (upper corner)
# (2, 19, 19) - White T10 (lower corner)
idx = np.arange(19)+1
m, n, z = rgb_pix.shape
assert m == n
# Approximate diameter of a stone in terms of pixels
stone_diam = n/19
# Calculate pixels where stone centers will be positioned
stone_centers = np.round(stone_diam*idx) - 0.5 * np.round(stone_diam) - 1
stone_centers = stone_centers.astype(int)
# For every stone center, we will check a square matrix centered around
# the stone center and find the average color. If it is black, then the
# stone is black, if it is white, then the stone is white, otherwise no stone
square_length_in_a_stone = int(np.round((n/19) / np.sqrt(2)))
if square_length_in_a_stone % 2 == 0:
d = square_length_in_a_stone / 2
else:
d = (square_length_in_a_stone-1) / 2
d = int(d-1) # just in case, make square smaller and integer
# Calculate the mean of a small matrix around every board point to find out
# if there is a black stone or white stone or nothing
stones = set()
for posi, i in enumerate(stone_centers, start=1):
for posj, j in enumerate(stone_centers, start=1):
# Find black stones
mat = rgb_pix[:,:,0]
color = np.mean(np.mean(mat[i:i+d+1, j:j+d+1]))
if color < 125:
stones.add((1, posj, posi)) # black stone
rgb_pix[i-d+1:i+d, j-d+1:j+d, :] = 0
# Find white stones
mat = rgb_pix[:,:,2]
color = np.mean(np.mean(mat[i:i+d+1, j:j+d+1]))
if color > 125:
stones.add((2, posj, posi)) # white stone
rgb_pix[i-d+1:i+d, j-d+1:j+d] = 255
# Plot for debugging
if plot_stuff:
plt.imshow(rgb_pix)
plt.show()
return stones
def KGS_goban_rgb_screenshot(UL_x, UL_y, goban_step):
UL_outer_x = UL_x - 0.5*goban_step
UL_outer_y = UL_y - 0.5*goban_step
BR_outer_x = UL_x + 18*goban_step + 0.5*goban_step
BR_outer_y = UL_y + 18*goban_step + 0.5*goban_step
im = pyscreeze.screenshot(region=(UL_outer_x, UL_outer_y, \
BR_outer_x-UL_outer_x, BR_outer_y-UL_outer_y))
pix = np.array(im)
rgb_pix = pix[...,:3]
return rgb_pix
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,237
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/temp/plot_save_coordinates_on_click.py
|
import matplotlib.pyplot as plt
xy=[]
def onclick(event):
print(event.xdata, event.ydata)
xy.append((event.xdata, event.ydata))
fig = plt.figure()
plt.plot(range(10))
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
print(xy)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,238
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/auto_goban_detection.py
|
import matplotlib.pyplot as plt
import imageio
import numpy as np
import src
IMG_PATH = 'images/empty_pyshical_goban1.png'
board_corners = []
def onclick(event):
print(event.xdata, event.ydata)
board_corners.append((event.xdata, event.ydata))
# Get RGB matrix of the picture with goban
rgb = imageio.imread(IMG_PATH)
fig = plt.figure()
plt.imshow(rgb)
plt.title("Please click on UL-UR-BL-BR corners...")
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
UL_outer_x, UL_outer_y = board_corners[0]
UR_outer_x, UR_outer_y = board_corners[1]
BL_outer_x, BL_outer_y = board_corners[2]
BR_outer_x, BR_outer_y = board_corners[3]
# Remove non-goban part from the RGB matrix and make it a square matrix
rgb = src.rescale_pyhsical_goban_rgb(rgb, \
UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y)
# Find the indices of board points in the new square RGB matrix
x_idx, y_idx = src.find_board_points(rgb, plot_stuff=True)
# Mark board points
src.mark_board_points(rgb, x_idx, y_idx)
#bxy, wxy = [(4,4), (16,4)], [(4,16),(16,16)]
#src.mark_board_points(rgb, x_idx, y_idx, bxy, wxy)
#red_scale_th, blue_scale_th = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
#bxy_new, wxy_new = src.mark_stones(rgb, x_idx, y_idx, red_scale_th, blue_scale_th)
#src.is_this_stone_on_the_board(rgb, x_idx, y_idx, red_scale_th, blue_scale_th, \
# 'black', 16,4)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,239
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/tests/test_play_handsfree_GO.py
|
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from pynput.mouse import Button, Controller
import pytest
import imageio
import src
# Write a test of play_handsfree_GO.py using already existing frames
img_name = []
folder_name = 'images/sample_game_log/ex1/'
# empty board for outer board boundary detection
img_name.append(folder_name + 'opencv_frame_1.png')
UL_outer_x, UL_outer_y = 376.27419354838713, 91.34516129032261
UR_outer_x, UR_outer_y = 962.08064516129020, 101.66774193548395
BL_outer_x, BL_outer_y = 120.79032258064518, 641.0225806451613
BR_outer_x, BR_outer_y = 1265.3064516129032, 652.6354838709677
# black stones on corners and a white stone at center
img_name.append(folder_name + 'opencv_frame_3.png')
# white stones on corners and a black stone at center
img_name.append(folder_name + 'opencv_frame_4.png')
# verifying calibration
img_name.append(folder_name + 'opencv_frame_b_1_1.png') # black at (1,1)
img_name.append(folder_name + 'opencv_frame_b_1_19.png') # black at (1,19)
img_name.append(folder_name + 'opencv_frame_b_19_19.png') # black at (19,19)
img_name.append(folder_name + 'opencv_frame_b_19_1.png') # black at (19,1)
img_name.append(folder_name + 'opencv_frame_b_10_10.png') # black at (10,10)
img_name.append(folder_name + 'opencv_frame_b_4_4.png') # black at (4,4)
img_name.append(folder_name + 'opencv_frame_b_4_10.png') # black at (4,10)
img_name.append(folder_name + 'opencv_frame_b_4_16.png') # black at (4,16)
img_name.append(folder_name + 'opencv_frame_b_16_16.png') # black at (16,16)
img_name.append(folder_name + 'opencv_frame_w_1_1.png') # white at (1,1)
img_name.append(folder_name + 'opencv_frame_w_10_10.png') # white at (10,10)
img_name.append(folder_name + 'opencv_frame_w_16_16.png') # white at (16,16)
img_name.append(folder_name + 'opencv_frame_w_19_19.png') # white at (19,19)
#opencv_frame_b_10_4.png
#opencv_frame_b_10_16.png
#opencv_frame_b_16_4.png
#opencv_frame_b_16_10.png
#opencv_frame_b_19_1.png
#opencv_frame_w_1_19.png
#opencv_frame_w_4_4.png
#opencv_frame_w_4_10.png
#opencv_frame_w_4_16.png
#opencv_frame_w_10_16.png
#opencv_frame_w_16_4.png
#opencv_frame_w_16_10.png
#opencv_frame_w_19_1.png
def test_play_handsfree_GO():
ps = False
# STEP 0 - EMPTY GOBAN
# Get outer boundaries of pyhsical goban -- skipped for speed
ob = [UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y]
# Remove non-goban part from the RGB matrix and make it a square matrix
# Find the indices of board points in the new square RGB matrix
#UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
# BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y = \
# src.get_pyhsical_board_outer_corners(img_name[0])
rgb = imageio.imread(img_name[0])
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
x_idx, y_idx = src.find_board_points(rgb, plot_stuff=ps)
# STEP 1 - GOBAN WITH BLACK STONES ON CORNERS AND A WHITE STONE AT CENTER
rgb = imageio.imread(img_name[1])
bxy, wxy = [(1,1), (19,19), (1,19), (19,1)], [(10,10)]
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
red_scale_th1, blue_scale_th1 = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
_, _ = src.mark_stones(rgb, x_idx, y_idx, \
red_scale_th1, blue_scale_th1, plot_stuff=ps)
# STEP 2 - GOBAN WITH WHITE STONES ON CORNERS AND A BLACK STONE AT CENTER
rgb = imageio.imread(img_name[2])
wxy, bxy = [(1,1), (19,19), (1,19), (19,1)], [(10,10)]
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
red_scale_th2, blue_scale_th2 = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
_, _ = src.mark_stones(rgb, x_idx, y_idx, \
red_scale_th2, blue_scale_th2, plot_stuff=ps)
red_scale_th = 0.5 * (red_scale_th1 + red_scale_th2)
blue_scale_th = 0.5 * (blue_scale_th1 + blue_scale_th2)
# STEP 3 - VERIFY CALIBRATION
verify_calibration_for_test_purposes(img_name[3], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 1, 1, ps)
verify_calibration_for_test_purposes(img_name[4], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 1, 19, ps)
verify_calibration_for_test_purposes(img_name[5], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 19, 19, ps)
verify_calibration_for_test_purposes(img_name[6], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 19, 1, ps)
verify_calibration_for_test_purposes(img_name[7], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 10, 10, ps)
verify_calibration_for_test_purposes(img_name[8], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 4, 4, ps)
verify_calibration_for_test_purposes(img_name[9], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 4, 10, ps)
verify_calibration_for_test_purposes(img_name[10], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 4, 16, ps)
verify_calibration_for_test_purposes(img_name[11], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'black', 16, 16, ps)
verify_calibration_for_test_purposes(img_name[12], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'white', 1, 1, ps)
verify_calibration_for_test_purposes(img_name[13], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'white', 10, 10, ps)
verify_calibration_for_test_purposes(img_name[14], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'white', 16, 16, ps)
verify_calibration_for_test_purposes(img_name[15], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, 'white', 19, 19, ps)
# DIGITAL BOARD DETECTION
# Ask the user to open a KGS board
print('\n OPEN A KGS BOARD/GAME NOW')
input('ENTER when the digital board is open: ')
# Get the user to click on come corners to get to know the digital board
UL_x, UL_y, goban_step = src.get_goban_corners()
# START REPLAYING PYHSICAL BOARD MOVES ON THE DIGITAL BOARD
mouse = Controller() # obtain mouse controller
print("Placing a black stone at (10,10)")
bxy, wxy = [], [] # empty board in the beginning
color, i, j = src.scan_next_move(img_name[7], ob, x_idx, y_idx, \
red_scale_th, blue_scale_th, bxy, wxy, plot_stuff=ps)
_, _ = src.play_next_move_on_digital_board(mouse, color, i, j, bxy, wxy, \
UL_x, UL_y, goban_step)
def verify_calibration_for_test_purposes(img, ob, x, y, r, b, c, i, j, ps):
rgb = imageio.imread(img)
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
print(f"Verifying a {c} stone at {src.convert_physical_board_ij_to_str(i,j)}...")
assert src.is_this_stone_on_the_board(rgb, x, y, r, b, c, i, j, ps)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,240
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/tests/test_mouse_actions.py
|
from pynput.mouse import Button, Controller
import time
import sys
import os
import pytest
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src
def test_str_to_integer_coordinates():
assert src.str_to_integer_coordinates('A19') == (1, 1)
assert src.str_to_integer_coordinates('D16') == (4, 4)
assert src.str_to_integer_coordinates('D10') == (4, 10)
assert src.str_to_integer_coordinates('T1') == (19, 19)
assert src.str_to_integer_coordinates('K10') == (10, 10)
def test_integer_coordinates_to_str():
assert src.int_coords_to_str(1, 1) == 'A19'
assert src.int_coords_to_str(4, 4) == 'D16'
assert src.int_coords_to_str(4, 10) == 'D10'
assert src.int_coords_to_str(19, 19) == 'T1'
assert src.int_coords_to_str(10, 10) == 'K10'
@pytest.mark.slow
def test_place_stones_on_all_stars():
print()
# Get goban corners
UL_x, UL_y, goban_step = src.get_goban_corners()
# Obtain mouse controller
mouse = Controller()
# Place stones on stars
print('\n', 41*'-')
print(5*'-', 'Placing stones on all stars', 5*'-')
print(41*'-', '\n')
for str in ['D16', 'K16', 'Q16', 'D10', 'K10', 'Q10', 'D4', 'K4', 'Q4']:
i, j = src.str_to_integer_coordinates(str)
x, y = src.int_coords_to_screen_coordinates(UL_x, UL_y, i, j, goban_step)
src.make_the_move(mouse, x, y)
# Get KGS goban as a square grayscale
rgb_pix = src.KGS_goban_rgb_screenshot(UL_x, UL_y, goban_step)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,241
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/setup.py
|
from setuptools import setup, find_packages
setup( name='Handsfree-KGS',
version='0.0',
description='Pay Handsfree Go on KGS',
author='Fatih Olmez',
author_email='folmez@gmail.com',
packages=find_packages())
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,242
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/src/picture_actions.py
|
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelmin
import imageio
import src
def play_next_move_on_digital_board(mouse, color, i, j, bxy, wxy, \
UL_x, UL_y, goban_step):
if color is not None:
print(f"New move: {color} played at {convert_physical_board_ij_to_str(i,j)}")
if color is 'black':
bxy.append((i,j))
elif color is 'white':
wxy.append((i,j))
# make the move
x, y = src.int_coords_to_screen_coordinates(UL_x, UL_y, i, j, goban_step)
src.make_the_move(mouse, x, y)
return bxy, wxy
def convert_physical_board_ij_to_str(i,j):
"""
The pyhsical board will have the upper-left corner labeled as (1,1) and the
bottom-right corner labeled as (19,19). This little script will help translate
and correct and misalignment between the here-described labeling and the
algorithm.
"""
return f"({i},{j})"
def scan_next_move(img_name, ob, x_idx, y_idx, red_scale_th, blue_scale_th, \
bxy, wxy, plot_stuff=False):
rgb = imageio.imread(img_name)
rgb = src.rescale_pyhsical_goban_rgb(rgb, ob)
bxy_new, wxy_new = src.mark_stones(rgb, x_idx, y_idx, \
red_scale_th, blue_scale_th, plot_stuff=plot_stuff)
print(bxy ,wxy, bxy_new, wxy_new)
if set(bxy_new) == set(bxy) and set(wxy_new) == set(wxy):
color, i, j = None, None, None
print('No new moves')
elif len(set(bxy_new)-set(bxy)) == 1 and set(wxy_new) == set(wxy):
color = 'black'
[(i,j)] = list(set(bxy_new)-set(bxy))
elif len(set(wxy_new)-set(wxy)) == 1 and set(bxy_new) == set(bxy):
color = 'white'
[(i,j)] = list(set(wxy_new)-set(wxy))
else:
raise ValueError('Move scanner error!')
return color, i, j
BOARD_CORNERS = []
def onclick(event):
print(event.xdata, event.ydata)
BOARD_CORNERS.append((event.xdata, event.ydata))
def get_pyhsical_board_outer_corners(img_name):
rgb = imageio.imread(img_name)
fig = plt.figure()
plt.imshow(rgb)
plt.title("Please click on UL-UR-BL-BR corners or close plot...")
fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
UL_outer_x, UL_outer_y = BOARD_CORNERS[0]
UR_outer_x, UR_outer_y = BOARD_CORNERS[1]
BL_outer_x, BL_outer_y = BOARD_CORNERS[2]
BR_outer_x, BR_outer_y = BOARD_CORNERS[3]
return UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y
def find_board_points(rgb, plot_stuff=False):
"""
You have the RGB matrix of the goban as a square matrix but you don't
know which entries correspon to the points on the board. This code finds
the board points by plotting average red, green and blue scales and
calculating the 19 local minima. Why? Because board points are
intersections of black lines and RGB value of black color is [0,0,0].
"""
if plot_stuff:
plt.subplot(221)
plt.imshow(rgb)
plt.subplot(222)
x1_idx = find_custom_local_minima(np.mean(rgb[:,:,0],axis=0), 'r', plot_stuff)
plt.subplot(223)
x2_idx = find_custom_local_minima(np.mean(rgb[:,:,1],axis=0), 'g', plot_stuff)
plt.subplot(224)
x3_idx = find_custom_local_minima(np.mean(rgb[:,:,2],axis=0), 'b', plot_stuff)
plt.show()
plt.subplot(221)
plt.imshow(rgb)
plt.subplot(222)
y1_idx = find_custom_local_minima(np.mean(rgb[:,:,0],axis=1), 'r', plot_stuff)
plt.subplot(223)
y2_idx = find_custom_local_minima(np.mean(rgb[:,:,1],axis=1), 'g', plot_stuff)
plt.subplot(224)
y3_idx = find_custom_local_minima(np.mean(rgb[:,:,2],axis=1), 'b', plot_stuff)
plt.show()
else:
x1_idx = find_custom_local_minima(np.mean(rgb[:,:,0],axis=0), 'r', plot_stuff)
x2_idx = find_custom_local_minima(np.mean(rgb[:,:,1],axis=0), 'g', plot_stuff)
x3_idx = find_custom_local_minima(np.mean(rgb[:,:,2],axis=0), 'b', plot_stuff)
y1_idx = find_custom_local_minima(np.mean(rgb[:,:,0],axis=1), 'r', plot_stuff)
y2_idx = find_custom_local_minima(np.mean(rgb[:,:,1],axis=1), 'g', plot_stuff)
y3_idx = find_custom_local_minima(np.mean(rgb[:,:,2],axis=1), 'b', plot_stuff)
# Sometimes indices found by red, green and blue scales don't agree
x_idx = src.make_indices_agree(x1_idx, x2_idx, x3_idx)
y_idx = src.make_indices_agree(y1_idx, y2_idx, y3_idx)
return x_idx, y_idx
def rescale_pyhsical_goban_rgb(rgb, ob):
# Get outer boundaries from ob
UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y = ob
# Rescale to n by n matrix
n = 300
# find n points on the left and on the right boundaries
x_left_vals, y_left_vals, rgb, _ = \
src.return_int_pnts(n, rgb, BL_outer_x, BL_outer_y, UL_outer_x, UL_outer_y)
x_right_vals, y_right_vals, rgb, _ = \
src.return_int_pnts(n, rgb, BR_outer_x, BR_outer_y, UR_outer_x, UR_outer_y)
# Calculate a new RGB matrix only for the board, by removing outside the board
new_rgb = np.zeros([n,n,3])
for i in range(n):
x1, y1 = x_left_vals[i], y_left_vals[i]
x2, y2 = x_right_vals[i], y_right_vals[i]
# print((x1,y1), (x2,y2))
_, _, rgb, v = src.return_int_pnts(n, rgb, x1, y1, x2, y2)
for j in range(n):
new_rgb[n-i-1, j, :] = v[j]
return new_rgb.astype(np.uint8)
def plot_goban_rgb(rgb, bxy=[], wxy=[]):
plt.imshow(rgb)
plt.ylabel('1st index = 1, ..., 19')
plt.xlabel('2nd index = 1, ..., 19')
plt.show()
def average_RGB(rgb, xMAX, yMAX, x, y, w):
# Calculates average RGB around a board point for stone detection
xL, xR = np.maximum(0, x-w), np.minimum(x+w+1, xMAX-1)
yL, yR = np.maximum(0, y-w), np.minimum(y+w+1, yMAX-1)
red_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 0]))
green_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 1]))
blue_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 2]))
return [red_scale, green_scale, blue_scale]
def make_indices_agree(x1, x2, x3):
# Board points are determined from local extrema of R,G,B values.
# But sometimes they don't match. In that case, choose the one whose
# second difference looks like a constant
a1 = np.amax(abs(np.diff(np.diff(x1))))
a2 = np.amax(abs(np.diff(np.diff(x2))))
a3 = np.amax(abs(np.diff(np.diff(x3))))
x = 0
x = x1 if a1 <= a2 and a1 <= a3 else x
x = x2 if a2 <= a1 and a2 <= a3 else x
x = x3 if a3 <= a1 and a3 <= a2 else x
assert x is not 0
return x
def calibrate(rgb, x_idx, y_idx, bxy=[], wxy=[]):
"""
Depending on light, laptop angle etc. the board may have different RGB values
at different times. So how do we distinguis black and white stones?
RGB of black = [0,0,0]
RGB of white = [255,255,255]
We will use red scale to distinguish black stones and blue scale to
distinguish white stones.
"""
xMAX, yMAX, _ = rgb.shape
roll_w = int(np.round(0.01*xMAX))
# BLACK STONE CALIBRATION
# Input black stone indices is bxy is empty
if not bxy:
msg = 'Enter black stone indices (e.g. 1 14 and 0 for end): '
while True:
input_text = input(msg)
if input_text == '0':
break
else:
j,i = list(map(int, input_text.split()))
bxy.append((i,j))
RGB = src.average_RGB(rgb, xMAX, yMAX, x_idx[i-1], y_idx[j-1], roll_w)
print('RGB = ', RGB)
# Find maximum red scale of black stones
RMAX = 0
for j,i in bxy:
RGB = src.average_RGB(rgb, xMAX, yMAX, x_idx[i-1], y_idx[j-1], roll_w)
print(f"Black stone at ({i},{j}) with RGB = ", RGB)
RMAX = np.maximum(RMAX, RGB[0])
# Find the min red scale of the rest to distinguish
RMIN_rest = 255
for i,x in enumerate(x_idx, start=1):
for j,y in enumerate(y_idx, start=1):
if (j,i) not in bxy:
RGB = src.average_RGB(rgb, xMAX, yMAX, x, y, roll_w)
RMIN_rest = np.minimum(RMIN_rest, RGB[0])
print('\nBlack stones have a maximum red scale =', RMAX)
print('Rest of the board have a minimum red scale', RMIN_rest)
print('Black stone red scale threshold will be average of these two.\n')
# Red scale threshold for black stone detection
assert RMAX < RMIN_rest
red_scale_th = 0.5 * RMAX + 0.5 * RMIN_rest
# WHITE STONE CALIBRATION
# Input white stone indices is wxy is empty
if not wxy:
msg = 'Enter white stone indices (e.g. 1 14 and 0 for end): '
while True:
input_text = input(msg)
if input_text == '0':
break
else:
j,i = list(map(int, input_text.split()))
wxy.append((i,j))
RGB = src.average_RGB(rgb, xMAX, yMAX, x_idx[i-1], y_idx[j-1], roll_w)
print('RGB = ', RGB)
# Find minimum blue scale of white stones
BMIN = 255
for (j,i) in wxy:
RGB = src.average_RGB(rgb, xMAX, yMAX, x_idx[i-1], y_idx[j-1], roll_w)
print(f"White stone at ({i},{j}) with RGB = ", RGB)
BMIN = np.minimum(BMIN, RGB[2])
# Find the max blue scale of the rest to distinguis
BMAX_rest = 0
for i,x in enumerate(x_idx, start=1):
for j,y in enumerate(y_idx, start=1):
if (j,i) not in wxy:
RGB = src.average_RGB(rgb, xMAX, yMAX, x, y,roll_w)
BMAX_rest = np.maximum(BMAX_rest, RGB[2])
print('\nWhite stones have a minimum blue scale >', BMIN)
print('Rest of the board have a maximum blue scale', BMAX_rest)
print('White stone blue scale threshold will be average of these two.\n')
# Blue scale threshold for white stone detection
assert BMIN > BMAX_rest
blue_scale_th = 0.5 * BMIN + 0.5 * BMAX_rest
return red_scale_th, blue_scale_th
def is_this_stone_on_the_board(rgb, x_idx, y_idx, red_scale_th, blue_scale_th, \
color, i, j, plot_stuff=False):
i,j = j,i # RGB matrix is messed up so this needs to be done
x, y = x_idx[i-1], y_idx[j-1]
if plot_stuff:
fig = plt.figure()
plt.imshow(rgb)
plt.ylabel('1st index = 1, ..., 19')
plt.xlabel('2nd index = 1, ..., 19')
plt.title(f"Checking if there is a {color} stone at ({j},{i})")
plt.plot(x, y, 'ro', markersize=20, fillstyle='none')
plt.show()
xMAX, yMAX, _ = rgb.shape
roll_w = int(np.round(0.01*xMAX))
xL, xR = np.maximum(0, x-roll_w), np.minimum(x+roll_w+1, xMAX-1)
yL, yR = np.maximum(0, y-roll_w), np.minimum(y+roll_w+1, yMAX-1)
red_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 0]))
blue_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 2]))
msg = f"There is {color} stone at {src.int_coords_to_str(i,j)} = ({i},{j})"
if color == 'black' and red_scale < red_scale_th:
print(msg)
return True
elif color == 'white' and blue_scale > blue_scale_th:
print(msg)
return True
else:
return False
def mark_stones(rgb, x_idx, y_idx, red_scale_th, blue_scale_th, plot_stuff=True):
xMAX, yMAX, _ = rgb.shape
roll_w = int(np.round(0.01*xMAX))
new_rgb = np.copy(rgb)
bxy, wxy = [], [] # black and white stone lists including pairs
for i, x in enumerate(x_idx, start=1):
for j, y in enumerate(y_idx, start=1):
xL, xR = np.maximum(0, x-roll_w), np.minimum(x+roll_w+1, xMAX-1)
yL, yR = np.maximum(0, y-roll_w), np.minimum(y+roll_w+1, yMAX-1)
red_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 0]))
blue_scale = np.mean(np.mean(rgb[yL:yR, xL:xR, 2]))
#print((x,y), red_scale, blue_scale)
if red_scale < red_scale_th or blue_scale > blue_scale_th:
if blue_scale > blue_scale_th:
wxy.append((j,i))
new_rgb[yL:yR, xL:xR,:] = 255, 255, 255 # white stone
elif red_scale < red_scale_th:
bxy.append((j,i))
new_rgb[yL:yR, xL:xR,:] = 255, 255, 0 # black stone
else:
new_rgb[yL:yR, xL:xR,:] = 255, 0, 0 # empty
if plot_stuff:
src.plot_goban_rgb(new_rgb)
return bxy, wxy
def mark_board_points(rgb, x_idx, y_idx, bxy=[], wxy=[]):
"""
Mark board points with red squares. Use yellow color for black stones and
white color for white stones that are inputted.
"""
xMAX, yMAX, _ = rgb.shape
roll_w = int(np.round(0.01*xMAX))
new_rgb = np.copy(rgb)
for i,x in enumerate(x_idx, start=1):
for j,y in enumerate(y_idx, start=1):
xL, xR = np.maximum(0, x-roll_w), np.minimum(x+roll_w+1, xMAX-1)
yL, yR = np.maximum(0, y-roll_w), np.minimum(y+roll_w+1, yMAX-1)
if (j,i) in bxy: # black stone
new_rgb[yL:yR, xL:xR,:] = 255, 255, 0 # yellow color
elif (j,i) in wxy: # white stone
new_rgb[yL:yR, xL:xR,:] = 255, 255, 255 # white color
else: # empty board point
new_rgb[yL:yR, xL:xR,:] = 255, 0, 0 # red color
src.plot_goban_rgb(new_rgb)
def find_custom_local_minima(ar1, color, plot_stuff):
roll_w = int(np.round(len(ar1)/100))
ar2 = subtract_rolling_sum(roll_w, ar1)
idx = find_local_minima(ar2)
if plot_stuff:
plt.plot(ar2, color)
for i in idx:
plt.plot(i, ar2[i], 'k*')
return idx
def find_local_minima(ar):
# Try to find the optional cut-off that may help determine the 19 points on
# the go board. Start with an interval [min_val, max_val] and squeeze until
# it hits exactly 19 points
# Find indices that correspond to local minima
x = argrelmin(ar)
idx_list = x[0]
target = 19
min_val, max_val = np.amin(ar), 100.0
# Assert that above choices are good
assert sum(ar[i] <= min_val for i in idx_list) < target
assert sum(ar[i] <= max_val for i in idx_list) > target
# Find the cut-off below which there are exactly 19 local minima
while True:
new_val = 0.5 * min_val + 0.5 * max_val
if sum(ar[i] <= new_val for i in idx_list) < target:
min_val = new_val
elif sum(ar[i] <= new_val for i in idx_list) > target:
max_val = new_val
elif sum(ar[i] <= new_val for i in idx_list) == target:
break
# Find the indices
return [i for i in idx_list if ar[i] <= new_val]
def rolling_sum(w, ar):
new_ar = np.zeros(len(ar))
for i in range(len(ar)):
if i >= w and i <= len(ar)-w-1:
new_ar[i] = np.mean(ar[i-w:i+w+1])
elif i < w:
new_ar[i] = np.mean(ar[0:i+1])
elif i > len(ar)-w-1:
new_ar[i] = np.mean(ar[i:len(ar)+1])
assert len(new_ar) == len(ar)
return new_ar
def subtract_rolling_sum(w, ar):
return ar - rolling_sum(w,ar)
def return_int_pnts(num, rgb, x1, y1, x2, y2):
x_vals = np.round(np.linspace(x1, x2, num=num, endpoint=True))
x_vals = x_vals.astype(int)
y_vals = np.round(np.linspace(y1, y2, num=num, endpoint=True))
y_vals = y_vals.astype(int)
# one of these two must not contain any duplicates
assert len(x_vals) == len(set(x_vals)) or len(y_vals) == len(set(y_vals))
# Return RGB values
return_array = [rgb[y,x,0:3] for x,y in zip(x_vals, y_vals)]
# make all red
# for x,y in zip(x_vals, y_vals):
# rgb[y,x,0:3] = 255, 0, 0
return x_vals, y_vals, rgb, return_array
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,243
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/src/__init__.py
|
from .mouse_actions import get_goban_corners, str_to_integer_coordinates
from .mouse_actions import int_coords_to_screen_coordinates, make_the_move
from .mouse_actions import int_coords_to_str
from .screenshot_actions import KGS_goban_rgb_screenshot, get_digital_goban_state
from .picture_actions import plot_goban_rgb, average_RGB, make_indices_agree
from .picture_actions import return_int_pnts, subtract_rolling_sum
from .picture_actions import rolling_sum, find_custom_local_minima
from .picture_actions import mark_board_points, is_this_stone_on_the_board
from .picture_actions import mark_stones, calibrate
from .picture_actions import find_board_points, rescale_pyhsical_goban_rgb
from .picture_actions import get_pyhsical_board_outer_corners
from .picture_actions import convert_physical_board_ij_to_str
from .picture_actions import play_next_move_on_digital_board, scan_next_move
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,244
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/tests/test_picture_actions.py
|
import pytest
import imageio
import sys, os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import src
# stones - upper-left corner is (1,1), lower-left corner is (19,1)
IMG_PATH = ['images/pyshical_goban_pic1.png', 'images/pyshical_goban_pic2.png', \
'images/pyshical_goban_pic3.png', 'images/pyshical_goban_pic4.png', \
'images/pyshical_goban_pic5.png']
bxy0, wxy0 = [(4,4), (16,4)], [(4,16),(16,16)]
bxy1, wxy1 = [(1,9), (16,8)], [(10,1),(13,19)]
bxy2, wxy2 = [(1,19), (17,3)], [(1,3),(19,19)]
bxy3, wxy3 = [(1,19), (19,1), (5,4), (6,16), (12,8), (14,6), (16,10), (19,13)], \
[(1,1), (4,10), (7,7), (10,4), (10,10), (12,11), (15,7), (19,19)]
bxy4, wxy4 = [(1,1), (19,19), (1,19), (19,1)], [(10,10)]
UL_outer_x0, UL_outer_y0 = 315, 24
UR_outer_x0, UR_outer_y0 = 999, 40
BL_outer_x0, BL_outer_y0 = 3, 585
BR_outer_x0, BR_outer_y0 = 1273, 621
UL_outer_x3, UL_outer_y3 = 321, 235
UR_outer_x3, UR_outer_y3 = 793, 244
BL_outer_x3, BL_outer_y3 = 92, 603
BR_outer_x3, BR_outer_y3 = 933, 608
UL_outer_x4, UL_outer_y4 = 414, 256
UR_outer_x4, UR_outer_y4 = 962, 269
BL_outer_x4, BL_outer_y4 = 217, 659
BR_outer_x4, BR_outer_y4 = 1211, 679
@pytest.mark.skip
def test_board_outer_corner():
UL_outer_x0_click, UL_outer_y0_click, _, _, _, _, _, _ = \
src.get_pyhsical_board_outer_corners(IMG_PATH[0])
assert abs(UL_outer_x0_click - UL_outer_x0) < 5 # five pixels
assert abs(UL_outer_y0_click - UL_outer_y0) < 5
def test_board_state_detection_from_camera_picture():
assert_board_state(IMG_PATH[4], bxy4, wxy4, 'black', bxy4[0], \
UL_outer_x4, UL_outer_y4, UR_outer_x4, UR_outer_y4, \
BL_outer_x4, BL_outer_y4, BR_outer_x4, BR_outer_y4, \
plot_stuff=False)
assert_board_state(IMG_PATH[0], bxy0, wxy0, 'black', bxy0[1], \
UL_outer_x0, UL_outer_y0, UR_outer_x0, UR_outer_y0, \
BL_outer_x0, BL_outer_y0, BR_outer_x0, BR_outer_y0)
assert_board_state(IMG_PATH[1], bxy1, wxy1, 'white', wxy1[0], \
UL_outer_x0, UL_outer_y0, UR_outer_x0, UR_outer_y0, \
BL_outer_x0, BL_outer_y0, BR_outer_x0, BR_outer_y0, \
plot_stuff=True)
assert_board_state(IMG_PATH[2], bxy2, wxy2, 'black', bxy2[0], \
UL_outer_x0, UL_outer_y0, UR_outer_x0, UR_outer_y0, \
BL_outer_x0, BL_outer_y0, BR_outer_x0, BR_outer_y0)
assert_board_state(IMG_PATH[3], bxy3, wxy3, 'white', wxy3[6], \
UL_outer_x3, UL_outer_y3, UR_outer_x3, UR_outer_y3, \
BL_outer_x3, BL_outer_y3, BR_outer_x3, BR_outer_y3)
def assert_board_state(IMG_PATH, bxy, wxy, color, ij_pair, \
UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y, \
plot_stuff=False):
# Get RGB matrix of the picture with goban
rgb = imageio.imread(IMG_PATH)
# Remove non-goban part from the RGB matrix and make it a square matrix
rgb = src.rescale_pyhsical_goban_rgb(rgb, \
UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y)
# Find the indices of board points in the new square RGB matrix
x_idx, y_idx = src.find_board_points(rgb, plot_stuff=plot_stuff)
# Find color thresholds for stone detection
red_scale_th, blue_scale_th = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
# Refind stones using the above thresholds
bxy_new, wxy_new = src.mark_stones(rgb, x_idx, y_idx, \
red_scale_th, blue_scale_th, plot_stuff=plot_stuff)
assert set(bxy) == set(bxy_new)
assert set(wxy) == set(wxy_new)
assert src.is_this_stone_on_the_board(rgb, x_idx, y_idx, \
red_scale_th, blue_scale_th, color, ij_pair[0], ij_pair[1], \
plot_stuff=True)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,245
|
folmez/Handsfree-KGS
|
refs/heads/master
|
/temp/process_pyhsical_goban_pic.py
|
import matplotlib.pyplot as plt
import imageio
import numpy as np
import src
IMG_PATH = 'images/pyshical_goban_pic1.png'
#IMG_PATH = 'images/pyshical_goban_pic2.png'
#IMG_PATH = 'images/pyshical_goban_pic3.png'
UL_outer_x, UL_outer_y = 315, 24
UR_outer_x, UR_outer_y = 999, 40
BL_outer_x, BL_outer_y = 3, 585
BR_outer_x, BR_outer_y = 1273, 621
#IMG_PATH = 'images/pyshical_goban_pic4.png'
#UL_outer_x, UL_outer_y = 321, 235
#UR_outer_x, UR_outer_y = 793, 244
#BL_outer_x, BL_outer_y = 92, 603
#BR_outer_x, BR_outer_y = 933, 608
# Get RGB matrix of the picture with goban
rgb = imageio.imread(IMG_PATH)
plt.imshow(rgb)
plt.show()
# Remove non-goban part from the RGB matrix and make it a square matrix
rgb = src.rescale_pyhsical_goban_rgb(rgb, \
UL_outer_x, UL_outer_y, UR_outer_x, UR_outer_y, \
BL_outer_x, BL_outer_y, BR_outer_x, BR_outer_y)
# Find the indices of board points in the new square RGB matrix
x_idx, y_idx = src.find_board_points(rgb, plot_stuff=True)
bxy, wxy = [(4,4), (16,4)], [(4,16),(16,16)]
src.mark_board_points(rgb, x_idx, y_idx, bxy, wxy)
red_scale_th, blue_scale_th = src.calibrate(rgb, x_idx, y_idx, bxy, wxy)
bxy_new, wxy_new = src.mark_stones(rgb, x_idx, y_idx, red_scale_th, blue_scale_th)
src.is_this_stone_on_the_board(rgb, x_idx, y_idx, red_scale_th, blue_scale_th, \
'black', 16,4)
|
{"/play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_screenshot_actions.py": ["/src/__init__.py"], "/src/mouse_actions.py": ["/src/__init__.py"], "/make_goban_speak.py": ["/src/__init__.py"], "/src/screenshot_actions.py": ["/src/__init__.py"], "/auto_goban_detection.py": ["/src/__init__.py"], "/tests/test_play_handsfree_GO.py": ["/src/__init__.py"], "/tests/test_mouse_actions.py": ["/src/__init__.py"], "/src/picture_actions.py": ["/src/__init__.py"], "/src/__init__.py": ["/src/mouse_actions.py", "/src/screenshot_actions.py", "/src/picture_actions.py"], "/tests/test_picture_actions.py": ["/src/__init__.py"], "/temp/process_pyhsical_goban_pic.py": ["/src/__init__.py"]}
|
1,249
|
KAcee77/django_sputnik_map
|
refs/heads/main
|
/django_sputnik_maps/apps.py
|
from django.apps import AppConfig
class DjangoSputnikMapsConfig(AppConfig):
name = 'django_sputnik_maps'
|
{"/sample/models.py": ["/django_sputnik_maps/fields.py"], "/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/fields.py", "/django_sputnik_maps/widgets.py", "/sample/models.py"]}
|
1,250
|
KAcee77/django_sputnik_map
|
refs/heads/main
|
/django_sputnik_maps/widgets.py
|
from django.conf import settings
from django.forms import widgets
class AddressWidget(widgets.TextInput):
'''a map will be drawn after the address field'''
template_name = 'django_sputnik_maps/widgets/mapwidget.html'
class Media:
css = {
'all': ('https://unpkg.com/leaflet@1.0.1/dist/leaflet.css',
settings.STATIC_URL + 'django_sputnik_maps/css/jquery-ui.min.css',
settings.STATIC_URL + 'django_sputnik_maps/css/base.css',)
}
js=(
"https://unpkg.com/leaflet@1.0.1/dist/leaflet.js",
settings.STATIC_URL + 'django_sputnik_maps/js/base.js',
settings.STATIC_URL + 'django_sputnik_maps/js/jquery-3.5.1.js',
settings.STATIC_URL + 'django_sputnik_maps/js/jquery-ui.min.js',
)
|
{"/sample/models.py": ["/django_sputnik_maps/fields.py"], "/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/fields.py", "/django_sputnik_maps/widgets.py", "/sample/models.py"]}
|
1,251
|
KAcee77/django_sputnik_map
|
refs/heads/main
|
/sample/models.py
|
from django.db import models
from django_sputnik_maps.fields import AddressField
# all fields must be present in the model
class SampleModel(models.Model):
region = models.CharField(max_length=100)
place = models.CharField(max_length=100)
street = models.CharField(max_length=100)
house = models.IntegerField()
lat = models.FloatField()
lon = models.FloatField()
address = AddressField(max_length=200)
|
{"/sample/models.py": ["/django_sputnik_maps/fields.py"], "/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/fields.py", "/django_sputnik_maps/widgets.py", "/sample/models.py"]}
|
1,252
|
KAcee77/django_sputnik_map
|
refs/heads/main
|
/django_sputnik_maps/fields.py
|
from django.db import models
class AddressField(models.CharField):
pass
|
{"/sample/models.py": ["/django_sputnik_maps/fields.py"], "/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/fields.py", "/django_sputnik_maps/widgets.py", "/sample/models.py"]}
|
1,253
|
KAcee77/django_sputnik_map
|
refs/heads/main
|
/django_sputnik_maps/__init__.py
|
from .widgets import AddressWidget
|
{"/sample/models.py": ["/django_sputnik_maps/fields.py"], "/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/fields.py", "/django_sputnik_maps/widgets.py", "/sample/models.py"]}
|
1,254
|
KAcee77/django_sputnik_map
|
refs/heads/main
|
/sample/admin.py
|
# from django.db import models
from django.contrib import admin
from django_sputnik_maps.fields import AddressField
from django_sputnik_maps.widgets import AddressWidget
from .models import SampleModel
@admin.register(SampleModel)
class SampleModelAdmin(admin.ModelAdmin):
formfield_overrides = {
AddressField: {
'widget': AddressWidget
}
}
|
{"/sample/models.py": ["/django_sputnik_maps/fields.py"], "/django_sputnik_maps/__init__.py": ["/django_sputnik_maps/widgets.py"], "/sample/admin.py": ["/django_sputnik_maps/fields.py", "/django_sputnik_maps/widgets.py", "/sample/models.py"]}
|
1,255
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/listsss/apps.py
|
from django.apps import AppConfig
class ListsssConfig(AppConfig):
name = 'listsss'
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,256
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/test/listsss/tests_views.py
|
from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from django.utils.html import escape
from listsss.models import Item, List
from listsss.views import home_page
import unittest
# Create your tests here.
class HomePageTest(TestCase):
def test_root_url_resolves_to_home_page_view(self):
print("第x个测试通过了")
found = resolve('/')
self.assertEqual(found.func, home_page)
def test_home_page_return_correct_html(self):
request = HttpRequest()
resp = home_page(request)
# 使用render_to_string ,django自带函数 生成string字符串,和渲染获取到的字符串对比
#### 注释:这个没有办法解决,两次生成得tocken值是不相同的,所以先注释掉这个字段对应的断言
expected_html = render_to_string('listsss/home.html', request=request)
# .decode()将字符串转换成unicode
# self.assertEqual(resp.content.decode(), expected_html)
# self.assertTrue(resp.content.startswith(b'<html>'))
self.assertIn(b"<title>To-Do lists</title>", resp.content)
self.assertTrue(resp.content.endswith(b'</html>'))
# def test_home_page_only_saves_items_when_necessary(self):
# request = HttpRequest()
# home_page(request)
# self.assertEqual(Item.objects.count(), 0)
# 中途这个用例不要了
# def test_home_page_displays_all_list_items(self):
# Item.objects.create(text='itemey 1')
# Item.objects.create(text='itemey 2')
#
# req = HttpRequest()
# rep = home_page(req)
#
# self.assertIn('itemey 1', rep.content.decode())
# self.assertIn('itemey 2', rep.content.decode())
class ListViewTest(TestCase):
# def test_home_page_displays_all_list_items(self):
def test_home_page_displays_only_items_for_that_list(self):
# list_ = List.objects.create()
# Item.objects.create(text='itemey 1', list=list_)
# Item.objects.create(text='itemey 2', list=list_)
correct_list = List.objects.create()
Item.objects.create(text='itemey 1', list=correct_list)
Item.objects.create(text='itemey 2', list=correct_list)
other_list = List.objects.create()
Item.objects.create(text='other itemey 1', list=other_list)
Item.objects.create(text='other itemey 2', list=other_list)
# resp = self.client.get('/list/the-only-list-in-the-world/')
resp = self.client.get('/list/%d/' % (correct_list.id,))
self.assertContains(resp, 'itemey 1')
self.assertContains(resp, 'itemey 2')
self.assertNotContains(resp, 'other itemey 1')
self.assertNotContains(resp, 'other itemey 2')
def test_uses_list_template(self):
# resp = self.client.get('/list/the-only-list-in-the-world/')
list_ = List.objects.create()
resp = self.client.get('/list/%d/' % (list_.id,))
self.assertTemplateUsed(resp, 'listsss/list.html')
def test_passes_correct_list_to_template(self):
other_list = List.objects.create()
correct_list = List.objects.create()
resp = self.client.get('/list/%d/' % (correct_list.id,))
self.assertEqual(resp.context['list'], correct_list)
def test_can_save_a_POST_to_an_existing_list(self):
other_list = List.objects.create()
correct_list = List.objects.create()
self.client.post('/list/%d/' % (correct_list.id,),
data={'item_text': 'A new item for an existiong list'})
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new item for an existiong list')
self.assertEqual(new_item.list, correct_list)
def test_POST_redirects_to_list_view(self):
other_list = List.objects.create()
correct_list = List.objects.create()
resp = self.client.post('/list/%d/' % (correct_list.id,),
data={'item_text': 'A new item for an existiong list'})
self.assertRedirects(resp, '/list/%d/' % (correct_list.id,))
def test_validation_errors_end_up_on_lists_page(self):
list_ = List.objects.create()
resp = self.client.post('/list/%d/'%(list_.id,), data={"item_text":''})
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed(resp, 'listsss/list.html')
ex_error=escape('You cant have an empty list item')
self.assertContains(resp, ex_error)
class NewListTest(TestCase):
def test_saving_a_POST_request(self):
self.client.post('/list/new', data={'item_text': 'A new list item'})
self.assertEqual(Item.objects.count(), 1)
new_item = Item.objects.first()
self.assertEqual(new_item.text, 'A new list item')
# requ = HttpRequest()
# requ.method = 'POST'
# requ.POST['item_text'] = 'A new list item'
#
# rep = home_page(requ)
#
# self.assertEqual(Item.objects.count(), 1)
# new_item = Item.objects.first()
# self.assertEqual(new_item.text, 'A new list item')
#
# # 下面这部分单独拿出去做一个 单独的单元测试
# # self.assertIn('A new list item', rep.content.decode())
# # post 请求后页面重定向
# # self.assertEqual(rep.status_code, 302)
# # self.assertEqual(rep['location'], '/')
def test_redirects_after_POST(self):
rep = self.client.post('/list/new', data={'item_text': 'A new list item'})
# self.assertEqual(rep.status_code, 302)
new_list = List.objects.first()
self.assertRedirects(rep, '/list/%d/' % (new_list.id,))
# django 的检查项
# self.assertRedirects(rep, '/list/the-only-list-in-the-world/')
# 这段重新修改
# requ = HttpRequest()
# requ.method = 'POST'
# requ.POST['item_text'] = 'A new list item'
#
# rep = home_page(requ)
# self.assertEqual(rep.status_code, 302)
# self.assertEqual(rep['location'], '/list/the-only-list-in-the-world/')
def test_validation_error_are_sent_back_to_home_page_template(self):
resp = self.client.post('/list/new', data={'item_text': ''})
self.assertEqual(resp.status_code, 200)
self.assertTemplateUsed(resp, 'listsss/home.html')
ex_error = escape("You cant have an empty list item")
print(resp.content.decode())
self.assertContains(resp, ex_error)
def test_invalid_list_items_arent_saved(self):
self.client.post('/list/new', data={"item_text": ''})
self.assertEqual(List.objects.count(), 0)
self.assertEqual(Item.objects.count(), 0)
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,257
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/functional_tests/base.py
|
# -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import unittest
from unittest import skip
class FunctionalTest(StaticLiveServerTestCase):
#不知道为什么加上下面两个方法之后就报错了
# @classmethod
# def setUpClass(cls):
# pass
#
# @classmethod
# def tearDownClass(cls):
# pass
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(3)
def tearDown(self):
self.driver.quit()
def check_for_row_in_list_table(self, row_text):
table = self.driver.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
self.assertIn(row_text, [row.text for row in rows])
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,258
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/test/listsss/tests_models.py
|
from django.test import TestCase
from django.urls import resolve
from django.http import HttpRequest
from django.template.loader import render_to_string
from listsss.models import Item, List
from listsss.views import home_page
import unittest
from django.core.exceptions import ValidationError
class ListAndItemModelsTest(TestCase):
def test_saving_and_retrieving_items(self):
list_ = List()
list_.save()
first_item = Item()
first_item.text = 'The first (ever) list item'
first_item.list = list_
first_item.save()
second_item = Item()
second_item.text = 'Item the second'
second_item.list = list_
second_item.save()
saved_liat = List.objects.first()
self.assertEqual(saved_liat, list_)
saved_items = Item.objects.all()
self.assertEqual(saved_items.count(), 2)
first_save_item = saved_items[0]
second_save_item = saved_items[1]
self.assertEqual(first_save_item.text, 'The first (ever) list item')
self.assertEqual(first_save_item.list, list_)
self.assertEqual(second_save_item.text, 'Item the second')
self.assertEqual(second_save_item.list, list_)
def test_cannot_save_empty_list_items(self):
list_=List.objects.create()
item = Item(list= list_, text='')
with self.assertRaises(ValidationError):
item.save()
item.full_clean()
def test_get_absolute_url(self):
list_ = List.objects.create()
self.assertEqual(list_.get_absolute_url(), '/list/%d/'%(list_.id,))
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,259
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/listsss/views.py
|
from django.shortcuts import render, redirect # redirect是python的重定向方法
from django.http import HttpResponse
from listsss.models import Item, List
from django.core.exceptions import ValidationError
# Create your views here.
def home_page(request):
# return HttpResponse("<html><title>To-Do lists</title></html>")
# if (request.method=='POST'):
# return HttpResponse(request.POST['item_text'])
# 新加了页面这里就可以删除了
# if (request.method == 'POST'):
# new_item_text = request.POST['item_text']
# Item.objects.create(text=new_item_text)
# return redirect('/list/the-only-list-in-the-world/')
##第二种方法
# else:
# new_item_text = ''
# return render(request, 'listsss/home.html', {'new_item_text':new_item_text})
##第一种方法
# item = Item()
# item.text = request.POST.get('item_text', '')
# item.save()
# return render(request, 'listsss/home.html', {'new_item_text':request.POST.get('item_text','')})
# 这里首页不用展示相关的数据了
# items_list = Item.objects.all()
# return render(request, 'listsss/home.html', {'items_list': items_list})
return render(request, 'listsss/home.html')
def view_list(request, list_id):
error = None
list_ = List.objects.get(id=list_id)
if request.method == 'POST':
try:
item = Item.objects.create(text=request.POST['item_text'], list=list_)
item.full_clean()
item.save()
#简化
#return redirect('/list/%d/' % (list_.id,))
return redirect(list_)
except ValidationError:
item.delete() # 不知道为什么要加这一步,书里面没有这步骤,书上说抓取到这个错误就不会存到数据库里面了,可还是存进去了
error = 'You cant have an empty list item'
return render(request, 'listsss/list.html', {'list': list_, 'error': error})
def new_list(request):
list_ = List.objects.create()
item = Item.objects.create(text=request.POST['item_text'], list=list_)
try:
item.full_clean()
item.save()
except ValidationError:
list_.delete()
item.delete() # 不知道为什么要加这一步,书里面没有这步骤,书上说抓取到这个错误就不会存到数据库里面了,可还是存进去了
error = 'You cant have an empty list item'
return render(request, 'listsss/home.html', {"error": error})
# 重新定义到有效地址
# return redirect('/list/the-only-list-in-the-world/')
# 去除硬编码
# return redirect('/list/%d/' % (list_.id,))
return redirect('view_list', list_.id)
def add_item(request, list_id):
list_ = List.objects.get(id=list_id)
Item.objects.create(text=request.POST['item_text'], list=list_)
return redirect('/list/%d/' % (list_.id,))
class home_page_class():
pass
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,260
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/functional_tests/test_simple_list_creation.py
|
# -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import unittest
from unittest import skip
from .base import FunctionalTest
class NewVisitorTest(FunctionalTest):
def test_can_start_a_list_and_retrieve_it_later(self):
# 类继承LiveServerTestCase 后将不使用实际部署的localhost 地址,使用 django提供的self.live_server_url地址
# self.driver.get("http://localhost:8000")
self.driver.get(self.live_server_url)
# 发现页面上显示的 TO-DO 字样
self.assertIn('To-Do', self.driver.title)
header_text = self.driver.find_element_by_tag_name('h1').text
self.assertIn('To-Do', header_text)
# 应用邀请输入一个代办事项
inputbox = self.driver.find_element_by_id('id_new_item')
self.assertEqual(inputbox.get_attribute('placeholder'), 'Enter a to-do item')
# 在输入框中输入购买孔雀羽毛
inputbox.send_keys('Buy peacock feathers')
# 点击回车后页面更新
# 代办事项中显示 ‘1:Buy peacock feathers’
inputbox.send_keys(Keys.ENTER)
edith_list_url = self.driver.current_url
self.assertRegex(edith_list_url, '/list/.+?')
table = self.driver.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
# self.assertTrue(any(row.text == '1:Buy peacock feathers' for row in rows), 'New to-do item did not appear in table - - its text was:\n%s' % (table.text))
# 页面又显示了一个文本框,可以输入其他代办事项
# 输入‘Use peacock feathers to make a fly’
inputbox = self.driver.find_element_by_id('id_new_item')
inputbox.send_keys('Use peacock feathers to make a fly')
inputbox.send_keys(Keys.ENTER)
table = self.driver.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
self.assertIn('1:Buy peacock feathers', [row.text for row in rows])
self.assertIn('2:Use peacock feathers to make a fly', [row.text for row in rows])
##我们需要新打开一个浏览器,并且不让cookice相互干扰
# 让录入的清单不会被别人看到
self.driver.quit()
# 其他人访问页面看不到刚才录入的清单
self.driver = webdriver.Firefox()
self.driver.get(self.live_server_url)
page_text = self.driver.find_element_by_tag_name('body').text
self.assertNotIn('Buy peacock feathers', page_text)
self.assertNotIn('make a fly', page_text)
# 他输入了新的代办事项,创建了一个新的代办清单
inputbox = self.driver.find_element_by_id('id_new_item')
inputbox.send_keys('Buy milk')
inputbox.send_keys(Keys.ENTER)
# 他获得了一个属于他自己的url
francis_list_url = self.driver.current_url
self.assertRegex(edith_list_url, '/list/.+?')
self.assertNotEquals(francis_list_url, edith_list_url)
# 这个页面还是没有其他人的清单
# 但是这个页面包含他自己的清单
page_text = self.driver.find_element_by_tag_name('body').text
self.assertNotIn('Buy peacock feathers', page_text)
self.assertIn('Buy milk', page_text)
# self.fail('Finisth the test')
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,261
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/functional_tests/tests_layout_and_styling.py
|
# -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import unittest
from unittest import skip
from .base import FunctionalTest
class LayoutAndStylingTest(FunctionalTest):
def test_layout_and_styling(self):
self.driver.get(self.live_server_url)
self.driver.set_window_size(1024, 768)
# 查看页面元素居中
inputbox = self.driver.find_element_by_id('id_new_item')
self.assertAlmostEqual(inputbox.location['x'] + inputbox.size['width'] / 2, 512, delta=10)
# 保存成功后,清单列表的输入框也居中
inputbox.send_keys('testing')
inputbox.send_keys(Keys.ENTER)
inputbox = self.driver.find_element_by_id('id_new_item')
self.assertAlmostEqual(inputbox.location['x'] + inputbox.size['width'] / 2, 512, delta=10)
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,262
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/functional_tests/tests_list_item_validation.py
|
# -*- coding: utf-8 -*-
# @Time : 2018/6/25 20:15
# @Author : Mat
# @Email : mat_wu@163.com
# @File : functional_tests1.py
# @Software: PyCharm
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
import unittest
from unittest import skip
from .base import FunctionalTest
class ItemValidationTest(FunctionalTest):
def test_cannot_add_empty_list_items(self):
self.driver.get(self.live_server_url)
self.driver.find_element_by_id('id_new_item').send_keys('\n')
error = self.driver.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You cant have an empty list item")
self.driver.find_element_by_id('id_new_item').send_keys('Buy milk\n')
self.check_for_row_in_list_table('1:Buy milk')
self.driver.find_element_by_id('id_new_item').send_keys('\n')
self.check_for_row_in_list_table('1:Buy milk')
error = self.driver.find_element_by_css_selector('.has-error')
self.assertEqual(error.text, "You cant have an empty list item")
self.driver.find_element_by_id('id_new_item').send_keys('Buy tea\n')
self.check_for_row_in_list_table('1:Buy milk')
self.check_for_row_in_list_table('2:Buy tea')
self.fail("write me!")
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,263
|
liuchao012/myPythonWeb
|
refs/heads/master
|
/functional_tests/__init__.py
|
# -*- coding: utf-8 -*-
# @Time : 2018/6/28 17:06
# @Author : Mat
# @Email : mat_wu@163.com
# @File : __init__.py.py
# @Software: PyCharm
'''
functional_tests,中的文件需要已tests开头系统命令才能读取到测试用例并执行测试
测试执行命令python manage.py test functional_tests,来完成功能测试
如果执行 python manage.py test 那么django 将会执行 功能测试和单元测试
如果想只运行单元测试则需要执行固定的app ,python manage.py test listsss
'''
|
{"/test/listsss/tests_views.py": ["/listsss/views.py"], "/test/listsss/tests_models.py": ["/listsss/views.py"], "/functional_tests/test_simple_list_creation.py": ["/functional_tests/base.py"], "/functional_tests/tests_layout_and_styling.py": ["/functional_tests/base.py"], "/functional_tests/tests_list_item_validation.py": ["/functional_tests/base.py"]}
|
1,265
|
strawberryblackhole/hippopotamus
|
refs/heads/master
|
/fillWithWiki.py
|
from htmlParser import getFormatedArticle
from chunkGenerator import *
from ZIMply.zimply import ZIMFile
from os import path
import math
import time
import argparse
from amulet.world_interface import load_world
def generateChunkList(totalArticleCount, chunkBookCapacity, target_pos, outputForceload = False):
#generate a square, that could fit (more than) all articles
sideLength = math.ceil(math.sqrt(totalArticleCount/chunkBookCapacity))
if outputForceload:
command = "/chunkgenerator:generatechunks %d %d %d %d"%(target_pos[0] - 1, target_pos[1] - 1, target_pos[0] + sideLength + 1, target_pos[1] + sideLength + 1)#+- 1 to include the outer border of the library
print(command)
return
chunkList = []
for x in range(sideLength):
for z in range(sideLength):
if len(chunkList) >= math.ceil(totalArticleCount/chunkBookCapacity): #stop if we have enough chunks
break
chunkList.append([x + target_pos[0] // 16, z + target_pos[1] // 16])
return chunkList
def generateWallList(chunkList):
wallChunkWithSlice = []
for chunk in chunkList:
#create chunk slices for the 4 chunks that would have walls to the center chunk
potentialWalls = []
potentialWalls.append([[1,0], [0, slice(0,16)]])
potentialWalls.append([[0,1], [slice(0,16), 0]])
potentialWalls.append([[-1,0], [15, slice(0,16)]])
potentialWalls.append([[0,-1], [slice(0,16), 15]])
#turn its local coordinates into world coordinates
for potWall in potentialWalls:
potWall[0][0] += chunk[0]
potWall[0][1] += chunk[1]
#only keep the wallchunk if its not in use
for potWall in potentialWalls:
if potWall[0] in chunkList:
continue
wallChunkWithSlice.append(potWall)
return wallChunkWithSlice
def getLastArticleId(zimfile):
article = None
for article in zimfile:
pass
return article[2]
def fill( booksPerBarrel,
position,
world = False,
dimension = "overworld",
skipChunk = 0,
skipArticles = 0,
filePath = "",
totalArticleCount = -1):
zimfile = ZIMFile(filePath,"utf-8")
if totalArticleCount == -1:
totalArticleCount = getLastArticleId(zimfile)
print("Article count: ", totalArticleCount)
barrelPositionList = generateBarrelPositionList()
barrelsPerChunk = len(barrelPositionList)
chunkBookCapacity = barrelsPerChunk * booksPerBarrel
chunkList = generateChunkList(totalArticleCount, chunkBookCapacity, position, world == False)
if world:
wallChunkList = generateWallList(chunkList)
totalChunkCount = len(chunkList) + len(wallChunkList)
completedChunks = 0
currentArticle = skipArticles
for chunkCoords in chunkList:
if skipChunk > 0:
skipChunk -= 1
completedChunks += 1
currentArticle += booksPerBarrel * barrelsPerChunk
continue
start = time.perf_counter()
worldObj = load_world(path.expandvars(world))
chunk = worldObj.get_chunk(chunkCoords[0], chunkCoords[1], dimension)
fillChunk(chunk, barrelPositionList, worldObj, dimension, currentArticle, booksPerBarrel, filePath, chunkList, position)
currentArticle += booksPerBarrel * barrelsPerChunk
worldObj.create_undo_point()#workaround suggested by amulet team so that saving works (can possibly be removed in the future)
worldObj.save()
worldObj.close()
completedChunks += 1
print("chunk time (m): ", (time.perf_counter() - start)/60)
print("completed chunk: ", completedChunks)
yield 100 * completedChunks / totalChunkCount
for wallChunkCoords, orientation in wallChunkList:
chunk = worldObj.get_chunk(wallChunkCoords[0], wallChunkCoords[1], dimension)
placeWall(chunk, orientation, worldObj)
completedChunks += 1
yield 100 * completedChunks / totalChunkCount
worldObj.create_undo_point()#workaround suggested by amulet team so that saving works (can possibly be removed in the future)
worldObj.save()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Puts a wiki into a Minecraft world')
parser.add_argument('-wiki', type=str, help='Location of the wiki file')
parser.add_argument('-world', type=str, help='Location of the world file. You may use %%APPDATA%%')
parser.add_argument('-booksPerBarrel', type=int, help='Number of books to put in a barrel', default=27)
parser.add_argument('-chunkSkip', type=int, help='Number of chunks to skip', default=0)
parser.add_argument('-articleCount', type=int, help='If the number of articles was counted before, specifying this can save startup time', default=-1)
parser.add_argument('-pos', metavar=("X","Z"),type=int, help='X Z coordinates of the starting chunk (block coordinates)', default=[0,0], nargs=2)
args = parser.parse_args()
#debug vars
bookSkip = 0
args.world = '%APPDATA%\\.minecraft\\saves\\loadedWorld\\'
args.chunkSkip = 5
args.booksPerBarrel = 50
args.pos = [0,0]
#args.wiki = path.dirname(path.realpath(__file__)) + "\\wikipedia_de_chemistry_nopic_2020-04.zim"
#args.articleCount = ????
args.wiki = path.dirname(path.realpath(__file__)) + "\\wikipedia_de_all_nopic_2020-04.zim"
#args.articleCount = 3979758
if args.world is not None:
for progress in fill(args.booksPerBarrel,
args.pos,
world = args.world,
skipArticles = bookSkip,
skipChunk = args.chunkSkip,
filePath = args.wiki,
totalArticleCount = args.articleCount):
print(progress)
else:
for progress in fill(args.booksPerBarrel,
args.pos,
world = False,
skipArticles = bookSkip,
skipChunk = args.chunkSkip,
filePath = args.wiki):
pass
|
{"/fillWithWiki.py": ["/htmlParser.py", "/chunkGenerator.py"], "/chunkGenerator.py": ["/htmlParser.py"], "/parserTester.py": ["/fillWithWiki.py"]}
|
1,266
|
strawberryblackhole/hippopotamus
|
refs/heads/master
|
/chunkGenerator.py
|
from amulet.api.block import Block
import amulet_nbt
from amulet.api.block_entity import BlockEntity
from htmlParser import getFormatedArticle
from functools import partial
import multiprocessing
from multiprocessing.pool import Pool
from multiprocessing.pool import ThreadPool
from ZIMply.zimply import ZIMFile
import time
import re
import json
def getBlock(world, block):
"""turns a block object into a usable block object, no idea what this actually does"""
tmp = world.world_wrapper.translation_manager.get_version(
"java",
(1, 15, 2)
).block.to_universal(
block
)[0]
return world.palette.get_add_block(tmp)
def createBlocks(world):
"""generates all needed Block objects"""
barrel = getBlock(world, Block("minecraft", "barrel", {"facing" : amulet_nbt.TAG_String("up"), "open" : amulet_nbt.TAG_String("false")}))
wool = getBlock(world, Block("minecraft", "red_wool"))
air = getBlock(world, Block("minecraft", "air"))
stone = getBlock(world, Block("minecraft", "stone"))
glowstone = getBlock(world, Block("minecraft", "glowstone"))
lantern = getBlock(world, Block("minecraft", "lantern", {"hanging" : amulet_nbt.TAG_String("false")}))
sign_north = getBlock(world, Block("minecraft", "acacia_wall_sign", {"facing" : amulet_nbt.TAG_String("north")}))
sign_south = getBlock(world, Block("minecraft", "acacia_wall_sign", {"facing" : amulet_nbt.TAG_String("south")}))
return [barrel, wool, glowstone, sign_north, sign_south, air, stone, lantern]
def generateBarrelPositionList():
"""Generates a list of coordinates in a chunk (16x16) where barrels should be"""
barrels = []
for row in [0,8]:
for y in range(5,7):
for x in range(1,8,2):
subList = [(x, y, z) for z in range(1 + row, 7 + row)]
barrels.extend(subList)
for x in range(8,15,2):
subList = [(x, y, z) for z in range(1 + row, 7 + row)]
barrels.extend(subList)
return barrels
def generateSignEntity(x, y, z, direction):
"""Generates the entity to make the sign display its position"""
return BlockEntity("java", "acacia_wall_sign", x, y, z,\
amulet_nbt.NBTFile(\
value = amulet_nbt.TAG_Compound(\
{\
"utags": amulet_nbt.TAG_Compound(\
{\
"keepPacked": amulet_nbt.TAG_Byte(0),\
"Text4": amulet_nbt.TAG_String("{\"text\":\"\"}"),\
"Text3": amulet_nbt.TAG_String("{\"text\":\"\"}"),\
"Text2": amulet_nbt.TAG_String("{\"text\":\"%d - %d\"}"%(z + direction, z + direction * 6)), \
"Text1": amulet_nbt.TAG_String("{\"text\":\"%d\"}"%x)\
}),\
"Color": amulet_nbt.TAG_String("black")\
})))
def fillSigns(chunk, world, dimension, sign_north, sign_south):
"""Generates all signs in the chunk and fills them with text"""
for z in [0, 8]:
for x in list(range(1,8,2)) + list(range(8,15,2)):
chunk.blocks[x,6,z] = sign_north
chunk.block_entities.insert(generateSignEntity(x + chunk.cx * 16, 6, z + chunk.cz * 16, 1))
for z in [7, 15]:
for x in list(range(1,8,2)) + list(range(8,15,2)):
chunk.blocks[x,6,z] = sign_south
chunk.block_entities.insert(generateSignEntity(x + chunk.cx * 16, 6, z + chunk.cz * 16, -1))
def fillbarrels(chunk, barrelPositionList, barrelBlock, currentArticle, booksPerBarrel, zimFilePath, chunkList, target_pos):
"""Generates all barrels in the chunk and fills them with books/articles"""
for barrelPos in barrelPositionList:
books = []
titles = []
start = time.perf_counter()
if booksPerBarrel > 30:
pool = Pool(processes=4) #on my laptop ~4 processes was faster than any amount of threads (4 = logic core count)
else:
pool = ThreadPool(processes=3)#the article reading is mostly cpu limited, so going high on process count doesnt help
outputs = pool.map(partial(tryGetArticle, zimFilePath = zimFilePath, barrelPositionList = barrelPositionList, booksPerBarrel = booksPerBarrel, chunkList = chunkList, target_pos = target_pos), range(currentArticle,currentArticle + booksPerBarrel))
pool.close()
#outputs = []
#for id in range(currentArticle, currentArticle + booksPerBarrel):
# outputs.append(tryGetArticle(id, zimFilePath))
currentArticle += booksPerBarrel
for output in outputs:
if output[0] == None:
continue
titles.append(output[1])
books.append(output[0])
stop = time.perf_counter()
#print("generating a book", (stop-start)/booksPerBarrel)
chunk.blocks[barrelPos] = barrelBlock
barrelEntity = BlockEntity("java", "barrel", barrelPos[0] + chunk.cx * 16, barrelPos[1], barrelPos[2] + chunk.cz * 16,\
amulet_nbt.NBTFile(\
value = amulet_nbt.TAG_Compound(\
{\
"utags": amulet_nbt.TAG_Compound(\
{\
"keepPacked": amulet_nbt.TAG_Byte(0),\
"isMovable": amulet_nbt.TAG_Byte(1),\
"Findable": amulet_nbt.TAG_Byte(0),\
"CustomName": amulet_nbt.TAG_String("{\"text\":\"x:%d y:%d z:%d\"}"%(barrelPos[0] + chunk.cx * 16, barrelPos[1], barrelPos[2] + chunk.cz * 16)),\
"Items": amulet_nbt.TAG_List(\
value = [
amulet_nbt.TAG_Compound(\
{\
"Slot": amulet_nbt.TAG_Byte(iBook),\
"Count": amulet_nbt.TAG_Byte(1),\
"id": amulet_nbt.TAG_String("minecraft:written_book"),\
"tag": amulet_nbt.TAG_Compound(\
{
"pages": amulet_nbt.TAG_List(\
value=[amulet_nbt.TAG_String(page) for page in books[iBook]],\
list_data_type = 8\
),\
"title": amulet_nbt.TAG_String(titles[iBook]),\
"author": amulet_nbt.TAG_String("Pos: x:%d y:%d z:%d, ID: %d"%(barrelPos[0] + chunk.cx * 16, barrelPos[1], barrelPos[2] + chunk.cz * 16, currentArticle + iBook)),
})
})
for iBook in range(len(books))
], list_data_type = 9\
)
})\
})))
chunk.block_entities.insert(barrelEntity)
def tryGetArticle(id, zimFilePath, barrelPositionList, booksPerBarrel, chunkList, target_pos):
"""Tries to find the article with the given id, returns [False, False] if no article was found, else article and its title are returned"""
start = time.perf_counter()
zimFile = ZIMFile(zimFilePath,"utf-8")
stop = time.perf_counter()
#print("some overhead ", stop - start)
start = time.perf_counter()
article = zimFile._get_article_by_index(id, follow_redirect=False)
if article != None:
if article.mimetype == "text/html":
articleTitle, articleContent = getFormatedArticle(article.data.decode("utf-8"), zimFile, barrelPositionList, booksPerBarrel, chunkList, target_pos)
re_pattern = re.compile(u'[^\u0000-\uD7FF\uE000-\uFFFF]', re.UNICODE)
articleContent = [re_pattern.sub(u'\uFFFD', page).replace(u'\xa0', u' ') for page in articleContent] # seems like mc cant handle 💲. (found in the article about the $ sign), this lead me to the assumption, that mc cant handle any surrogate unicode pair. https://stackoverflow.com/questions/3220031/how-to-filter-or-replace-unicode-characters-that-would-take-more-than-3-bytes/3220210#3220210
stop = time.perf_counter()
#print("parsing ", stop - start)
return articleContent, json.dumps(article.url.replace(u'\xa0', u' '), ensure_ascii=False)[1:-1]
if article.is_redirect == True:
coordinates = getArticleLocationById(article.mimetype, barrelPositionList, booksPerBarrel, chunkList, target_pos)
return ["{\"text\":\"Redirect to article with ID %d at x:%d y:%d z:%d\"}"%tuple([id] + coordinates)], json.dumps(article.url.replace(u'\xa0', u' '), ensure_ascii=False)[1:-1]
return None, None
def getArticleLocationById(id, barrelPositionList, booksPerBarrel, chunkList, target_pos):
booksPerChunk = len(barrelPositionList) * booksPerBarrel
chunk = int(id) // booksPerChunk
bookNumberInChunk = (int(id) - chunk * booksPerChunk)
barrel = (bookNumberInChunk - 1)// booksPerBarrel #-1 because if booksNumberInChunk == booksPerBarrel, it should be 0
return [chunkList[chunk][0] * 16 + barrelPositionList[barrel][0] + target_pos[0], barrelPositionList[barrel][1], chunkList[chunk][1] * 16 + barrelPositionList[barrel][2] + target_pos[1]]
def fillChunk(chunk, barrelPositionList, world, dimension, currentArticle, booksPerBarrel, zimfilePath, chunkList, target_pos):
"""Fills the chunk with all blocks and content"""
barrel, wool, glowstone, sign_north, sign_south, air, stone, lantern = createBlocks(world)
chunk.blocks[:,5:9:,:] = air
chunk.blocks[:,3,:] = stone
chunk.blocks[:,9,:] = stone
for innerRow in [1,5,14,10]:
for positionInRow in [6,9]:
chunk.blocks[innerRow,7,positionInRow] = lantern
for outerRow in [3,7,8,12]:
for positionInRow in [1,14]:
chunk.blocks[outerRow,7,positionInRow] = lantern
fillSigns(chunk, world, dimension, sign_north, sign_south)
chunk.blocks[:,4,:] = wool
chunk.blocks[0,4,7:9] = glowstone
chunk.blocks[0,4,0] = glowstone
chunk.blocks[0,4,15] = glowstone
chunk.blocks[15,4,7:9] = glowstone
chunk.blocks[15,4,0] = glowstone
chunk.blocks[15,4,15] = glowstone
fillbarrels(chunk, barrelPositionList, barrel, currentArticle, booksPerBarrel, zimfilePath, chunkList, target_pos)
chunk.changed = True
def placeWall(chunk, orientation, world):
"""Places a wall on the wanted side of the chunk"""
barrel, wool, glowstone, sign_north, sign_south, air, stone, lantern = createBlocks(world)
chunk.blocks[orientation[0],3:9,orientation[1]] = stone
chunk.changed = True
|
{"/fillWithWiki.py": ["/htmlParser.py", "/chunkGenerator.py"], "/chunkGenerator.py": ["/htmlParser.py"], "/parserTester.py": ["/fillWithWiki.py"]}
|
1,267
|
strawberryblackhole/hippopotamus
|
refs/heads/master
|
/htmlParser.py
|
from html.parser import HTMLParser
from bs4 import BeautifulSoup
import json
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
def feed(self, in_html, zimFile, barrelPositionList, booksPerBarrel, chunkList, target_pos):
self._data = [""]
self._formats = [[[],[]]]
self._attrs = []
self._title = ""
self._zimFile = zimFile
self._barrelPositionList = barrelPositionList
self._booksPerBarrel = booksPerBarrel
self._chunkList = chunkList
self._target_pos = target_pos
super(MyHTMLParser, self).feed(in_html)
articleContent = self._data[0]
articleFormating = self._formats[0]
pages = ['{"extra":[{"text":"']
charsOnPage = 0
for iChar in range(len(articleContent)):
#if page not too long
if charsOnPage < 200:
#if the formating has to be defined
if charsOnPage == 0 or articleFormating[0][iChar] != articleFormating[0][iChar -1] or articleFormating[1][iChar] != articleFormating[1][iChar -1]:
pages[-1] += '"},{'
if articleFormating[0][iChar] > 0:
pages[-1] += '"bold":true,'
if articleFormating[1][iChar] > 0:
pages[-1] += '"italic":true,'
pages[-1] += '"text":"'
pages[-1] += json.dumps(articleContent[iChar], ensure_ascii=False)[1:-1]
charsOnPage += 1
if articleContent[iChar] == "\n":
charsOnPage += 12
else:
pages[-1] += '"}],"text":""}'
pages.append('{"extra":[{')
if articleFormating[0][iChar] > 0:
pages[-1] += '"bold":true,'
if articleFormating[1][iChar] > 0:
pages[-1] += '"italic":true,'
pages[-1] +='"text":"' + json.dumps(articleContent[iChar], ensure_ascii=False)[1:-1]
charsOnPage = 0
pages[-1] += ' The original work has been modified."}],"text":""}'
return json.dumps(self._title, ensure_ascii=False), pages
def handle_data(self, data):
self._data[-1] += data
for formating in self._formats[-1]:
formating.extend([0]*len(data))
def handle_starttag(self, tag, attrs):
self._data.append("")
self._formats.append([[],[]])
self._attrs.append(attrs)
def remove_data(self, replacement = "", replacementFormatings = [0,0]):
self._data[-1] = replacement
self._formats[-1] = [[0] * len(replacement), [0] * len(replacement)]
self.collaps_last_block_and_format(formatings=replacementFormatings)
def collaps_last_block_and_format(self, prefix = "", postfix = "", formatings = [0,0]):
self._data[-1] = prefix + self._data[-1] + postfix
#extend format by pre/postfix length
for iFormat in range(len(self._formats[-1])):
#turn on formating, but dont turn it off (because allready collapsed formats should keep their formating and should not be overwritten)
for iElement in range(len(self._formats[-1][iFormat])):
self._formats[-1][iFormat][iElement] += formatings[iFormat]
self._formats[-1][iFormat][:0] = [formatings[iFormat]] * len(prefix)
self._formats[-1][iFormat].extend([formatings[iFormat]] * len(postfix))
#collaps the last array entry
self._data[-2] += self._data[-1]
for iFormat in range(len(self._formats[-2])):
self._formats[-2][iFormat].extend(self._formats[-1][iFormat])
#delete last array entry
self._data.pop()
self._formats.pop()
self._attrs.pop()
def handle_endtag(self, tag):
if tag == 'a' :
foundiAtt = -1
for iAtt in range(len(self._attrs[-1])):
try:
self._attrs[-1][iAtt].index("href")
foundiAtt = iAtt
break
except ValueError:
continue
if foundiAtt != -1:
url = self._attrs[-1][iAtt][1].split("#")[0]
entry, idx = self._zimFile._get_entry_by_url("A", url)
if(idx != None):
location = getArticleLocationById(idx,self._barrelPositionList, self._booksPerBarrel, self._chunkList, self._target_pos)
self.collaps_last_block_and_format("", "[ID %d at x:%d y:%d z:%d]"%tuple([idx] + location))
else:
self.collaps_last_block_and_format("", "[%s]"%url)
else:
self.collaps_last_block_and_format()
elif tag == 'br' :
self.collaps_last_block_and_format("\n", "")
elif tag == 'div' :
if self._data[-1] != "" and self._data[-1][-1] != "\n":
self.collaps_last_block_and_format("\n ", "\n")
else:
self.collaps_last_block_and_format()
elif tag == 'h1' :
if ('class', 'section-heading') in self._attrs[-1]: #if its the title of the article
self._title = self._data[-1]
self.collaps_last_block_and_format("", "\n", [1,0])
else:
self.collaps_last_block_and_format("\n\n", "\n", [1,0])
elif tag == 'h2' :
self.collaps_last_block_and_format("\n\n", "\n", [1,0])
elif tag == 'h3' :
self.collaps_last_block_and_format("\n\n", "\n")
elif tag == 'li' :
self.collaps_last_block_and_format("\n -", "")
elif tag == 'p' :
if self._data[-1] != "":
self.collaps_last_block_and_format("\n ", "\n")
else:
self.collaps_last_block_and_format()
elif tag == 'ol' :
self.collaps_last_block_and_format("\n")
elif tag == 'ul' :
self.collaps_last_block_and_format("\n")
elif tag == 'script' :
self.remove_data()
elif tag == 'style' :
self.remove_data()
elif tag == 'table' :
self.remove_data("\nCan't display table\n", [0,1])
elif tag == 'title' :
self.remove_data()
else:
self.collaps_last_block_and_format()
def getArticleLocationById(id, barrelPositionList, booksPerBarrel, chunkList, target_pos):
booksPerChunk = len(barrelPositionList) * booksPerBarrel
chunk = int(id) // booksPerChunk
bookNumberInChunk = (int(id) - chunk * booksPerChunk)
barrel = (bookNumberInChunk - 1)// booksPerBarrel #-1 because if booksNumberInChunk == booksPerBarrel, it should be 0
return [chunkList[chunk][0] * 16 + barrelPositionList[barrel][0] + target_pos[0], barrelPositionList[barrel][1], chunkList[chunk][1] * 16 + barrelPositionList[barrel][2] + target_pos[1]]
def getFormatedArticle(html, zimFile, barrelPositionList, booksPerBarrel, chunkList, target_pos):
parser = MyHTMLParser()
soup = BeautifulSoup(html, features ="html.parser")
title, text = parser.feed(str(soup).replace("\n", "").replace("\t", ""), zimFile, barrelPositionList, booksPerBarrel, chunkList, target_pos)
#text = parser.feed(html.replace("\n", "").replace("\t", "")) # some things break when not using bfs
parser.close()
return title, text
|
{"/fillWithWiki.py": ["/htmlParser.py", "/chunkGenerator.py"], "/chunkGenerator.py": ["/htmlParser.py"], "/parserTester.py": ["/fillWithWiki.py"]}
|
1,268
|
strawberryblackhole/hippopotamus
|
refs/heads/master
|
/parserTester.py
|
from amulet.api.selection import SelectionGroup
from amulet.api.block import Block
from amulet.api.data_types import Dimension
from amulet import log
import amulet_nbt
from amulet.api.block_entity import BlockEntity
from ZIMply.zimply import ZIMFile
import os
import math
import time
from fillWithWiki import getFormatedArticle
zimfile = ZIMFile(os.path.dirname(os.path.realpath(__file__)) + "\\wikipedia_de_basketball_nopic_2020-04.zim","utf-8")
articleCount = list(zimfile)[-1][2]
count = 0
articles = list(zimfile)
for article in range(articleCount):
print(article)
start = time.perf_counter()
article = [x for x in articles if x[2] == article]
print("article search", time.perf_counter() - start)
if len(article) > 1:
raise Exception()
foundArticle = len(article) == 1
articleStop = 0
if foundArticle:
article = article[0]
articleTitle = article[1]
articleId = article[2]
start = time.perf_counter()
a = zimfile._get_article_by_index(articleId).data.decode("utf-8")
print("article read", time.perf_counter() - start)
start = time.perf_counter()
formatedArticle = getFormatedArticle(a)
print("article parse", time.perf_counter() - start)
print(formatedArticle)
if count > 4:
break
count += 1
|
{"/fillWithWiki.py": ["/htmlParser.py", "/chunkGenerator.py"], "/chunkGenerator.py": ["/htmlParser.py"], "/parserTester.py": ["/fillWithWiki.py"]}
|
1,279
|
gausszh/sae_site
|
refs/heads/master
|
/utils/filters.py
|
# coding=utf8
"""
jinja2的过滤器
"""
import markdown
def md2html(md):
"""
@param {unicode} md
@return {unicode html}
"""
return markdown.markdown(md, ['extra', 'codehilite', 'toc', 'nl2br'], safe_mode="escape")
JINJA2_FILTERS = {
'md2html': md2html,
}
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,280
|
gausszh/sae_site
|
refs/heads/master
|
/models/base.py
|
#coding=utf8
"""
基础类--用户信息
"""
from sqlalchemy import (
MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime,
ForeignKey, Date, UniqueConstraint)
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from models import sae_engine
from models import create_session
Base = declarative_base()
metadata = MetaData()
class User(Base):
"""
发布历史日志
"""
__tablename__ = 'user'
__table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
id = Column(Integer, primary_key=True)
open_id = Column(String(45), nullable=False, index=True)
token = Column(String(64), nullable=False, index=True)
name = Column(String(45))
email = Column(String(60))
address = Column(String(150))
tel = Column(String(15))
school = Column(String(45))
create_time = Column(DateTime)
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return unicode(self.id)
def __repr__(self):
return '<User %r>' % (self.name)
if __name__ == '__main__':
Base.metadata.create_all(bind=sae_engine)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,281
|
gausszh/sae_site
|
refs/heads/master
|
/views/base.py
|
#coding=utf8
import datetime
from flask import Blueprint, request, jsonify, render_template, redirect
import flask_login
import weibo as sinaweibo
from models.base import create_session, User
from utils import user_cache
from configs import settings
bp_base = Blueprint('base', __name__, url_prefix='/base')
@bp_base.route('/weibo/login/')
def weibo_login():
api = sinaweibo.Client(settings.API_KEY,settings.API_SECRET,settings.REDIRECT_URI)
code = request.args.get('code')
try:
api.set_code(code)
except Exception, e:
return redirect('/blog/')
sinainfo = api.token
user = user_cache.get_user(sinainfo.get('uid'), format='object')
if user:
flask_login.login_user(user, remember=True)
else:
user = User()
user.open_id = sinainfo.get('uid')
user.token = sinainfo.get('access_token')
userinfo = api.get('users/show', uid=sinainfo.get('uid'))
user.name = userinfo.get('name')
user.address = userinfo.get('location')
user.create_time = datetime.datetime.now()
session = create_session()
session.add(user)
session.commit()
flask_login.login_user(user, remember=True)
session.close()
return redirect('/blog/')
@bp_base.route('/logout/')
def logout():
flask_login.logout_user()
return redirect('/blog/')
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,282
|
gausszh/sae_site
|
refs/heads/master
|
/flask_app.py
|
#!/usr/bin/python
# coding=utf8
from flask import Flask, render_template, g
import flask_login
from configs import settings
from utils.filters import JINJA2_FILTERS
from utils import user_cache
from views import blog, base, security
def create_app(debug=settings.DEBUG):
app = Flask(__name__)
app.register_blueprint(blog.bp_blog)
app.register_blueprint(base.bp_base)
app.register_blueprint(security.bp_security)
app.jinja_env.filters.update(JINJA2_FILTERS)
app.debug = debug
app.secret_key = "gausszh"
@app.route('/')
def index():
return render_template('index.html')
@app.before_request
def check_user():
g.user = flask_login.current_user
login_manager = flask_login.LoginManager()
login_manager.setup_app(app)
@login_manager.user_loader
def load_user(userid):
user = user_cache.get_user(userid, format='object')
return user
login_manager.unauthorized = blog.list
# login_manager.anonymous_user = AnonymousUserMixin
return app
app = create_app(settings.DEBUG)
if __name__ == '__main__':
host = settings.APP_HOST
port = settings.APP_PORT
app.run(host=host, port=port)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,283
|
gausszh/sae_site
|
refs/heads/master
|
/models/__init__.py
|
#coding=utf-8
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from configs import settings
sae_engine = create_engine(settings.DB_SAE_URI+'?charset=utf8', encoding='utf-8',
convert_unicode=True, pool_recycle=settings.DB_POOL_RECYCLE_TIMEOUT,
echo=settings.DB_ECHO)
create_session = sessionmaker(autocommit=False, autoflush=False,
bind=sae_engine)
Base = declarative_base()
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,284
|
gausszh/sae_site
|
refs/heads/master
|
/utils/__init__.py
|
#coding=utf8
import datetime
import redis
import flask_login
from models.base import User, create_session
from utils import user_cache
from configs import settings
def AnonymousUserMixin():
'''
This is the default object for representing an anonymous user.
'''
session = create_session()
user = User()
count = user_cache.get_anonymous_count()
anonymouser_id = 1000 + count
user.open_id = 'anonymous%s' % anonymouser_id
user.name = u'游客%s' % anonymouser_id
user.token = ''
user.create_time = datetime.datetime.now()
session.add(user)
session.commit()
user_cache.incr_anonymous_count()
flask_login.login_user(user, remember=True)
session.close()
return user
redis_pool = redis.ConnectionPool(host=settings.REDIS_IP,
port=settings.REDIS_PORT,
db=settings.REDIS_DB)
def redis_connection():
return redis.Redis(connection_pool=redis_pool)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,285
|
gausszh/sae_site
|
refs/heads/master
|
/utils/blog_cache.py
|
# coding=utf8
from configs import settings
from utils import redis_connection
APP = "blog"
def set_draft_blog(uid, markdown):
_cache = redis_connection()
key = str("%s:draft:blog:%s" % (APP, uid))
_cache.set(key, markdown, settings.DRAFT_BLOG_TIMEOUT)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,286
|
gausszh/sae_site
|
refs/heads/master
|
/configs/settings_dev.py
|
#coding=utf8
import os
# system setting
DEBUG = True
APP_HOST = '127.0.0.1'
APP_PORT = 7020
STORAGE_BUCKET_DOMAIN_NAME = 'blogimg'
# database
if os.environ.get('SERVER_SOFTWARE'):#线上
import sae
DB_SAE_URI = 'mysql://%s:%s@%s:%s/database_name' % (sae.const.MYSQL_USER,
sae.const.MYSQL_PASS, sae.const.MYSQL_HOST, sae.const.MYSQL_PORT)
DB_POOL_RECYCLE_TIMEOUT = 10
DB_ECHO = True
else:
DB_SAE_URI = 'mysql://user:pass@127.0.0.1:3306/database_name'
# DB_SAE_URI = 'sqlite:////database.db'
DB_POOL_RECYCLE_TIMEOUT = 10
DB_ECHO = True
# cache
REDIS_HOST = "127.0.0.1"
REDIS_PORT = 6379
REDIS_DB = 1
CACHE_TIMEOUT = 3
# app
API_KEY = '***'
API_SECRET = '****'
REDIRECT_URI = 'http://****'
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,287
|
gausszh/sae_site
|
refs/heads/master
|
/utils/user_cache.py
|
# coding=utf8
try:
import simplejson as json
except Exception:
import json
import datetime
from sqlalchemy.sql import or_
from models.base import create_session, User
from models.blog import BlogArticle
from configs import settings
from utils import redis_connection
# import sae.kvdb
APP = "base"
def get_user(uid, format="json"):
_cache = redis_connection()
key = str("%s:user:%s" % (APP, uid))
userinfo = _cache.get(key)
new = False
if not userinfo:
session = create_session()
userinfo = session.query(User).filter(or_(User.id == uid,
User.open_id == uid)).first()
userinfo = orm2json(userinfo)
_cache.set(key, json.dumps(userinfo), settings.CACHE_TIMEOUT)
new = True
session.close()
if not new:
userinfo = json.loads(userinfo)
if format == 'object' and userinfo:
user = User()
for k in userinfo:
setattr(user, k, userinfo.get(k))
userinfo = user
return userinfo or None
def delete_user(uid):
_cache = redis_connection()
key = str("%s:user:%s" % (APP, uid))
_cache.delete(key)
def get_anonymous_count():
_cache = redis_connection()
key = "%s:anonymous:count" % APP
count = _cache.get(key)
if not count:
session = create_session()
count = session.query(User).filter(
User.open_id.startswith("anonymous")).count()
_cache.set(key, count, settings.CACHE_TIMEOUT)
session.close()
return int(count)
def incr_anonymous_count():
_cache = redis_connection()
key = "%s:anonymous:count" % APP
count = get_anonymous_count()
_cache.set(key, count + 1, settings.CACHE_TIMEOUT)
def get_blog(blog_id):
"""
获取博客的数据
"""
_cache = redis_connection()
key = str("%s:blog:%s" % (APP, blog_id))
bloginfo = _cache.get(key)
new = False
if not bloginfo:
session = create_session()
bloginfo = session.query(BlogArticle).filter_by(id=blog_id).first()
bloginfo = orm2json(bloginfo)
_cache.set(key, json.dumps(bloginfo), settings.CACHE_TIMEOUT)
new = True
session.close()
if not new:
bloginfo = json.loads(bloginfo)
return bloginfo
def delete_blog(blog_id):
_cache = redis_connection()
key = str("%s:blog:%s" % (APP, blog_id))
_cache.delete(key)
def orm2json(orm):
"""
将sqlalchemy返回的对象转换为可序列话json类型的对象
"""
def single2py(instance):
d = {}
if instance:
keys = instance.__dict__.keys()
for key in keys:
if key.startswith('_'):
continue
value = getattr(instance, key)
d[key] = isinstance(value, datetime.datetime) and \
value.strftime('%Y-%m-%d %H:%M:%S') or value
return d
if isinstance(orm, list):
return [single2py(ins) for ins in orm]
return single2py(orm)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,288
|
gausszh/sae_site
|
refs/heads/master
|
/views/security.py
|
# coding=utf8
"""
学web安全用到的一些页面
"""
from flask import Blueprint, render_template
from sae.storage import Bucket
from configs import settings
bp_security = Blueprint('security', __name__, url_prefix='/security')
bucket = Bucket(settings.STORAGE_BUCKET_DOMAIN_NAME)
bucket.put()
@bp_security.route('/wanbo/video/')
def wanbo_video():
return render_template('security/wanbo_video.html')
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,289
|
gausszh/sae_site
|
refs/heads/master
|
/views/blog.py
|
# coding=utf8
import datetime
import urllib
from flask import Blueprint, request, jsonify, render_template, g
import flask_login
from sae.storage import Bucket
from models.blog import create_session, BlogArticle
from utils.blog_cache import set_draft_blog
from configs import settings
bp_blog = Blueprint('blog', __name__, url_prefix='/blog')
bucket = Bucket(settings.STORAGE_BUCKET_DOMAIN_NAME)
bucket.put()
@bp_blog.route('/')
@bp_blog.route('/list/')
def list():
session = create_session()
blogs = session.query(BlogArticle).order_by(BlogArticle.update_time.desc())\
.all()
session.close()
return render_template('blog/blog_list.html', blogs=blogs)
@bp_blog.route('/delete/<int:blog_id>/', methods=['POST'])
@flask_login.login_required
def delete(blog_id):
session = create_session()
blog = session.query(BlogArticle).filter_by(id=blog_id).first()
if blog.create_by == g.user.id:
blog.is_active = 0
session.commit()
session.close()
return jsonify(ok=True, data={'blog_id': blog_id})
session.close()
return jsonify(ok=False, reason=u'数据错误')
@bp_blog.route('/draft/', methods=['POST'])
@flask_login.login_required
def draft():
"""
保存未上传的文章为草稿
"""
form = request.form
markdown = form.get('markdown', '')
set_draft_blog(flask_login.current_user.id, markdown)
return jsonify(ok=True)
@bp_blog.route('/edit/<int:blog_id>/', methods=['GET', 'POST'])
@bp_blog.route('/edit/', methods=['GET', 'POST'])
@flask_login.login_required
def edit(blog_id=0):
if request.method == 'GET':
if blog_id == 0:
blog = None
else:
session = create_session()
blog = session.query(BlogArticle).filter_by(id=blog_id).first()
session.close()
return render_template('blog/blog_edit.html', blog=blog)
if request.method == 'POST':
form = request.form
markdown = form.get('markdown')
title = form.get('title')
blog_id = form.get('blog_id')
if markdown and title and (len(markdown.strip()) *
len(title.strip()) > 0):
session = create_session()
now = datetime.datetime.now()
# blog_id belong to this user
if blog_id:
blog = session.query(BlogArticle).filter_by(id=blog_id).first()
if not blog_id or not blog:
blog = BlogArticle()
blog.create_by = flask_login.current_user.id
blog.create_time = now
blog.is_active = 1
blog.update_time = now
blog.title = title
blog.markdown = markdown
session.add(blog)
session.commit()
blog_id = blog.id
session.close()
return jsonify(ok=True, data={'blog_id': blog_id})
return jsonify(ok=False, reason=u'数据错误')
@bp_blog.route('/view/<int:blog_id>/')
def view_blog(blog_id):
session = create_session()
query = session.query(BlogArticle).filter_by(id=blog_id)
if not flask_login.current_user.is_active():
query = query.filter_by(is_active=1)
blog = query.first()
session.close()
return render_template('blog/blog_view.html', blog=blog)
@bp_blog.route('/files/', methods=['POST'])
@flask_login.login_required
def save_file():
"""
存储上传的图片
"""
files_name = request.files.keys()
ret = []
for fn in files_name:
# 暂未做安全校验 PIL
img_file = request.files.get(fn)
bucket.put_object(fn, img_file)
link = bucket.generate_url(fn)
ret.append({'name': fn, 'link': link})
http_files_link = request.form.keys()
for fn in http_files_link:
http_link = request.form.get(fn)
img_file = urllib.urlopen(http_link)
bucket.put_object(fn, img_file)
link = bucket.generate_url(fn)
ret.append({'name': fn, 'link': link})
return jsonify(ok=True, data=ret)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,290
|
gausszh/sae_site
|
refs/heads/master
|
/models/blog.py
|
#!/usr/bin/python
#coding=utf8
import datetime
from sqlalchemy import (
MetaData, Table, Column, Integer, BigInteger, Float, String, Text, DateTime,
ForeignKey, Date, UniqueConstraint)
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from models import sae_engine
from models import create_session
Base = declarative_base()
metadata = MetaData()
class BlogArticle(Base):
"""
发布历史日志
"""
__tablename__ = 'blog_article'
__table_args__ = {'mysql_engine': 'InnoDB', 'mysql_charset': 'utf8'}
id = Column(Integer, primary_key=True)
title = Column(String(50))
markdown = Column(Text)
html = Column(Text)
create_by = Column(Integer, index=True, nullable=False)
create_time = Column(DateTime, nullable=False)
update_time = Column(DateTime, index=True, nullable=False,)
is_active = Column(Integer, nullable=False, default=1)
if __name__ == '__main__':
Base.metadata.create_all(bind=sae_engine)
|
{"/models/base.py": ["/models/__init__.py"], "/flask_app.py": ["/utils/filters.py", "/utils/__init__.py"], "/utils/__init__.py": ["/models/base.py"], "/utils/blog_cache.py": ["/utils/__init__.py"], "/utils/user_cache.py": ["/models/base.py", "/models/blog.py", "/utils/__init__.py"], "/views/blog.py": ["/models/blog.py", "/utils/blog_cache.py"], "/models/blog.py": ["/models/__init__.py"]}
|
1,291
|
Garlinsk/Password-Locker
|
refs/heads/main
|
/passlock_test.py
|
import unittest #Importing the unittest module
from passlock import User #Importing the user class
from passlock import Credentials
import pyperclip
class TestCredentials(unittest.Testcase):
"""
Test class that defines test cases for the User class.
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
"""
Method that runs before each individual test methods run.
"""
self.new_user = User("FrankGarlinsk","1234zx", "garlinsk@email.com")
self.new_credential = Credentials('email','FrankGarlinsk','1234zx')
def test_init(self):
"""
test class to check if the object has been initialized correctly
"""
def save_details(self):
"""
method to store a new credential to the credentials list
"""
Credentials.credentials_list.append(self)
self.assertEqual(self.new_user.username,"FrankGarlinsk")
self.assertEqual(self.new_user.password,"1234zx")
self.assertEqual(self.new_user.email,"garlinsk@email.com")
def test_save_user(self):
"""
test case to test if a new user instance has been saved into the User list
"""
self.new_user.save_user() # saving the new user
self.assertEqual(len(User.user_list),1)
def test_save_multiple_user(self):
"""
test_save_multiple_user to check if we can save multiple user
objects to our user_list
"""
self.new_user.save_user()
test_user = User("Test","user","1235zx","test@email.com") # new user
test_user.save_user()
self.assertEqual(len(User.user_list),2)
def test_del_user(self):
"""
test class to test delete user method
"""
self.new_user.delete_user()# Deleting a contact object
self.assertEqual(len(User.user_list),0)
def test_find_user_by_username(self):
'''
test to check if we can find a user by username and display information
'''
self.new_user.save_user()
test_user = User("Test","user","1235zx","test@user.com") # new user
test_user.save_user()
found_user = User.find_by_username("FrankGarlinsk")
self.assertEqual(found_user.email,test_user.email)
def save_credential_test(self):
"""
test case to test if the crential object is saved into the credentials list.
"""
self.new_credential.save_details()
self.assertEqual(len(Credentials.credentials_list),1)
def test_save_many_accounts(self):
'''
test to check if we can save multiple credentials objects to our credentials list
'''
self.new_credential.save_details()
test_credential = Credentials("Twitter","mikeycharles","Mfh45hfk")
test_credential.save_details()
self.assertEqual(len(Credentials.credentials_list),2)
if __name__ == "__main__":
unittest.main()
|
{"/passlock_test.py": ["/passlock.py"], "/run.py": ["/passlock.py"]}
|
1,292
|
Garlinsk/Password-Locker
|
refs/heads/main
|
/run.py
|
#!/usr/bin/env python3.9
from os import name
from passlock import User
def create_contact(fname,lname,phone,email):
'''
Function to create a new user
'''
new_user = User(fname,lname,phone,email)
return new_user
def save_users(user):
'''
Function to save user
'''
user.save_user()
def del_user(user):
'''
Function to delete a user
'''
user.delete_user()
def find_user(name):
'''
Function that finds a contact by number and returns the user
'''
return name.find_by_username(name)
def check_existing_users(name):
'''
Function that check if a user exists with that name and return a Boolean
'''
return User.user_exist(name)
def display_users():
'''
Function that returns all the saved users
'''
return User.display_users()
|
{"/passlock_test.py": ["/passlock.py"], "/run.py": ["/passlock.py"]}
|
1,293
|
Garlinsk/Password-Locker
|
refs/heads/main
|
/passlock.py
|
from os import name
import pyperclip
class User:
"""
Class that generates new instances of user.
"""
user_list = [] # Empty user list
def __init__(self, username, password, email):
# docstring removed for simplicity
self.username = username
self.password = password
self.email = email
def save_user(self):
"""
A method that saves a new user instace into the user list
"""
User.user_list.append(self)
def save_multiple_user(self):
"""
save_multiple_user method is to check if we can save multiple user
objects to our user_list
"""
self.new_user.save_user()
def delete_user(self):
'''
delete_account method deletes a saved account from the list
'''
User.user_list.remove(self)
class Credentials():
"""
Create credentials class to help create new objects of credentials
"""
credentials_list = []
@classmethod
def find_by_username(cls,user):
'''
Method that takes in a name and returns a username that matches that name.
Args:
user: Username to search for
Returns :
Name of person that matches the user.
'''@classmethod
def copy_email(cls,user):
user_found = user.find_by_username(user)
pyperclip.copy(user_found.email)
for user in cls.user_list:
if user.user_name == user:
return user
def __init__(self,account,userName, password):
"""
method that defines user credentials to be stored
"""
def save_details(self):
"""
method to store a new credential to the credentials list
"""
Credentials.credentials_list.append(self)
@classmethod
def copy_email(cls,user):
user_found = User.find_by_username(name)
pyperclip.copy(user_found.email)
|
{"/passlock_test.py": ["/passlock.py"], "/run.py": ["/passlock.py"]}
|
1,310
|
AlexsandroMO/Bitcoin
|
refs/heads/master
|
/Write_SQL.py
|
import pandas as pd
import pandasql as pdsql
import sqlite3
from datetime import date
from datetime import datetime
import CreateTable_SQL
#--------------------------------------------
#Adicionar dados no banco - VarBitcoin
def add_var_bitcoin(btc_last,btc_buy,btc_sell,date_btc):
# CreateTable_SQL.create_VarBTC()
# CreateTable_SQL.create_Wallet()
conn = sqlite3.connect('DB/DB_COINS.db')
c = conn.cursor()
qsl_datas = f"""INSERT INTO VARBTC(VAR_BTC_LAST,VAR_BTC_BUY,VAR_BTC_SELL,VAR_BTC_DATE)
VALUES ({btc_last},{btc_buy},{btc_sell},'{date_btc}');
"""
c.execute(qsl_datas)
conn.commit()
conn.close()
def add_var_wallet(my_wallet_control,profit,date_today):
# CreateTable_SQL.create_VarBTC()
# CreateTable_SQL.create_Wallet()
conn = sqlite3.connect('DB/DB_COINS.db')
c = conn.cursor()
qsl_datas = f"""INSERT INTO WALLET(VAR_WALLET,WIN_LOSE,DATE_NEGOCIATION)
VALUES ({my_wallet_control}, {profit},'{date_today}');
"""
c.execute(qsl_datas)
conn.commit()
conn.close()
def add_var_wallet_start(wallet,win_lose,date_today):
# CreateTable_SQL.create_VarBTC()
# CreateTable_SQL.create_Wallet()
conn = sqlite3.connect('DB/DB_COINS.db')
c = conn.cursor()
qsl_datas = f"""INSERT INTO COINCOIN(VAR_WALLET,WIN_LOSE,DATE_NEGOCIATION)
VALUES ({wallet},{win_lose},'{date_today}');
"""
c.execute(qsl_datas)
conn.commit()
conn.close()
|
{"/Write_SQL.py": ["/CreateTable_SQL.py"]}
|
1,311
|
AlexsandroMO/Bitcoin
|
refs/heads/master
|
/coin/admin.py
|
from django.contrib import admin
from .models import TypeWallet, MYWallet
class ListaMYWallet(admin.ModelAdmin):
list_display = ('name_wallet','var_wallet','type_wallet','log_create')
admin.site.register(TypeWallet)
admin.site.register(MYWallet, ListaMYWallet)
|
{"/Write_SQL.py": ["/CreateTable_SQL.py"]}
|
1,312
|
AlexsandroMO/Bitcoin
|
refs/heads/master
|
/CreateTable_SQL.py
|
import pandas as pd
import pandasql as pdsql
import sqlite3
from datetime import date
from datetime import datetime
import os
def verify():
directory = 'DB'
dir = directory
if not os.path.exists(directory):
os.makedirs(dir)
#-------------------------------------------------------
#Criar Tabela VARBITCOIN
def create_VarBTC():
verify()
conn = sqlite3.connect('DB/DB_COINS.db')
c = conn.cursor()
table_createdb = f"""
CREATE TABLE IF NOT EXISTS VARBTC (
ID INTEGER PRIMARY KEY,
VAR_BTC_LAST DOUBLE NOT NULL,
VAR_BTC_BUY DOUBLE NOT NULL,
VAR_BTC_SELL DOUBLE NOT NULL,
VAR_BTC_DATE DATE NOT NULL
)
"""
c.execute(table_createdb)
conn.commit()
conn.close()
#-------------------------------------------------------
#Criar Tabela Wallet
def create_Wallet():
verify()
conn = sqlite3.connect('DB/DB_COINS.db')
c = conn.cursor()
table_createdb = f"""
CREATE TABLE IF NOT EXISTS COINCOIN (
ID INTEGER PRIMARY KEY,
VAR_WALLET DOUBLE NOT NULL,
WIN_LOSE DOUBLE NOT NULL,
DATE_NEGOCIATION DATE NOT NULL
)
"""
c.execute(table_createdb)
conn.commit()
conn.close()
#-------------------------
#db = TinyDB('db.json')
#Ft = Query()
|
{"/Write_SQL.py": ["/CreateTable_SQL.py"]}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.