index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
23,785
ddu365/datawhale-code
refs/heads/master
/task2/array.py
class DynamicArray: def __init__(self, capacity=10): self._capacity = capacity self._array = [None] * self._capacity self._size = 0 def __str__(self): return str([e for e in self]) def __iter__(self): for i in range(self._capacity): yield self._array[i] def __len__(self): return self._size # 读 def __getitem__(self, item): if not 0 <= item < self._capacity: raise IndexError('index out of range') return self._array[item] # 改 def __setitem__(self, key, value): if not 0 <= key < self._capacity: raise IndexError('index out of range') self._array[key] = value # 删 def __delitem__(self, key): if not 0 <= key < self._capacity: raise IndexError('index out of range') self._array[key] = None self._size -= 1 # 增 def append(self, value): if self._size == self._capacity: self._resize(2*self._capacity) self._array[self._size] = value self._size += 1 def get_capacity(self): return self._capacity def _resize(self, capacity): tmp = [None] * capacity self._capacity = capacity for i in range(self._size): tmp[i] = self._array[i] self._array = tmp
{"/task1/linkedlist_test.py": ["/task1/linkedlist.py"], "/task2/array_test.py": ["/task2/array.py"], "/task5/priority_queue.py": ["/task5/heap.py"], "/task2/trie_test.py": ["/task2/trie.py"]}
23,786
ddu365/datawhale-code
refs/heads/master
/task3/heap_sort.py
""" 堆是一种完全二叉树的数据结构 算法流程: 1.将待排序列表构建成完全二叉树 2.调整完全二叉树节点的顺序,使其成为最大堆(初始无序区),即父节点大于孩子节点[从最后一个父节点开始从右往左从下往上地调整,调整后还需反向检查调整后的节点是否满足最大堆的性质] 3.将堆顶元素L[1]与最后一个元素L[n]交换,得到新的无序区(L[1],L[2]...,L[n-1])和新的有序区L[n] 4.将新得到的无序区调整为最大堆,然后再次将调整后的最大堆的堆顶元素L[1]与最后一个元素L[n-1]交换,得到新的无序区(L[1],L[2]...,L[n-2])和新的有序区L[n-1],L[n] 5.重复上述过程直到有序区元素的个数为n-1 参考链接: http://www.cnblogs.com/0zcl/p/6737944.html """ def max_heap_sort(s): """ sort the elements of list s using the max-heap-sort algorithm in ascending order Complexity: best O(n*log(n)) avg O(n*log(n)), worst O(n*log(n)) """ for i in range(len(s)-1, 0, -1): max_heapify(s, i) return s # 将索引下标从0到end的序列s构成大顶堆,并交换生成堆的第一个元素和最后一个元素 def max_heapify(s, end): last_parent = (end - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent while current_parent <= last_parent: # Find greatest child of current_parent child = 2 * current_parent + 1 if child + 1 <= end and s[child] < s[child + 1]: child += 1 # Swap if child is greater than parent if s[child] > s[current_parent]: s[current_parent], s[child] = s[child], s[current_parent] current_parent = child # If no swap occured, no need to keep iterating else: break s[0], s[end] = s[end], s[0] def min_heap_sort(s): """ Heap Sort that uses a min heap to sort an array in ascending order Complexity: O(n*log(n)) """ for i in range(0, len(s) - 1): min_heapify(s, i) return s # 将索引下标从start到len(s)-1的序列s构成小顶堆 def min_heapify(s, start): """ Min heapify helper for min_heap_sort """ # Offset last_parent by the start (last_parent calculated as if start index was 0) # All array accesses need to be offset by start end = len(s) - 1 last_parent = (end - start - 1) // 2 # Iterate from last parent to first for parent in range(last_parent, -1, -1): current_parent = parent # Iterate from current_parent to last_parent while current_parent <= last_parent: # Find lesser child of current_parent child = 2 * current_parent + 1 if child + 1 <= end - start and s[child + start] > s[child + 1 + start]: child = child + 1 # Swap if child is less than parent if s[child + start] < s[current_parent + start]: s[current_parent + start], s[child + start] = \ s[child + start], s[current_parent + start] current_parent = child # If no swap occured, no need to keep iterating else: break if __name__ == '__main__': ul = [85, 24, 63, 45, 17, 31, 96, 50] # built-in heap queue (a.k.a. priority queue) import heapq heapq.heapify(ul) print(ul) print(heapq.nlargest(3, ul)) print([heapq.heappop(ul) for _ in range(len(ul))]) # custom heap print(max_heap_sort(ul)) ul = [85, 24, 63, 45, 17, 31, 96, 50] print(min_heap_sort(ul))
{"/task1/linkedlist_test.py": ["/task1/linkedlist.py"], "/task2/array_test.py": ["/task2/array.py"], "/task5/priority_queue.py": ["/task5/heap.py"], "/task2/trie_test.py": ["/task2/trie.py"]}
23,787
ddu365/datawhale-code
refs/heads/master
/task2/trie_test.py
import task2.trie as trie if __name__ == '__main__': try: t = trie.Trie() t.insert('hello') t.insert('he') t.search('hello') print(t.search('he')) print(t.search('hel')) print(t.search('hello')) print(t.starts_with('hell')) except Exception as e: print(f'test happen error:{e}')
{"/task1/linkedlist_test.py": ["/task1/linkedlist.py"], "/task2/array_test.py": ["/task2/array.py"], "/task5/priority_queue.py": ["/task5/heap.py"], "/task2/trie_test.py": ["/task2/trie.py"]}
23,792
BANZZAAAIIII/Search_and_Sort
refs/heads/master
/search.py
import math from typing import List def binary_search(dataset, city_value, lat_value): def search(data, left_index, right_index): if right_index > 1: middle = (left_index + right_index) // 2 # Is using isclose a good idea? 41.728_ has a lot of cities if math.isclose(data[middle]["lat"], lat_value) and data[middle]["city"] == city_value: return data[middle] if data[middle]["lat"] > lat_value: return search(data, left_index, middle - 1) else: return search(data, middle + 1, right_index) else: return None return search(dataset, 0, len(dataset) - 1) def OBST_search(dataset: List[dict], city_value, lat_value, printy=False): def optimalBinarySearchTree(data, n): # Based on: https://www.radford.edu/~nokie/classes/360/dp-opt-bst.html cost = [[0 for _ in range(n)] for _ in range(n)] root = [[0 for _ in range(n)] for _ in range(n)] node = [[0 for _ in range(n)] for _ in range(n)] # Diagonal cost for i in range(n): root[i][i] = data[i]["lat"] cost[i][i] = data[i]["freq"] for size in range(2, n + 1): for row in range(n - size + 2): col = row + size - 1 if row >= n or col >= n: break cost[row][col] = math.inf # Checks cost of all nodes, from row to col, as root for r in range(row, col + 1): # Cost of current node currentCost = sum(data[i]["freq"] for i in range(row, col + 1)) # Adds cost of left subtree if r != row: currentCost += cost[row][r - 1] # Adds cost of right subtree if r != col: currentCost += cost[r + 1][col] # Checks if this node has a lower cost if currentCost < cost[row][col]: root[row][col] = data[r]["lat"] # Updates root node[row][col] = r # updates index cost[row][col] = currentCost # Updates cost return root, node, cost # dataset = [{"lat": 10, "freq": 4}, {"lat": 20, "freq": 2}, {"lat": 30, "freq": 6}, {"lat": 40, "freq": 3}] root, node, cost = optimalBinarySearchTree(dataset, len(dataset)) print(f"\tOBST Cost: {cost[0][len(dataset) - 1]}") print(f"\tRoot node: {root[0][len(dataset) - 1]}") print(f"\tNode node: {dataset[node[0][len(dataset) - 1]]}") if printy: print("\tRoot:") for d in root: print(f"\t\t{d}") print("\tNode:") for d in node: print(f"\t\t{d}") print("\tCost:") for d in cost: print(f"\t\t{d}") def search(): for i, row in enumerate(root): for j, col in enumerate(row): if col == lat_value: if dataset[i]["city"] == city_value: return dataset[i] return None print(f"\tSearch result: {search()}") return root, node, cost
{"/main.py": ["/search.py", "/sorts.py"]}
23,793
BANZZAAAIIII/Search_and_Sort
refs/heads/master
/sorts.py
from typing import List, Optional import random import math merge_count = 0 node_count = 0 def reset_globals(): global merge_count global node_count merge_count = 0 node_count = 0 def calculateDistance(lat1, lng1): """" uses haversine formula from: https://www.movable-type.co.uk/scripts/latlong.html a = sin²(delta_phi/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) c = 2 ⋅ atan2( √a, √(1−a) ) d = R ⋅ c """ def inner(lat2, lng2): R = 6371 # earths radius in km phi1 = math.radians(lat1) lambda1 = math.radians(lng1) phi2 = math.radians(lat2) lambda2 = math.radians(lng2) delta_phi = phi2 - phi1 delta_lambda = lambda2 - lambda1 a = (math.sin(delta_phi / 2) * math.sin(delta_phi / 2) + math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) * math.sin(delta_lambda / 2)) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) return R * c return inner def add_dist_to_dataset(data, dist_from): for d in data: d["dist"] = dist_from(d["lat"], d["lng"]) def mergesort(data: List[dict], compare: str) -> List[dict]: global merge_count global node_count node_count += 1 if len(data) > 1: # Gets middle index as int m = len(data) // 2 left = mergesort(data[:m], compare) right = mergesort(data[m:], compare) Left_index = 0 # current index of left side right_index = 0 # current index of right side current_index = 0 # current index of list index l_len = len(left) if left is not None else 0 r_len = len(right) if right is not None else 0 while Left_index < l_len and right_index < r_len: merge_count += 1 if left[Left_index][compare] < right[right_index][compare]: data[current_index] = left[Left_index] Left_index += 1 else: data[current_index] = right[right_index] right_index += 1 current_index += 1 # Adds any remaining elements from left or right side to the and of the list while Left_index < l_len: merge_count += 1 data[current_index] = left[Left_index] Left_index += 1 current_index += 1 while right_index < r_len: merge_count += 1 data[current_index] = right[right_index] right_index += 1 current_index += 1 return data else: return data def mergesort_from_pos(dataset, lat, lng): """ Sorts wordlcities datasets with distance from given coordinate with mergesort """ dist_from_x = calculateDistance(lat, lng) add_dist_to_dataset(dataset, dist_from_x) return mergesort(dataset, "dist") def quicksort(dataset: List[dict], compare: str, rand=True) -> List[dict]: """ Sorts worldcites dataset by latitudes with quicksort """ def sort(data: List[dict], left_index: int, right_index: int) -> Optional[List[dict]]: global node_count node_count += 1 if left_index <= right_index: p = partition(data, left_index, right_index) sort(data, left_index, p - 1) sort(data, p + 1, right_index) else: return return data def partition(data: List[dict], left_index: int, right_index: int) -> int: global merge_count # Choosing a random pivot by swapping random index with right most index if rand: r = random.randrange(left_index, right_index + 1) data[r], data[right_index] = data[right_index], data[r] pivot_index = right_index pivot = data[pivot_index][compare] i = left_index - 1 for j in range(left_index, pivot_index): if data[j][compare] < pivot: i += 1 data[i], data[j] = data[j], data[i] merge_count += 1 data[i + 1], data[pivot_index] = data[pivot_index], data[i + 1] return i + 1 return sort(dataset, 0, len(dataset) - 1) def quicksort_from_pos(dataset, lat, lng) -> List[dict]: """ Sorts wordlcities datasets with distance from given coordinate quicksort """ dist_from_x = calculateDistance(lat, lng) add_dist_to_dataset(dataset, dist_from_x) return quicksort(dataset, "dist")
{"/main.py": ["/search.py", "/sorts.py"]}
23,794
BANZZAAAIIII/Search_and_Sort
refs/heads/master
/main.py
import random from operator import itemgetter from itertools import groupby from random import shuffle import filemanager import filemanager as fm import search import sorts def main(): dataset = fm.get_data() print("1.1:") sorted_by_lat = sorts.mergesort(list(dataset), "lat") print(f"\tnumber of merges done: {sorts.merge_count}") print(f"\tnumber of nodes visited: {sorts.node_count}") sorts.reset_globals() print("\n1.2:") print("\tShuffling list") shuffled_list = list(dataset) shuffle(shuffled_list) sorted_by_lat_shuffled = sorts.mergesort(shuffled_list, "lat") print(f"\tnumber of merges done: {sorts.merge_count}") print(f"\tnumber of nodes visited: {sorts.node_count}") sorts.reset_globals() print("\n1.3:") print("Sorting by distant") sorted_from_pos = sorts.mergesort_from_pos(list(dataset), 1, 1) print(f"\tnumber of merges done: {sorts.merge_count}") print(f"\tnumber of nodes visited: {sorts.node_count}") sorts.reset_globals() print("\n2.1:") sorted_by_lat = sorts.quicksort(list(dataset), "lat") print(f"\tnumber of merges done: {sorts.merge_count}") print(f"\tnumber of nodes visited: {sorts.node_count}") sorts.reset_globals() print("\n2.2:") print("\tShuffling list") shuffled_list = list(dataset) shuffle(shuffled_list) sorted_by_lat_shuffled = sorts.quicksort(shuffled_list, "lat") print(f"\tnumber of merges done: {sorts.merge_count}") print(f"\tnumber of nodes visited: {sorts.node_count}") sorts.reset_globals() print("\n2.3:") print("Sorting by distant") sorted_from_pos = sorts.quicksort_from_pos(list(dataset), 1, 1) print(f"\tnumber of merges done: {sorts.merge_count}") print(f"\tnumber of nodes visited: {sorts.node_count}") print("\n3.1 search") print("\t" + str(search.binary_search(sorted_by_lat, "Catas Altas", -20.0750))) print("\t" + str(search.binary_search(sorted_by_lat, "Itaúna", -20.0750))) print("\n4 Optimal Binary search") dataset_norway = fm.get_data(True) for d in dataset_norway: d["freq"] = random.randrange(0, 100)/100 root, node, cost = search.OBST_search(dataset_norway, "Grimstad", 58.3405) if __name__ == "__main__": main()
{"/main.py": ["/search.py", "/sorts.py"]}
23,795
KimSunUk/confidant
refs/heads/master
/tests/unit/confidant/encrypted_settings_test.py
import unittest from mock import patch from mock import Mock from confidant import settings from confidant.encrypted_settings import EncryptedSettings class EncprytedSettingsTest(unittest.TestCase): def test_register(self): enc_set = EncryptedSettings(None) enc_set.register('Foo', 'Bar') self.assertEqual(enc_set.secret_names, ['Foo']) def test_get_registered(self): enc_set = EncryptedSettings(None) enc_set.register('Foo', 'Bar') enc_set.decrypted_secrets = {'Foo': 'DecryptedBar'} self.assertEqual(enc_set.get_secret('Foo'), 'DecryptedBar') def test_get_registered_default(self): enc_set = EncryptedSettings(None) enc_set.register('Foo', 'Bar') enc_set.register('Bar', 'Baz') enc_set.decrypted_secrets = {'Foo': 'DecryptedFoo'} self.assertEqual(enc_set.get_secret('Bar'), 'Baz') @patch( 'confidant.encrypted_settings.cryptolib.decrypt_datakey', return_value='1cVUbJT58SbMt4Wk4xmEZoNhZGdWO_vg1IJiXwc6HGs=' ) @patch( 'confidant.encrypted_settings.Fernet.decrypt', return_value='{secret: value, secret2: value2}\n' ) def test_bootstrap(self, mockdecryptkey, mockdecrypt): enc_set = EncryptedSettings(None) decrypted = enc_set._bootstrap( '{"secrets": "encryptedstring", "data_key": "dGhla2V5"}' ) self.assertEqual(decrypted['secret2'], 'value2') def test_bootstrap_filefail(self): enc_set = EncryptedSettings(None) decrypted = enc_set._bootstrap('file://FILE/DOES/NOT/EXIST') self.assertEqual(decrypted, {})
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,796
KimSunUk/confidant
refs/heads/master
/tests/__init__.py
# Make the tests directory a python module # so that all unit tests are reported as part of the tests package. import os # Inject mandatory environment variables env_settings = [ ('SESSION_SECRET', 'secret'), ('DYNAMODB_TABLE', 'confidant-testing'), ('DYNAMODB_URL', 'http://dynamo:7777'), ('DYNAMODB_CREATE_TABLE', 'false'), ('GEVENT_RESOLVER', 'ares'), ('AWS_DEFAULT_REGION', 'us-east-1'), ('USER_AUTH_KEY', 'authnz-usertesting'), ('AUTH_KEY', 'authnz-testing'), ('SCOPED_AUTH_KEYS', '{"sandbox-auth-key":"sandbox","primary-auth-key":"primary"}'), ('KMS_MASTER_KEY', 'confidant-mastertesting'), ('DEBUG', 'true'), ('STATIC_FOLDER', 'public') ] for env_setting in env_settings: os.environ[env_setting[0]] = os.getenv(env_setting[0], env_setting[1])
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,797
KimSunUk/confidant
refs/heads/master
/confidant/utils/__init__.py
import statsd from confidant.app import app stats = statsd.StatsClient( app.config['STATSD_HOST'], app.config['STATSD_PORT'], prefix='confidant' )
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,798
KimSunUk/confidant
refs/heads/master
/confidant/routes/__init__.py
from confidant.routes import static_files # noqa from confidant.routes import v1 # noqa from confidant.routes import saml # noqa
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,799
KimSunUk/confidant
refs/heads/master
/tests/unit/confidant/ciphermanager_test.py
import unittest from nose.tools import assert_raises from cryptography.fernet import Fernet from confidant.ciphermanager import CipherManager from confidant.ciphermanager import CipherManagerError class CipherManagerTest(unittest.TestCase): def test_cipher_version_2(self): key = Fernet.generate_key() cipher = CipherManager(key, 2) ciphertext = cipher.encrypt('testdata') # Assert we're getting back some form of altered data self.assertNotEquals(ciphertext, 'testdata') cipher = CipherManager(key, 2) plaintext = cipher.decrypt(ciphertext) # Assert that decrypting using a new cipher object with the same key # and version give back the same plaintext. self.assertEquals(plaintext, 'testdata') def test_cipher_version_1(self): key = Fernet.generate_key() cipher = CipherManager(key, 1) with assert_raises(CipherManagerError): cipher.encrypt('testdata') with assert_raises(CipherManagerError): cipher.decrypt('random_text') def test_cipher_version_3(self): key = Fernet.generate_key() cipher = CipherManager(key, 3) with assert_raises(CipherManagerError): cipher.encrypt('testdata') with assert_raises(CipherManagerError): cipher.decrypt('random_text')
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,800
KimSunUk/confidant
refs/heads/master
/confidant/models/__init__.py
from confidant.app import app from confidant.utils.dynamodb import create_dynamodb_tables if app.config['DYNAMODB_CREATE_TABLE']: create_dynamodb_tables()
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,801
KimSunUk/confidant
refs/heads/master
/confidant/utils/misc.py
def dict_deep_update(a, b): """ Deep merge in place of two dicts. For all keys in `b`, override matching keys in `a`. If both `a` and `b` have a dict at a given key, recursively update `a`. :param a: Left hand side dict to update in place :type a: dict :param b: Right hand side with values to pull in :type b: dict """ for key, val in b.iteritems(): if isinstance(a.get(key), dict) and isinstance(val, dict): dict_deep_update(a[key], val) else: a[key] = val
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,802
KimSunUk/confidant
refs/heads/master
/confidant/models/connection_cls.py
import pynamodb.connection from confidant.app import app class DDBConnection(pynamodb.connection.Connection): def __init__(self, *args, **kwargs): super(DDBConnection, self).__init__(*args, **kwargs) _timeout_secs = app.config['PYNAMO_REQUEST_TIMEOUT_SECONDS'] self._request_timeout_seconds = _timeout_secs
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,803
KimSunUk/confidant
refs/heads/master
/confidant/routes/v1.py
#python은 기본적으로 json 표준 라이브러리 제공, 라이브러리 사용시 python타입의 object를 json문자열로 변경가능(json인코딩), 또한 json문자열을 다시 python타입으로 변환 가능(json디코딩) import json #uuid는 기본적으로 어떤 개체(데이터)를 고유하게 식별하는 데 사용되는 16바이트 길이의 숫 예 : 022db29c-d0e2-11e5-bb4c-60f81dca7676 import uuid #객체를 복사하기 위한 용도 import copy #로그를 찍기위한 라이브러리 import logging #base64인코딩,디코딩을 위한 라이브러리 ##인코딩 : 정보의 형태나 형식을 부호화/암호화시킨다, 디코딩 : 부호화/암호화를 해체한다 import base64 #정규 표현식을 지원하기 위해 제공되는 모 import re #PynamoDB : 파이썬 2와 3을 지원하는 아마존의 DynamoDB의 Pythonic interface #PutError->아이템이 생성 실패 시 "Error putting item"이란 말을 올린다. #DoesNotExist->아이템의 쿼리가 존제하지 않을 시 "Item does not exitst"이란 말을 올린다. from pynamodb.exceptions import PutError, DoesNotExist #객체에 담긴 HTTP요청에 대한 상세를 request해주기 위해 from flask import request #플라스크의 목록을 jsonify하기 위한 라이브러리 from flask import jsonify #클라이언트오류에 대한 예외처리를 위한 라이브러리 from botocore.exceptions import ClientError #confidant 외부 서비스에 접속을 위한 라이브러리(모듈) import confidant.services from confidant import keymanager from confidant import authnz from confidant import graphite from confidant import settings from confidant import webhook from confidant.app import app from confidant.utils import stats from confidant.utils import maintenance from confidant.ciphermanager import CipherManager from confidant.models.credential import Credential from confidant.models.blind_credential import BlindCredential from confidant.models.service import Service #iam_resource라는 변수에 iam리소스 값을 가져온다 iam_resource = confidant.services.get_boto_resource('iam') #kms_client라는 변수에 클라이언트의 kms인증키를 받아온다 kms_client = confidant.services.get_boto_client('kms') #VALUE_LENGTH변수에 50 대입 VALUE_LENGTH = 50 #로그인 흐름에 따라 유저 로그인 시키기 위한 함수 정의 @app.route('/v1/login', methods=['GET', 'POST']) def login(): ''' Send user through login flow. ''' return authnz.log_in() #바로 최근에 로그인 된 유저로부터 이메일주소 정보 가져오기 없으면 None 가져오기 위한 함수 정의 @app.route('/v1/user/email', methods=['GET', 'POST']) @authnz.require_auth def get_user_info(): ''' Get the email address of the currently logged-in user. ''' try: #email에 대한 JSON타입의 http response 생성된 값을 response변수에 대입 response = jsonify({'email': authnz.get_logged_in_user()}) except authnz.UserUnknownError: #UserUnknownError가 뜰 시 none을 response변수에 대입 response = jsonify({'email': None}) #response 변수 리턴 return response #클라이언트가 bootstrap하는 것을 도와주기 위해 configuration을 가져오기 위한 함수 정의 @app.route('/v1/client_config', methods=['GET']) @authnz.require_auth def get_client_config(): ''' Get configuration to help clients bootstrap themselves. ''' # TODO: add more config in here. #configuration에 대한 JSON타입의 http response 생성된 값을 response변수에 대입 response = jsonify({ 'defined': app.config['CLIENT_CONFIG'], 'generated': { #kms인증키 가져오기 'kms_auth_manage_grants': app.config['KMS_AUTH_MANAGE_GRANTS'], #aws계정 가져오기 'aws_accounts': app.config['SCOPED_AUTH_KEYS'].values(), #쿠키 이름 가져오기 'xsrf_cookie_name': app.config['XSRF_COOKIE_NAME'], #maintenance_mode 값 가져오기 'maintenance_mode': app.config['MAINTENANCE_MODE'] } }) #response 변수 리턴 return response #service리스트 가져오기 위한 함수 정의 @app.route('/v1/services', methods=['GET']) @authnz.require_auth def get_service_list(): #services라는 리스트 생성 services = [] #Service.data_type_date_index.query('service')양 만큼의 반복문이 실행되며 리스트에 id,account,enabled,revision,modified_date,modified_by를 추가한다 for service in Service.data_type_date_index.query('service'): services.append({ 'id': service.id, 'account': service.account, 'enabled': service.enabled, 'revision': service.revision, 'modified_date': service.modified_date, 'modified_by': service.modified_by }) #리스트릴 jsonify시켜 리턴해준다. return jsonify({'services': services}) @app.route('/v1/roles', methods=['GET']) @authnz.require_auth #iam_roles_list를 가져오기 위한 함수 정의 def get_iam_roles_list(): try: roles = [x.name for x in iam_resource.roles.all()] except ClientError: return jsonify({'error': 'Unable to roles.'}), 500 return jsonify({'roles': roles}) @app.route('/v1/services/<id>', methods=['GET']) @authnz.require_auth #서비스의 메타데이타와 모든 credentials를 가져오기 위한 함수 정의 def get_service(id): ''' Get service metadata and all credentials for this service. This endpoint allows basic authentication. ''' #_init_.py에 정의된 user_is_user_type함수를 통해 service값이라면 제어문 안으로 if authnz.user_is_user_type('service'): #_init_.py에 정의된 user_is_service함수를 통해 함수의 파라메터 값으로 받아온 id가 아니라면 로그에 'Authz failed for service {0}.', 'Authenticated user is not authorized.'라는 메시지와 함께 401error를 띄운다 if not authnz.user_is_service(id): logging.warning('Authz failed for service {0}.'.format(id)) msg = 'Authenticated user is not authorized.' return jsonify({'error': msg}), 401 try: #service라는 변수에 id값 대입 service = Service.get(id) #_init_.py에 정의된 service_in_account함수를 통해 account값이 일치하지 않는다면 제어문 안으로 if not authnz.service_in_account(service.account): #아래와 같은 로그를 남긴다 logging.warning( 'Authz failed for service {0} (wrong account).'.format(id) ) #msg에 아래와 같은 문자 대입 msg = 'Authenticated user is not authorized.' #401error를 msg에 대입된 문자열과 함께 jsonify시켜 리턴 return jsonify({'error': msg}), 401 #위 try문의 코드에 error발생 시 예외처리 except DoesNotExist: return jsonify({}), 404 if (service.data_type != 'service' and service.data_type != 'archive-service'): return jsonify({}), 404 logging.debug('Authz succeeded for service {0}.'.format(id)) try: #credential을 가져온다 credentials = _get_credentials(service.credentials) except KeyError: #error발생 시 500error발생 logging.exception('KeyError occurred in getting credentials') return jsonify({'error': 'Decryption error.'}), 500 blind_credentials = _get_blind_credentials(service.blind_credentials) return jsonify({ 'id': service.id, 'account': service.account, 'credentials': credentials, 'blind_credentials': blind_credentials, 'enabled': service.enabled, 'revision': service.revision, 'modified_date': service.modified_date, 'modified_by': service.modified_by }) @app.route('/v1/archive/services/<id>', methods=['GET']) @authnz.require_auth #아카이브 서비스 revision(개정, 정정)가져오는 함수 정의 def get_archive_service_revisions(id): try: service = Service.get(id) except DoesNotExist: logging.warning( 'Item with id {0} does not exist.'.format(id) ) #아이템 없으 시 404error return jsonify({}), 404 #자료 형식 service와 일치하지 않을 시 404error if (service.data_type != 'service' and service.data_type != 'archive-service'): return jsonify({}), 404 #revision list revisions = [] _range = range(1, service.revision + 1) ids = [] for i in _range: #ids리스트에 id들 _range정의된 범위만큼의 id추가 ids.append("{0}-{1}".format(id, i)) for revision in Service.batch_get(ids): #revisions리스트에 ids리스트 크기만큼 아래 내용 추가 revisions.append({ 'id': revision.id, 'account': revision.account, 'revision': revision.revision, 'enabled': revision.enabled, 'credentials': list(revision.credentials), 'blind_credentials': list(revision.blind_credentials), 'modified_date': revision.modified_date, 'modified_by': revision.modified_by }) return jsonify({ 'revisions': sorted( revisions, key=lambda k: k['revision'], reverse=True ) }) @app.route('/v1/archive/services', methods=['GET']) @authnz.require_auth #아카이브 서비스 리스트 가져오는 함수 정의 def get_archive_service_list(): services = [] for service in Service.data_type_date_index.query( 'archive-service', scan_index_forward=False): services.append({ 'id': service.id, 'account': service.account, 'revision': service.revision, 'enabled': service.enabled, 'credentials': list(service.credentials), 'modified_date': service.modified_date, 'modified_by': service.modified_by }) #servises jsonify시켜 리턴 return jsonify({'services': services}) @app.route('/v1/grants/<id>', methods=['PUT']) @authnz.require_auth @authnz.require_csrf_token @maintenance.check_maintenance_mode #해당 id에 아래 예외처리들로 안정성 부여하는 함수 정의 def ensure_grants(id): try: _service = Service.get(id) if _service.data_type != 'service': msg = 'id provided is not a service.' return jsonify({'error': msg}), 400 except DoesNotExist: msg = 'id provided does not exist.' return jsonify({'error': msg}), 400 try: keymanager.ensure_grants(id) except keymanager.ServiceCreateGrantError: msg = 'Failed to add grants for service.' logging.error(msg) return jsonify({'error': msg}), 400 try: grants = keymanager.grants_exist(id) except keymanager.ServiceGetGrantError: msg = 'Failed to get grants.' return jsonify({'error': msg}), 500 return jsonify({ 'id': id, 'grants': grants }) @app.route('/v1/grants/<id>', methods=['GET']) @authnz.require_auth #해당 id grants 가져오는 함수 정의 def get_grants(id): try: _service = Service.get(id) if _service.data_type != 'service': msg = 'id provided is not a service.' return jsonify({'error': msg}), 400 except DoesNotExist: msg = 'id provided does not exist.' return jsonify({'error': msg}), 400 try: grants = keymanager.grants_exist(id) except keymanager.ServiceGetGrantError: msg = 'Failed to get grants.' return jsonify({'error': msg}), 500 #id와 grants jsonify시켜 리턴 return jsonify({ 'id': id, 'grants': grants }) @app.route('/v1/services/<id>', methods=['PUT']) @authnz.require_auth @authnz.require_csrf_token @maintenance.check_maintenance_mode #서비스의 credentials mapping 하는 함수 정의 def map_service_credentials(id): #json 데이터 받아오기 data = request.get_json() try: _service = Service.get(id) #서비스가 아니라면 error if _service.data_type != 'service': msg = 'id provided is not a service.' return jsonify({'error': msg}), 400 revision = _service.revision + 1 _service_credential_ids = _service.credentials except DoesNotExist: revision = 1 _service_credential_ids = [] #존제하는 credentials가 있다면 제어문 안으로 if data.get('credentials') or data.get('blind_credentials'): conflicts = _pair_key_conflicts_for_credentials( data.get('credentials', []), data.get('blind_credentials', []), ) if conflicts: ret = { 'error': 'Conflicting key pairs in mapped service.', 'conflicts': conflicts } return jsonify(ret), 400 accounts = app.config['SCOPED_AUTH_KEYS'].values() if data.get('account') and data['account'] not in accounts: ret = {'error': '{0} is not a valid account.'} return jsonify(ret), 400 # If this is the first revision, we should attempt to create a grant for # this service. #첫 번째 revision인 경우 허가를 부여하기 위한 예외처리 if revision == 1: try: keymanager.ensure_grants(id) except keymanager.ServiceCreateGrantError: msg = 'Failed to add grants for {0}.'.format(id) logging.error(msg) # Try to save to the archive try: Service( id='{0}-{1}'.format(id, revision), data_type='archive-service', credentials=data.get('credentials'), blind_credentials=data.get('blind_credentials'), account=data.get('account'), enabled=data.get('enabled'), revision=revision, modified_by=authnz.get_logged_in_user() ).save(id__null=True) except PutError as e: logging.error(e) return jsonify({'error': 'Failed to add service to archive.'}), 500 try: service = Service( id=id, data_type='service', credentials=data.get('credentials'), blind_credentials=data.get('blind_credentials'), account=data.get('account'), enabled=data.get('enabled'), revision=revision, modified_by=authnz.get_logged_in_user() ) service.save() except PutError as e: logging.error(e) return jsonify({'error': 'Failed to update active service.'}), 500 added = list(set(service.credentials) - set(_service_credential_ids)) removed = list(set(_service_credential_ids) - set(service.credentials)) msg = 'Added credentials: {0}; Removed credentials {1}; Revision {2}' msg = msg.format(added, removed, service.revision) graphite.send_event([id], msg) webhook.send_event('service_update', [service.id], service.credentials) try: credentials = _get_credentials(service.credentials) except KeyError: return jsonify({'error': 'Decryption error.'}), 500 blind_credentials = _get_blind_credentials(service.blind_credentials) return jsonify({ 'id': service.id, 'account': service.account, 'credentials': credentials, 'blind_credentials': blind_credentials, 'revision': service.revision, 'enabled': service.enabled, 'modified_date': service.modified_date, 'modified_by': service.modified_by }) @app.route('/v1/credentials', methods=['GET']) @authnz.require_auth #credential리스트 가져오기 함수 정의 def get_credential_list(): credentials = [] for cred in Credential.data_type_date_index.query('credential'): credentials.append({ 'id': cred.id, 'name': cred.name, 'revision': cred.revision, 'enabled': cred.enabled, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) credentials = sorted(credentials, key=lambda k: k['name']) return jsonify({'credentials': credentials}) @app.route('/v1/credentials/<id>', methods=['GET']) @authnz.require_auth #credential id가져오기 함수 정의 def get_credential(id): try: cred = Credential.get(id) except DoesNotExist: logging.warning( 'Item with id {0} does not exist.'.format(id) ) return jsonify({}), 404 if (cred.data_type != 'credential' and cred.data_type != 'archive-credential'): return jsonify({}), 404 services = [] for service in Service.data_type_date_index.query('service'): services.append(service.id) if cred.data_type == 'credential': context = id else: context = id.split('-')[0] data_key = keymanager.decrypt_datakey( cred.data_key, encryption_context={'id': context} ) cipher_version = cred.cipher_version cipher = CipherManager(data_key, cipher_version) _credential_pairs = cipher.decrypt(cred.credential_pairs) _credential_pairs = json.loads(_credential_pairs) return jsonify({ 'id': id, 'name': cred.name, 'credential_pairs': _credential_pairs, 'metadata': cred.metadata, 'services': services, 'revision': cred.revision, 'enabled': cred.enabled, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) @app.route('/v1/archive/credentials/<id>', methods=['GET']) @authnz.require_auth #아카이브 credential revisions 가져오기 함수 정의 def get_archive_credential_revisions(id): try: cred = Credential.get(id) except DoesNotExist: logging.warning( 'Item with id {0} does not exist.'.format(id) ) return jsonify({}), 404 if (cred.data_type != 'credential' and cred.data_type != 'archive-credential'): return jsonify({}), 404 revisions = [] _range = range(1, cred.revision + 1) ids = [] for i in _range: ids.append("{0}-{1}".format(id, i)) for revision in Credential.batch_get(ids): revisions.append({ 'id': revision.id, 'name': revision.name, 'revision': revision.revision, 'enabled': revision.enabled, 'modified_date': revision.modified_date, 'modified_by': revision.modified_by, 'documentation': revision.documentation }) return jsonify({ 'revisions': sorted( revisions, key=lambda k: k['revision'], reverse=True ) }) @app.route('/v1/archive/credentials', methods=['GET']) @authnz.require_auth #아카이브 credential list 가져오기 함수 정의 def get_archive_credential_list(): credentials = [] for cred in Credential.data_type_date_index.query( 'archive-credential', scan_index_forward=False): credentials.append({ 'id': cred.id, 'name': cred.name, 'revision': cred.revision, 'enabled': cred.enabled, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) return jsonify({'credentials': credentials}) #credentials 가져오는 함수 정의 def _get_credentials(credential_ids): credentials = [] with stats.timer('service_batch_get_credentials'): for cred in Credential.batch_get(copy.deepcopy(credential_ids)): data_key = keymanager.decrypt_datakey( cred.data_key, encryption_context={'id': cred.id} ) cipher_version = cred.cipher_version cipher = CipherManager(data_key, cipher_version) _credential_pairs = cipher.decrypt(cred.credential_pairs) _credential_pairs = json.loads(_credential_pairs) credentials.append({ 'id': cred.id, 'data_type': 'credential', 'name': cred.name, 'enabled': cred.enabled, 'revision': cred.revision, 'credential_pairs': _credential_pairs, 'metadata': cred.metadata, 'documentation': cred.documentation }) return credentials #blind_credentials 가져오는 함수 정의 def _get_blind_credentials(credential_ids): credentials = [] with stats.timer('service_batch_get_blind_credentials'): for cred in BlindCredential.batch_get(copy.deepcopy(credential_ids)): credentials.append({ 'id': cred.id, 'data_type': 'blind-credential', 'name': cred.name, 'enabled': cred.enabled, 'revision': cred.revision, 'credential_pairs': cred.credential_pairs, 'credential_keys': list(cred.credential_keys), 'metadata': cred.metadata, 'data_key': cred.data_key, 'cipher_version': cred.cipher_version, 'cipher_type': cred.cipher_type, 'documentation': cred.documentation }) return credentials #credentials의 key쌍을 얻기 위한 함수 정의 def _pair_key_conflicts_for_credentials(credential_ids, blind_credential_ids): #conflicts, pair_keys 라는 dictionary생성(key-value) conflicts = {} pair_keys = {} # If we don't care about conflicts, return immediately #충돌에 대하여 상관하지않는다면 즉시 리턴 if app.config['IGNORE_CONFLICTS']: return conflicts # For all credentials, get their credential pairs and track which # 모든 credentials에 대해서, 각각의 credential 쌍을 얻는다 # credentials have which keys #credential이 which keys를 가지고 있다. credentials = _get_credentials(credential_ids) credentials.extend(_get_blind_credentials(blind_credential_ids)) for credential in credentials: if credential['data_type'] == 'credential': keys = credential['credential_pairs'] elif credential['data_type'] == 'blind-credential': keys = credential['credential_keys'] for key in keys: data = { 'id': credential['id'], 'data_type': credential['data_type'] } if key in pair_keys: pair_keys[key].append(data) else: pair_keys[key] = [data] # Iterate the credential pair keys, if there's any keys with more than # one credential add it to the conflict dict. #자격증 명 쌍 키 반복, 하나 이상의 credential이있는 키가있는 경우 conflicts dictionary에 추가합니다. for key, data in pair_keys.iteritems(): if len(data) > 1: blind_ids = [k['id'] for k in data if k['data_type'] == 'blind-credential'] ids = [k['id'] for k in data if k['data_type'] == 'credential'] conflicts[key] = { 'credentials': ids, 'blind_credentials': blind_ids } return conflicts #credential 서비스 -> 서비스 리스트에 가져오는 함수 정의 def _get_services_for_credential(_id): services = [] for service in Service.data_type_date_index.query('service'): if _id in service.credentials: services.append(service) return services #blind_credential 서비스 -> 서비스 리스트에 가져오는 함수 정의 def _get_services_for_blind_credential(_id): services = [] for service in Service.data_type_date_index.query('service'): if _id in service.blind_credentials: services.append(service) return services #credential의 쌍을 check하기 위한 함수 정의 def _check_credential_pair_values(credential_pairs): for key, val in credential_pairs.iteritems(): if isinstance(val, dict) or isinstance(val, list): ret = {'error': 'credential pairs must be key: value'} return (False, ret) return (True, {}) #service_map을 가져오기 위한 함수 정의 def _get_service_map(services): service_map = {} for service in services: #credentials를 위한 for credential in service.credentials: #credential에 service_map이 있다면 append를 통해 if credential in service_map: service_map[credential]['service_ids'].append(service.id) else: service_map[credential] = { 'data_type': 'credential', 'service_ids': [service.id] } #blind_credentials를 위한 원리는 credentials 와 동일 for credential in service.blind_credentials: if credential in service_map: service_map[credential]['service_ids'].append(service.id) else: service_map[credential] = { 'data_type': 'blind-credential', 'service_ids': [service.id] } return service_map #services의 key쌍을 얻기 위한 함수 정의 def _pair_key_conflicts_for_services(_id, credential_keys, services): conflicts = {} # If we don't care about conflicts, return immediately #충돌에 대해 상관하지 않는다면 즉시 리턴한다. if app.config['IGNORE_CONFLICTS']: return conflicts #service_map불러오기 service_map = _get_service_map(services) credential_ids = [] blind_credential_ids = [] for credential, data in service_map.iteritems(): #id,credential매칭 if _id == credential: continue #credential인 경우와 blind_credential인 경우를 나누어서 append if data['data_type'] == 'credential': credential_ids.append(credential) elif data['data_type'] == 'blind-credential': blind_credential_ids.append(credential) #credentials 가져오기 credentials = _get_credentials(credential_ids) #blind_credential_ids추가 credentials.extend(_get_blind_credentials(blind_credential_ids)) for credential in credentials: services = service_map[credential['id']]['service_ids'] if credential['data_type'] == 'credential': data_type = 'credentials' lookup = 'credential_pairs' elif credential['data_type'] == 'blind-credential': data_type = 'blind_credentials' lookup = 'credential_keys' for key in credential_keys: if key in credential[lookup]: if key not in conflicts: conflicts[key] = { data_type: [credential['id']], 'services': services } else: conflicts[key]['services'].extend(services) conflicts[key][data_type].append(credential['id']) conflicts[key]['services'] = list( set(conflicts[key]['services']) ) conflicts[key][data_type] = list( set(conflicts[key][data_type]) ) return conflicts #credential_pairs 소문자로 변경 함수 정의 def _lowercase_credential_pairs(credential_pairs): return {i.lower(): j for i, j in credential_pairs.iteritems()} @app.route('/v1/credentials', methods=['POST']) @authnz.require_auth @authnz.require_csrf_token @maintenance.check_maintenance_mode #credential생성 함수 정의 def create_credential(): data = request.get_json() #data들을 받아오지 못한경우 error처리 발생 if not data.get('documentation') and settings.get('ENFORCE_DOCUMENTATION'): return jsonify({'error': 'documentation is a required field'}), 400 if not data.get('credential_pairs'): return jsonify({'error': 'credential_pairs is a required field'}), 400 if not isinstance(data.get('metadata', {}), dict): return jsonify({'error': 'metadata must be a dict'}), 400 # Ensure credential pair keys are lowercase # credential pair key들이 소문자인지 안전하게 하기 위해 다시 사용 credential_pairs = _lowercase_credential_pairs(data['credential_pairs']) _check, ret = _check_credential_pair_values(credential_pairs) #check해서 false이면 error발생 if not _check: return jsonify(ret), 400 for cred in Credential.data_type_date_index.query( 'credential', name__eq=data['name']): # Conflict, the name already exists # 이미 이름이 있는지 점검 있으면 error발생 msg = 'Name already exists. See id: {0}'.format(cred.id) return jsonify({'error': msg, 'reference': cred.id}), 409 # Generate an initial stable ID to allow name changes # 이름 변경을 허용하기 위해 아래 id만들기 id = str(uuid.uuid4()).replace('-', '') # Try to save to the archive # 아카이브에 저장하기 위해 revision = 1 # credential_pairs json인코딩을 위해 credential_pairs = json.dumps(credential_pairs) #key 생성 data_key = keymanager.create_datakey(encryption_context={'id': id}) #key암호화(??확실x) cipher = CipherManager(data_key['plaintext'], version=2) credential_pairs = cipher.encrypt(credential_pairs) cred = Credential( id='{0}-{1}'.format(id, revision), data_type='archive-credential', name=data['name'], credential_pairs=credential_pairs, metadata=data.get('metadata'), revision=revision, enabled=data.get('enabled'), data_key=data_key['ciphertext'], cipher_version=2, modified_by=authnz.get_logged_in_user(), documentation=data.get('documentation') ).save(id__null=True) # Make this the current revision # 현재 버전으로 만든다 cred = Credential( id=id, data_type='credential', name=data['name'], credential_pairs=credential_pairs, metadata=data.get('metadata'), revision=revision, enabled=data.get('enabled'), data_key=data_key['ciphertext'], cipher_version=2, modified_by=authnz.get_logged_in_user(), documentation=data.get('documentation') ) #저장 cred.save() #마무리 최종 저장된 값들 리턴 return jsonify({ 'id': cred.id, 'name': cred.name, 'credential_pairs': json.loads(cipher.decrypt(cred.credential_pairs)), 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) @app.route('/v1/credentials/<id>/services', methods=['GET']) @authnz.require_auth #credential의 종속물 가져오는 함수정의 def get_credential_dependencies(id): services = _get_services_for_credential(id) _services = [{'id': x.id, 'enabled': x.enabled} for x in services] return jsonify({ 'services': _services }) @app.route('/v1/credentials/<id>', methods=['PUT']) @authnz.require_auth @authnz.require_csrf_token @maintenance.check_maintenance_mode #credential 업데이트 하는 함수 정의 def update_credential(id): #credentialid가져오는 중 없을 경우 error발생 예외처리 try: _cred = Credential.get(id) except DoesNotExist: return jsonify({'error': 'Credential not found.'}), 404 #자료의 종류가 credential인지 아닌지 check 아닐 경우 error msg와 함께 리턴 if _cred.data_type != 'credential': msg = 'id provided is not a credential.' return jsonify({'error': msg}), 400 #데이터 갖고온다 data = request.get_json() #update라는 dictionary생성 update = {} #가장 최근의 revision을 가져온다 revision = _get_latest_credential_revision(id, _cred.revision) #이름 업데이트 update['name'] = data.get('name', _cred.name) #data에 'enabled'이 있을 경우 제어문 안으로 if 'enabled' in data: #허용 안되는 부분이 bool 인스턴스가 아니라면 error발생 if not isinstance(data['enabled'], bool): return jsonify({'error': 'Enabled must be a boolean.'}), 400 #'enabled'data 대입 update['enabled'] = data['enabled'] else: #data에 없다면 _cred에서 대입 update['enabled'] = _cred.enabled #metadata가 dictionary타입이 아닌 경우 error발생 if not isinstance(data.get('metadata', {}), dict): return jsonify({'error': 'metadata must be a dict'}), 400 #credential의 서비스 가져오기 services = _get_services_for_credential(id) #data에 credential_pairs가 있다면 제어문 안으로 if 'credential_pairs' in data: # Ensure credential pair keys are lowercase # credential pair key가 소문자인지 확실하게 하기 위해 소문자로 만드는 함수를 사용해 credential_pairs가져오기 credential_pairs = _lowercase_credential_pairs( data['credential_pairs'] ) #확인하기 위해 확인 값 가져오기 _check, ret = _check_credential_pair_values(credential_pairs) #확인 if not _check: return jsonify(ret), 400 # Ensure credential pairs don't conflicts with pairs from other services # 다른 서비스와 충돌하지 않는지 확인 conflicts = _pair_key_conflicts_for_services( id, credential_pairs.keys(), services ) # 충돌한다면 error발생 if conflicts: ret = { 'error': 'Conflicting key pairs in mapped service.', 'conflicts': conflicts } return jsonify(ret), 400 update['credential_pairs'] = json.dumps(credential_pairs) #data에 credential_pairs가 없다면 제어문 안으로 else: #key생성 data_key = keymanager.decrypt_datakey( _cred.data_key, encryption_context={'id': id} ) cipher_version = _cred.cipher_version cipher = CipherManager(data_key, cipher_version) update['credential_pairs'] = cipher.decrypt(_cred.credential_pairs) data_key = keymanager.create_datakey(encryption_context={'id': id}) cipher = CipherManager(data_key['plaintext'], version=2) credential_pairs = cipher.encrypt(update['credential_pairs']) update['metadata'] = data.get('metadata', _cred.metadata) update['documentation'] = data.get('documentation', _cred.documentation) # Enforce documentation, EXCEPT if we are restoring an old revision #오래된 버전을 복원 중이지 않는 이상 문서 실행 if (not update['documentation'] and settings.get('ENFORCE_DOCUMENTATION') and not data.get('revision')): return jsonify({'error': 'documentation is a required field'}), 400 # Try to save to the archive # 아카이브 저장을 위한 try문 try: Credential( id='{0}-{1}'.format(id, revision), name=update['name'], data_type='archive-credential', credential_pairs=credential_pairs, metadata=update['metadata'], enabled=update['enabled'], revision=revision, data_key=data_key['ciphertext'], cipher_version=2, modified_by=authnz.get_logged_in_user(), documentation=update['documentation'] ).save(id__null=True) except PutError as e: logging.error(e) return jsonify({'error': 'Failed to add credential to archive.'}), 500 try: cred = Credential( id=id, name=update['name'], data_type='credential', credential_pairs=credential_pairs, metadata=update['metadata'], enabled=update['enabled'], revision=revision, data_key=data_key['ciphertext'], cipher_version=2, modified_by=authnz.get_logged_in_user(), documentation=update['documentation'] ) cred.save() except PutError as e: logging.error(e) return jsonify({'error': 'Failed to update active credential.'}), 500 if services: service_names = [x.id for x in services] msg = 'Updated credential "{0}" ({1}); Revision {2}' msg = msg.format(cred.name, cred.id, cred.revision) graphite.send_event(service_names, msg) webhook.send_event('credential_update', service_names, [cred.id]) #update된 내용 리턴 return jsonify({ 'id': cred.id, 'name': cred.name, 'credential_pairs': json.loads(cipher.decrypt(cred.credential_pairs)), 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) @app.route('/v1/blind_credentials', methods=['GET']) @authnz.require_auth # blind credential list가져오는 함수 정의 def get_blind_credential_list(): blind_credentials = [] for cred in BlindCredential.data_type_date_index.query('blind-credential'): blind_credentials.append({ 'id': cred.id, 'name': cred.name, 'revision': cred.revision, 'enabled': cred.enabled, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) return jsonify({'blind_credentials': blind_credentials}) @app.route('/v1/blind_credentials/<id>', methods=['GET']) @authnz.require_auth # blind credential 가져오는 함수 정의 def get_blind_credential(id): #id로 부터 가져오는 try문 중 error발생 시 예외처리 try: cred = BlindCredential.get(id) except DoesNotExist: logging.warning( 'Item with id {0} does not exist.'.format(id) ) return jsonify({}), 404 # 자료 형식 일치하지 않을 시 error if (cred.data_type != 'blind-credential' and cred.data_type != 'archive-blind-credential'): return jsonify({}), 404 return jsonify({ 'id': cred.id, 'name': cred.name, 'credential_pairs': cred.credential_pairs, 'credential_keys': list(cred.credential_keys), 'cipher_type': cred.cipher_type, 'cipher_version': cred.cipher_version, 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'data_key': cred.data_key, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) #최근의 credential의 revision 가져오는 함수 정의 def _get_latest_credential_revision(id, revision): i = revision + 1 while True: _id = '{0}-{1}'.format(id, i) try: Credential.get(_id) except DoesNotExist: return i i = i + 1 #최근의 blind credential의 revision 가져오는 함수 정의 def _get_latest_blind_credential_revision(id, revision): i = revision + 1 while True: _id = '{0}-{1}'.format(id, i) try: BlindCredential.get(_id) except DoesNotExist: return i i = i + 1 @app.route('/v1/archive/blind_credentials/<id>', methods=['GET']) @authnz.require_auth #아카이브 blind credential revision들을 가져오는 함수 정의 def get_archive_blind_credential_revisions(id): #해당 id의 blind_credential 가져오는 try문 없을 경우 예외처리 try: cred = BlindCredential.get(id) except DoesNotExist: return jsonify({}), 404 #자료 형식이 'blind-credential', 'archive-blind-credential'이 아닌 경우 warning if (cred.data_type != 'blind-credential' and cred.data_type != 'archive-blind-credential'): logging.warning( 'Item with id {0} does not exist.'.format(id) ) return jsonify({}), 404 revisions = [] _range = range(1, cred.revision + 1) ids = [] #ids에 revisions들 추가 for i in _range: ids.append("{0}-{1}".format(id, i)) for revision in BlindCredential.batch_get(ids): revisions.append({ 'id': cred.id, 'name': cred.name, 'credential_pairs': cred.credential_pairs, 'credential_keys': list(cred.credential_keys), 'cipher_type': cred.cipher_type, 'cipher_version': cred.cipher_version, 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'data_key': cred.data_key, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) #jsonify 시켜 revisions리턴 return jsonify({ 'revisions': sorted( revisions, key=lambda k: k['revision'], reverse=True ) }) @app.route('/v1/archive/blind_credentials', methods=['GET']) @authnz.require_auth #아카이브 blind credential list 가져오는 함수 정의 def get_archive_blind_credential_list(): blind_credentials = [] for cred in BlindCredential.data_type_date_index.query( 'archive-blind-credential', scan_index_forward=False): blind_credentials.append({ 'id': cred.id, 'name': cred.name, 'credential_pairs': cred.credential_pairs, 'credential_keys': list(cred.credential_keys), 'cipher_type': cred.cipher_type, 'cipher_version': cred.cipher_version, 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'data_key': cred.data_key, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) return jsonify({'blind_credentials': blind_credentials}) @app.route('/v1/blind_credentials', methods=['POST']) @authnz.require_auth @authnz.require_csrf_token @maintenance.check_maintenance_mode #blind_credential생성하는 함수정의 def create_blind_credential(): data = request.get_json() missing = [] ###################################################################### required_args = ['cipher_version', 'cipher_type', 'credential_pairs', 'data_key'] if settings.get('ENFORCE_DOCUMENTATION'): required_args.append('documentation') for arg in required_args: if not data.get(arg): missing.append(arg) if missing: return jsonify({ 'error': 'The following fields are required: {0}'.format(missing) }), 400 if not isinstance(data['data_key'], dict): return jsonify({ 'error': 'data_key must be a dict with a region/key mapping.' }), 400 if not isinstance(data.get('credential_keys', []), list): return jsonify({ 'error': 'credential_keys must be a list.' }), 400 if not isinstance(data.get('metadata', {}), dict): return jsonify({'error': 'metadata must be a dict'}), 400 for cred in BlindCredential.data_type_date_index.query( 'blind-credential', name__eq=data['name']): # Conflict, the name already exists #이름이 이미 존제 할 시 충돌 발생 msg = 'Name already exists. See id: {0}'.format(cred.id) return jsonify({'error': msg, 'reference': cred.id}), 409 # Generate an initial stable ID to allow name changes id = str(uuid.uuid4()).replace('-', '') # Try to save to the archive # 아카이브 저장 시도 revision = 1 cred = BlindCredential( id='{0}-{1}'.format(id, revision), data_type='archive-blind-credential', name=data['name'], credential_pairs=data['credential_pairs'], credential_keys=data.get('credential_keys'), metadata=data.get('metadata'), revision=revision, enabled=data.get('enabled'), data_key=data['data_key'], cipher_type=data['cipher_type'], cipher_version=data['cipher_version'], modified_by=authnz.get_logged_in_user(), documentation=data.get('documentation') ).save(id__null=True) # Make this the current revision # 현재 버전으로 만든다 cred = BlindCredential( id=id, data_type='blind-credential', name=data['name'], credential_pairs=data['credential_pairs'], credential_keys=data.get('credential_keys'), metadata=data.get('metadata'), revision=revision, enabled=data.get('enabled'), data_key=data['data_key'], cipher_type=data['cipher_type'], cipher_version=data['cipher_version'], modified_by=authnz.get_logged_in_user(), documentation=data.get('documentation') ) #저장 cred.save() #최종 저장된 값들을 리턴 return jsonify({ 'id': cred.id, 'name': cred.name, 'credential_pairs': cred.credential_pairs, 'credential_keys': list(cred.credential_keys), 'cipher_type': cred.cipher_type, 'cipher_version': cred.cipher_version, 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'data_key': cred.data_key, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) @app.route('/v1/blind_credentials/<id>/services', methods=['GET']) @authnz.require_auth # blind credential dependencies 가져오는 함수 정의 def get_blind_credential_dependencies(id): services = _get_services_for_blind_credential(id) _services = [{'id': x.id, 'enabled': x.enabled} for x in services] return jsonify({ 'services': _services }) @app.route('/v1/blind_credentials/<id>', methods=['PUT']) @authnz.require_auth @authnz.require_csrf_token @maintenance.check_maintenance_mode #blind_credential 업데이트 하는 함수 정의 (방법은 credential업데이트와 비슷) def update_blind_credential(id): try: _cred = BlindCredential.get(id) except DoesNotExist: return jsonify({'error': 'Blind credential not found.'}), 404 if _cred.data_type != 'blind-credential': msg = 'id provided is not a blind-credential.' return jsonify({'error': msg}), 400 data = request.get_json() update = {} revision = _get_latest_blind_credential_revision(id, _cred.revision) update['name'] = data.get('name', _cred.name) if 'enabled' in data: if not isinstance(data['enabled'], bool): return jsonify({'error': 'Enabled must be a boolean.'}), 400 update['enabled'] = data['enabled'] else: update['enabled'] = _cred.enabled if not isinstance(data.get('metadata', {}), dict): return jsonify({'error': 'metadata must be a dict'}), 400 services = _get_services_for_blind_credential(id) if 'credential_pairs' in data: for key in ['data_key', 'cipher_type', 'cipher_version']: if key not in data: msg = '{0} required when updating credential_pairs.' msg = msg.format(key) return jsonify({'error': msg}), 400 update['credential_pairs'] = data['credential_pairs'] update['credential_keys'] = data.get('credential_keys', []) if not isinstance(update['credential_keys'], list): return jsonify({ 'error': 'credential_keys must be a list.' }), 400 # Ensure credential keys don't conflicts with pairs from other # services conflicts = _pair_key_conflicts_for_services( id, data['credential_keys'], services ) if conflicts: ret = { 'error': 'Conflicting key pairs in mapped service.', 'conflicts': conflicts } return jsonify(ret), 400 if not isinstance(data['data_key'], dict): return jsonify({ 'error': 'data_key must be a dict with a region/key mapping.' }), 400 update['data_key'] = data['data_key'] update['cipher_type'] = data['cipher_type'] update['cipher_version'] = data['cipher_version'] else: update['credential_pairs'] = _cred.credential_pairs update['credential_keys'] = _cred.credential_keys update['data_key'] = _cred.data_key update['cipher_type'] = _cred.cipher_type update['cipher_version'] = _cred.cipher_version update['metadata'] = data.get('metadata', _cred.metadata) update['documentation'] = data.get('documentation', _cred.documentation) # Enforce documentation, EXCEPT if we are restoring an old revision if (not update['documentation'] and settings.get('ENFORCE_DOCUMENTATION') and not data.get('revision')): return jsonify({'error': 'documentation is a required field'}), 400 # Try to save to the archive try: BlindCredential( id='{0}-{1}'.format(id, revision), data_type='archive-blind-credential', name=update['name'], credential_pairs=update['credential_pairs'], credential_keys=update['credential_keys'], metadata=update['metadata'], revision=revision, enabled=update['enabled'], data_key=update['data_key'], cipher_type=update['cipher_type'], cipher_version=update['cipher_version'], modified_by=authnz.get_logged_in_user(), documentation=update['documentation'] ).save(id__null=True) except PutError as e: logging.error(e) return jsonify( {'error': 'Failed to add blind-credential to archive.'} ), 500 try: cred = BlindCredential( id=id, data_type='blind-credential', name=update['name'], credential_pairs=update['credential_pairs'], credential_keys=update['credential_keys'], metadata=update['metadata'], revision=revision, enabled=update['enabled'], data_key=update['data_key'], cipher_type=update['cipher_type'], cipher_version=update['cipher_version'], modified_by=authnz.get_logged_in_user(), documentation=update['documentation'] ) cred.save() except PutError as e: logging.error(e) return jsonify( {'error': 'Failed to update active blind-credential.'} ), 500 if services: service_names = [x.id for x in services] msg = 'Updated credential "{0}" ({1}); Revision {2}' msg = msg.format(cred.name, cred.id, cred.revision) graphite.send_event(service_names, msg) webhook.send_event('blind_credential_update', service_names, [cred.id]) return jsonify({ 'id': cred.id, 'name': cred.name, 'credential_pairs': cred.credential_pairs, 'credential_keys': list(cred.credential_keys), 'cipher_type': cred.cipher_type, 'cipher_version': cred.cipher_version, 'metadata': cred.metadata, 'revision': cred.revision, 'enabled': cred.enabled, 'data_key': cred.data_key, 'modified_date': cred.modified_date, 'modified_by': cred.modified_by, 'documentation': cred.documentation }) @app.route('/v1/value_generator', methods=['GET']) #kms값 생성하는 함수 정의 def generate_value(): value = kms_client.generate_random(NumberOfBytes=128)['Plaintext'] value = base64.urlsafe_b64encode(value) value = re.sub('[\W_]+', '', value) if len(value) > VALUE_LENGTH: value = value[:VALUE_LENGTH] return jsonify({'value': value})
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,804
KimSunUk/confidant
refs/heads/master
/confidant/models/session_cls.py
from botocore.vendored.requests import Session as BotoRequestsSession from botocore.vendored.requests.adapters import HTTPAdapter as BotoHTTPAdapter from confidant.app import app class DDBSession(BotoRequestsSession): def __init__(self): super(DDBSession, self).__init__() self.mount('https://', BotoHTTPAdapter( pool_maxsize=app.config['PYNAMO_CONNECTION_POOL_SIZE'] )) self.mount('http://', BotoHTTPAdapter( pool_maxsize=app.config['PYNAMO_CONNECTION_POOL_SIZE'] ))
{"/confidant/routes/v1.py": ["/confidant/utils/__init__.py"]}
23,809
laranea/coronavirus-wallpaper
refs/heads/master
/wallpaper.py
import os import ctypes import PIL import api import config from PIL import Image, ImageFilter, ImageDraw, ImageFont d = os.getcwd() # Get current working dir globally def set_wallpaper_from_file(filename: str): use = os.path.normpath(config.resource_path(filename)) ctypes.windll.user32.SystemParametersInfoW(20, 0, use, 0) def generate_wallpaper_and_set(): image = Image.open(config.resource_path('img/base.png')) small = ImageFont.truetype('arial.ttf', 72) large = ImageFont.truetype('arial.ttf', 90) draw = ImageDraw.Draw(image) if config.load_option_from_config('country') != "World": draw.text(xy=(815,359), text=str(api.get_country_stats(api.get_country_id(config.load_option_from_config('country')))[0]), fill = (255,255,255), font=large) draw.text(xy=(490,680), text=str(api.get_country_stats(api.get_country_id(config.load_option_from_config('country')))[1]), fill = (255,255,255), font=small) draw.text(xy=(1265,680), text=str(api.get_country_stats(api.get_country_id(config.load_option_from_config('country')))[2]), fill = (255,255,255), font=small) else: draw.text(xy=(815,359), text=str(api.get_world_cases()[0]), fill = (255,255,255), font=large) draw.text(xy=(490,680), text=str(api.get_world_cases()[1]), fill = (255,255,255), font=small) draw.text(xy=(1265,680), text=str(api.get_world_cases()[2]), fill = (255,255,255), font=small) image.save(config.resource_path('wallpaper.png')) set_wallpaper_from_file('wallpaper.png')
{"/wallpaper.py": ["/api.py"]}
23,810
laranea/coronavirus-wallpaper
refs/heads/master
/api.py
import COVID19Py correspondence = { "Thailand":0, "Japan":1, "Singapore":2, "Nepal":3, "Malaysia":4, "British Columbia, CA":5, "New South Wales, AU":6, "Victoria, AU":7, "Queensland, AU":8, "Cambodia":9, "Sri Lanka":10, "Germany":11, "Finland":12, "United Arab Emirates":13, "Philippines":14, "India":15, "Italy":16, "Sweden":17, "Spain":18, "South Australia, AU":19, "Belgium":20, "Egypt":21, "From Diamond Princess, AU":22, "Lebanon":23, "Iraq":24, "Oman":25, "Afghanistan":26, "Bahrain":27, "Kuwait":28, "Algeria":29, "Croatia":30, "Switzerland":31, "Austria":32, "Israel":33, "Pakistan":34, "Brazil":35, "Georgia":36, "Greece":37, "North Macedonia":38, "Norway":39, "Romania":40, "Estonia":41, "San Marino":42, "Belarus":43, "Iceland":44, "Lithuania":45, "Mexico":46, "New Zealand":47, "Nigeria":48, "Western Australia, AU":49, "Ireland":50, "Luxembourg":51, "Monaco":52, "Qatar":53, "Ecuador":54, "Azerbaijan":55, "Armenia":56, "Dominican Republic":57, "Indonesia":58, "Portugal":59, "Andorra":60, "Tasmania, AU":61, "Latvia":62, "Morocco":63, "Saudi Arabia":64, "Senegal":65, "Argentina":66, "Chile":67, "Jordan":68, "Ukraine":69, "Hungary":70, "Northern Territory, AU":71, "Liechtenstein":72, "Poland":73, "Tunisia":74, "Bosnia and Herzegovina":75, "Slovenia":76, "South Africa":77, "Bhutan":78, "Cameroon":79, "Colombia":80, "Costa Rica":81, "Peru":82, "Serbia":83, "Slovakia":84, "Togo":85, "Malta":86, "Martinique":87, "Bulgaria":88, "Maldives":89, "Bangladesh":90, "Paraguay":91, "Ontario, CA":92, "Alberta, CA":93, "Quebec, CA":94, "Albania":95, "Cyprus":96, "Brunei":97, "Washington, US":98, "New York, US":99, "California, US":100, "Massachusetts, US":101, "Diamond Princess, US":102, "Grand Princess, US":103, "Georgia, US":104, "Colorado, US":105, "Florida, US":106, "New Jersey, US":107, "Oregon, US":108, "Texas, US":109, "Illinois, US":110, "Pennsylvania, US":111, "Iowa, US":112, "Maryland, US":113, "North Carolina, US":114, "South Carolina, US":115, "Tennessee, US":116, "Virginia, US":117, "Arizona, US":118, "Indiana, US":119, "Kentucky, US":120, "District of Columbia, US":121, "Nevada, US":122, "New Hampshire, US":123, "Minnesota, US":124, "Nebraska, US":125, "Ohio, US":126, "Rhode Island, US":127, "Wisconsin, US":128, "Connecticut, US":129, "Hawaii, US":130, "Oklahoma, US":131, "Utah, US":132, "Burkina Faso":133, "Holy See":134, "Mongolia":135, "Panama":136, "Kansas, US":137, "Louisiana, US":138, "Missouri, US":139, "Vermont, US":140, "Alaska, US":141, "Arkansas, US":142, "Delaware, US":143, "Idaho, US":144, "Maine, US":145, "Michigan, US":146, "Mississippi, US":147, "Montana, US":148, "New Mexico, US":149, "North Dakota, US":150, "South Dakota, US":151, "West Virginia, US":152, "Wyoming, US":153, "Hubei, CN":154, "Iran":155, "Korea, South":156, "France, FR":157, "Guangdong, CN":158, "Henan, CN":159, "Zhejiang, CN":160, "Hunan, CN":161, "Anhui, CN":162, "Jiangxi, CN":163, "Shandong, CN":164, "Diamond Princess, XX":165, "Jiangsu, CN":166, "Chongqing, CN":167, "Sichuan, CN":168, "Heilongjiang, CN":169, "Denmark, DK":170, "Beijing, CN":171, "Shanghai, CN":172, "Hebei, CN":173, "Fujian, CN":174, "Guangxi, CN":175, "Shaanxi, CN":176, "Yunnan, CN":177, "Hainan, CN":178, "Guizhou, CN":179, "Tianjin, CN":180, "Shanxi, CN":181, "Gansu, CN":182, "Hong Kong, CN":183, "Liaoning, CN":184, "Jilin, CN":185, "Czechia":186, "Xinjiang, CN":187, "Inner Mongolia, CN":188, "Ningxia, CN":189, "Taiwan*":190, "Vietnam":191, "Russia":192, "Qinghai, CN":193, "Macau, CN":194, "Moldova":195, "Bolivia":196, "Faroe Islands, DK":197, "St Martin, FR":198, "Honduras":199, "Channel Islands, GB":200, "New Brunswick, CA":201, "Tibet, CN":202, "Congo (Kinshasa)":203, "Cote d'Ivoire":204, "Saint Barthelemy, FR":205, "Jamaica":206, "Turkey":207, "Gibraltar, GB":208, "Kitsap, WA, US":209, "Solano, CA, US":210, "Santa Cruz, CA, US":211, "Napa, CA, US":212, "Ventura, CA, US":213, "Worcester, MA, US":214, "Gwinnett, GA, US":215, "DeKalb, GA, US":216, "Floyd, GA, US":217, "Fayette, GA, US":218, "Gregg, TX, US":219, "Monmouth, NJ, US":220, "Burlington, NJ, US":221, "Camden, NJ, US":222, "Passaic, NJ, US":223, "Union, NJ, US":224, "Eagle, CO, US":225, "Larimer, CO, US":226, "Arapahoe, CO, US":227, "Gunnison, CO, US":228, "Kane, IL, US":229, "Monroe, PA, US":230, "Philadelphia, PA, US":231, "Norfolk, VA, US":232, "Arlington, VA, US":233, "Spotsylvania, VA, US":234, "Loudoun, VA, US":235, "Prince George's, MD, US":236, "Pottawattamie, IA, US":237, "Camden, NC, US":238, "Pima, AZ, US":239, "Noble, IN, US":240, "Adams, IN, US":241, "Boone, IN, US":242, "Dane, WI, US":243, "Pierce, WI, US":244, "Cuyahoga, OH, US":245, "Weber, UT, US":246, "Bennington County, VT, US":247, "Carver County, MN, US":248, "Charlotte County, FL, US":249, "Cherokee County, GA, US":250, "Collin County, TX, US":251, "Jefferson County, KY, US":252, "Jefferson Parish, LA, US":253, "Shasta County, CA, US":254, "Spartanburg County, SC, US":255, "Harrison County, KY, US":256, "Johnson County, IA, US":257, "Berkshire County, MA, US":258, "Davidson County, TN, US":259, "Douglas County, OR, US":260, "Fresno County, CA, US":261, "Harford County, MD, US":262, "Hendricks County, IN, US":263, "Hudson County, NJ, US":264, "Johnson County, KS, US":265, "Kittitas County, WA, US":266, "Manatee County, FL, US":267, "Marion County, OR, US":268, "Okaloosa County, FL, US":269, "Polk County, GA, US":270, "Riverside County, CA, US":271, "Shelby County, TN, US":272, "St, Louis County, MO, US":273, "Suffolk County, NY, US":274, "Ulster County, NY, US":275, "Volusia County, FL, US":276, "Fairfax County, VA, US":277, "Rockingham County, NH, US":278, "Washington, DC, US":279, "Montgomery County, PA, US":280, "Alameda County, CA, US":281, "Broward County, FL, US":282, "Lee County, FL, US":283, "Pinal County, AZ, US":284, "Rockland County, NY, US":285, "Saratoga County, NY, US":286, "Charleston County, SC, US":287, "Clark County, WA, US":288, "Cobb County, GA, US":289, "Davis County, UT, US":290, "El Paso County, CO, US":291, "Honolulu County, HI, US":292, "Jackson County, OR, US":293, "Jefferson County, WA, US":294, "Kershaw County, SC, US":295, "Klamath County, OR, US":296, "Madera County, CA, US":297, "Pierce County, WA, US":298, "Tulsa County, OK, US":299, "Douglas County, CO, US":300, "Providence County, RI, US":301, "Chatham County, NC, US":302, "Delaware County, PA, US":303, "Douglas County, NE, US":304, "Fayette County, KY, US":305, "Marion County, IN, US":306, "Middlesex County, MA, US":307, "Nassau County, NY, US":308, "Ramsey County, MN, US":309, "Washoe County, NV, US":310, "Wayne County, PA, US":311, "Yolo County, CA, US":312, "Santa Clara County, CA, US":313, "Clark County, NV, US":314, "Fort Bend County, TX, US":315, "Grant County, WA, US":316, "Santa Rosa County, FL, US":317, "Williamson County, TN, US":318, "New York County, NY, US":319, "Montgomery County, MD, US":320, "Suffolk County, MA, US":321, "Denver County, CO, US":322, "Summit County, CO, US":323, "Bergen County, NJ, US":324, "Harris County, TX, US":325, "San Francisco County, CA, US":326, "Contra Costa County, CA, US":327, "Orange County, CA, US":328, "Norfolk County, MA, US":329, "Maricopa County, AZ, US":330, "Wake County, NC, US":331, "Westchester County, NY, US":332, "Grafton County, NH, US":333, "Hillsborough, FL, US":334, "Placer County, CA, US":335, "San Mateo, CA, US":336, "Sonoma County, CA, US":337, "Umatilla, OR, US":338, "Fulton County, GA, US":339, "Washington County, OR, US":340, "Snohomish County, WA, US":341, "Humboldt County, CA, US":342, "Sacramento County, CA, US":343, "San Diego County, CA, US":344, "San Benito, CA, US":345, "Los Angeles, CA, US":346, "King County, WA, US":347, "Cook County, IL, US":348, "Skagit, WA, US":349, "Thurston, WA, US":350, "Island, WA, US":351, "Whatcom, WA, US":352, "Marin, CA, US":353, "Calaveras, CA, US":354, "Stanislaus, CA, US":355, "San Joaquin, CA, US":356, "Essex, MA, US":357, "Charlton, GA, US":358, "Collier, FL, US":359, "Pinellas, FL, US":360, "Alachua, FL, US":361, "Nassau, FL, US":362, "Pasco, FL, US":363, "Dallas, TX, US":364, "Tarrant, TX, US":365, "Montgomery, TX, US":366, "Middlesex, NJ, US":367, "Jefferson, CO, US":368, "Multnomah, OR, US":369, "Polk, OR, US":370, "Deschutes, OR, US":371, "McHenry, IL, US":372, "Lake, IL, US":373, "Bucks, PA, US":374, "Hanover, VA, US":375, "Lancaster, SC, US":376, "Sullivan, TN, US":377, "Johnson, IN, US":378, "Howard, IN, US":379, "St, Joseph, IN, US":380, "Knox, NE, US":381, "Stark, OH, US":382, "Anoka, MN, US":383, "Olmsted, MN, US":384, "Summit, UT, US":385, "Fairfield, CT, US":386, "Litchfield, CT, US":387, "Orleans, LA, US":388, "Pennington, SD, US":389, "Beadle, SD, US":390, "Charles Mix, SD, US":391, "Davison, SD, US":392, "Minnehaha, SD, US":393, "Bon Homme, SD, US":394, "Socorro, NM, US":395, "Bernalillo, NM, US":396, "Oakland, MI, US":397, "Wayne, MI, US":398, "New Castle, DE, US":399, "Cuba":400, "Guyana":401, "Australian Capital Territory, AU":402, "United Kingdom, GB":403, "Kazakhstan":404, "French Polynesia, FR":405, "Manitoba, CA":406, "Saskatchewan, CA":407, "Ethiopia":408, "Sudan":409, "Guinea":410, "Grand Princess, CA":411, "Kenya":412, "Antigua and Barbuda":413, "Alabama, US":414, "Uruguay":415, "Ghana":416, "Puerto Rico, US":417, "Namibia":418, "Seychelles":419, "Trinidad and Tobago":420, "Venezuela":421, "Eswatini":422, "Gabon":423, "Guatemala":424, "Mauritania":425, "Rwanda":426, "Saint Lucia":427, "Saint Vincent and the Grenadines":428, "Suriname":429, "French Guiana, FR":430, "Guam, US":431, "Kosovo":432, "Newfoundland and Labrador, CA":433, "Prince Edward Island, CA":434, "Central African Republic":435, "Congo (Brazzaville)":436, "Equatorial Guinea":437, "Mayotte, FR":438, "Uzbekistan":439, "Netherlands, NL":440, "Nova Scotia, CA":441, "Guadeloupe, FR":442, "Benin":443, "Greenland":444, "Liberia":445, "Curacao, NL":446, "Somalia":447, "Tanzania":448, "The Bahamas":449, "Virgin Islands, US":450, "Cayman Islands, GB":451, "Reunion, FR":452, "Barbados":453, "Montenegro":454, "Kyrgyzstan":455, "Mauritius":456, "Aruba, NL":457, "Zambia":458, "Djibouti":459, "Gambia, The":460, "Montserrat, GB":461 } def get_world_cases(): covid19 = COVID19Py.COVID19() data = covid19.getLatest() return data['confirmed'], data['deaths'], data['recovered'] def get_country_id(name: str): return correspondence[name] def get_country_stats(c_id: int): covid19 = COVID19Py.COVID19() data = covid19.getLocationById(c_id) return data['latest']['confirmed'], data['latest']['deaths'], data['latest']['recovered'] def get_country_list(): l = ["World"] for i in correspondence: l.append(i.replace('.', ',')) return l
{"/wallpaper.py": ["/api.py"]}
23,886
johnfelipe/pmg-cms-2
refs/heads/master
/backend/models.py
from random import random import string import datetime import logging from sqlalchemy import desc, Index from sqlalchemy.orm import backref from sqlalchemy import UniqueConstraint from flask.ext.security import UserMixin, RoleMixin, \ Security, SQLAlchemyUserDatastore from flask.ext.sqlalchemy import models_committed from app import app, db import serializers from search import Search STATIC_HOST = app.config['STATIC_HOST'] logger = logging.getLogger(__name__) class ApiKey(db.Model): __tablename__ = "api_key" id = db.Column(db.Integer, primary_key=True) key = db.Column(db.String(128), unique=True, nullable=False) user_id = db.Column( db.Integer, db.ForeignKey('user.id'), unique=True, nullable=False) user = db.relationship('User') def generate_key(self): self.key = ''.join( random.choice( string.ascii_uppercase + string.digits) for _ in range(128)) return def __unicode__(self): s = u'%s' % self.key return s def to_dict(self, include_related=False): return {'user_id': self.user_id, 'key': self.key} class Role(db.Model, RoleMixin): __tablename__ = "role" id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __unicode__(self): return unicode(self.name) class User(db.Model, UserMixin): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True, nullable=True) password = db.Column(db.String(255)) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(100)) current_login_ip = db.Column(db.String(100)) login_count = db.Column(db.Integer) roles = db.relationship('Role', secondary='roles_users', backref=db.backref('users', lazy='dynamic')) def __unicode__(self): return unicode(self.email) def to_dict(self, include_related=False): tmp = serializers.model_to_dict(self, include_related=include_related) tmp.pop('password') tmp.pop('last_login_ip') tmp.pop('current_login_ip') tmp.pop('last_login_at') tmp.pop('current_login_at') tmp.pop('confirmed_at') tmp.pop('login_count') return tmp roles_users = db.Table( 'roles_users', db.Column( 'user_id', db.Integer(), db.ForeignKey('user.id')), db.Column( 'role_id', db.Integer(), db.ForeignKey('role.id'))) # Setup Flask-Security user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) class House(db.Model): __tablename__ = "house" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) name_short = db.Column(db.String(20), nullable=False) def __unicode__(self): return unicode(self.name) class Party(db.Model): __tablename__ = "party" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __unicode__(self): return unicode(self.name) class Province(db.Model): __tablename__ = "province" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False) def __unicode__(self): return unicode(self.name) class BillType(db.Model): __tablename__ = "bill_type" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) prefix = db.Column(db.String(5)) description = db.Column(db.Text) def __unicode__(self): return unicode(self.name) class BillStatus(db.Model): __tablename__ = "bill_status" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), unique=True, nullable=False) description = db.Column(db.Text) def __unicode__(self): return unicode(self.name) class Bill(db.Model): __tablename__ = "bill" __table_args__ = ( db.UniqueConstraint( 'number', 'year', 'type_id'), {}) id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(250), nullable=False) number = db.Column(db.Integer) year = db.Column(db.Integer) date_of_introduction = db.Column(db.Date) date_of_assent = db.Column(db.Date) effective_date = db.Column(db.Date) act_name = db.Column(db.String(250)) status_id = db.Column(db.Integer, db.ForeignKey('bill_status.id')) status = db.relationship('BillStatus', backref='bill', lazy=False) type_id = db.Column(db.Integer, db.ForeignKey('bill_type.id')) type = db.relationship('BillType', backref='bill', lazy=False) place_of_introduction_id = db.Column(db.Integer, db.ForeignKey('house.id')) place_of_introduction = db.relationship('House') introduced_by_id = db.Column(db.Integer, db.ForeignKey('member.id')) introduced_by = db.relationship('Member') file_id = db.Column(db.Integer, db.ForeignKey('file.id')) files = db.relationship("File") def get_code(self): out = self.type.prefix if self.type else "X" out += str(self.number) if self.number else "" out += "-" + str(self.year) return unicode(out) def to_dict(self, include_related=False): tmp = serializers.model_to_dict(self, include_related=include_related) tmp['code'] = self.get_code() return tmp def __unicode__(self): out = self.get_code() if self.title: out += " - " + self.title return unicode(out) class Briefing(db.Model): __tablename__ = "briefing" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) briefing_date = db.Column(db.Date) summary = db.Column(db.Text) minutes = db.Column(db.Text) presentation = db.Column(db.Text) files = db.relationship("File", secondary='briefing_file_join') start_date = db.Column(db.Date()) briefing_file_table = db.Table( 'briefing_file_join', db.Model.metadata, db.Column( 'briefing_id', db.Integer, db.ForeignKey('briefing.id')), db.Column( 'file_id', db.Integer, db.ForeignKey('file.id'))) class File(db.Model): __tablename__ = "file" id = db.Column(db.Integer, primary_key=True) filemime = db.Column(db.String(50)) origname = db.Column(db.String(255)) description = db.Column(db.String(255)) duration = db.Column(db.Integer, default=0) playtime = db.Column(db.String(10)) url = db.Column(db.String(255)) def __unicode__(self): return u'%s' % self.url # M2M table bill_event_table = db.Table( 'bill_event', db.Model.metadata, db.Column('event_id', db.Integer, db.ForeignKey('event.id')), db.Column('bill_id', db.Integer, db.ForeignKey('bill.id')) ) class Event(db.Model): __tablename__ = "event" id = db.Column(db.Integer, index=True, primary_key=True) date = db.Column(db.DateTime(timezone=True)) title = db.Column(db.String(256)) type = db.Column(db.String(50), index=True, nullable=False) member_id = db.Column(db.Integer, db.ForeignKey('member.id'), index=True) member = db.relationship('Member', backref='events') committee_id = db.Column( db.Integer, db.ForeignKey('committee.id'), index=True) committee = db.relationship( 'Committee', lazy=False, backref=backref( 'events', order_by=desc('Event.date'))) house_id = db.Column( db.Integer, db.ForeignKey('house.id'), index=True) house = db.relationship( 'House', lazy=False, backref=backref( 'events', order_by=desc('Event.date'))) bills = db.relationship('Bill', secondary='event_bills', backref=backref('events')) def to_dict(self, include_related=False): tmp = serializers.model_to_dict(self, include_related=include_related) if self.type == "committee-meeting": if tmp.get('committee_meeting_report'): tmp['body'] = tmp['committee_meeting_report'].get('body') tmp['summary'] = tmp['committee_meeting_report'].get('summary') tmp.pop('committee_meeting_report') return tmp def __unicode__(self): if self.type == "committee-meeting": tmp = "unknown date" if self.date: tmp = self.date.date().isoformat() if self.committee: tmp += " [" + unicode(self.committee) + "]" if self.title: tmp += " - " + self.title return unicode(tmp) tmp = self.type if self.date: tmp += " - " + self.date.date().isoformat() if self.title: tmp += " - " + self.title return unicode(tmp) event_bills = db.Table( 'event_bills', db.Column( 'event_id', db.Integer(), db.ForeignKey('event.id')), db.Column( 'bill_id', db.Integer(), db.ForeignKey('bill.id'))) class MembershipType(db.Model): __tablename__ = "membership_type" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) def to_dict(self, include_related=False): # reduce this model to a string return self.name def __unicode__(self): return unicode(self.name) class Member(db.Model): __tablename__ = "member" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(100), nullable=False) profile_pic_url = db.Column(db.String(255)) bio = db.Column(db.Text()) house_id = db.Column(db.Integer, db.ForeignKey('house.id')) house = db.relationship(House) party_id = db.Column(db.Integer, db.ForeignKey('party.id')) party = db.relationship(Party, backref="members", lazy='joined') province_id = db.Column(db.Integer, db.ForeignKey('province.id')) province = db.relationship(Province) start_date = db.Column(db.Date()) pa_link = db.Column(db.String(255)) def __unicode__(self): return u'%s' % self.name def to_dict(self, include_related=False): tmp = serializers.model_to_dict(self, include_related=include_related) if tmp['profile_pic_url']: tmp['profile_pic_url'] = STATIC_HOST + tmp['profile_pic_url'] return tmp class Committee(db.Model): __tablename__ = "committee" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False, unique=True) about = db.Column(db.Text()) contact_details = db.Column(db.Text()) house_id = db.Column(db.Integer, db.ForeignKey('house.id')) house = db.relationship('House', lazy='joined') tabled_committee_reports = db.relationship( "TabledCommitteeReport", lazy=True) questions_replies = db.relationship("QuestionReply", lazy=True) calls_for_comments = db.relationship("CallForComment", lazy=True) def __unicode__(self): tmp = self.name if self.house: tmp = self.house.name_short + " " + tmp return unicode(tmp) class Membership(db.Model): __tablename__ = 'committee_members' id = db.Column(db.Integer, primary_key=True) type_id = db.Column(db.Integer, db.ForeignKey('membership_type.id')) type = db.relationship(MembershipType, lazy='joined') committee_id = db.Column(db.Integer, db.ForeignKey('committee.id')) committee = db.relationship( Committee, backref="memberships", lazy='joined') member_id = db.Column(db.Integer, db.ForeignKey('member.id')) member = db.relationship( Member, backref=backref( "memberships", lazy="joined"), lazy='joined') def __unicode__(self): tmp = u" - ".join([unicode(self.type), unicode(self.member), unicode(self.committee)]) return unicode(tmp) class Hansard(db.Model): __tablename__ = "hansard" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255)) meeting_date = db.Column(db.Date()) start_date = db.Column(db.Date()) body = db.Column(db.Text()) # === Schedule === # class Schedule(db.Model): __tablename__ = "schedule" id = db.Column(db.Integer, primary_key=True) description = db.Column(db.Text) meeting_date = db.Column(db.Date()) meeting_time = db.Column(db.Text()) houses = db.relationship("House", secondary='schedule_house_join') schedule_house_table = db.Table( 'schedule_house_join', db.Model.metadata, db.Column('schedule_id', db.Integer, db.ForeignKey('schedule.id')), db.Column('house_id', db.Integer, db.ForeignKey('house.id')) ) # === Questions Replies === # class QuestionReply(db.Model): __tablename__ = "question_reply" id = db.Column(db.Integer, primary_key=True) committee_id = db.Column(db.Integer, db.ForeignKey('committee.id')) committee = db.relationship( 'Committee', backref=db.backref( 'question-replies-committee', lazy='dynamic')) title = db.Column(db.String(255), nullable=False) start_date = db.Column(db.Date) body = db.Column(db.Text) question_number = db.Column(db.String(255)) # === Tabled Committee Report === # class TabledCommitteeReport(db.Model): __tablename__ = "tabled_committee_report" id = db.Column(db.Integer, primary_key=True) committee_id = db.Column(db.Integer, db.ForeignKey('committee.id')) committee = db.relationship( 'Committee', backref=db.backref( 'committee', lazy='dynamic')) title = db.Column(db.Text()) start_date = db.Column(db.Date()) body = db.Column(db.Text()) summary = db.Column(db.Text()) nid = db.Column(db.Integer()) files = db.relationship( "File", secondary='tabled_committee_report_file_join') tabled_committee_report_file_table = db.Table( 'tabled_committee_report_file_join', db.Model.metadata, db.Column( 'tabled_committee_report_id', db.Integer, db.ForeignKey('tabled_committee_report.id')), db.Column( 'file_id', db.Integer, db.ForeignKey('file.id'))) # === Calls for comment === # class CallForComment(db.Model): __tablename__ = "call_for_comment" id = db.Column(db.Integer, primary_key=True) committee_id = db.Column(db.Integer, db.ForeignKey('committee.id')) committee = db.relationship( 'Committee', backref=db.backref( 'call-for-comment-committee', lazy='dynamic')) title = db.Column(db.Text()) start_date = db.Column(db.Date()) end_date = db.Column(db.Date()) body = db.Column(db.Text()) summary = db.Column(db.Text()) nid = db.Column(db.Integer()) # === Policy document === # class PolicyDocument(db.Model): __tablename__ = "policy_document" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255)) effective_date = db.Column(db.Date()) files = db.relationship("File", secondary='policy_document_file_join') start_date = db.Column(db.Date()) nid = db.Column('nid', db.Integer()) policy_document_file_table = db.Table( 'policy_document_file_join', db.Model.metadata, db.Column( 'policy_document_id', db.Integer, db.ForeignKey('policy_document.id')), db.Column( 'file_id', db.Integer, db.ForeignKey('file.id')), ) # === Gazette === # class Gazette(db.Model): __tablename__ = "gazette" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255)) effective_date = db.Column(db.Date()) files = db.relationship("File", secondary='gazette_file_join') start_date = db.Column(db.Date()) nid = db.Column('nid', db.Integer()) gazette_file_table = db.Table( 'gazette_file_join', db.Model.metadata, db.Column( 'gazette_id', db.Integer, db.ForeignKey('gazette.id')), db.Column( 'file_id', db.Integer, db.ForeignKey('file.id'))) # === Featured Content === # class Featured(db.Model): __tablename__ = "featured" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255)) blurb = db.Column(db.Text()) link = db.Column(db.String(255)) start_date = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow) committee_meeting_report = db.relationship( 'CommitteeMeetingReport', secondary='featured_committee_meeting_report_join') tabled_committee_report = db.relationship( 'TabledCommitteeReport', secondary='featured_tabled_committee_report_join') featured_committee_meeting_report_join = db.Table( 'featured_committee_meeting_report_join', db.Model.metadata, db.Column( 'featured_id', db.Integer, db.ForeignKey('featured.id')), db.Column( 'committee_meeting_report_id', db.Integer, db.ForeignKey('committee_meeting_report.id'))) featured_tabled_committee_report_join = db.Table( 'featured_tabled_committee_report_join', db.Model.metadata, db.Column( 'featured_id', db.Integer, db.ForeignKey('featured.id')), db.Column( 'tabled_committee_report_id', db.Integer, db.ForeignKey('tabled_committee_report.id'))) # === Daily schedules === # class DailySchedule(db.Model): __tablename__ = "daily_schedule" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text()) start_date = db.Column(db.Date()) schedule_date = db.Column(db.Date()) body = db.Column(db.Text()) nid = db.Column(db.Integer()) files = db.relationship("File", secondary='daily_schedule_file_join') daily_schedule_file_table = db.Table( 'daily_schedule_file_join', db.Model.metadata, db.Column( 'daily_schedule_id', db.Integer, db.ForeignKey('daily_schedule.id')), db.Column( 'file_id', db.Integer, db.ForeignKey('file.id'))) class CommitteeMeetingReport(db.Model): __tablename__ = "committee_meeting_report" id = db.Column(db.Integer, index=True, primary_key=True) body = db.Column(db.Text()) summary = db.Column(db.Text()) event_id = db.Column(db.Integer, db.ForeignKey('event.id'), index=True) event = db.relationship('Event', backref=backref('committee_meeting_report', lazy='joined', uselist=False)) def __unicode__(self): return unicode(self.id) class Content(db.Model): __tablename__ = "content" id = db.Column(db.Integer, index=True, primary_key=True) type = db.Column(db.String(50), index=True, nullable=False) title = db.Column(db.String(200)) file_path = db.Column(db.String(200)) event_id = db.Column(db.Integer, db.ForeignKey('event.id'), index=True) event = db.relationship('Event', backref=backref('content', lazy='joined')) def __unicode__(self): return unicode(self.title) class HitLog(db.Model): __tablename__ = "hit_log" id = db.Column(db.Integer, index=True, primary_key=True) timestamp = db.Column(db.DateTime(timezone=True), default=datetime.datetime.utcnow) ip_addr = db.Column(db.String(40), index=True) user_agent = db.Column(db.String(255)) url = db.Column(db.String(255)) # Listen for model updates @models_committed.connect_via(app) def on_models_changed(sender, changes): searcher = Search() for obj, change in changes: # obj is the changed object, change is one of: update, insert, delete if searcher.indexable(obj): logger.debug('Reindexing changed item: %s %s' % (change, obj)) if change == 'delete': # deleted searcher.delete_obj(obj) else: # updated or inserted searcher.add_obj(obj)
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,887
johnfelipe/pmg-cms-2
refs/heads/master
/backend/admin.py
from app import app, db from models import * from flask import Flask, flash, redirect, url_for, request, render_template, g, abort from flask.ext.admin import Admin, expose, BaseView, AdminIndexView from flask.ext.admin.contrib.sqla import ModelView from flask.ext.admin.form import RenderTemplateWidget from flask.ext.admin.model.form import InlineFormAdmin from flask.ext.admin.contrib.sqla.form import InlineModelConverter from flask.ext.admin.contrib.sqla.fields import InlineModelFormList from flask.ext.admin.model.template import macro from flask.ext.security import current_user from wtforms import fields, widgets import logging from sqlalchemy import func from werkzeug import secure_filename import os from s3_upload import S3Bucket import urllib from operator import itemgetter FRONTEND_HOST = app.config['FRONTEND_HOST'] API_HOST = app.config['API_HOST'] STATIC_HOST = app.config['STATIC_HOST'] UPLOAD_PATH = app.config['UPLOAD_PATH'] ALLOWED_EXTENSIONS = app.config['ALLOWED_EXTENSIONS'] s3_bucket = S3Bucket() logger = logging.getLogger(__name__) if not os.path.isdir(UPLOAD_PATH): os.mkdir(UPLOAD_PATH) def allowed_file(filename): logger.debug(filename) tmp = '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS logger.debug(tmp) return tmp @app.context_processor def inject_paths(): context_vars = { 'FRONTEND_HOST': FRONTEND_HOST, 'API_HOST': API_HOST, 'STATIC_HOST': STATIC_HOST, } return context_vars @app.template_filter('add_commas') def jinja2_filter_add_commas(quantity): out = "" quantity_str = str(quantity) while len(quantity_str) > 3: tmp = quantity_str[-3::] out = "," + tmp + out quantity_str = quantity_str[0:-3] return quantity_str + out @app.template_filter('dir') def jinja2_filter_dir(value): res = [] for k in dir(value): res.append('%r %r\n' % (k, getattr(value, k))) return '<br>'.join(res) # Define wtforms widget and field class CKTextAreaWidget(widgets.TextArea): def __call__(self, field, **kwargs): kwargs.setdefault('class_', 'ckeditor') return super(CKTextAreaWidget, self).__call__(field, **kwargs) class CKTextAreaField(fields.TextAreaField): widget = CKTextAreaWidget() class MyIndexView(AdminIndexView): @expose("/") def index(self): record_counts = [ ('Members', 'member.index_view', Member.query.count()), ('Bill', 'bill.index_view', Bill.query.count()), ('Committee', 'committee.index_view', Committee.query.count()), ('Committee Meetings', 'committee_meeting.index_view', Event.query.filter_by(type="committee-meeting").count()), ('Questions & Replies', 'question.index_view', QuestionReply.query.count()), ('Calls for Comment', 'call_for_comment.index_view', CallForComment.query.count()), ('Daily Schedules', 'schedule.index_view', DailySchedule.query.count()), ('Gazette', 'gazette.index_view', Gazette.query.count()), ('Hansards', 'hansard.index_view', Hansard.query.count()), ('Media Briefings', 'briefing.index_view', Briefing.query.count()), ('Policy Documents', 'policy.index_view', PolicyDocument.query.count()), ('Tabled Committee Reports', 'tabled_report.index_view', TabledCommitteeReport.query.count()), ] record_counts = sorted(record_counts, key=itemgetter(2), reverse=True) file_count = Content.query.count() return self.render( 'admin/my_index.html', record_counts=record_counts, file_count=file_count) def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if not current_user.has_role( 'editor') or not current_user.has_role('user-admin'): return False return True def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): return redirect( '/security/login?next=' + urllib.quote_plus( request.url), code=302) class MyModelView(ModelView): can_create = True can_edit = True can_delete = True edit_template = 'admin/my_edit.html' create_template = 'admin/my_create.html' list_template = 'admin/my_list.html' def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if not current_user.has_role('editor'): return False return True def _handle_view(self, name, **kwargs): """ Override builtin _handle_view in order to redirect users when a view is not accessible. """ if not self.is_accessible(): return redirect( '/security/login?next=' + urllib.quote_plus( request.url), code=302) class MyRestrictedModelView(MyModelView): def is_accessible(self): if not current_user.is_active() or not current_user.is_authenticated(): return False if not current_user.has_role( 'editor') or not current_user.has_role('user-admin'): return False return True class UserView(MyRestrictedModelView): can_create = False can_delete = True column_list = [ 'email', 'active', 'confirmed_at', 'last_login_at', 'current_login_at', 'last_login_ip', 'current_login_ip', 'login_count', ] column_searchable_list = ('email',) form_excluded_columns = [ 'password', 'confirmed_at', 'last_login_at', 'current_login_at', 'last_login_ip', 'current_login_ip', 'login_count', ] # This widget uses custom template for inline field list class InlineMembershipsWidget(RenderTemplateWidget): def __init__(self): super( InlineMembershipsWidget, self).__init__('admin/inline_membership.html') # This InlineModelFormList will use our custom widget, when creating a # list of forms class MembershipsFormList(InlineModelFormList): widget = InlineMembershipsWidget() # Create custom InlineModelConverter to link the form to its model class MembershipModelConverter(InlineModelConverter): inline_field_list_type = MembershipsFormList class CommitteeView(MyModelView): column_list = ( 'name', 'house', 'memberships' ) column_labels = {'memberships': 'Members', } column_sortable_list = ( 'name', ('house', 'house.name'), ) column_default_sort = (Committee.name, False) column_searchable_list = ('name', ) column_formatters = dict( memberships=macro('render_membership_count'), ) form_columns = ( 'name', 'house', 'memberships', ) inline_models = (Membership, ) inline_model_form_converter = MembershipModelConverter class EventView(MyModelView): form_excluded_columns = ('type', ) column_exclude_list = ('type', ) form_ajax_refs = { 'content': { 'fields': ('title', 'type'), 'page_size': 25 } } def __init__(self, model, session, **kwargs): self.type = kwargs.pop('type') super(EventView, self).__init__(model, session, **kwargs) def on_model_change(self, form, model, is_created): if is_created: # set some default values when creating a new record model.type = self.type def get_query(self): """ Add filter to return only records of the specified type. """ return self.session.query(self.model) \ .filter(self.model.type == self.type) def get_count_query(self): """ Add filter to return only records of the specified type. """ return self.session.query(func.count('*')).select_from(self.model) \ .filter(self.model.type == self.type) # This widget uses custom template for inline field list class InlineContentWidget(RenderTemplateWidget): def __init__(self): super(InlineContentWidget, self).__init__('admin/inline_content.html') # This InlineModelFormList will use our custom widget, when creating a # list of forms class ContentFormList(InlineModelFormList): widget = InlineContentWidget() # Create custom InlineModelConverter to link the form to its model class ContentModelConverter(InlineModelConverter): inline_field_list_type = ContentFormList class InlineContent(InlineFormAdmin): form_excluded_columns = ('type', 'file_path', ) def postprocess_form(self, form_class): # add a field for handling the file upload form_class.upload = fields.FileField('File') return form_class def on_model_change(self, form, model): # save file, if it is present file_data = request.files.get(form.upload.name) if file_data: if not allowed_file(file_data.filename): raise Exception("File type not allowed.") filename = secure_filename(file_data.filename) model.type = file_data.content_type logger.debug('saving uploaded file: ' + filename) file_data.save(os.path.join(UPLOAD_PATH, filename)) model.file_path = filename s3_bucket.upload_file(filename) class CommitteeMeetingView(EventView): column_list = ('date', 'committee', 'title', 'content') column_labels = {'committee': 'Committee', } column_sortable_list = ( 'date', 'title', ('committee', 'committee.name'), ) column_default_sort = (Event.date, True) column_searchable_list = ('title', 'committee.name') column_formatters = dict( content=macro('render_event_content'), ) form_excluded_columns = ( 'event', 'member', ) form_columns = ( 'committee', 'date', 'title', 'summary', 'body', 'content', ) form_extra_fields = { 'summary': CKTextAreaField('Summary'), 'body': CKTextAreaField('Body'), } form_widget_args = { 'body': { 'class': 'ckeditor' }, 'summary': { 'class': 'ckeditor' } } inline_models = ( InlineContent(Content), ) inline_model_form_converter = ContentModelConverter def on_form_prefill(self, form, id): event_obj = Event.query.get(id) form.summary.data = event_obj.committee_meeting_report.summary form.body.data = event_obj.committee_meeting_report.body return def on_model_change(self, form, model, is_created): # create / update related CommitteeMeetingReport if is_created: committee_meeting_report = CommitteeMeetingReport(event=model) else: committee_meeting_report = model.committee_meeting_report committee_meeting_report.summary = form.summary.data committee_meeting_report.body = form.body.data db.session.add(committee_meeting_report) return super(CommitteeMeetingView, self).on_model_change(form, model, is_created) class MemberView(MyModelView): column_list = ( 'name', 'house', 'party', 'province', 'memberships', 'bio', 'pa_link', 'profile_pic_url', ) column_labels = {'memberships': 'Committees', } column_sortable_list = ( 'name', ('house', 'house.name'), ('party', 'party.name'), ('province', 'province.name'), 'bio', 'profile_pic_url', ) column_default_sort = (Member.name, False) column_searchable_list = ('name', ) column_formatters = dict( profile_pic_url=macro('render_profile_pic'), memberships=macro('render_committee_membership'), pa_link=macro('render_external_link'), ) form_columns = ( 'name', 'house', 'party', 'province', 'bio', 'pa_link', 'upload', ) form_extra_fields = { 'upload': fields.FileField('Profile pic') } form_overrides = dict(bio=fields.TextAreaField) form_ajax_refs = { 'events': { 'fields': ('date', 'title', 'type'), 'page_size': 25 } } form_widget_args = { 'bio': { 'rows': '10' }, } edit_template = "admin/edit_member.html" def on_model_change(self, form, model): # save profile pic, if it is present file_data = request.files.get(form.upload.name) if file_data: if not allowed_file(file_data.filename): raise Exception("File type not allowed.") filename = secure_filename(file_data.filename) logger.debug('saving uploaded file: ' + filename) file_data.save(os.path.join(UPLOAD_PATH, filename)) s3_bucket.upload_file(filename) model.profile_pic_url = filename class QuestionView(MyModelView): column_exclude_list = ( 'body', ) column_default_sort = ('start_date', True) column_searchable_list = ('title', 'question_number') form_widget_args = { 'body': { 'class': 'ckeditor' }, } class CallForCommentView(MyModelView): column_exclude_list = ( 'body', 'summary', ) column_default_sort = ('start_date', True) column_searchable_list = ('title', ) form_widget_args = { 'body': { 'class': 'ckeditor' }, 'summary': { 'class': 'ckeditor' }, } class DailyScheduleView(MyModelView): column_exclude_list = ( 'body', ) column_default_sort = ('start_date', True) column_searchable_list = ('title', ) form_widget_args = { 'body': { 'class': 'ckeditor' }, } class GazetteView(MyModelView): column_default_sort = ('effective_date', True) column_searchable_list = ('title', ) class HansardView(MyModelView): column_exclude_list = ( 'body', ) column_default_sort = ('meeting_date', True) column_searchable_list = ('title', ) form_widget_args = { 'body': { 'class': 'ckeditor' }, } class BriefingView(MyModelView): column_exclude_list = ( 'minutes', 'summary', 'presentation', ) column_default_sort = ('briefing_date', True) column_searchable_list = ('title', ) form_widget_args = { 'minutes': { 'class': 'ckeditor' }, 'summary': { 'class': 'ckeditor' }, 'presentation': { 'class': 'ckeditor' }, } class PolicyDocumentView(MyModelView): column_default_sort = ('effective_date', True) column_searchable_list = ('title', ) class TabledReportView(MyModelView): column_exclude_list = ( 'body', 'summary', ) column_default_sort = ('start_date', True) column_searchable_list = ('title', ) form_widget_args = { 'body': { 'class': 'ckeditor' }, 'summary': { 'class': 'ckeditor' }, } # initialise admin instance admin = Admin( app, name='PMG-CMS', base_template='admin/my_base.html', index_view=MyIndexView( name='Home'), template_mode='bootstrap3') # add admin views for each model admin.add_view(UserView(User, db.session, name="Users", endpoint='user')) admin.add_view( CommitteeView( Committee, db.session, name="Committees", endpoint='committee', category="Committees")) admin.add_view( CommitteeMeetingView( Event, db.session, type="committee-meeting", name="Committee Meetings", endpoint='committee_meeting', category="Committees")) admin.add_view( TabledReportView( TabledCommitteeReport, db.session, name="Tabled Committee Reports", endpoint='tabled_report', category="Committees")) admin.add_view( MemberView( Member, db.session, name="Members", endpoint='member')) admin.add_view( MyModelView( Bill, db.session, name="Bills", endpoint='bill')) admin.add_view( QuestionView( QuestionReply, db.session, name="Questions & Replies", endpoint='question', category="Other Content")) admin.add_view( CallForCommentView( CallForComment, db.session, name="Calls for Comment", endpoint='call_for_comment', category="Other Content")) admin.add_view( GazetteView( Gazette, db.session, name="Gazettes", endpoint='gazette', category="Other Content")) admin.add_view( HansardView( Hansard, db.session, name="Hansards", endpoint='hansard', category="Other Content")) admin.add_view( PolicyDocumentView( PolicyDocument, db.session, name="Policy Document", endpoint='policy', category="Other Content")) admin.add_view( DailyScheduleView( DailySchedule, db.session, name="Daily Schedules", endpoint='schedule', category="Other Content")) admin.add_view( BriefingView( Briefing, db.session, name="Media Briefings", endpoint='briefing', category="Other Content")) admin.add_view( MyModelView( MembershipType, db.session, name="Membership Type", endpoint='membership-type', category="Form Options")) admin.add_view( MyModelView( BillStatus, db.session, name="Bill Status", endpoint='bill-status', category="Form Options")) admin.add_view( MyModelView( BillType, db.session, name="Bill Type", endpoint='bill-type', category="Form Options"))
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,888
johnfelipe/pmg-cms-2
refs/heads/master
/backend/s3_upload.py
import boto import boto.s3 from boto.s3.key import Key import boto.s3.connection import math import os from app import db, app import logging UPLOAD_PATH = app.config['UPLOAD_PATH'] S3_BUCKET = app.config['S3_BUCKET'] logger = logging.getLogger(__name__) def rounded_megabytes(bytes): megabytes = bytes / float(1024 * 1024) megabytes = math.ceil(megabytes * 1000) / 1000 # round the float return megabytes class S3Bucket(): def __init__(self): self.bucket = None return def get_bucket(self): conn = boto.s3.connect_to_region('eu-west-1') self.bucket = conn.get_bucket(S3_BUCKET) return def upload_file(self, filename): try: if not self.bucket: self.get_bucket() # assemble key path = os.path.join(UPLOAD_PATH, filename) bytes = os.path.getsize(path) megabytes = rounded_megabytes(bytes) logger.debug("uploading: " + path + " (" + str(megabytes) + " MB)") # test if the key already exists tmp_key = self.bucket.get_key(filename) if tmp_key is not None: raise ValueError("file already uploaded") else: # only upload if the key doesn't exist yet tmp_key = Key(self.bucket) tmp_key.key = filename tmp_key.set_contents_from_filename(path) except Exception as e: logger.error("Cannot upload file to S3. Removing file from disc.") # remove file from disc os.remove(path) raise e # remove file from disc os.remove(path) return if __name__ == "__main__": filename = "5-elephant.jpg" # a sample file, inside UPLOAD_PATH directory tmp = S3Bucket() tmp.upload_file(filename)
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,889
johnfelipe/pmg-cms-2
refs/heads/master
/fabfile.py
from __future__ import with_statement from fabdefs import * from fabric.api import * from contextlib import contextmanager @contextmanager def virtualenv(): with cd(env.project_dir): with prefix(env.activate): yield def rebuild_db(): sudo("supervisorctl stop pmg_cms") with virtualenv(): with cd(env.project_dir): sudo('source production-env.sh && python rebuild_db.py') sudo("supervisorctl start pmg_cms") def copy_db(): local("pg_dump -dpmg -Upmg --clean --no-owner --no-privileges > pmg.sql") local("tar cvzf pmg.sql.tar.gz pmg.sql") put('pmg.sql.tar.gz', '/tmp/pmg.sql.tar.gz') sudo('tar xvzf /tmp/pmg.sql.tar.gz') sudo('psql -dpmg -f pmg.sql', user="postgres") local('rm pmg.sql') # local('rm pmg.sql.tar.gz') sudo('rm /tmp/pmg.sql.tar.gz') sudo('rm pmg.sql') def setup_db(): sudo("createuser pmg -S -D -R -e", user="postgres") sudo("createdb --locale=en_US.utf-8 -E utf-8 -O pmg pmg -T template0", user="postgres") rebuild_db() # sudo('echo "grant all privileges on database pmg to pmg;" | psql') def scrape_tabled_reports(): with virtualenv(): with shell_env(FLASK_ENV='production'): with cd('/var/www/pmg-cms'): run("source production-env.sh; python scrapers/scraper.py tabledreports") def scrape_schedule(): with virtualenv(): with shell_env(FLASK_ENV='production'): with cd('/var/www/pmg-cms'): run("source production-env.sh; python scrapers/scraper.py schedule") def index_search(): with virtualenv(): with shell_env(FLASK_ENV='production'): with cd('/var/www/pmg-cms'): run('source production-env.sh; python backend/search.py --reindex') def restart(): sudo("supervisorctl restart pmg_cms") sudo("supervisorctl restart pmg_frontend") sudo('service nginx restart') return def set_permissions(): """ Ensure that www-data has access to the application folder """ sudo('chown -R www-data:www-data ' + env.project_dir) return def setup(): sudo('apt-get update') # install packages sudo('apt-get -y install git') sudo('apt-get -y install build-essential python-dev sqlite3 libsqlite3-dev libpq-dev') sudo('apt-get -y install python-pip supervisor') sudo('pip install virtualenv') # create application directory if it doesn't exist yet with settings(warn_only=True): if run("test -d %s" % env.project_dir).failed: sudo('git clone https://github@github.com/code4sa/pmg-cms-2.git %s' % env.project_dir) sudo('mkdir %s/instance' % env.project_dir) if run("test -d %s/env" % env.project_dir).failed: # create virtualenv sudo('virtualenv --no-site-packages %s/env' % env.project_dir) # install nginx sudo('apt-get -y install nginx') # restart nginx after reboot sudo('update-rc.d nginx defaults') with settings(warn_only=True): sudo('rm /etc/nginx/sites-enabled/default') with settings(warn_only=True): sudo('service nginx start') # Database setup sudo('apt-get -y install postgresql') return def deploy(): # push any local changes to github local('git push origin ' + env.git_branch) # enter application directory and pull latest code from github with cd(env.project_dir): # first, discard local changes, then pull with settings(warn_only=True): sudo('git reset --hard') sudo('git pull origin ' + env.git_branch) # ensure we are on the target branch sudo('git checkout -f ' + env.git_branch) # install dependencies with virtualenv(): sudo('pip install -r %s/requirements.txt' % env.project_dir) with cd(env.project_dir): # nginx sudo('ln -sf ' + env.config_dir + '/nginx.conf /etc/nginx/sites-enabled/pmg.org.za') sudo('service nginx reload') # move supervisor config sudo('ln -sf ' + env.config_dir + '/supervisor.conf /etc/supervisor/conf.d/supervisor_pmg.conf') sudo('supervisorctl reread') sudo('supervisorctl update') set_permissions() restart() return
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,890
johnfelipe/pmg-cms-2
refs/heads/master
/backend/app.py
import logging import logging.config from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import sys import os from flask_mail import Mail env = os.environ.get('FLASK_ENV', 'development') app = Flask(__name__, static_folder="not_static") app.config.from_pyfile('../config/%s/config.py' % env) db = SQLAlchemy(app) mail = Mail(app) # setup logging with open('config/%s/logging.yaml' % env) as f: import yaml logging.config.dictConfig(yaml.load(f)) import views import admin
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,891
johnfelipe/pmg-cms-2
refs/heads/master
/frontend/views.py
import logging from flask import request, flash, make_response, url_for, session, render_template, abort, redirect from frontend import app import requests from datetime import datetime, date import dateutil.parser import urllib import math import random import arrow import re import json API_HOST = app.config['API_HOST'] error_bad_request = 400 app.session = session logger = logging.getLogger(__name__) @app.template_filter('pretty_date') def _jinja2_filter_datetime(iso_str): if not iso_str: return "" format = '%d %b %Y' date = dateutil.parser.parse(iso_str) return date.strftime(format) @app.template_filter('search_snippet') def _jinja2_filter_search_snippet(snippet): if not snippet: return "" # snippet = re.sub('<[^<]+?>', '', snippet) # snippet = snippet.strip() # if (len(snippet) > 180): # pos = re.match("\*\*(.*)/\*\*", snippet) # print "query_statement", pos # if pos: # snippet = snippet.replace("/**", "") # snippet = snippet.replace("**", "") # words = re.split('\s', snippet) # startpos = pos.start() - 75 # wc = 0 # tmp = "" # while (words and wc < 150): # tmp = tmp + words.pop() + " " # snippet = str(pos.start()) + tmp[:pos.start()] + "*" + tmp[pos.start():] # snippet = snippet.replace("/**", "</strong>") # snippet = snippet.replace("**", "<strong>") return snippet @app.template_filter('ellipse') def _jinja2_filter_ellipse(snippet): return "...&nbsp;" + snippet.strip() + "&nbsp;..." @app.template_filter('nbsp') def _jinja2_nbsp(str): return str.replace(" ", "&nbsp;") @app.template_filter('human_date') def _jinja2_filter_humandate(iso_str): if not iso_str: return "" return arrow.get(iso_str).humanize() @app.template_filter('file') def _jinja2_filter_file(filename): return app.config['STATIC_HOST'] + filename @app.context_processor def pagination_processor(): def pagination(page_count, current_page, per_page, url): # Source: # https://github.com/jmcclell/django-bootstrap-pagination/blob/master/bootstrap_pagination/templatetags/bootstrap_pagination.py#L154 range_length = 15 logger.debug("Building pagination") if range_length is None: range_min = 1 range_max = page_count else: if range_length < 1: raise Exception( "Optional argument \"range\" expecting integer greater than 0") elif range_length > page_count: range_length = page_count range_length -= 1 range_min = max(current_page - (range_length / 2) + 1, 1) range_max = min(current_page + (range_length / 2) + 1, page_count) range_diff = range_max - range_min if range_diff < range_length: shift = range_length - range_diff if range_min - shift > 0: range_min -= shift else: range_max += shift page_range = range(range_min, range_max + 1) s = "" for i in page_range: active = "" if ((i - 1) == current_page): active = "active" query_string = "" if (request.query_string): query_string = "?" + request.query_string s += "<li class='{0}'><a href='{1}/{2}/{4}'>{3}</a></li>".format( active, url, i - 1, i, query_string) return s return dict(pagination=pagination) class ApiException(Exception): """ Class for handling all of our expected API errors. """ def __init__(self, status_code, message): Exception.__init__(self) self.message = message self.status_code = status_code def to_dict(self): rv = { "code": self.status_code, "message": self.message } return rv @app.errorhandler(ApiException) def handle_api_exception(error): """ Error handler, used by flask to pass the error on to the user, rather than catching it and throwing a HTTP 500. """ logger.error("API error: %s" % error.message) flash(error.message + " (" + str(error.status_code) + ")", "danger") # catch 'Unauthorised' status if error.status_code == 401: session.clear() return redirect( url_for('login') + "?next=" + urllib.quote_plus( request.path)) return render_template('500.html', error=error), 500 def load_from_api( resource_name, resource_id=None, page=None, return_everything=False, params={}): query_str = resource_name + "/" if resource_id: query_str += str(resource_id) + "/" if page: params["page"] = str(page) headers = {} # add auth header if session and session.get('api_key'): headers = {'Authentication-Token': session.get('api_key')} try: response = requests.get( API_HOST + query_str, headers=headers, params=params) if response.status_code != 200: try: msg = response.json().get('message') except Exception: msg = None raise ApiException( response.status_code, msg or "An unspecified error has occurred.") out = response.json() if return_everything: next_response_json = out i = 0 while next_response_json.get('next') and i < 1000: next_response = requests.get( next_response_json.get('next'), headers=headers) next_response_json = next_response.json() out['results'] += next_response_json['results'] i += 1 if out.get('next'): out.pop('next') if out.get('current_user'): session['current_user'] = out['current_user'] return out except requests.ConnectionError: flash('Error connecting to backend service.', 'danger') pass return def send_to_api(resource_name, resource_id=None, data=None): query_str = resource_name + "/" if resource_id: query_str += str(resource_id) + "/" headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' } # add auth header if session and session.get('authentication_token'): headers['Authentication-Token'] = session['authentication_token'] try: response = requests.post( API_HOST + query_str, headers=headers, data=data) out = response.json() if response.status_code != 200: raise ApiException( response.status_code, response.json().get( 'message', "An unspecified error has occurred.")) return out except requests.ConnectionError: flash('Error connecting to backend service.', 'danger') pass return @app.route('/') def index(): """ """ logger.debug("index page called") committee_meetings_api = load_from_api('committee-meeting') committee_meetings = [] for committee_meeting in committee_meetings_api["results"]: if committee_meeting["committee_id"]: committee_meetings.append(committee_meeting) if len(committee_meetings) == 10: break bills = load_from_api('bill')["results"][:10] schedule = load_from_api('schedule')["results"] scheduledates = [] curdate = False for item in schedule: print item if item["meeting_date"] != curdate: curdate = item["meeting_date"] scheduledates.append(curdate) stock_pic = "stock" + str(random.randint(1, 18)) + ".jpg" featured_list = load_from_api('featured')["results"] featured_content = load_from_api('featured', featured_list[0]["id"]) return render_template( 'index.html', committee_meetings=committee_meetings, bills=bills, schedule=schedule, scheduledates=scheduledates, stock_pic=stock_pic, featured_content=featured_content) @app.route('/bills/') @app.route('/bills/<int:page>/') def bills(page=0): """ Page through all available bills. """ logger.debug("bills page called") bill_list = load_from_api('bill', return_everything=True) bills = bill_list['results'] # filters = {} # params = {} count = bill_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) url = "/bills" return render_template( 'list.html', results=bills, num_pages=num_pages, page=page, url=url, icon="file-text-o", content_type="bill", title="Bills") @app.route('/bill/<int:bill_id>/') def bill(bill_id): """ With Bills, we try to send them to BillTracker if it exists. Else we serve the PDF. If that doesn't work, we Kill Bill """ logger.debug("bill page called") bill = load_from_api('bill', bill_id) return render_template('bill_detail.html', bill=bill) @app.route('/committee/<int:committee_id>/') def committee_detail(committee_id): """ Display all available detail for the committee. """ logger.debug("committee detail page called") committee = load_from_api('committee', committee_id) return render_template('committee_detail.html', committee=committee) @app.route('/committees/') def committees(): """ Page through all available committees. """ logger.debug("committees page called") committee_list = load_from_api('committee', return_everything=True) committees = committee_list['results'] return render_template('committee_list.html', committees=committees, ) @app.route('/committee-meetings/') @app.route('/committee-meetings/<int:page>/') def committee_meetings(page=0): """ Page through all available committee meetings. """ committee_list = load_from_api('committee', return_everything=True) committees = committee_list['results'] filters = {} params = {} filters["committee"] = params[ 'filter[committee_id]'] = request.args.get('filter[committee]') committee_meetings_list = load_from_api( 'committee-meeting', page=page, params=params) committee_meetings = committee_meetings_list['results'] count = committee_meetings_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) url = "/committee-meetings" return render_template( 'list.html', results=committee_meetings, num_pages=num_pages, page=page, url=url, title="Committee Meeting Reports", content_type="committee-meeting", icon="comment", committees=committees, filters=filters) @app.route('/committee-meeting/<int:event_id>/') def committee_meeting(event_id): """ Display committee meeting details, including report and any other related content. """ event = load_from_api('committee-meeting', event_id) related_docs = [] audio = [] if event.get('content'): for item in event['content']: if "audio" in item['type']: audio.append(item) else: related_docs.append(item) return render_template( 'committee_meeting.html', event=event, audio=audio, related_docs=related_docs, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/tabled-committee-reports/') @app.route('/tabled-committee-reports/<int:page>/') def tabled_committee_reports(page=0): """ Page through all available tabled-committee-reports. """ logger.debug("tabled-committee-reports page called") committee_list = load_from_api('committee', return_everything=True) committees = committee_list['results'] filters = {} params = {} filters["committee"] = params[ 'filter[committee_id]'] = request.args.get('filter[committee]') tabled_committee_reports_list = load_from_api( 'tabled_committee_report', page=page, params=params) count = tabled_committee_reports_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) tabled_committee_reports = tabled_committee_reports_list['results'] url = "/tabled-committee-reports" return render_template( 'list.html', results=tabled_committee_reports, content_type="tabled_committee_report", title="Tabled Committee Reports", num_pages=num_pages, page=page, url=url, icon="briefcase", committees=committees, filters=filters) @app.route('/tabled-committee-report/<int:tabled_committee_report_id>/') def tabled_committee_report(tabled_committee_report_id): """ Tabled Committee Report """ logger.debug("tabled-committee-report page called") tabled_committee_report = load_from_api( 'tabled_committee_report', tabled_committee_report_id) logger.debug(tabled_committee_report) return render_template( 'tabled_committee_report_detail.html', tabled_committee_report=tabled_committee_report, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/calls-for-comments/') @app.route('/calls-for-comments/<int:page>/') def calls_for_comments(page=0): """ Page through all available calls-for-comments. """ logger.debug("calls-for-comments page called") committee_list = load_from_api('committee', return_everything=True) committees = committee_list['results'] filters = {} params = {} filters["committee"] = params[ 'filter[committee_id]'] = request.args.get('filter[committee]') call_for_comment_list = load_from_api( 'call_for_comment', page=page, params=params) count = call_for_comment_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) calls_for_comments = call_for_comment_list['results'] url = "/calls-for-comments" return render_template( 'list.html', results=calls_for_comments, num_pages=num_pages, page=page, url=url, icon="comments", content_type="call_for_comment", title="Calls for Comments", committees=committees, filters=filters) @app.route('/call-for-comment/<int:call_for_comment_id>/') def call_for_comment(call_for_comment_id): """ Tabled Committee Report """ logger.debug("call-for-comment page called") call_for_comment = load_from_api( 'call_for_comment', call_for_comment_id) logger.debug(call_for_comment) return render_template( 'call_for_comment_detail.html', call_for_comment=call_for_comment, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/policy-documents/') @app.route('/policy-documents/<int:page>/') def policy_documents(page=0): """ Page through all available policy-documents. """ logger.debug("policy-documents page called") policy_documents_list = load_from_api('policy_document', page=page) count = policy_documents_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) policy_documents = policy_documents_list['results'] url = "/policy-documents" return render_template( 'list.html', results=policy_documents, num_pages=num_pages, page=page, url=url, icon="", content_type="policy_document", title="Policy Documents") @app.route('/policy-document/<int:policy_document_id>/') def policy_document(policy_document_id): """ Policy Document """ logger.debug("policy-document page called") policy_document = load_from_api('policy_document', policy_document_id) logger.debug(policy_document) return render_template( 'policy_document_detail.html', policy_document=policy_document, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/gazettes/') @app.route('/gazettes/<int:page>/') def gazettes(page=0): """ Page through all available gazettes. """ logger.debug("gazettes page called") gazettes_list = load_from_api('gazette', page=page) count = gazettes_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) gazettes = gazettes_list['results'] url = "/gazettes" return render_template( 'list.html', results=gazettes, num_pages=num_pages, page=page, url=url, icon="file-text-o", content_type="gazette", title="Gazettes") @app.route('/gazette/<int:gazette_id>/') def gazette(gazette_id): """ Policy Document """ logger.debug("gazette page called") gazette = load_from_api('gazette', gazette_id) logger.debug(gazette) return render_template( 'gazette_detail.html', gazette=gazette, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/members/') @app.route('/members/<int:page>/') def members(page=0): """ Page through all available members. """ logger.debug("members page called") members_list = load_from_api('member', page=page) count = members_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) members = members_list['results'] url = "/members" return render_template( 'list.html', results=members, num_pages=num_pages, page=page, url=url, icon="user", content_type="member", title="Members") @app.route('/member/<int:member_id>') def member(member_id): logger.debug("member page called") member = load_from_api('member', member_id) return render_template( 'member_detail.html', member=member, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/hansard/<int:hansard_id>') def hansard(hansard_id): logger.debug("hansard page called") hansard = load_from_api('hansard', hansard_id) return render_template( 'hansard_detail.html', hansard=hansard, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/hansards/') @app.route('/hansards/<int:page>/') def hansards(page=0): """ Page through all available hansards. """ logger.debug("hansards page called") hansards_list = load_from_api('briefing', page=page) count = hansards_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) hansards = hansards_list['results'] url = "/hansards" return render_template( 'list.html', results=hansards, num_pages=num_pages, page=page, url=url, icon="archive", title="Hansards", content_type="hansard") @app.route('/briefing/<int:briefing_id>') def briefing(briefing_id): logger.debug("briefing page called") briefing = load_from_api('briefing', briefing_id) return render_template( 'briefing_detail.html', briefing=briefing, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/briefings/') @app.route('/briefings/<int:page>/') def briefings(page=0): """ Page through all available briefings. """ logger.debug("briefings page called") briefings_list = load_from_api('briefing', page=page) count = briefings_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) briefings = briefings_list['results'] url = "/briefings" return render_template( 'list.html', results=briefings, num_pages=num_pages, page=page, url=url, icon="bullhorn", title="Media Briefings", content_type="briefing", ) @app.route('/daily_schedule/<int:daily_schedule_id>') def daily_schedule(daily_schedule_id): logger.debug("daily_schedule page called") daily_schedule = load_from_api('daily_schedule', daily_schedule_id) return render_template( 'daily_schedule_detail.html', daily_schedule=daily_schedule, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/daily_schedules/') @app.route('/daily_schedules/<int:page>/') def daily_schedules(page=0): """ Page through all available daily_schedules. """ logger.debug("daily_schedules page called") daily_schedules_list = load_from_api('daily_schedule', page=page) count = daily_schedules_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) daily_schedules = daily_schedules_list['results'] url = "/daily_schedules" return render_template( 'list.html', results=daily_schedules, num_pages=num_pages, page=page, url=url, icon="calendar", title="Daily Schedules", content_type="daily_schedule") @app.route('/question_reply/<int:question_reply_id>') def question_reply(question_reply_id): logger.debug("question_reply page called") question_reply = load_from_api('question_reply', question_reply_id) return render_template( 'question_reply_detail.html', question_reply=question_reply, STATIC_HOST=app.config['STATIC_HOST']) @app.route('/question_replies/') @app.route('/question_replies/<int:page>/') def question_replies(page=0): """ Page through all available question_replies. """ logger.debug("question_replies page called") committee_list = load_from_api('committee', return_everything=True) committees = committee_list['results'] filters = {} params = {} filters["committee"] = params[ 'filter[committee_id]'] = request.args.get('filter[committee]') question_replies_list = load_from_api( 'question_reply', page=page, params=params) count = question_replies_list["count"] per_page = app.config['RESULTS_PER_PAGE'] num_pages = int(math.ceil(float(count) / float(per_page))) question_replies = question_replies_list['results'] url = "/question_replies" return render_template( 'list.html', results=question_replies, num_pages=num_pages, page=page, url=url, icon="question-circle", title="Questions and Replies", content_type="question_reply", committees=committees, filters=filters) @app.route('/search/') @app.route('/search/<int:page>/') def search(page=0): """ Display search page """ logger.debug("search page called") params = {} filters = {} q = params["q"] = request.args.get('q') params["page"] = page filters["type"] = params['filter[type]'] = request.args.get('filter[type]') filters["start_date"] = params[ 'filter[start_date]'] = request.args.get('filter[start_date]') filters["end_date"] = params[ 'filter[end_date]'] = request.args.get('filter[end_date]') filters["committee"] = params[ 'filter[committee]'] = request.args.get('filter[committee]') if (filters["type"] == "None"): params['filter[type]'] = filters["type"] = None if (filters["start_date"] == "None"): params['filter[start_date]'] = filters["start_date"] = None if (filters["end_date"] == "None"): params['filter[end_date]'] = filters["end_date"] = None if (filters["committee"] == "None"): params['filter[committee]'] = filters["committee"] = None query_string = request.query_string per_page = app.config['RESULTS_PER_PAGE'] if (request.args.get('per_page')): per_page = int(request.args.get('per_page')) print params searchresult = load_from_api('search', params=params) result = {} result = searchresult["result"] count = searchresult["count"] search_url = request.url_root + "search" years = range(1997, datetime.now().year + 1) years.reverse() num_pages = int(math.ceil(float(count) / float(per_page))) # bincounts = search.count(q) # bincount_array = bincounts[0]["aggregations"]["types"]["buckets"] # print "query_statement", bincounts[1]["aggregations"]["years"]["buckets"] bincount = {} for bin in searchresult["bincount"]["types"]: bincount[bin["key"]] = bin["doc_count"] yearcount = {} for year in searchresult["bincount"]["years"]: yearcount[int(year["key_as_string"][:4])] = year["doc_count"] committee_list = load_from_api('committee', return_everything=True) committees = committee_list['results'] return render_template( 'search.html', STATIC_HOST=app.config['STATIC_HOST'], q=q, results=result, count=count, num_pages=num_pages, page=page, per_page=per_page, url=search_url, query_string=query_string, filters=filters, years=years, bincount=bincount, yearcount=yearcount, committees=committees) @app.route('/hitlog/') @app.route('/hitlog/<string:random>/') def hitlog(random=False): """ Records a hit from the end-user. Should be called in a non-blocking manner """ logger.debug("caught a hit") print "Remote addr", request.remote_addr print "User agent", request.user_agent print "Url", request.url hitlog = {} hitlog["ip_addr"] = request.remote_addr hitlog["user_agent"] = request.user_agent if request.referrer: hitlog["url"] = request.referrer else: hitlog["url"] = request.url headers = { # 'Accept': 'application/json', # 'Content-Type': 'application/json' } url = API_HOST + "hitlog/" response = requests.post(url, headers=headers, data=hitlog) return response.content
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,892
johnfelipe/pmg-cms-2
refs/heads/master
/frontend/__init__.py
import logging import logging.config from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os os.environ['PMG_LAYER'] = 'frontend' env = os.environ.get('FLASK_ENV', 'development') app = Flask(__name__, static_folder="static") app.config.from_pyfile('../config/%s/config.py' % env) db = SQLAlchemy(app) # setup logging with open('config/%s/logging.yaml' % env) as f: import yaml logging.config.dictConfig(yaml.load(f)) # setup assets from flask.ext.assets import Environment, Bundle assets = Environment(app) assets.url_expire = False assets.debug = app.debug # source files assets.load_path = ['%s/static' % app.config.root_path] assets.register('css', Bundle( 'resources/css/*.css', 'font-awesome-4.2.0/css/font-awesome.min.css', 'chosen/chosen.min.css', output='app.%(version)s.css')) assets.register('js', Bundle( 'bower_components/jquery/dist/jquery.min.js', 'bower_components/bootstrap/js/tab.js', 'bower_components/bootstrap/js/transition.js', 'bower_components/bootstrap/js/alert.js', 'chosen/chosen.jquery.js', 'resources/javascript/*.js', output='app.%(version)s.js')) import views import user_management
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,893
johnfelipe/pmg-cms-2
refs/heads/master
/backend/search.py
import sys import math import argparse import logging import requests from pyelasticsearch import ElasticSearch from sqlalchemy import types from inflection import underscore, camelize from app import db, app import models from transforms import * class Search: esserver = app.config['ES_SERVER'] index_name = "pmg" search_fields = ["title^3", "description^2", "fulltext"] es = ElasticSearch(esserver) per_batch = 50 logger = logging.getLogger(__name__) reindex_changes = app.config['SEARCH_REINDEX_CHANGES'] """ Should updates to models be reindexed? """ def reindex_all(self, data_type): """ Index all content of a data_type """ try: self.drop_index(data_type) except: self.logger.warn("Couldn't find %s index" % data_type) Model = self.model_for_data_type(data_type) ids = [r[0] for r in db.session.query(Model.id).all()] count = len(ids) pages = int(math.ceil(float(count) / float(self.per_batch))) self.logger.info("Pages %s, Count %s" % (pages, count)) while len(ids): self.logger.info("Items left %s" % len(ids)) id_subsection = [] for x in xrange(0, self.per_batch): if ids: id_subsection.append(ids.pop()) rows = db.session.query(Model).filter(Model.id.in_(id_subsection)).all() items = [Transforms.serialise(data_type, r) for r in rows] self.add_many(data_type, items) def drop_index(self, data_type): self.logger.info("Dropping %s index" % data_type) self.es.delete_all(self.index_name, data_type) self.logger.info("Dropped %s index" % data_type) def add_obj(self, obj): data_type = self.data_type_for_obj(obj) item = Transforms.serialise(data_type, obj) self.add(data_type, item) def add_many(self, data_type, items): self.es.bulk_index(self.index_name, data_type, items) def add(self, data_type, item): self.add_many(data_type, [item]) def delete_obj(self, obj): self.delete(self.data_type_for_obj(obj), obj.id) def data_type_for_obj(self, obj): # QuestionReply -> question_reply return underscore(type(obj).__name__) def model_for_data_type(self, data_type): # question_reply -> QuestionReply class return getattr(models, camelize(data_type)) def delete(self, data_type, uid): try: self.es.delete(self.index_name, data_type, uid) except ElasticHttpNotFoundError: pass def get(self, data_type, uid): try: return self.es.get(self.index_name, data_type, uid) except: return False def indexable(self, obj): """ Should this object be indexed for searching? """ return self.reindex_changes and (self.data_type_for_obj(obj) in Transforms.convert_rules) def mapping(self, data_type): mapping = { "properties": { "title": { "type": "string", "analyzer": "english", "index_options": "offsets" }, "fulltext": { "type": "string", "analyzer": "english", "index_options": "offsets" }, "description": { "type": "string", "analyzer": "english", "index_options": "offsets" } } } self.es.put_mapping(self.index_name, data_type, mapping) def search( self, query, size=10, es_from=0, start_date=False, end_date=False, content_type=False, committee=False): q = { "from": es_from, "size": size, "query": { "filtered": { "filter": {}, "query": {}, }, }, } q["query"]["filtered"]["query"] = { "multi_match": { "query": query, "fields": self.search_fields, "type": "phrase" }, } if start_date and end_date: q["query"]["filtered"]["filter"]["range"] = { "date": { "gte": start_date, "lte": end_date, } } if committee: q["query"]["filtered"]["filter"]["term"] = { "committee_id": committee } q["highlight"] = { "pre_tags": ["<strong>"], "post_tags": ["</strong>"], "fields": { "title": {}, "description": { "fragment_size": 500, "number_of_fragments": 1, "no_match_size": 250, "tag_schema": "styled"}, "fulltext": { "fragment_size": 500, "number_of_fragments": 1, "no_match_size": 250, "tag_schema": "styled"}}} self.logger.debug("query_statement: %s" % q) if (content_type): return self.es.search( q, index=self.index_name, doc_type=content_type) else: return self.es.search(q, index=self.index_name) def count( self, query, content_type=False, start_date=False, end_date=False): q1 = { "query": { "multi_match": { "query": query, "fields": self.search_fields, "type": "phrase" }, }, "aggregations": { "types": { "terms": { "field": "_type" } } } } q2 = { "query": { "multi_match": { "query": query, "fields": self.search_fields, "type": "phrase" }, }, "aggregations": { "years": { "date_histogram": { "field": "date", "interval": "year" } } } } return [ self.es.search( q1, index=self.index_name, size=0), self.es.search( q2, index=self.index_name, size=0)] def reindex_everything(self): for data_type in Transforms.data_types(): self.reindex_all(data_type) def delete_everything(self): self.es.delete_index(self.index_name) if __name__ == "__main__": # print "ElasticSearch PMG library" parser = argparse.ArgumentParser(description='ElasticSearch PMG library') parser.add_argument( '--import', dest='import_data_type', choices=Transforms.data_types(), help='Imports the data from a content type to ElasticSearch') parser.add_argument('--test', action="store_true") parser.add_argument('--reindex', action="store_true") parser.add_argument('--delete', action="store_true") args = parser.parse_args() search = Search() if (args.test): search.test() if (args.import_data_type): search.reindex_all(args.import_data_type) if (args.reindex): search.reindex_everything() if (args.delete): search.delete_everything()
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,894
johnfelipe/pmg-cms-2
refs/heads/master
/backend/transforms.py
from bs4 import BeautifulSoup class Transforms: @classmethod def data_types(cls): return cls.convert_rules.keys() # If there is a rule defined here, the corresponding CamelCase model # will be indexed convert_rules = { "committee": { "id": "id", "title": "name", "description": ["info", "about"] }, "committee_meeting": { "id": "id", "title": "title", "description": "summary", "fulltext": "body", "date": "date", "committee_name": ["organisation", "name"], "committee_id": ["organisation", "id"], }, "member": { "id": "id", "title": "name", "description": "bio", "date": "start_date", }, "bill": { "id": "id", "title": "title", "description": "bill_code" }, "hansard": { "id": "id", "title": "title", "fulltext": "body", "date": "start_date", }, "briefing": { "id": "id", "title": "title", "description": "summary", "fulltext": "minutes", "date": "start_date", "committee_name": ["committee", "name"], "committee_id": ["committee", "id"], }, "question_reply": { "id": "id", "title": "title", "fulltext": "body", "date": "start_date", "committee_name": ["committee", "name"], "committee_id": ["committee", "id"], }, "tabled_committee_report": { "id": "id", "title": "title", "fulltext": "body", "date": "start_date", "committee_name": ["committee", "name"], "committee_id": ["committee", "id"], }, "call_for_comment": { "id": "id", "title": "title", "fulltext": "body", "date": "start_date", "committee_name": ["committee", "name"], "committee_id": ["committee", "id"], }, "policy_document": { "id": "id", "title": "title", "date": "start_date", }, "gazette": { "id": "id", "title": "title", "date": "start_date", }, "daily_schedule": { "id": "id", "title": "title", "fulltext": "body", "date": "start_date", }, } @classmethod def serialise(cls, data_type, obj): item = {} for key, field in Transforms.convert_rules[data_type].iteritems(): val = cls.get_val(obj, field) if isinstance(val, unicode): val = BeautifulSoup(val).get_text().strip() item[key] = val return item @classmethod def get_val(cls, obj, field): if isinstance(field, list): if (len(field) == 1): if hasattr(obj, field[0]): return getattr(obj, field[0]) key = field[:1][0] if isinstance(key, int): if len(obj) > key: return cls.get_val(obj[key], field[1:]) return None if hasattr(obj, key): newobj = getattr(obj, key) return cls.get_val(newobj, field[1:]) else: return None else: return getattr(obj, field)
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,895
johnfelipe/pmg-cms-2
refs/heads/master
/frontend/user_management.py
from flask import render_template, g, request, redirect, session, url_for, abort, flash from frontend import app from views import ApiException, load_from_api import os import forms import requests from requests import ConnectionError import json import logging API_HOST = app.config['API_HOST'] logger = logging.getLogger(__name__) # chat with backend API def user_management_api(endpoint, data=None): query_str = "security/" + endpoint headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' } if endpoint != 'login' and session and session.get('authentication_token'): headers['Authentication-Token'] = session['authentication_token'] try: response = requests.post( API_HOST + query_str, data=data, headers=headers, allow_redirects=False) try: out = response.json() if response.status_code != 200: raise ApiException( response.status_code, out.get( 'message', u"An unspecified error has occurred.")) if out.get('response') and out['response'].get('errors'): for field, messages in out['response']['errors'].iteritems(): for message in messages: flash(message, 'danger') except ValueError: logger.error("Error interpreting response from API. No JSON object could be decoded") flash(u"Error interpreting response from API.", 'danger') logger.debug(response.text) return try: logger.debug(json.dumps(out, indent=4)) except Exception: logger.debug("Error logging response from API") return out['response'] except ConnectionError: flash(u'Error connecting to backend service.', 'danger') pass return @app.route('/login/', methods=['GET', 'POST']) def login(): """View function for login view""" form = forms.LoginForm(request.form) if request.args.get('next'): form.next.data = request.args['next'] if form.validate_on_submit(): data = { 'email': form.email.data, 'password': form.password.data } response = user_management_api('login', json.dumps(data)) # save auth token if response and response.get('user') and response['user'].get('authentication_token'): session['api_key'] = response['user']['authentication_token'] update_current_user() if request.values.get('next'): return redirect(request.values['next']) return render_template('user_management/login_user.html', form=form) @app.route('/logout/', methods=['GET', ]) def logout(): """View function which handles a logout request.""" response = user_management_api('logout/') session.clear() if response: flash(u'You have been logged out successfully.', 'success') return redirect(request.args.get('next', None) or url_for('index')) return redirect(url_for('index')) @app.route('/register/', methods=['GET', 'POST']) def register(): """View function which handles a registration request.""" form = forms.RegisterForm(request.form) if request.args.get('next'): form.next.data = request.args['next'] if form.validate_on_submit(): data = { 'email': form.email.data, 'password': form.password.data } response = user_management_api('register', json.dumps(data)) # save Api Key and redirect user if response and response.get('user') and response['user'].get('authentication_token'): logger.debug("saving authentication_token to the session") session['api_key'] = response['user']['authentication_token'] update_current_user() flash( u'You have been registered. Please check your email for a confirmation.', 'success') if request.values.get('next'): return redirect(request.values['next']) return render_template('user_management/register_user.html', form=form) @app.route('/send-confirmation/', methods=['GET', 'POST']) def send_confirmation(): """View function which sends confirmation instructions.""" form = forms.SendConfirmationForm(request.form) if form.validate_on_submit(): data = { 'email': form.email.data, } response = user_management_api('confirm', json.dumps(data)) # redirect user if response and response.get('user'): flash( u'Your confirmation email has been resent. Please check your inbox.', 'success') if request.values.get('next'): return redirect(request.values['next']) return render_template( 'user_management/send_confirmation.html', send_confirmation_form=form) @app.route('/forgot-password/', methods=['GET', 'POST']) def forgot_password(): """View function that handles a forgotten password request.""" form = forms.ForgotPasswordForm(request.form) if form.validate_on_submit(): data = { 'email': form.email.data, } response = user_management_api('reset', json.dumps(data)) # redirect user if response and not response.get('errors'): flash( u'You will receive an email with instructions for resetting your password. Please check your inbox.', 'success') if request.values.get('next'): return redirect(request.values['next']) return render_template( 'user_management/forgot_password.html', forgot_password_form=form) @app.route('/reset-password/<token>', methods=['GET', 'POST']) def reset_password(token): """View function that handles a reset password request.""" form = forms.ResetPasswordForm() if form.validate_on_submit(): data = { "password": form.password.data, "password_confirm": form.password_confirm.data, } response = user_management_api('reset/' + token, json.dumps(data)) # redirect user if response and not not response.get('errors'): flash(u'Your password has been changed successfully.', 'success') if request.values.get('next'): return redirect(request.values['next']) return render_template( 'user_management/reset_password.html', reset_password_form=form, reset_password_token=token) @app.route('/change-password/', methods=['GET', 'POST']) def change_password(): """View function which handles a change password request.""" form = forms.ChangePasswordForm() if form.validate_on_submit(): data = { "password": form.password.data, "new_password": form.new_password.data, "new_password_confirm": form.new_password_confirm.data, } response = user_management_api('change', json.dumps(data)) # redirect user if response and not response.get('errors'): flash(u'Your password has been changed successfully.', 'success') if request.values.get('next'): return redirect(request.values['next']) return render_template( 'user_management/change_password.html', change_password_form=form) @app.route('/confirm-email/<confirmation_key>', methods=['GET', ]) def confirm_email(confirmation_key): """View function for confirming an email address.""" response = user_management_api('confirm/' + confirmation_key) if response and not response.get('errors'): flash(u'Thanks. Your email address has been confirmed.', 'success') return redirect(url_for('index')) def update_current_user(): """ Hit the API, and update our session's 'current_user' if necessary. """ tmp = load_from_api("") # hit the API's index page if tmp.get('current_user'): session['current_user'] = tmp['current_user'] return
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,896
johnfelipe/pmg-cms-2
refs/heads/master
/rebuild_db.py
import os import json import time, datetime import parsers import logging import csv import re import requests from sqlalchemy import types from backend.app import app, db from backend.models import * from backend.search import Search from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound from sqlalchemy import Date, cast logger = logging.getLogger('rebuild_db') logging.getLogger('sqlalchemy.engine').level = logging.WARN STATIC_HOST = app.config['STATIC_HOST'] db.echo = False def strip_filepath(filepath): return "/".join(filepath.split("/")[1::]) def dump_db(name): try: os.remove(name) except Exception as e: logger.debug(e) pass return def read_data(filename): start = time.time() logger.debug("reading " + filename) with open('data/' + filename, 'r') as f: records = [] lines = f.readlines() for line in lines: records.append(json.loads(line)) return records def db_date_from_utime(utime): try: return datetime.datetime.fromtimestamp(float(utime)) except: try: datetime.strptime(utime, '%Y-%m-%dT%H:%m:%s') except: return None def construct_obj(obj, mappings): """ Returns a result with the properties mapped by mapping, including all revisions """ result_obj = {} # print obj for key in mappings.keys(): if (obj.has_key(key)): result_obj[key] = obj[key] if (obj.has_key("revisions") and (type(obj["revisions"]) is list) and (len(obj["revisions"]) > 0)): for revision in obj["revisions"]: tmp = construct_obj(revision, mappings) result_obj.update(tmp) return result_obj def find_files(obj): files = [] if (obj.has_key("files") and (type(obj["files"]) is list) and (len(obj["files"]) > 0)): # print obj["files"] for f in obj["files"]: fobj = File( filemime=f["filemime"], origname = f["origname"], url = f["filepath"].replace("files/", ""), ) db.session.add(fobj) files.append(fobj) db.session.commit() if (obj.has_key("audio") and (type(obj["audio"]) is list) and (len(obj["audio"]) > 0)): # print obj["audio"] for f in obj["audio"]: fobj = File( filemime=f["filemime"], origname = f["origname"], url = "audio/" + f["filename"].replace("files/", ""), playtime = f["playtime"], description = f["title_format"] ) db.session.add(fobj) files.append(fobj) db.session.commit() return files def find_committee(obj): committees = [] if (obj.has_key("terms") and (type(obj["terms"]) is list) and (len(obj["terms"]) > 0)): # print obj["terms"] for term in obj["terms"]: committee = Committee.query.filter_by(name = term).first() # print committee, term if committee: committees.append(committee) # else: # print term return committees def prep_table(model_class): print "Deleted rows: ", model_class.query.delete() def rebuild_table(table_name, model_class, mappings): logger.debug("Rebuilding %s" % table_name) prep_table(model_class) i = 0 with open('data/' + table_name + '.json', 'r') as f: lines = f.readlines() logger.debug("Found %i records" % (len(lines))) for line in lines: try: obj = json.loads(line) newobj = construct_obj(obj, mappings) # Check for Dates for mapping in mappings.keys(): row_type = getattr(model_class, mapping).property.columns[0].type if (row_type.__str__() == "DATE"): if (newobj.has_key(mappings[mapping])): newobj[mappings[mapping]] = db_date_from_utime(newobj[mappings[mapping]]) new_rec = model_class() files = find_files(obj) committees = find_committee(obj) if hasattr(new_rec, 'committee_id'): if len(committees): new_rec.committee_id = committees[0].id else: if (committees): for committee in committees: new_rec.committee.append(committee) if (len(files)): for f in files: new_rec.files.append(f) for key,val in newobj.iteritems(): setattr(new_rec, key, val) db.session.add(new_rec) i += 1 if (i == 100): db.session.commit() i = 0 logger.debug("Wrote 100 rows...") except: logger.warning("Error reading row for " + table_name) db.session.commit() def guess_pa_link(name, names): name_parts = re.split(",", name) first_letter = None surname = name_parts[0] if (len(name_parts) > 1): name_parts = re.split(" ", name_parts[1].strip()) if (len(name_parts) > 1 and len(name_parts[1])): first_letter = name_parts[1][0] for pa_name in names: # print pa_name[1], surname if surname in pa_name[1].decode("utf-8"): if first_letter and first_letter is pa_name[1].decode("utf-8")[0]: return pa_name[0] return None def rebuild_db(): """ Save json fixtures into a structured database, intended for use in our app. """ start = time.time() # populate houses of parliament joint_obj = House(name="Joint (NA + NCOP)", name_short="Joint") ncop_obj = House(name="National Council of Provinces", name_short="NCOP") na_obj = House(name="National Assembly", name_short="NA") presidents_office_obj = House(name="The President's Office", name_short="President") for obj in [joint_obj, ncop_obj, na_obj, presidents_office_obj]: db.session.add(obj) db.session.commit() # populate membership_type chairperson = MembershipType(name="chairperson") db.session.add(chairperson) db.session.commit() # populate bill_type options tmp = [ ('X', 'Draft', 'Draft'), ('B', 'S74', 'Section 74: Constitutional amendments'), ('B', 'S75', 'Section 75: Ordinary Bills not affecting the provinces'), ('B', 'S76', 'Section 76: Ordinary Bills affecting the provinces'), ('B', 'S77', 'Section 77: Money Bills'), ('PMB', 'Private Member Bill', 'Private Member Bill: Bills that are drawn up by private members, as opposed to ministers or committees.') ] for (prefix, name, description) in tmp: bill_type = BillType(prefix=prefix, name=name, description=description) db.session.add(bill_type) db.session.commit() # populate bill_status options tmp = [ ('lapsed', 'Lapsed'), ('withdrawn', 'Withdrawn'), ('na', 'Under consideration by the National Assembly.'), ('ncop', 'Under consideration by the National Council of Provinces.'), ('president', 'Approved by parliament. Waiting to be signed into law.'), ('enacted', 'The bill has been signed into law.'), ('act-commenced', 'Act commenced'), ('act-partly-commenced', 'Act partially commenced'), ] for (name, description) in tmp: bill_status = BillStatus(name=name, description=description) db.session.add(bill_status) db.session.commit() # populate committees committees = {} committee_list = read_data('comm_info_page.json') for committee in committee_list: if committee['terms']: name = committee['terms'][0].strip() if name not in committees.keys(): committees[name] = {} committee_obj = construct_obj(committee, { "comm_info_type": "comm_info_type", "body": "body" }) # logger.debug(committee_obj) if committee_obj.has_key("comm_info_type"): if committee_obj["comm_info_type"] == 'About': committees[name]["about"] = committee_obj["body"] elif committee_obj["comm_info_type"] == 'Contact': committees[name]["contact"] = committee_obj["body"] for key, val in committees.iteritems(): # logger.debug(val) committee = Committee() committee.name = key # set parent relation if "ncop" in committee.name.lower(): committee.house_id = ncop_obj.id elif "joint" in committee.name.lower(): committee.house_id = joint_obj.id else: committee.house_id = na_obj.id # committee_info = CommitteeInfo() if val.get("about"): committee.about = val["about"] if val.get("contact"): committee.contact_details = val["contact"] db.session.add(committee) val['model'] = committee db.session.commit() # populate committee members pa_members = [] with open('./scrapers/members.csv', 'r') as csvfile: membersreader = csv.reader(csvfile) for row in membersreader: pa_members.append(row) members = read_data('committee_member.json') for member in members: member_obj = Member( name=member['title'].strip(), start_date = db_date_from_utime(member['start_date']), pa_link = guess_pa_link(member['title'].strip(), pa_members) ) if member.get('files'): member_obj.profile_pic_url = strip_filepath(member["files"][-1]['filepath']) logger.debug(member_obj.name) logger.debug(member_obj.profile_pic_url) # extract bio info if member['revisions']: bio = member['revisions'][0]['body'] if bio: index = bio.find("Further information will be provided shortly on:") if index and index > 0: bio = bio[0:index].strip() logger.debug(bio) member_obj.bio = bio # set committee relationships for term in member['terms']: if committees.get(term): org_model = committees[term]['model'] membership_obj = Membership(committee=org_model) member_obj.memberships.append(membership_obj) else: logger.debug("committee not found: " + term) # set party membership party = member['mp_party'] if party: logger.debug(party) party_obj = Party.query.filter_by(name=party).first() if not party_obj: party_obj = Party(name=party) db.session.add(party_obj) db.session.commit() member_obj.party_id = party_obj.id # set house membership house = member['mp_province'] if house == "National Assembly": member_obj.house_id = na_obj.id elif house and "NCOP" in house: member_obj.house_id = ncop_obj.id # logger.debug(house) province_obj = Province.query.filter_by(name=house[5::]).first() if not province_obj: province_obj = Province(name=house[5::]) db.session.add(province_obj) db.session.commit() member_obj.province_id = province_obj.id db.session.add(member_obj) logger.debug('') db.session.commit() # select a random chairperson for each committee tmp_committees = Committee.query.all() for committee in tmp_committees: if committee.memberships: membership_obj = committee.memberships[0] membership_obj.type_id = 1 db.session.add(membership_obj) db.session.commit() # populate committee reports i = 0 db.session.commit() logger.debug("reading report.js") with open('data/report.json', 'r') as f: records = [] lines = f.readlines() for line in lines: report = json.loads(line) parsed_report = parsers.MeetingReportParser(report) committee_obj = committees.get(parsed_report.committee) if committee_obj: committee_obj = committee_obj['model'] event_obj = Event( type="committee-meeting", committee=committee_obj, date=parsed_report.date, title=parsed_report.title ) db.session.add(event_obj) report_obj = CommitteeMeetingReport( body=parsed_report.body, summary=parsed_report.summary, event=event_obj ) db.session.add(report_obj) for item in parsed_report.related_docs: doc_obj = Content( event=event_obj, type=item["filemime"], ) doc_obj.file_path=item["filepath"] doc_obj.title=item["title"] db.session.add(doc_obj) for item in parsed_report.audio: audio_obj = Content( event=event_obj, type=item["filemime"], ) if item["filepath"].startswith('files/'): audio_obj.file_path=item["filepath"][6::] else: audio_obj.file_path=item["filepath"] if item.get("title_format"): audio_obj.title=item["title_format"] elif item.get("filename"): audio_obj.title=item["filename"] elif item.get("origname"): audio_obj.title=item["origname"] else: audio_obj.title="Unnamed audio" db.session.add(audio_obj) i += 1 if i % 500 == 0: logger.debug("writing 500 reports...") db.session.commit() return def addChild(Child, val): if (val): tmpobj = Child.query.filter_by(name = val).first() if not tmpobj: tmpobj = Child(name=val) db.session.add(tmpobj) db.session.commit() return tmpobj.id return None def bills(): prep_table("bill") r = requests.get('http://billsapi.pmg.org.za/bill/') bills = r.json() for billobj in bills: bill = Bill() bill.title = billobj["name"] bill.bill_code = billobj["code"] # act_name = db.Column(db.String(250)) bill.number = billobj["number"] bill.year = billobj["year"] # date_of_introduction = db.Column(db.Date) # date_of_assent = db.Column(db.Date) # effective_date = db.Column(db.Date) bill.objective = billobj["objective"] bill.is_deleted = billobj["is_deleted"] bill.status_id = addChild(BillStatus, billobj["status"]) bill.type_id = addChild(BillType, billobj["bill_type"]) # place_of_introduction_id = db.Column(db.Integer, db.ForeignKey('committee.id')) # place_of_introduction = db.relationship('Committee') # introduced_by_id = db.Column(db.Integer, db.ForeignKey('member.id')) # introduced_by = db.relationship('Member') db.session.add(bill) db.session.commit() def add_featured(): committeemeetings = CommitteeMeetingReport.query.limit(5) tabledreports = TabledCommitteeReport.query.limit(5) featured = Featured() for committeemeeting in committeemeetings: featured.committee_meeting_report.append(committeemeeting) for tabledreport in tabledreports: featured.tabled_committee_report.append(tabledreport) featured.title = "LivemagSA Launched Live From Parliament" featured.blurb = "For the next six months, LiveMagSA be teaming up with PMG to report directly from parliament, bringing you the highlights and telling you about the policy decisions that affect you." featured.link = "http://livemag.co.za/welcome-parliament/" db.session.add(featured) db.session.commit() def clear_db(): logger.debug("Dropping all") db.drop_all() logger.debug("Creating all") db.create_all() def disable_reindexing(): Search.reindex_changes = False def merge_billtracker(): na_obj = House.query.filter_by(name_short="NA").one() ncop_obj = House.query.filter_by(name_short="NCOP").one() joint_obj = House.query.filter_by(name_short="Joint").one() president_obj = House.query.filter_by(name_short="President").one() location_map = { 1: na_obj, 2: ncop_obj, 3: president_obj, 4: joint_obj, } entry_count = 0 committee_meeting_count = 0 encoding_error_count = 0 unmatched_count = 0 ambiguous_match_count = 0 with open("data/billtracker_dump.txt", "r") as f: data=f.read() bills = json.loads(data) for rec in bills: bill_obj = Bill( title=rec['name'], number=rec['number'], year=rec['year'], ) if rec.get('bill_type'): bill_obj.type = BillType.query.filter_by(name=rec['bill_type']).one() if rec.get('status'): bill_obj.status = BillStatus.query.filter_by(name=rec['status']).one() # effective_date # act_name # introduced_by_id # introduced_by # tag committee meetings (based on title, because we have nothing better) for entry in rec['entries']: entry_count += 1 entry_date = None if entry['date'] and not entry['date'] == "None": entry_date = datetime.datetime.strptime(entry['date'], "%Y-%m-%d").date() if entry['type'] == "committee-meeting": committee_meeting_count += 1 try: title = unicode(entry['title'].replace('\\"', '').replace('\\r', '').replace('\\n', '').replace('\\t', '')) event_obj = Event.query.filter(cast(Event.date, Date) == entry_date) \ .filter(Event.title.like('%' + title[5:35] + '%')).one() bill_obj.events.append(event_obj) except UnicodeEncodeError as e: encoding_error_count += 1 pass except NoResultFound as e: unmatched_count += 1 pass except MultipleResultsFound as e: ambiguous_match_count += 1 elif entry['type'] == "default": if "introduced" in entry['title']: tmp_location = na_obj if entry['location']: tmp_location = location_map[entry['location']] bill_obj.place_of_introduction = tmp_location if entry_date: bill_obj.date_of_introduction = entry_date tmp_event = Event( type="bill-introduced", title=entry['title'], date=entry_date, house=tmp_location ) tmp_event.bills.append(bill_obj) db.session.add(tmp_event) elif "passed by" in entry['title']: if "council" in entry['title'].lower() or "ncop" in entry['title'].lower(): location = ncop_obj elif "assembly" in entry['title'].lower() or "passed by na" in entry['title'].lower(): location = na_obj else: print entry raise Exception("error locating bill-passed event") tmp_event = Event( type="bill-passed", title=entry['title'], date=entry_date, house=location ) tmp_event.bills.append(bill_obj) db.session.add(tmp_event) elif "enacted" in entry['title'].lower() + entry['description'].lower() and entry['agent']['type'] == "president": tmp_event = Event( type="bill-enacted", title=entry['description'] + " - " + entry['title'], date=entry_date ) tmp_event.bills.append(bill_obj) bill_obj.date_of_assent = entry_date db.session.add(tmp_event) elif "signed" in entry['title'].lower() and entry['agent']['type'] == "president": tmp_event = Event( type="bill-signed", title=entry['title'], date=entry_date ) tmp_event.bills.append(bill_obj) db.session.add(tmp_event) db.session.add(bill_obj) db.session.commit() print entry_count, "entries" print committee_meeting_count, "committee meetings" print encoding_error_count, "encoding errors" print unmatched_count, "orphans" print ambiguous_match_count, "ambiguous matches" return if __name__ == '__main__': disable_reindexing() clear_db() rebuild_db() rebuild_table("hansard", Hansard, { "title": "title", "meeting_date": "meeting_date", "start_date": "start_date", "body": "body" }) rebuild_table("briefing", Briefing, {"title": "title", "briefing_date": "briefing_date", "summary": "summary", "minutes": "minutes", "presentation": "presentation", "start_date": "start_date" }) rebuild_table("questions_replies", QuestionReply, {"title": "title", "body": "body", "start_date": "start_date", "question_number": "question_number"}) rebuild_table("tabled_committee_report", TabledCommitteeReport, { "title": "title", "start_date": "start_date", "body": "body", "summary": "teaser", "nid": "nid" }) rebuild_table("calls_for_comment", CallForComment, { "title": "title", "start_date": "start_date", "end_date": "comment_exp", "body": "body", "summary": "teaser", "nid": "nid" }) rebuild_table("policy_document", PolicyDocument, { "title": "title", "effective_date": "effective_date", "start_date": "start_date", "nid": "nid" }) rebuild_table("gazette", Gazette, { "title": "title", "effective_date": "effective_date", "start_date": "start_date", "nid": "nid" }) rebuild_table("daily_schedule", DailySchedule, { "title": "title", "start_date": "start_date", "body": "body", "schedule_date": "daily_sched_date", "nid": "nid" }) add_featured() # add default roles admin_role = Role(name="editor") db.session.add(admin_role) superuser_role = Role(name="user-admin") db.session.add(superuser_role) # add a default admin user user = User(email="admin@pmg.org.za", password="3o4ukjren3", active=True, confirmed_at=datetime.datetime.now()) user.roles.append(admin_role) user.roles.append(superuser_role) db.session.add(user) db.session.commit() # add billtracker data merge_billtracker()
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,897
johnfelipe/pmg-cms-2
refs/heads/master
/parsers/main.py
from backend.app import logging from datetime import datetime import json class MyParser(): def __init__(self): print "i'm a parser" def strip_rtf(self, rtf_str): if rtf_str: return unicode(rtf_str.replace('\\"', '').replace('\\r', '').replace('\\n', '').replace('\\t', '')) else: return None def remove_html(self, html_str): return html_str def unpack_field_document_data(self, str_in): out = {} tmp = str_in.split('\"') # logger.debug(tmp) # file description i = tmp.index('description') if i >= 0: out['description'] = tmp[i+2] return out class MeetingReportParser(MyParser): def __init__(self, report_dict): self.source = report_dict self.title = None self.committee = None self.date = None if report_dict.get('meeting_date'): try: timestamp = int(report_dict['meeting_date'].strip('"')) self.date = datetime.fromtimestamp( timestamp ) except (TypeError, AttributeError) as e: pass self.summary = None self.body = None self.related_docs = [] self.audio = [] self.related_bills = [] self.extract_title() self.extract_committee() self.extract_summary() self.extract_related_docs() self.extract_audio() self.extract_body() def extract_title(self): self.title = self.strip_rtf(self.source['title']) return def extract_committee(self): if self.source['terms']: self.committee = self.strip_rtf(self.source['terms'][0]) return def extract_summary(self): self.summary = None if self.source.get('summary'): self.summary = self.strip_rtf(self.source['summary']) return def extract_related_docs(self): tmp_list = [] for file in self.source['files']: if file["filepath"].startswith('files/'): file["filepath"] = file["filepath"][6::] # duplicate entries exist, but they don't both have all of the detail if not file["fid"] in tmp_list: tmp_list.append(file["fid"]) self.related_docs.append(file) # update the document title i = tmp_list.index(file["fid"]) doc = self.related_docs[i] if file.get("field_document_data"): tmp_data = self.unpack_field_document_data(file["field_document_data"]) if tmp_data.get("description"): doc["title"] = tmp_data.get("description") if file.get("field_document_description"): doc["title"] = file.get("field_document_description") elif not doc.get("title") and file.get("filename"): doc["title"] = file.get("filename") elif not doc.get("title") and file.get("origname"): doc["title"] = file.get("origname") elif not doc.get("title"): doc["title"] = "Unnamed document" return def extract_audio(self): tmp = [] for file in self.source['audio']: if not file["fid"] in tmp: tmp.append(file["fid"]) self.audio.append(file) return def extract_body(self): if self.source.get('minutes'): minutes_clean = self.strip_rtf(self.source['minutes']) else: minutes_clean = None self.body = minutes_clean return
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,898
johnfelipe/pmg-cms-2
refs/heads/master
/scrapers/scraper.py
from datetime import datetime import requests from lxml import html from flask import Flask import re import sys from cssselect import GenericTranslator import argparse import sys, os sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../'))) from backend.app import app, db from backend import models from backend.models import * import parsers from sqlalchemy import types from bs4 import BeautifulSoup import csv from urlparse import urljoin app = Flask(__name__) import logging logger = logging.getLogger() class Scraper: dows = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"] missing_committees = [] def test(self): print "Test!" return def _save_schedule(self, items): for key in items: print items[key] schedule = Schedule() schedule.description = items[key]["description"] schedule.meeting_date = key schedule.meeting_time = items[key]["time"] # for house in items[key]["house"]: # print house # schedule.houses.append(house) if (schedule.description): db.session.add(schedule) db.session.commit() def schedule(self): url = "http://www.pmg.org.za/schedule" url = "http://www.pmg.org.za/daily-schedule/" + datetime.datetime.now().strftime('%Y/%m/%d') + "/daily-schedule" print "Fetching ", url page = requests.get(url) tree = html.fromstring(page.text) # content = tree.xpath('//*[@id="content"]/div[3]/div[1]/div/div/div[3]/p[3]/text()') xpath = GenericTranslator().css_to_xpath('#content > div.node > div.content') for p in tree.xpath(xpath + "/p"): content = p.text_content().encode('utf8', 'replace').strip() if content.split(', ', 1)[0] in self.dows: break; in_date = False result = {} for part in content.split("\n"): part = part.strip() if part: if part.split(', ', 1)[0] in self.dows: in_date = date_object = datetime.datetime.strptime(part, '%A, %d %B %Y') result[in_date] = {} else: result[in_date]["house"] = [] if part.find("(National Assembly and National Council of Provinces)") > -1: result[in_date]["house"] = ["National Assembly", "NCOP"] part = re.sub("\(National Assembly and National Council of Provinces\),", "", part).strip() elif part.find("(National Assembly)") > -1: result[in_date]["house"] = ["National Assembly"] part = re.sub("\(National Assembly\),", "", part).strip() elif part.find("(National Council of Provinces)") > -1: result[in_date]["house"] = ["NCOP"] part = re.sub("\(National Council of Provinces\),", "", part).strip() time = re.search(r"[0-9][0-9]\:[0-9][0-9]", part) if time: result[in_date]["time"] = time.group() part = re.sub(r"\,\s[0-9][0-9]\:[0-9][0-9]", "", part) result[in_date]["description"] = re.sub(r"[^\w\s]", "", part) print result self._save_schedule(result) return def _save_tabledreport(self, title, committee_name, body): tabled_committee_report = Tabled_committee_report() committee = Organisation.query.filter_by(name=committee_name).first() if (committee): tabled_committee_report.title = title tabled_committee_report.body = body tabled_committee_report.committee.append(committee) db.session.add(tabled_committee_report) else: if committee_name not in self.missing_committees: self.missing_committees.append(committee_name) db.session.commit() def _report_exists(self, title, committee_name): committee = Organisation.query.filter_by(name=committee_name).first() if (committee): check = Tabled_committee_report.query.filter_by(title=title).first() if check: return True return False def tabledreports(self): # url = "http://pmg.org.za/tabled-committee-reports-2008-2013" # print "Fetching", url # page = requests.get(url) # txt = page.text f = open("./scrapers/tabled-committee-reports-2008-2013.html", "r") txt = f.read().decode('utf8') name_boundary_pairs = [] startpos = re.search('\<a name', txt).start() current_section = "" with open('./scrapers/committees.csv', 'r') as csvfile: committeesreader = csv.reader(csvfile) for row in committeesreader: for test in re.finditer('\<a name="' + row[0] + '"', txt): if (current_section): name_boundary_pairs.append([startpos, test.start(), current_section]) startpos = test.start() current_section = row[1] queue = [] for interval in name_boundary_pairs: # print "=== %s ===" % interval[2] soup = BeautifulSoup(txt[interval[0]:interval[1]]) for link in soup.find_all("a", href = True): if (link.get_text() != "back to top"): url = link['href'] if not re.match("http://", url): url = "http://www.pmg.org/" + url.replace("../../../../../../", "") queue.append({ "link": url, "name": link.get_text(), "committee": interval[2].strip()}) for item in queue: if (self._report_exists(item["name"], item["committee"]) == False): # print "Processing report %s" % item["name"] page = requests.get(item["link"]).text self._save_tabledreport(item["name"], item["committee"], page) print self.missing_committees def members(self): list_url = "http://www.pa.org.za/organisation/national-assembly/people/" with open('./scrapers/members.csv', 'w') as csvfile: memberswriter = csv.writer(csvfile) memberswriter.writerow(["url", "name"]) while True: html = requests.get(list_url).content soup = BeautifulSoup(html) for item in soup.select(".person-list-item a"): url = item["href"] if "person" in url: name = item.select(".name")[0].get_text() member = [ url, name.encode("utf-8") ] memberswriter.writerow(member); next = soup.select("a.next") if next: list_url = urljoin(list_url, next[0]["href"]) else: break if (__name__ == "__main__"): parser = argparse.ArgumentParser(description='Scrapers for PMG') parser.add_argument('scraper') args = parser.parse_args() scraper = Scraper() method = getattr(scraper, args.scraper) if not method: raise Exception("Method %s not implemented" % args.scraper) method()
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,899
johnfelipe/pmg-cms-2
refs/heads/master
/backend/views.py
import logging from app import db, app from models import * import flask from flask import g, request, abort, redirect, url_for, session, make_response import json from sqlalchemy import func, or_, distinct, desc from sqlalchemy.orm import joinedload from sqlalchemy.orm.exc import NoResultFound import datetime from operator import itemgetter import re import serializers import sys from search import Search import math from flask_security import current_user from flask_security.decorators import load_user API_HOST = app.config["API_HOST"] # handling static files (only relevant during development) app.static_folder = 'static' app.add_url_rule('/static/<path:filename>', endpoint='static', view_func=app.send_static_file) logger = logging.getLogger(__name__) class ApiException(Exception): """ Class for handling all of our expected API errors. """ def __init__(self, status_code, message): Exception.__init__(self) self.message = message self.status_code = status_code def to_dict(self): rv = { "code": self.status_code, "message": self.message } return rv def get_filter(): filters = [] args = flask.request.args.to_dict() for key in args: if "filter" in key: fieldname = re.search("filter\[(.*)\]", key).group(1) if fieldname: filters.append({fieldname: args[key]}) return filters @app.errorhandler(ApiException) def handle_api_exception(error): """ Error handler, used by flask to pass the error on to the user, rather than catching it and throwing a HTTP 500. """ response = flask.jsonify(error.to_dict()) response.status_code = error.status_code response.headers['Access-Control-Allow-Origin'] = "*" return response def send_api_response(data_json): response = flask.make_response(data_json) response.headers['Access-Control-Allow-Origin'] = "*" response.headers['Content-Type'] = "application/json" return response def api_resources(): current_time = datetime.datetime.utcnow() return { "committee": db.session.query(Committee) .order_by(Committee.house_id, Committee.name), "committee-meeting": db.session.query(Event) .filter(Event.type == 'committee-meeting') .order_by(desc(Event.date)), "bill": db.session.query(Bill) .order_by(desc(Bill.year)), "member": db.session.query(Member) .order_by(Member.name), "hansard": db.session.query(Hansard) .order_by(desc(Hansard.meeting_date)), "briefing": db.session.query(Briefing) .order_by(desc(Briefing.briefing_date)), "question_reply": db.session.query(QuestionReply) .order_by(desc(QuestionReply.start_date)), "schedule": db.session.query(Schedule) .order_by(desc(Schedule.meeting_date)) .filter(Schedule.meeting_date >= current_time), "tabled_committee_report": db.session.query(TabledCommitteeReport) .order_by(desc(TabledCommitteeReport.start_date)), "call_for_comment": db.session.query(CallForComment) .order_by(desc(CallForComment.start_date)), "policy_document": db.session.query(PolicyDocument) .order_by(desc(PolicyDocument.start_date)), "gazette": db.session.query(Gazette) .order_by(desc(Gazette.start_date)), "featured": db.session.query(Featured) .order_by(desc(Featured.start_date)), "daily_schedule": db.session.query(DailySchedule) .order_by(desc(DailySchedule.start_date)), } # ------------------------------------------------------------------- # API endpoints: # @app.route('/search/') def search(): """ Search through ElasticSearch """ search = Search() filters = {} logger.debug("Search args: %s" % request.args) q = request.args.get('q') page = 0 if (request.args.get('page')): page = int(request.args.get('page')) per_page = app.config['RESULTS_PER_PAGE'] if (request.args.get('per_page')): per_page = int(request.args.get('per_page')) filters["start_date"] = request.args.get('filter[start_date]') filters["end_date"] = request.args.get('filter[end_date]') filters["type"] = request.args.get('filter[type]') filters["committee"] = request.args.get('filter[committee]') searchresult = search.search( q, per_page, page * per_page, content_type=filters["type"], start_date=filters["start_date"], end_date=filters["end_date"], committee=filters["committee"]) bincounts = search.count(q) result = {} result["result"] = searchresult["hits"]["hits"] result["count"] = searchresult["hits"]["total"] result["max_score"] = searchresult["hits"]["max_score"] result["bincount"] = {} result["bincount"]["types"] = bincounts[ 0]["aggregations"]["types"]["buckets"] result["bincount"]["years"] = bincounts[ 1]["aggregations"]["years"]["buckets"] logger.debug("Pages %i", math.ceil(result["count"] / per_page)) if result["count"] > (page + 1) * per_page: result["next"] = flask.request.url_root + "search/?q=" + q + \ "&page=" + str(page + 1) + "&per_page=" + str(per_page) result["last"] = flask.request.url_root + "search/?q=" + q + "&page=" + \ str(int(math.ceil(result["count"] / per_page))) + "&per_page=" + str(per_page) result["first"] = flask.request.url_root + "search/?q=" + \ q + "&page=0" + "&per_page=" + str(per_page) return json.dumps(result) @app.route('/hitlog/', methods=['GET', 'POST']) def hitlog(): """ Records a hit from the end-user. Should be called in a non-blocking manner """ logger.debug("caught a hit") hitlog = HitLog( ip_addr=flask.request.form["ip_addr"], user_agent=flask.request.form["user_agent"], url=flask.request.form["url"]) db.session.add(hitlog) db.session.commit() return "" @app.route('/<string:resource>/', ) @app.route('/<string:resource>/<int:resource_id>/', ) @load_user('token', 'session') def resource_list(resource, resource_id=None): """ Generic resource endpoints. """ base_query = api_resources().get(resource) if not base_query: raise ApiException(400, "The specified resource type does not exist.") # validate paging parameters page = 0 per_page = app.config['RESULTS_PER_PAGE'] if flask.request.args.get('page'): try: page = int(flask.request.args.get('page')) except ValueError: raise ApiException(422, "Please specify a valid 'page'.") # if flask.request.args.get('filter'): filters = get_filter() if (len(filters)): for f in filters: base_query = base_query.filter_by(**f) if resource_id: try: queryset = base_query.filter_by(id=resource_id).one() count = 1 except NoResultFound: raise ApiException(404, "Not found") else: queryset = base_query.limit(per_page).offset(page * per_page).all() count = base_query.count() next = None if count > (page + 1) * per_page: next = flask.request.url_root + resource + "/?page=" + str(page + 1) out = serializers.queryset_to_json( queryset, count=count, next=next, current_user=current_user) return send_api_response(out) @app.route('/', ) @load_user('token', 'session') def landing(): """ List available endpoints. """ out = {'endpoints': []} for resource in api_resources().keys(): out['endpoints'].append(API_HOST + resource) if current_user and current_user.is_active(): try: out['current_user'] = serializers.to_dict(current_user) except Exception: logger.exception("Error serializing current user.") pass return send_api_response(json.dumps(out, indent=4))
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,900
johnfelipe/pmg-cms-2
refs/heads/master
/sync_content.py
import boto import boto.s3 from boto.s3.key import Key import boto.s3.connection import datetime import math import os from os.path import isfile, isdir, join def rounded_megabytes(bytes): megabytes = bytes/float(1024*1024) megabytes = math.ceil(megabytes*1000)/1000 # round the float return megabytes def get_file_size(directory_path, filename): bytes = os.path.getsize(join(directory_path, filename)) return bytes def get_bucket(bucket_name): # conn = boto.connect_s3() conn = boto.s3.connect_to_region('eu-west-1') bucket = conn.get_bucket(bucket_name) return bucket def upload_file(bucket, filename, directory_path, root_path): bytes = get_file_size(directory_path, filename) megabytes = rounded_megabytes(bytes) print "uploading: " + join(directory_path, filename) + " (" + str(megabytes) + " MB)" # assemble key key = join(directory_path, filename).split(root_path)[1] # test if the key already exists tmp_key = bucket.get_key(key) if tmp_key is not None: print " file already uploaded" raise ValueError, "file already uploaded" else: # only upload if the key doesn't exist yet tmp_key = Key(bucket) tmp_key.key = key tmp_key.set_contents_from_filename(join(directory_path, filename)) return def download_file(bucket, filename, directory_path): tmp_key = Key(bucket) tmp_key.key = filename tmp_key.get_contents_to_filename(join(directory_path, filename)) return def upload_directory(bucket, directory_path, root_path=None): if root_path is None: root_path = directory_path # assemble a list of files in the directory content = os.listdir(directory_path) file_list = [] directory_list = [] for item in content: if isfile(join(directory_path, item)): file_list.append(item) elif isdir(join(directory_path, item)): directory_list.append(item) # calculate overall size (in this file only) to be uploaded total_bytes = 0 progress = 0 for filename in file_list: bytes = get_file_size(directory_path, filename) total_bytes += bytes i = 0 start = datetime.datetime.now() for filename in file_list: bytes = get_file_size(directory_path, filename) try: upload_file(bucket, filename, directory_path, root_path) progress += bytes except ValueError: total_bytes -= bytes pass i += 1 if i % 10 == 0: tmp = str(int(100*(progress/float(total_bytes)))) print "\n" + str(rounded_megabytes(progress)) + " MB out of " + str(rounded_megabytes(total_bytes)) + " MB uploaded (" + tmp + "%)" lapsed = (datetime.datetime.now()-start).seconds if lapsed >= 1: speed = int((progress / 1024) / lapsed) print str(speed) + " kbps average upload speed" if speed >= 1: seconds_remaining = int(((total_bytes - progress) / 1024) / speed) hours_remaining = seconds_remaining / float(3600) hours_remaining = math.ceil(hours_remaining*10)/10 print str(hours_remaining) + " hours remaining" for directory_name in directory_list: upload_directory(bucket, join(directory_path, directory_name), root_path) return if __name__ == "__main__": # bucket = get_bucket('eu-west-1-pmg') bucket = get_bucket('test-pmg-2') bucket.set_acl('public-read') upload_directory(bucket, "/var/www/websitedata/drupal/files/")
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,901
johnfelipe/pmg-cms-2
refs/heads/master
/backend/utils.py
from __future__ import division import nltk def levenshtein(first, second): """ Return a similarity ratio of two pieces of text. 0 means the strings are not similar at all, 1.0 means they're identical. This is the Levenshtein ratio: (lensum - ldist) / lensum where lensum is the sum of the length of the two strings and ldist is the Levenshtein distance (edit distance). See https://groups.google.com/forum/#!topic/nltk-users/u94RFDWbGyw """ lensum = len(first) + len(second) ldist = nltk.edit_distance(first, second) if lensum == 0: return 0 return (lensum - ldist) / lensum
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,902
johnfelipe/pmg-cms-2
refs/heads/master
/fabdefs.py
from fabric.api import * """ Define the server environments that this app will be deployed to. Ensure that you have SSH access to the servers for the scripts in 'fabfile.py' to work. """ def production(): """ Env parameters for the production environment. """ env.host_string = 'ubuntu@new.pmg.org.za' env.project_dir = '/var/www/pmg-cms' env.config_dir = env.project_dir + '/config/production' env.git_branch = 'master' env.activate = 'source %s/env/bin/activate' % env.project_dir print("PRODUCTION ENVIRONMENT\n") return
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,903
johnfelipe/pmg-cms-2
refs/heads/master
/config/development/config.py
DEBUG = True SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://pmg:pmg@localhost/pmg' SECRET_KEY = "AEORJAEONIAEGCBGKMALMAENFXGOAERGN" API_HOST = "http://api.pmg.dev:5001/" FRONTEND_HOST = "http://pmg.dev:5000/" SESSION_COOKIE_DOMAIN = "pmg.dev" RESULTS_PER_PAGE = 50 SQLALCHEMY_ECHO = False STATIC_HOST = "http://eu-west-1-pmg.s3-website-eu-west-1.amazonaws.com/" ES_SERVER = "http://ec2-54-77-69-243.eu-west-1.compute.amazonaws.com:9200" SEARCH_REINDEX_CHANGES = False # don't reindex changes to models S3_BUCKET = "eu-west-1-pmg" UPLOAD_PATH = "/tmp/pmg_upload/" ES_SERVER = "http://localhost:9200" MAX_CONTENT_LENGTH = 50 * 1024 * 1024 # size cap on uploads ALLOWED_EXTENSIONS = set( [ "doc", "jpg", "jpeg", "mp3", "pdf", "ppt", "rtf", "txt", "wav", "xls", ] ) # Flask-Mail MAIL_SERVER = 'smtp.gmail.com' MAIL_PORT = 465 MAIL_USE_SSL = True MAIL_USERNAME = "pmgorg.noreply@gmail.com" MAIL_PASSWORD = "agoaiejlagrAIERJaerknj" MAIL_DEFAULT_SENDER = "pmgorg.noreply@gmail.com" # Flask-Security config SECURITY_HOST = FRONTEND_HOST SECURITY_URL_PREFIX = "/security" SECURITY_PASSWORD_HASH = "pbkdf2_sha512" SECURITY_PASSWORD_SALT = "ioaefroijaAMELRK#$(aerieuh984akef#$graerj" SECURITY_EMAIL_SENDER = "pmgorg.noreply@gmail.com" SECURITY_TOKEN_AUTHENTICATION_HEADER = "Authentication-Token" SECURITY_POST_LOGIN_VIEW = "/admin" SECURITY_POST_LOGOUT_VIEW = "/admin" # Flask-Security features SECURITY_CONFIRMABLE = True SECURITY_LOGIN_WITHOUT_CONFIRMATION = True SECURITY_REGISTERABLE = True SECURITY_RECOVERABLE = True SECURITY_TRACKABLE = True SECURITY_CHANGEABLE = True # enable CSRF only for the frontend. The backend must have it disable so that Flask-Security can be used as an API import os WTF_CSRF_ENABLED = os.environ.get('PMG_LAYER') == 'frontend'
{"/fabfile.py": ["/fabdefs.py"], "/frontend/user_management.py": ["/frontend/__init__.py"]}
23,904
slavi104/frog_leap_puzzle_python
refs/heads/master
/tests.py
from hw1 import * # test next_step function if next_step([-1, -1, -1, 0, 1, 1, 1]) == [-1, 0, -1, -1, 1, 1, 1]: print('OK') else: print(next_step([-1, -1, -1, 0, 1, 1, 1])) # if next_step(generate_start_step(3)) == [-1, 0, -1, -1, 1, 1, 1]: print('OK') else: print(next_step(generate_start_step(3))) # if next_step([1, 1, 1, 0, -1, -1, -1]): print('OK') else: print(next_step([1, 1, 1, 0, -1, -1, -1])) # if next_step(generate_final_step(21)): print('OK') else: print(next_step(generate_final_step(21))) # if next_step(generate_start_step(3), [[-1, 0, -1, -1, 1, 1, 1]]) == [-1, -1, 0, -1, 1, 1, 1]: print('OK') else: print(next_step(generate_start_step(3))) # if next_step(generate_start_step(3), [[-1, 0, -1, -1, 1, 1, 1], [-1, -1, 0, -1, 1, 1, 1]]) == [-1, -1, -1, 1, 0, 1, 1]: print('OK') else: print(next_step(generate_start_step(3))) # if next_step(generate_start_step(3), [[-1, 0, -1, -1, 1, 1, 1], [-1, -1, 0, -1, 1, 1, 1], [-1, -1, -1, 1, 0, 1, 1]]) == [-1, -1, -1, 1, 1, 0, 1]: print('OK') else: print(next_step(generate_start_step(3))) # if next_step(generate_start_step(3), [[-1, 0, -1, -1, 1, 1, 1], [-1, -1, 0, -1, 1, 1, 1], [-1, -1, -1, 1, 0, 1, 1], [-1, -1, -1, 1, 1, 0, 1]]): print(next_step(generate_start_step(3))) else: print('OK') # if next_step([-1, 1, -1, 0, 1, -1, 1]) == [-1, 1, 0, -1 , 1, -1, 1]: print('OK') else: print(next_step([-1, 1, -1, 0 , 1, -1, 1])) # if next_step([-1, 1, 1, 0, -1, 1, -1]) == [-1, 1, 1, 1, -1, 0, -1]: print('OK') else: print(next_step([-1, 1, -1, 0 , 1, -1, 1])) # if next_step([-1, 1, -1, -1, 1, 1, 0]): print(next_step([-1, 1, -1, -1, 1, 1, 0])) else: print('OK') # if next_step([0, -1, -1, -1, 1, 1, 1]): print(next_step([0, -1, -1, -1, 1, 1, 1])) else: print('OK') # if next_step([-1, 1, -1, 1, -1, 1, 0]) == [-1, 1, -1, 1, 0, 1, -1]: print('OK') else: print(next_step([-1, 1, -1, 1, -1, 1, 0])) # if next_step([0, -1, 1, -1, -1, 1, 1]) == [1, -1, 0, -1, -1, 1, 1]: print('OK') else: print(next_step([0, -1, 1, -1, -1, 1, 1]))
{"/tests.py": ["/hw1.py"]}
23,905
slavi104/frog_leap_puzzle_python
refs/heads/master
/hw1_work2.py
# HW 1 #!python3 import threading from queue import Queue import time def generate_final_step(n): n = int(n) elements_number = (2*n)+1 final_step = [0] * elements_number for i in range(0, elements_number): if (i < n): final_step[i] = 1; elif (i == n): final_step[i] = 0; else: final_step[i] = -1; return final_step def generate_start_step(n): n = int(n) elements_number = (2*n)+1 final_step = [0] * elements_number for i in range(0, elements_number): if (i < n): final_step[i] = -1; elif (i == n): final_step[i] = 0; else: final_step[i] = 1; return final_step def next_step(current_step = [], wrong_paths = []): n = len(current_step) zero_position = current_step.index(0) next_zero_pos1 = zero_position - 2 next_zero_pos2 = zero_position - 1 next_zero_pos3 = zero_position + 1 next_zero_pos4 = zero_position + 2 current_step1 = current_step[:] current_step2 = current_step[:] current_step3 = current_step[:] current_step4 = current_step[:] if current_step in wrong_paths: return -1 if next_zero_pos1 >= 0 and current_step1[next_zero_pos1] == -1: current_step1[next_zero_pos1] = 0 current_step1[zero_position] = -1 if current_step1 not in wrong_paths: return current_step1 if next_zero_pos2 >= 0 and current_step2[next_zero_pos2] == -1: current_step2[next_zero_pos2] = 0 current_step2[zero_position] = -1 if current_step2 not in wrong_paths: return current_step2 # print(next_zero_pos3 , current_step3) if next_zero_pos3 < n and current_step3[next_zero_pos3] == 1: current_step3[next_zero_pos3] = 0 current_step3[zero_position] = 1 if current_step3 not in wrong_paths: return current_step3 if next_zero_pos4 < n and current_step4[next_zero_pos4] == 1: current_step4[next_zero_pos4] = 0 current_step4[zero_position] = 1 if current_step4 not in wrong_paths: return current_step4 if current_step == generate_final_step((n-1)/2): return True return False def path_finder(last_step = [], path = [], wrong_paths = []): next_step_path = next_step(last_step, wrong_paths) if type(next_step_path) is list: path.append(next_step_path) return path_finder(next_step_path, path, wrong_paths) elif next_step_path: return [True, path] else: # path.append(last_step) path.append(next_step_path) return [False, path] def find_solution(n = 2): first_step = generate_start_step(n) final_solution_list = [first_step] wrong_paths = [] while True: temp_solution = path_finder(first_step, [], wrong_paths) if temp_solution[0]: if temp_solution[0] == -1: temp_solution[1][0] wrong_paths.append(temp_solution[1][1]) print(temp_solution[1][1], wrong_paths) else: final_solution_list.extend(temp_solution[1]) break else: wrong_paths.extend(temp_solution[1]) return final_solution_list print(find_solution())
{"/tests.py": ["/hw1.py"]}
23,906
slavi104/frog_leap_puzzle_python
refs/heads/master
/hw1.py
# HW 1 #!python3 import sys, getopt CALCULATIONS = 0 def generate_final_step(n): n = int(n) elements_number = (2*n)+1 final_step = [0] * elements_number for i in range(0, elements_number): if (i < n): final_step[i] = 1; elif (i == n): final_step[i] = 0; else: final_step[i] = -1; return final_step def generate_start_step(n): n = int(n) elements_number = (2*n)+1 final_step = [0] * elements_number for i in range(0, elements_number): if (i < n): final_step[i] = -1; elif (i == n): final_step[i] = 0; else: final_step[i] = 1; return final_step def next_step(current_step = [], wrong_paths = []): n = len(current_step) zero_position = current_step.index(0) next_zero_pos1 = zero_position - 2 next_zero_pos2 = zero_position - 1 next_zero_pos3 = zero_position + 1 next_zero_pos4 = zero_position + 2 current_step1 = current_step[:] current_step2 = current_step[:] current_step3 = current_step[:] current_step4 = current_step[:] global CALCULATIONS CALCULATIONS+=1 if next_zero_pos1 >= 0 and current_step1[next_zero_pos1] == -1: current_step1[next_zero_pos1] = 0 current_step1[zero_position] = -1 if current_step1 not in wrong_paths: return current_step1 if next_zero_pos2 >= 0 and current_step2[next_zero_pos2] == -1: current_step2[next_zero_pos2] = 0 current_step2[zero_position] = -1 if current_step2 not in wrong_paths: return current_step2 # print(next_zero_pos3 , current_step3) if next_zero_pos3 < n and current_step3[next_zero_pos3] == 1: current_step3[next_zero_pos3] = 0 current_step3[zero_position] = 1 if current_step3 not in wrong_paths: return current_step3 if next_zero_pos4 < n and current_step4[next_zero_pos4] == 1: current_step4[next_zero_pos4] = 0 current_step4[zero_position] = 1 if current_step4 not in wrong_paths: return current_step4 if current_step == generate_final_step((n-1)/2): return True return False def path_finder(last_step = [], path = [], wrong_paths = []): next_step_path = next_step(last_step, wrong_paths) if type(next_step_path) is list: path.append(next_step_path) return path_finder(next_step_path, path, wrong_paths) elif next_step_path: return [True, path] else: return [False, path] def find_solution(n = 7): first_step = generate_start_step(n) final_solution_list = [first_step] wrong_paths = [] iters = 0 while True: temp_solution = path_finder(first_step, [], wrong_paths) if temp_solution[0]: if temp_solution[0] == 42: temp_solution[1][0] wrong_paths.append(temp_solution[1][1]) else: final_solution_list.extend(temp_solution[1]) break else: wrong_paths.append(temp_solution[1].pop()) return final_solution_list # print(find_solution()) if __name__ == "__main__": path = find_solution(sys.argv[1:][0]) for node in path: for index, item in enumerate(node): if item == -1: node[index] = '>' elif item == 1: node[index] = '<' else: node[index] = '_' print(' '.join(node)) print('You need to make', len(path), 'moves!') print('Computer makes', CALCULATIONS, 'checks until gets correct solution!')
{"/tests.py": ["/hw1.py"]}
23,926
NitayRe/Team-Yafo
refs/heads/master
/dice.py
import pygame import random as rnd class Dice: IMGS = [pygame.image.load("number1.png") ,pygame.image.load("number2.png") ,pygame.image.load("number3.png") ,pygame.image.load("number4.png") ,pygame.image.load("number5.png") ,pygame.image.load("number6.png")] def __init__(self, x, y): self.value = -1 self.x = x self.y = y def roll(self): self.value = rnd.randint(1, 6) def get_dice(self): return self.value def draw(self, screen): if self.value == -1: return dice = Dice.IMGS[self.value-1] screen.blit(dice, [self.x, self.y])
{"/logic.py": ["/pieces.py", "/dice.py", "/game.py"], "/game.py": ["/pieces.py", "/dice.py", "/logic.py"]}
23,927
NitayRe/Team-Yafo
refs/heads/master
/logic.py
import pieces import dice import pygame as pg from game import message_display, whichStack import time WHITE = pieces.Piece.WHITE BLACK = pieces.Piece.BLACK clock = pg.time.Clock() homeBlack = {x for x in range(6)} homeWhite = {x for x in range(23, 23-6, -1)} # assume islegal function was called before, and the move found as legal. def move(src, dest, stacks, removed): if (len(stacks[dest]) == 1) and (stacks[dest].getColor() != stacks[src].getColor()): pieceToRemove = stacks[dest].pop() if pieceToRemove.getColor() == WHITE: removed[0].push(pieceToRemove) else: removed[1].push(pieceToRemove) stacks[dest].push(stacks[src].pop()) def islegal(stacks, src, dest, possibleSteps, turn, removed): if hasOut(removed, turn): return False if stacks[src].isEmpty() or stacks[src].getColor() != turn: return False sign = 1 if turn == pieces.Piece.BLACK: sign = -1 if sign*(dest-src) not in possibleSteps or stacks[src].isEmpty(): return False emptyColomn = stacks[dest].isEmpty() if emptyColomn: return True sameColor = stacks[dest].getColor() == stacks[src].getColor() eatable = (not sameColor) and len(stacks[dest]) == 1 available = sameColor or eatable if not available: return False return True def isEndOfGame(stacks, color): home = homeWhite if color == BLACK: home = homeBlack for i in range(24): if i in home: continue if stacks[i].isEmpty(): continue if (stacks[i].getColor() == color): return False return True def hasOut(removed, color): if color == WHITE: return not removed[0].isEmpty() return not removed[1].isEmpty() def trySpecialMove(stacks, possibleSteps, removed, turn, index): removeIndex = 0 if turn == BLACK: removeIndex = 1 if hasOut(removed, turn): oppHome = homeBlack if turn == BLACK: oppHome = homeWhite step = min(index + 1, 24 - index) if index not in oppHome: return False if step in possibleSteps: if stacks[index].isEmpty() or stacks[index].getColor() == turn: stacks[index].push(removed[removeIndex].pop()) possibleSteps.remove(step) return True if len(stacks[index]) == 1: removed[1-removeIndex].push(stacks[index].pop()) stacks[index].push(removed[removeIndex].pop()) possibleSteps.remove(step) return True return False if isEndOfGame(stacks, turn) and (not stacks[index].isEmpty()) and stacks[index].getColor() == turn: step = min(index, 23 - index) for x in possibleSteps: if x >= step: stacks[index].pop() possibleSteps.remove(x) return True return False def getCoordinate(): while True: mousePressed = False for event in pg.event.get(): if event.type == pg.MOUSEBUTTONDOWN: if event.button == 1: mousePressed = True if event.type == pg.QUIT: exit(1) x = pg.mouse.get_pos()[0] y = pg.mouse.get_pos()[1] index = whichStack(x, y) if mousePressed: clock.tick(300) return index mousePressed = False clock.tick(30) def playOneTurn(stacks, dice1, dice2, turn, removed): possibleSteps = [dice1, dice2] if dice1 == dice2: possibleSteps *= 2 possibleSteps.sort() while len(possibleSteps) != 0: if not moveExists(stacks, turn, removed, possibleSteps): message_display("No valid Moves", 400,60) time.sleep(1) return print(possibleSteps) src = getCoordinate() played = trySpecialMove(stacks, possibleSteps, removed, turn, src) if played: yield 1 continue dest = getCoordinate() if islegal(stacks, src, dest, possibleSteps, turn, removed): move(src, dest,stacks, removed) possibleSteps.remove(abs(dest-src)) yield 1 def isAvailable(stacks, turn, index): return stacks[index].isEmpty() or stacks[index].getColor() == turn or len(stacks[index]) == 1 def moveExists(stacks, turn, removed, possibleSteps): if hasOut(removed, turn): for i in possibleSteps: if turn == WHITE: if isAvailable(stacks, turn, i-1): return True if turn == BLACK: if isAvailable(stacks, turn, 24-i): return True return False srcs = {i for i in range(24) if (not stacks[i].isEmpty()) and stacks[i].getColor() == turn} if len(srcs) == 0: return False if isEndOfGame(stacks, turn): maxDie = max(possibleSteps) if turn == WHITE: if max(srcs) + maxDie > 23: return True if turn == BLACK: if min(srcs) - maxDie < 0: return True for src in srcs: for dest in range(24): if islegal(stacks, src, dest,possibleSteps, turn, removed): return True return False def hasLeft(stacks, color): for stack in stacks: if (not stack.isEmpty()) and stack.getColor() == color: return True return False
{"/logic.py": ["/pieces.py", "/dice.py", "/game.py"], "/game.py": ["/pieces.py", "/dice.py", "/logic.py"]}
23,928
NitayRe/Team-Yafo
refs/heads/master
/pieces.py
import pygame as pg WIDTH = 800 HEIGHT = 600 class Piece: BLACK = 0,0,0 WHITE = 255,255,255 def __init__(self, color): self.color = color def getColor(self): return self.color def draw(self, screen, x, y): pg.draw.circle(screen, self.getColor(), (x + 45, y), 20) oppColor = 255-self.color[0], 255-self.color[1], 255-self.color[2] pg.draw.circle(screen, oppColor, (x + 45, y), 20, 2) class Stack: def __init__(self, x, y): self.items = [] self.x = x self.y = y def __len__(self): return len(self.items) def isEmpty(self): return len(self) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def getColor(self): return self.peek().getColor() def draw(self, screen): x = self.x y = self.y if y == 0: for piece in self.items: piece.draw(screen, x, y + 40) y += 40 if abs(y - self.y) > HEIGHT // 2 - 120: y = 5 x -= 5 else: for piece in self.items: piece.draw(screen, x, y - 40) y -= 40 if abs(y - self.y) > HEIGHT // 2 - 120: y = self.y - 5 x -= 5 class OutStack(Stack): def draw(self, screen): x = self.x y = self.y for piece in self.items: piece.draw(screen, x, y) x += 40
{"/logic.py": ["/pieces.py", "/dice.py", "/game.py"], "/game.py": ["/pieces.py", "/dice.py", "/logic.py"]}
23,929
NitayRe/Team-Yafo
refs/heads/master
/game.py
import pygame as pg from pieces import Stack, Piece, OutStack from dice import Dice import logic WIDTH = 800 HEIGHT = 600 DIFF_X=65 screen = pg.display.set_mode((WIDTH, HEIGHT)) background_image = pg.image.load("background.bmp") clock = pg.time.Clock() stacks = [] stackX = 0 stackY = 0 for _ in range(12): stacks.append(Stack(stackX, stackY)) stackX += DIFF_X stackX -= DIFF_X stackY = HEIGHT for _ in range(12): stacks.append(Stack(stackX, stackY)) stackX -= DIFF_X removedPieces = [] stackY = HEIGHT // 2 - 38 for _ in range(12): removedPieces.append(OutStack(WIDTH // 2 - 2*DIFF_X, stackY)) stackY += DIFF_X stacks += removedPieces def regularStart(): for i in range(2): stacks[0].push(Piece(Piece.WHITE)) for i in range(5): stacks[5].push(Piece(Piece.BLACK)) for i in range(3): stacks[7].push(Piece(Piece.BLACK)) for i in range(5): stacks[11].push(Piece(Piece.WHITE)) for i in range(5): stacks[12].push(Piece(Piece.BLACK)) for i in range(3): stacks[16].push(Piece(Piece.WHITE)) for i in range(5): stacks[18].push(Piece(Piece.WHITE)) for i in range(2): stacks[23].push(Piece(Piece.BLACK)) def chooseStartGamePlaces(): left_mouse_down = False right_mouse_down = False middle_mouse_down = False finished = False while not finished: for event in pg.event.get(): if event.type == pg.MOUSEBUTTONDOWN: if event.button == 1: left_mouse_down = True if event.button == 2: middle_mouse_down = True if event.button == 3: right_mouse_down = True if event.type == pg.QUIT: exit(1) x = pg.mouse.get_pos()[0] y = pg.mouse.get_pos()[1] index = whichStack(x, y) if left_mouse_down: if stacks[index].isEmpty() or stacks[index].getColor() == Piece.BLACK: stacks[index].push(Piece(Piece.BLACK)) if right_mouse_down: if stacks[index].isEmpty() or stacks[index].getColor() == Piece.WHITE: stacks[index].push(Piece(Piece.WHITE)) if middle_mouse_down and not stacks[index].isEmpty(): stacks[index].pop() if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE or event.key == pg.K_RETURN : finished = True left_mouse_down = False right_mouse_down = False middle_mouse_down = False screen.blit(background_image, [0, 0]) for s in stacks: s.draw(screen) message_display("press ESC or ENTER to start game", WIDTH//2, 300) pg.display.flip() clock.tick(30) def text_objects(text, font): black = (0, 0, 0) textSurface = font.render(text, True, black) return textSurface, textSurface.get_rect() def message_display(text, centerX, centerY): green = (0, 255, 0) blue = (0, 0, 128) font = pg.font.Font('freesansbold.ttf', 35) text = font.render(text, True, green, blue) textRect = text.get_rect() textRect.center = (centerX, centerY) screen.blit(text, textRect) pg.display.flip() def whichStack(x, y): if y < HEIGHT//2: return x // DIFF_X else: return 23 - x // DIFF_X size = 40 mid = HEIGHT // 2 - 22 dices = [] dices.append(Dice(0, mid - size // 2)) dices.append(Dice(0, mid + size // 2)) def main(): pg.font.init() message_display('for a regular game, press 1', WIDTH//2, 200) message_display('to choose the start situation, press 2', WIDTH//2, 400) chosen = False while not chosen: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_1: regularStart() chosen = True elif event.key == pg.K_2: chooseStartGamePlaces() chosen = True if event.type == pg.QUIT: exit(1) break clock.tick(30) turn = 0 turns = [Piece.WHITE, Piece.BLACK] while True: for event in pg.event.get(): if event.type == pg.QUIT: exit(1) for dice in dices: dice.roll() screen.blit(background_image, [0, 0]) for s in stacks: s.draw(screen) for dice in dices: dice.draw(screen) pg.display.flip() clock.tick(30) font = pg.font.Font('freesansbold.ttf', 20) text = "turn" if turn == 0: text = "White " + text else: text = "Black " + text text = font.render(text, False, Piece.BLACK) textRect = text.get_rect() textRect.center = (size + 50, mid + 10) screen.blit(text, textRect) pg.display.flip() for _ in logic.playOneTurn(stacks, dices[0].get_dice(), dices[1].get_dice(), turns[turn], removedPieces): screen.blit(background_image, [0, 0]) screen.blit(text, textRect) for s in stacks: s.draw(screen) for dice in dices: dice.draw(screen) pg.display.flip() clock.tick(30) if not logic.hasLeft(stacks, turns[turn]): if turn == 0: return "White" if turn == 1: return "Black" turn = 1 - turn if __name__ == '__main__': pg.init() message_display(main() + " has won", WIDTH//2, 300) message_display("To exit press ESC", WIDTH // 2, 500) done = False while not done: for event in pg.event.get(): if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: done = True if event.type == pg.QUIT: done = True clock.tick(30) pg.quit()
{"/logic.py": ["/pieces.py", "/dice.py", "/game.py"], "/game.py": ["/pieces.py", "/dice.py", "/logic.py"]}
23,930
tina-pivk/Minesweeper
refs/heads/master
/minesweeper2.py
import tkinter as tk import model2 BARVE = ['0', 'blue2', 'green2', 'red4', 'purple1', 'cyan3', 'DarkOrange1', 'state gray', 'DarkGoldenrod2'] def meni(): meni_vrstica = tk.Menu(okno) meni_seznam = tk.Menu(okno, tearoff=0) meni_seznam.add_command(label='lahko', command=lambda: nova_igra(8, 8, 10)) meni_seznam.add_command(label='srednje', command=lambda: nova_igra(16, 16, 40)) meni_seznam.add_command(label='težko', command=lambda: nova_igra(16, 31, 99)) meni_seznam.add_command(label='po želji', command=lambda: po_zelji()) meni_vrstica.add_cascade(label="zahtevnost", menu=meni_seznam) okno.config(menu=meni_vrstica) def nova_igra(visina=8, sirina=8, st_bomb=10): for x in okno.winfo_children(): if type(x) != tk.Menu: x.destroy() Minesweeper(okno, visina, sirina, st_bomb) def po_zelji(): okno2 = tk.Tk() okno2.title('Zahtevnost') def ok(vrstice, stolpci, bombe): nova_igra(vrstice, stolpci, bombe) okno2.destroy() v = tk.Entry(okno2) s = tk.Entry(okno2) b = tk.Entry(okno2) v.grid(row=1, column=2) s.grid(row=2, column=2) b.grid(row=3, column=2) v_l = tk.Label(okno2, text='vrstice').grid(row=1, column=1) s_l = tk.Label(okno2, text='stolpci').grid(row=2, column=1) b_l = tk.Label(okno2, text='bombe').grid(row=3, column=1) b1 = tk.Button(okno2, text="OK", width=10, command=lambda: ok(int(v.get()), int(s.get()), int(b.get()))) b1.grid(row=4, column=1, padx=10, pady=10) b2 = tk.Button(okno2, text="Cancel", width=10, command=lambda: okno2.destroy()) b2.grid(row=4, column=2, padx=10, pady=10) okno2.mainloop() class Minesweeper: def __init__(self, okno, visina=8, sirina=8, st_bomb=10): self.visina = visina self.sirina = sirina self.st_bomb = st_bomb self.plosca = model2.Plosca(self.visina, self.sirina, self.st_bomb) self.zacni_znova = tk.Button(okno, text='Minesweeper', command=lambda: nova_igra(), width=12) self.zacni_znova.grid(row=0, column=1) self.stevec_potez = tk.Label(okno, text='0', width=3) self.stevec_potez.grid(row=0, column=2) self.stevec_bomb = tk.Label(okno, text='{}'.format(self.plosca.st_bomb), width=3) self.stevec_bomb.grid(row=0, column=0) prikaz_plosce = tk.Frame(okno) self.gumbi = [] for vrstica in range(self.plosca.visina): vrstica_gumbov = [] for stolpec in range(self.plosca.sirina): def desni_klik(event, vrstica=vrstica, stolpec=stolpec): self.odkrij(vrstica, stolpec) def levi_klik(event, vrstica=vrstica, stolpec=stolpec): self.oznaci(vrstica, stolpec) gumb = tk.Button(prikaz_plosce, text='', height=1, width=2) gumb.grid(row=vrstica, column=stolpec) gumb.bind('<Button-1>', desni_klik) gumb.bind('<Button-3>', levi_klik) vrstica_gumbov.append(gumb) self.gumbi.append(vrstica_gumbov) prikaz_plosce.grid(row=1, column=0, columnspan=2) def odkrij(self, vrsta, stolp): stanje = self.plosca.odkrij_polje(vrsta, stolp) if stanje == model2.MEJNA: sos_bombe = self.plosca.polja[vrsta][stolp].sosednje_bombe self.gumbi[vrsta][stolp].config(text='{}'.format(sos_bombe), state='disabled', relief='groove', disabledforeground=BARVE[sos_bombe]) self.konec_igre_1() elif stanje == model2.PRAZNA: for vrstica in range(self.plosca.visina): for stolpec in range(self.plosca.sirina): if self.plosca.polja[vrstica][stolpec] in self.plosca.odkriti: if self.plosca.polja[vrstica][stolpec].sosednje_bombe == 0: self.gumbi[vrstica][stolpec].config(state='disabled', relief='groove') if self.plosca.polja[vrstica][stolpec].sosednje_bombe > 0: sos_bombe = self.plosca.polja[vrstica][stolpec].sosednje_bombe self.gumbi[vrstica][stolpec].config(text='{}'.format(sos_bombe), state='disabled', relief='groove', disabledforeground=BARVE[sos_bombe]) self.konec_igre_1() elif stanje == model2.ZADETA_BOMBA: self.gumbi[vrsta][stolp].config(state='disabled', relief='groove', bg='red') self.zacni_znova.config(text='BOOM!') self.konec_igre_3() self.stevec_potez.config(text=str(self.plosca.poteza)) def oznaci(self, vrsta, stolp): self.plosca.oznaci_bombo(vrsta, stolp) if self.plosca.polja[vrsta][stolp].oznacena == True: self.gumbi[vrsta][stolp].config(text='?') elif self.plosca.polja[vrsta][stolp].oznacena == False: self.gumbi[vrsta][stolp].config(text='') self.konec_igre_2() self.stevec_bomb.config(text=str(self.plosca.st_bomb - self.plosca.st_oznacenih)) def konec_igre_1(self): if (len(self.plosca.odkriti) + self.plosca.st_bomb) == (self.plosca.visina * self.plosca.sirina): self.zacni_znova.config(text='ZMAGA!') self.konec_igre_3() def konec_igre_2(self): if self.plosca.st_oznacenih == self.plosca.st_bomb: stevilo = 0 for bomba in self.plosca.bombe: if bomba in self.plosca.oznaceni: stevilo += 1 if stevilo == self.plosca.st_bomb: self.zacni_znova.config(text='ZMAGA!') self.konec_igre_3() def konec_igre_3(self): for vrstica in range(self.plosca.visina): for stolpec in range(self.plosca.sirina): if self.plosca.polja[vrstica][stolpec].sosednje_bombe == -1: if self.plosca.polja[vrstica][stolpec].oznacena == True: self.gumbi[vrstica][stolpec].config(text='¤', state='disabled', disabledforeground='violet red') else: self.gumbi[vrstica][stolpec].config(text='x', state='disabled', disabledforeground='red') elif self.plosca.polja[vrstica][stolpec] not in self.plosca.odkriti: self.gumbi[vrstica][stolpec].config(state='disabled', relief='flat') okno = tk.Tk() okno.title('Minesweeper') meni() Minesweeper(okno) okno.mainloop()
{"/minesweeper2.py": ["/model2.py"]}
23,931
tina-pivk/Minesweeper
refs/heads/master
/model2.py
from random import randint MEJNA = '#' PRAZNA = '0' ZADETA_BOMBA = 'B' NEVELJAVNA_POTEZA = '*' class Polje: def __init__(self, vrstica, stolpec): self.vrstica = vrstica self.stolpec = stolpec self.oznacena = False self.sosednje_bombe = 0 def __repr__(self): return 'Polje({0}, {1})'.format( self.vrstica, self.stolpec ) class Plosca: def __init__(self, visina=8, sirina=8, st_bomb=10): self.visina = visina self.sirina = sirina self.st_bomb = st_bomb self.polja = [] for vrstica in range(self.visina): vrstica_polj = [] for stolpec in range(self.sirina): Polje(vrstica, stolpec) vrstica_polj.append(Polje(vrstica, stolpec)) self.polja.append(vrstica_polj) self.bombe = [] self.odkriti = [] self.oznaceni =[] self.poteza = 0 self.st_oznacenih = 0 def __repr__(self): return 'Plosca(visina={}, sirina={}, bombe={})'.format( self.visina, self.sirina, self.bombe ) def postavi_bombe(self): for n in range(self.st_bomb): while True: x = randint(0, self.visina - 1) y = randint(0, self.sirina - 1) if self.polja[x][y] in self.odkriti: pass elif self.polja[x][y].sosednje_bombe == 0: self.polja[x][y].sosednje_bombe = -1 self.bombe.append(self.polja[x][y]) break def stevilo_sosednjih_bomb(self): sosedi = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for vrstica in range(self.visina): for stolpec in range(self.sirina): if self.polja[vrstica][stolpec].sosednje_bombe != -1: for (dx, dy) in sosedi: if 0 <= (vrstica + dx) < (self.visina) and 0 <= (stolpec + dy) < (self.sirina): if self.polja[vrstica + dx][stolpec + dy].sosednje_bombe == -1: self.polja[vrstica][stolpec].sosednje_bombe += 1 def odkrij_polje(self, vrstica, stolpec): if self.odkriti == []: self.odkriti.append(self.polja[vrstica][stolpec]) self.postavi_bombe() self.stevilo_sosednjih_bomb() self.poteza += 1 if self.polja[vrstica][stolpec].sosednje_bombe > 0: return MEJNA elif self.polja[vrstica][stolpec].sosednje_bombe == 0: self.odkrij_sosede(vrstica, stolpec) return PRAZNA elif (self.polja[vrstica][stolpec] in self.odkriti) or (self.polja[vrstica][stolpec] in self.oznaceni): return NEVELJAVNA_POTEZA else: self.poteza += 1 if self.polja[vrstica][stolpec].sosednje_bombe == -1: self.odkriti.append(self.polja[vrstica][stolpec]) return ZADETA_BOMBA elif self.polja[vrstica][stolpec].sosednje_bombe > 0: self.odkriti.append(self.polja[vrstica][stolpec]) return MEJNA elif self.polja[vrstica][stolpec].sosednje_bombe == 0: self.odkriti.append(self.polja[vrstica][stolpec]) self.odkrij_sosede(vrstica, stolpec) return PRAZNA def odkrij_sosede(self, vrstica, stolpec): sosedi = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] for (dx, dy) in sosedi: if 0 <= (vrstica + dx) < (self.visina) and 0 <= (stolpec + dy) < (self.sirina): if self.polja[vrstica + dx][stolpec + dy] not in self.odkriti: self.odkriti.append(self.polja[vrstica + dx][stolpec + dy]) if self.polja[vrstica + dx][stolpec + dy].sosednje_bombe == 0: self.odkrij_sosede(vrstica + dx, stolpec + dy) def oznaci_bombo(self, vrstica, stolpec): if self.polja[vrstica][stolpec] in self.odkriti: pass elif self.polja[vrstica][stolpec].oznacena == False: self.polja[vrstica][stolpec].oznacena = True self.oznaceni.append(self.polja[vrstica][stolpec]) self.st_oznacenih += 1 else: self.polja[vrstica][stolpec].oznacena = False self.oznaceni.remove(self.polja[vrstica][stolpec]) self.st_oznacenih -=1
{"/minesweeper2.py": ["/model2.py"]}
23,938
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/Nodo.py
class Nodo(): def __init__(self,nombre,fila,columna,f,c): self.fila = fila self.columna = columna self.nombre = nombre self.f = f self.c = c
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,939
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/celda.py
class Celda(): def __init__(self,a,b,d): self.fila = a self.columna = b self.valor = d def getFila(self): return self.fila def getColumna(self): return self.columna def getValor(self): return self.valor
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,940
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/NodoMatriz.py
class NodoMatriz(): def __init__(self,dato,fila,columna): self.dato = dato self.fila = fila self.columna = columna self.siguiente = None self.atras = None self.arriba = None self.abajo = None def getDato(self): return self.dato
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,941
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/main.py
from tkinter import Tk,Button,Label,Entry from tkinter import ttk import copy import webbrowser import time import subprocess from tkinter.colorchooser import askcolor from tkinter.filedialog import askopenfilename from tkinter.filedialog import askdirectory import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element, SubElement, tostring from xml.dom import minidom import xml.dom.minidom from xml.etree import ElementTree from graphviz import Digraph import os from ListaDoble import ListaDoble from Matriz import Matriz from tkinter import messagebox from NodoLista import NodoLista archivo_Seleccionado = False salida = False log = [] listaImagenes = ListaDoble() procesar = False x1 = 0 y1 = 0 x2 = 0 y2 = 0 elementos = 0 filas = 0 columnas = 0 def reporte(): mensaje = """<!doctype html> <html> <head> <title>REPORTE</title> <link href="CSS\pa.css" rel="stylesheet" type="text/css"> </head> <body> <div class="container"> <header> <a href=""> <h6 class="logo">REPORTE</h6> </a> </header> <section class="hero" id="hero"> <h3 class="hero_header">REPORTE</h3> </section> <section class="banner"> """ i = 1 tamaño = 20 for lo in log: mensaje = mensaje + """ <h4><font color = "white">"""+lo+"""</font></h4>""" i = i + 1 tamaño = tamaño + 38 mens =""" <div class="copyright">&copy;2020- <strong>Edwin estuardo reyes reyes</strong></div> </div> </body> </html>""" mensaje = mensaje + mens css = """@charset "UTF-8"; /* Body */ html { font-size: 30px; } body { font-family: source-sans-pro; background-color: #f2f2f2; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; font-style: normal; font-weight: 200; } .container { width: 70%; margin-left: auto; margin-right: auto; height: 700px; } header { width: 100%; height: 8%; background-color: #52bad5; border-bottom: 1px solid #2C9AB7; } .logo { color: #fff; font-weight: bold; text-align: undefined; width: 10%; float: left; margin-top: 15px; margin-left: 25px; letter-spacing: 4px; } .hero_header { color: #FFFFFF; text-align: center; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; letter-spacing: 4px; } .hero { background-color: #B3B3B3; padding-top: 100px; padding-bottom: 80px; } .light { font-weight: bold; color: #717070; } .tagline { text-align: center; color: #FFFFFF; margin-top: 4px; font-weight: lighter; text-transform: uppercase; letter-spacing: 1px; } .banner { background-color: #2D9AB7; background-image: url(../images/parallax.png); +height:"""+str(tamaño)+"""px; background-attachment: fixed; background-size: cover; background-repeat: no-repeat; } .parallaxx { color: #FFFFFF; text-align: left; padding-left: 200px; padding-right: 100px; padding-top: 50px; letter-spacing: 2px; margin-top: 0px; margin-bottom: 0px } .parallax { color: #FFFFFF; text-align: left; padding-left: 200px; padding-right: 100px; padding-top: 10px; letter-spacing: 2px; margin-top: 0px; margin-bottom: 0px } .paralla { color: #ffffff5e; text-align: left; padding-left: 200px; padding-right: 100px; padding-top: 10px; letter-spacing: 2px; margin-top: 0px; margin-bottom: 0px } .copyright { text-align: center; padding-top: 20px; padding-bottom: 20px; background-color: #717070; color: #ffffff; text-transform: uppercase; font-weight: lighter; letter-spacing: 2px; border-top-width: 2px; } """ if os.path.exists("CSS") == False : os.makedirs("CSS") g = open("CSS\pa.css",'wb') g.write(bytes(css,"ascii")) g.close() f = open('Reporte.html','wb') f.write(bytes(mensaje,"ascii")) f.close() webbrowser.open_new_tab('Reporte.html') def carga(): root = Tk() root.withdraw() root.wm_attributes("-topmost", 1) archivo = askopenfilename(filetypes =(("Archivo TXT", "*.xml"),("Todos Los Archivos","*.*")),title = "Busque su archivo.") root.update() root.destroy() xmldoc = xml.dom.minidom.parse(archivo) for n in xmldoc.getElementsByTagName("matriz"): for name in n.getElementsByTagName("nombre"): nombre = name.firstChild.data print(nombre) for fi in n.getElementsByTagName("filas"): fila = fi.firstChild.data for co in n.getElementsByTagName("columnas"): columna = co.firstChild.data for img in n.getElementsByTagName("imagen"): imagen = img.firstChild.data x = 0 fi = 1 state = 0 colu = 1 matriz = Matriz(nombre,fila,columna) llena = 0 vacia = 0 while x < len(imagen): actual = imagen[x] if state == 0: if ord(actual) == 10 : x = x + 1 elif ord(actual) == 45 or ord(actual) == 42: state = 1 else: x = x + 1 ####################################################################################################### elif state == 1: if ord(actual) == 45: # guion x = x + 1 if fi>int(fila) or colu>int(columna): print("Error Matriz mayor que establecida") else: matriz.Agregar(fi,colu,'-') vacia = vacia + 1 elif ord(actual) == 42: # asterisco x = x + 1 if fi>int(fila) or colu>int(columna): print("Error Matriz mayor que establecida") else: matriz.Agregar(fi,colu,'*') llena = llena + 1 else: fi = fi + 1 state = 0 colu = 0 colu = colu + 1 Nodo = NodoLista(matriz,nombre,fila,columna) listaImagenes.Agregar(Nodo) texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ nombre+" - Espacio lleno: "+str(llena)+" - Espacio vacio: "+str(vacia) log.append(texto) print("Se agrego Imagen: "+nombre) def ventanaEmergente(texto): messagebox.showinfo(message=texto, title="Avisos") def close_window(objeto): objeto.destroy() def operaciones(): if listaImagenes.primero == None : ventanaEmergente("Porfavor Seleccione Carga Primero") else: tamaño = 17 windows = Tk() windows['bg'] = '#B3B3B3' windows.title("Operaciones Validas") ancho_ventana = 700 alto_ventana = 400 x_ventana = raiz.winfo_screenwidth() // 2 - ancho_ventana // 2 y_ventana = raiz.winfo_screenheight() // 2 - alto_ventana // 2 posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(x_ventana) + "+" + str(y_ventana) windows.geometry(posicion) Lb1 = Label(windows,text="Imagenes Existentes: ",bg="#B3B3B3",font=("Lucida Console",15)) Lb1.place(x=60,y=30) combo = ttk.Combobox(windows,font=("Lucida Console",13)) combo.place(x=320,y=30) opciones = ['Seleccione Imagen'] aux = listaImagenes.primero while aux != None: opciones.append(aux.nombre) aux = aux.siguiente combo['values']=opciones combo.current(0) windows.iconbitmap("codificacion.ico") button = Button(windows, text="ver",command = lambda: verImagen(combo),bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",15)) button.place(x=560,y=20) combo1 = ttk.Combobox(windows,font=("Lucida Console",13)) combo1.place(x=50,y=170) opc = ['Seleccione Opcion','1. Rotacion Horizontal','2. Rotacion Vertical','3. Transpuesta','4. Limpiar Zona','5. Agregar Linea Horizontal','6. Agregar Linea Vertical','7. Agregar Rectangulo','8. Agregar Triangulo Rectangular'] combo1['values']=opc combo1.current(0) i = Label(windows,text="Operaciones con 1 Imagen",bg="#B3B3B3",font=("Lucida Console",15)) i.place(x=20,y=100) combo2 = ttk.Combobox(windows,font=("Lucida Console",13)) combo2.place(x=50,y=220) opcione = ['Seleccione Imagen'] aux = listaImagenes.primero while aux != None: opcione.append(aux.nombre) aux = aux.siguiente combo2['values']=opcione combo2.current(0) ii = Label(windows,text="Operaciones con 2 Imagenes",bg="#B3B3B3",font=("Lucida Console",15)) ii.place(x=350,y=100) b1 = Button(windows,text="Calcular",command = lambda: operacion1(combo1,combo2,windows),bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",15)) b1.place(x=100,y=280) combo5 = ttk.Combobox(windows,font=("Lucida Console",13)) combo5.place(x=440,y=170) opc = ['Seleccione 1. Imagen'] aux = listaImagenes.primero while aux != None: opc.append(aux.nombre) aux = aux.siguiente combo5['values']=opc combo5.current(0) combo6 = ttk.Combobox(windows,font=("Lucida Console",13)) combo6.place(x=440,y=220) opcione = ['Seleccione 2. Imagen'] aux = listaImagenes.primero while aux != None: opcione.append(aux.nombre) aux = aux.siguiente combo6['values']=opcione combo6.current(0) combo7 = ttk.Combobox(windows,font=("Lucida Console",13)) combo7.place(x=440,y=270) opcione = ['Seleccione Opcion','1. Union','2. Interseccion','3. Diferencia','4. Diferencia Simetrica'] aux = listaImagenes.primero combo7['values']=opcione combo7.current(0) b1 = Button(windows,text="Calcular",command = lambda: operacion2(combo5,combo6,combo7,windows),bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",15)) b1.place(x=480,y=320) windows.mainloop() def operacion2(combo1,combo2,combo3,ventana): img1 = combo1.get() img2 = combo2.get() opcion = combo3.get() if img1 == 'Seleccione 1. Imagen': ventanaEmergente("Porfavor Seleccione primera imagen Valida") elif img2 == 'Seleccione 2. Imagen': ventanaEmergente("Porfavor Seleccione segunda imagen Valida") elif opcion == 'Seleccione Opcion': ventanaEmergente("Porfavor Seleccione Opcion Primero") else: ima1 = listaImagenes.BuscarMatriz(img1) # Nodo que cuenta con la matriz de aqui tengo que remplazar ima2 = listaImagenes.BuscarMatriz(img2) if opcion == '1. Union': newMatriz = Matriz("g",100,100) aux1 = ima1.matriz.primero.fila.primero.Nodo aux2 = ima2.matriz.primero.fila.primero.Nodo c = 1 f = 1 texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Union - Matrices Usadas: "+ima1.matriz.primero.nombre+" y "+ ima2.matriz.primero.nombre log.append(texto) while aux1 != None or aux2 != None: fila1 = aux1 fila2 = aux2 while fila1 != None or fila2 != None: if fila1 != None or fila2 != None: if fila1 != None and fila1.dato == '*': newMatriz.Agregar(f,c,'*') elif fila2 != None and fila2.dato == '*': newMatriz.Agregar(f,c,'*') else: newMatriz.Agregar(f,c,'-') if fila1 != None: fila1 = fila1.siguiente if fila2 != None: fila2 = fila2.siguiente c = c + 1 if aux1 != None: aux1 = aux1.abajo if aux2 != None: aux2 = aux2.abajo c = 1 f = f + 1 elif opcion == '2. Interseccion': newMatriz = Matriz("g",100,100) aux1 = ima1.matriz.primero.fila.primero.Nodo aux2 = ima2.matriz.primero.fila.primero.Nodo texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Interseccion - Matrices Usadas: "+ima1.matriz.primero.nombre+" y "+ ima2.matriz.primero.nombre log.append(texto) c = 1 f = 1 while aux1 != None or aux2 != None: fila1 = aux1 fila2 = aux2 while fila1 != None or fila2 != None: if fila1 != None or fila2 != None: if fila1 != None and fila1.dato == '*': if fila2 != None and fila2.dato == '*': newMatriz.Agregar(f,c,'*') else: newMatriz.Agregar(f,c,'-') else: newMatriz.Agregar(f,c,'-') if fila1 != None: fila1 = fila1.siguiente if fila2 != None: fila2 = fila2.siguiente c = c + 1 if aux1 != None: aux1 = aux1.abajo if aux2 != None: aux2 = aux2.abajo c = 1 f = f + 1 elif opcion == '3. Diferencia': newMatriz = Matriz("g",100,100) aux1 = ima1.matriz.primero.fila.primero.Nodo aux2 = ima2.matriz.primero.fila.primero.Nodo c = 1 f = 1 texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Diferencia - Matrices Usadas: "+ima1.matriz.primero.nombre+" y "+ ima2.matriz.primero.nombre log.append(texto) while aux1 != None or aux2 != None: fila1 = aux1 fila2 = aux2 while fila1 != None or fila2 != None: if fila1 != None or fila2 != None: if fila1 != None and fila1.dato == '*': if fila2 != None and fila2.dato == '-': newMatriz.Agregar(f,c,'*') elif fila2 == None: newMatriz.Agregar(f,c,'*') else: newMatriz.Agregar(f,c,'-') else: newMatriz.Agregar(f,c,'-') if fila1 != None: fila1 = fila1.siguiente if fila2 != None: fila2 = fila2.siguiente c = c + 1 if aux1 != None: aux1 = aux1.abajo if aux2 != None: aux2 = aux2.abajo c = 1 f = f + 1 elif opcion == '4. Diferencia Simetrica': newMatriz = Matriz("g",100,100) aux1 = ima1.matriz.primero.fila.primero.Nodo aux2 = ima2.matriz.primero.fila.primero.Nodo c = 1 f = 1 texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Diferencia Simetrica - Matrices Usadas: "+ima1.matriz.primero.nombre+" y "+ ima2.matriz.primero.nombre log.append(texto) while aux1 != None or aux2 != None: fila1 = aux1 fila2 = aux2 while fila1 != None or fila2 != None: if fila1 != None or fila2 != None: if fila1 != None and fila1.dato == '*': if fila2 != None and fila2.dato == '-': newMatriz.Agregar(f,c,'*') elif fila2 == None: newMatriz.Agregar(f,c,'*') else: newMatriz.Agregar(f,c,'-') elif fila2 != None and fila2.dato == '*': if fila1 != None and fila1.dato == '-': newMatriz.Agregar(f,c,'*') elif fila1 == None: newMatriz.Agregar(f,c,'*') else: newMatriz.Agregar(f,c,'-') else: newMatriz.Agregar(f,c,'-') if fila1 != None: fila1 = fila1.siguiente if fila2 != None: fila2 = fila2.siguiente c = c + 1 if aux1 != None: aux1 = aux1.abajo if aux2 != None: aux2 = aux2.abajo c = 1 f = f + 1 newMatriz.primero.f = f newMatriz.primero.c = c vent = Tk() vent.title("Ingreso de Datos") ancho = 460 alto = 270 x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) vent.geometry(posicion) lb = ttk.Label(vent,text="Operacion Realizada Exitosamente!",font=("Lucida Console",14)) lb.place(x=33,y=10) lb1 = ttk.Label(vent,text="Agregar Matriz : Ingrese nombre",font=("Lucida Console",10)) lb1.place(x=10,y=60) entry1 = ttk.Entry(vent) entry1.place(x=275,y=60) b1 = ttk.Button(vent,text="Agregar Matriz",command = lambda: agregar(ventana,vent,entry1.get(),newMatriz,f,c,ima1.matriz,ima2.matriz)) b1.place(x=165,y=105) lb1 = ttk.Label(vent,text="Sustituir Matriz : Escoja Nombre",font=("Lucida Console",10)) lb1.place(x=10,y=160) combo6 = ttk.Combobox(vent,font=("Lucida Console",13)) combo6.place(x=290,y=160) opcione = ['Seleccione Imagen'] aux = listaImagenes.primero while aux != None: opcione.append(aux.nombre) aux = aux.siguiente combo6['values']=opcione combo6.current(0) b2 = ttk.Button(vent,text="Sustituir Matriz",command = lambda: sustituir(ventana,vent,newMatriz,f,c,combo6.get(),ima1.matriz,ima2.matriz)) b2.place(x=165,y=205) vent.mainloop() def sustituir(ventana,vent,matriz,f,c,nombre,im1,im2): matri = listaImagenes.BuscarMatriz(nombre) matri.matriz = matriz resultante = matriz.Pintando() imagen1 = im1.Pintando() imagen2 = im2.Pintando() tamaño = 25 tamaño1 = 25 tamaño2 = 25 anchoResultante = 0.83*float(tamaño)*float(matriz.primero.c) altoResultante = 1.36*float(tamaño)*float(matriz.primero.f) if altoResultante >= 400 or anchoResultante >= 200: while altoResultante>= 380 and anchoResultante >= 200 : tamaño1 = tamaño1-0.3 altoResultante = 1.36*float(tamaño)*float(matriz.primero.f) anchoResultante = 0.83*float(tamaño)*float(matriz.primero.c) anchoIma1 = 0.83*float(tamaño1)*float(im1.primero.c) altoIma1 = 1.36*float(tamaño1)*float(im1.primero.f) if altoIma1 >= 400 or anchoIma1 >= 200: while altoIma1>= 380 and anchoIma1 >= 200 : tamaño1 = tamaño1-0.3 altoIma1 = 1.36*float(tamaño1)*float(im1.primero.f) anchoIma1 = 0.83*float(tamaño1)*float(im1.primero.c) anchoIma2 = 0.83*float(tamaño2)*float(im2.primero.c) altoIma2 = 1.36*float(tamaño2)*float(im2.primero.f) if altoIma2 >= 400 or anchoIma2 >= 200: while altoIma2>= 380 and anchoIma2 >= 200 : tamaño2 = tamaño2-0.3 altoIma2 = 1.36*float(tamaño2)*float(im2.primero.f) anchoIma2 = 0.83*float(tamaño2)*float(im2.primero.c) px = (210-anchoIma1)/2+5 im1 = Label(raiz,text=imagen1,font=("Lucida Console",int(tamaño1))) im1.place(x=px,y=90) im3 = Label(raiz,text="1ra. Imagen",font=("Lucida Console",10)) im3.place(x=px+40,y=90+altoIma1) px1 = ((210-anchoIma2)/2)+220 im2 = Label(raiz,text=imagen2,font=("Lucida Console",int(tamaño2))) im2.place(x=px1,y=90) im4 = Label(raiz,text="2da. Imagen",font=("Lucida Console",10)) im4.place(x=px1+40,y=90+altoIma2) px2 = ((210-anchoResultante)/2)+350 im2 = Label(raiz,text=resultante,font=("Lucida Console",int(tamaño))) im2.place(x=px2,y=90) im4 = Label(raiz,text="Resultado",font=("Lucida Console",10)) im4.place(x=px2+50,y=40+altoResultante) ventana.destroy() vent.destroy() def agregar(ventana,vent,c1,matriz,f,c,im1,im2): Nodo = NodoLista(matriz,c1,f,c) listaImagenes.Agregar(Nodo) resultante = matriz.Pintando() imagen1 = im1.Pintando() imagen2 = im2.Pintando() tamaño = 25 tamaño1 = 25 tamaño2 = 25 anchoResultante = 0.83*float(tamaño)*float(matriz.primero.c) altoResultante = 1.36*float(tamaño)*float(matriz.primero.f) if altoResultante >= 400 or anchoResultante >= 200: while altoResultante>= 380 and anchoResultante >= 200 : tamaño1 = tamaño1-0.3 altoResultante = 1.36*float(tamaño)*float(matriz.primero.f) anchoResultante = 0.83*float(tamaño)*float(matriz.primero.c) anchoIma1 = 0.83*float(tamaño1)*float(im1.primero.c) altoIma1 = 1.36*float(tamaño1)*float(im1.primero.f) if altoIma1 >= 400 or anchoIma1 >= 200: while altoIma1>= 380 and anchoIma1 >= 200 : tamaño1 = tamaño1-0.3 altoIma1 = 1.36*float(tamaño1)*float(im1.primero.f) anchoIma1 = 0.83*float(tamaño1)*float(im1.primero.c) anchoIma2 = 0.83*float(tamaño2)*float(im2.primero.c) altoIma2 = 1.36*float(tamaño2)*float(im2.primero.f) if altoIma2 >= 400 or anchoIma2 >= 200: while altoIma2>= 380 and anchoIma2 >= 200 : tamaño2 = tamaño2-0.3 altoIma2 = 1.36*float(tamaño2)*float(im2.primero.f) anchoIma2 = 0.83*float(tamaño2)*float(im2.primero.c) px = (210-anchoIma1)/2+5 im1 = Label(raiz,text=imagen1,font=("Lucida Console",int(tamaño1))) im1.place(x=px,y=90) im3 = Label(raiz,text="1ra. Imagen",font=("Lucida Console",10)) im3.place(x=px+30,y=90+altoIma1) px1 = ((210-anchoIma2)/2)+220 im2 = Label(raiz,text=imagen2,font=("Lucida Console",int(tamaño2))) im2.place(x=px1,y=90) im4 = Label(raiz,text="2da. Imagen",font=("Lucida Console",10)) im4.place(x=px1+15,y=90+altoIma2) px2 = ((210-anchoResultante)/2)+350 im2 = Label(raiz,text=resultante,font=("Lucida Console",int(tamaño))) im2.place(x=px2,y=90) im4 = Label(raiz,text="Resultado",font=("Lucida Console",10)) im4.place(x=px2+15,y=100+altoResultante) ventana.destroy() vent.destroy() def operacion1(combo1,combo2,ventana): global x1,x2,y1,y2,filas,columnas,elementos cb = combo1.get() cb2 = combo2.get() if cb == 'Seleccione Opcion': ventanaEmergente("Porfavor Seleccione una Opcion Valida") elif cb2 == 'Seleccione Imagen': ventanaEmergente("Porfavor Seleccione una Imagen Valida") else: tamaño = 25 aux = listaImagenes.BuscarMatriz(cb2) # Nodo que cuenta con la matriz de aqui tengo que remplazar matriz = aux.matriz if cb == '1. Rotacion Horizontal': newMatriz = Matriz(matriz.primero.nombre,matriz.primero.f,matriz.primero.c) fila = matriz.primero.f auxiliar = matriz.primero.fila.Buscar(int(fila)) aux1 = auxiliar.Nodo fi = 1 while aux1 != None: aux2 = aux1 co = 1 while aux2 != None: newMatriz.Agregar(fi,co,aux2.dato) aux2 = aux2.siguiente co = co + 1 aux1 = aux1.arriba fi = fi + 1 aux.matriz = newMatriz t1 = matriz.Pintando() t2 = newMatriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño)),bg = "#B3B3B3") im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",13),bg = "#2D9AB7",fg = "#FFFFFF") im3.place(x=px+25,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño)),bg = "#2D9AB7",fg = "#FFFFFF") im2.place(x=px1,y=90) im4 = Label(raiz,text="Rotacion Horizontal",font=("Lucida Console",13),bg = "#2D9AB7",fg = "#FFFFFF") im4.place(x=px+360,y=90+alto) texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Rotacion Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventana.destroy() elif cb == '2. Rotacion Vertical': newMatriz = Matriz(matriz.primero.nombre,matriz.primero.f,matriz.primero.c) auxiliar = matriz.primero.fila.Buscar(1) aux1 = auxiliar.Nodo fi = 1 while aux1 != None: auxili = aux1 aux1 = aux1.siguiente while auxili != None: aux2 = auxili co = 1 while aux2 != None: newMatriz.Agregar(fi,co,aux2.dato) aux2 = aux2.atras co = co + 1 auxili = auxili.abajo fi = fi + 1 aux.matriz = newMatriz t1 = matriz.Pintando() t2 = newMatriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Rotacion Verticalmente",font=("Lucida Console",10)) im4.place(x=px+350,y=90+alto) texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Rotacion Vertical - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventana.destroy() elif cb == '3. Transpuesta': newMatriz = Matriz(matriz.primero.nombre,matriz.primero.f,matriz.primero.c) fila = matriz.primero.f auxiliar = matriz.primero.fila.Buscar(1) aux1 = auxiliar.Nodo fi = 1 while aux1 != None: aux2 = aux1 co = 1 while aux2 != None: newMatriz.Agregar(fi,co,aux2.dato) aux2 = aux2.abajo co = co + 1 aux1 = aux1.siguiente fi = fi + 1 aux.matriz = newMatriz t1 = matriz.Pintando() t2 = newMatriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Transpuesta",font=("Lucida Console",10)) im4.place(x=px+390,y=90+alto) texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Transpuesta - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventana.destroy() elif cb == '4. Limpiar Zona': vent = Tk() vent.title("Ingreso de Datos") ancho = 360 alto = 260 x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) vent.geometry(posicion) lb = ttk.Label(vent,text="Ingrese los siguientes datos",font=("Lucida Console",14)) lb.place(x=23,y=10) lb1 = ttk.Label(vent,text="Ingrese F:1 =",font=("Lucida Console",11)) lb1.place(x=90,y=60) entry1 = ttk.Entry(vent,width=5) entry1.place(x=220,y=60) lb1 = ttk.Label(vent,text="Ingrese C:1 =",font=("Lucida Console",11)) lb1.place(x=90,y=90) entry2 = ttk.Entry(vent,width=5) entry2.place(x=220,y=90) lb1 = ttk.Label(vent,text="Ingrese F:2 =",font=("Lucida Console",11)) lb1.place(x=90,y=120) entry3 = ttk.Entry(vent,width=5) entry3.place(x=220,y=120) lb1 = ttk.Label(vent,text="Ingrese C:2 =",font=("Lucida Console",11)) lb1.place(x=90,y=150) entry4 = ttk.Entry(vent,width=5) entry4.place(x=220,y=150) bo = ttk.Button(vent,text="Aceptar",command = lambda: guardar(ventana,vent,entry1.get(),entry2.get(),entry3.get(),entry4.get(),matriz.primero.f,matriz.primero.c,matriz)) bo.place(x=140,y=200) elif cb == '5. Agregar Linea Horizontal': vent = Tk() vent.title("Ingreso de Datos") ancho = 360 alto = 260 x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) vent.geometry(posicion) lb = ttk.Label(vent,text="Ingrese los siguientes datos",font=("Lucida Console",14)) lb.place(x=23,y=10) lb1 = ttk.Label(vent,text="Ingrese F =",font=("Lucida Console",11)) lb1.place(x=90,y=60) entry1 = ttk.Entry(vent,width=5) entry1.place(x=220,y=60) lb1 = ttk.Label(vent,text="Ingrese C =",font=("Lucida Console",11)) lb1.place(x=90,y=90) entry2 = ttk.Entry(vent,width=5) entry2.place(x=220,y=90) lb1 = ttk.Label(vent,text="Ingrese Cantidad de Elementos =",font=("Lucida Console",11)) lb1.place(x=90,y=120) entry3 = ttk.Entry(vent,width=5) entry3.place(x=220,y=120) bo = ttk.Button(vent,text="Aceptar",command = lambda: agregarH(ventana,vent,entry1.get(),entry2.get(),entry3.get(),matriz.primero.f,matriz.primero.c,matriz)) bo.place(x=140,y=200) elif cb == '6. Agregar Linea Vertical': vent = Tk() vent.title("Ingreso de Datos") ancho = 360 alto = 260 x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) vent.geometry(posicion) lb = ttk.Label(vent,text="Ingrese los siguientes datos",font=("Lucida Console",14)) lb.place(x=23,y=10) lb1 = ttk.Label(vent,text="Ingrese F =",font=("Lucida Console",11)) lb1.place(x=90,y=60) entry1 = ttk.Entry(vent,width=5) entry1.place(x=220,y=60) lb1 = ttk.Label(vent,text="Ingrese C =",font=("Lucida Console",11)) lb1.place(x=90,y=90) entry2 = ttk.Entry(vent,width=5) entry2.place(x=220,y=90) lb1 = ttk.Label(vent,text="Ingrese Cantidad de Elementos =",font=("Lucida Console",11)) lb1.place(x=90,y=120) entry3 = ttk.Entry(vent,width=5) entry3.place(x=220,y=120) bo = ttk.Button(vent,text="Aceptar",command = lambda: agregarV(ventana,vent,entry1.get(),entry2.get(),entry3.get(),matriz.primero.f,matriz.primero.c,matriz)) bo.place(x=140,y=200) elif cb == '7. Agregar Rectangulo': vent = Tk() vent.title("Ingreso de Datos") ancho = 360 alto = 260 x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) vent.geometry(posicion) lb = ttk.Label(vent,text="Ingrese los siguientes datos",font=("Lucida Console",14)) lb.place(x=23,y=10) lb1 = ttk.Label(vent,text="Ingrese F:1 =",font=("Lucida Console",11)) lb1.place(x=90,y=60) entry1 = ttk.Entry(vent,width=5) entry1.place(x=220,y=60) lb1 = ttk.Label(vent,text="Ingrese C:1 =",font=("Lucida Console",11)) lb1.place(x=90,y=90) entry2 = ttk.Entry(vent,width=5) entry2.place(x=220,y=90) lb1 = ttk.Label(vent,text="Ingrese F:2 =",font=("Lucida Console",11)) lb1.place(x=90,y=120) entry3 = ttk.Entry(vent,width=5) entry3.place(x=220,y=120) lb1 = ttk.Label(vent,text="Ingrese C:2 =",font=("Lucida Console",11)) lb1.place(x=90,y=150) entry4 = ttk.Entry(vent,width=5) entry4.place(x=220,y=150) bo = ttk.Button(vent,text="Aceptar",command = lambda: guardarA(ventana,vent,entry1.get(),entry2.get(),entry3.get(),entry4.get(),matriz.primero.f,matriz.primero.c,matriz)) bo.place(x=140,y=200) elif cb == '8. Agregar Triangulo Rectangular': vent = Tk() vent.title("Ingreso de Datos") ancho = 360 alto = 260 x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) vent.geometry(posicion) lb = ttk.Label(vent,text="Ingrese los siguientes datos",font=("Lucida Console",14)) lb.place(x=23,y=10) lb1 = ttk.Label(vent,text="Ingrese F =",font=("Lucida Console",11)) lb1.place(x=90,y=60) entry1 = ttk.Entry(vent,width=5) entry1.place(x=220,y=60) lb1 = ttk.Label(vent,text="Ingrese C =",font=("Lucida Console",11)) lb1.place(x=90,y=90) entry2 = ttk.Entry(vent,width=5) entry2.place(x=220,y=90) lb1 = ttk.Label(vent,text="Ingrese Cantidad de Elementos =",font=("Lucida Console",11)) lb1.place(x=90,y=120) entry3 = ttk.Entry(vent,width=5) entry3.place(x=220,y=120) bo = ttk.Button(vent,text="Aceptar",command = lambda: guardarv(ventana,vent,entry1.get(),entry2.get(),entry3.get(),matriz.primero.f,matriz.primero.c,matriz)) bo.place(x=140,y=200) def guardarv(ventana,windows,s1,s2,d1,f,c,matriz): global x1,x2,y1,y2,filas,columnas,elementos auxiliar = copy.deepcopy(matriz) if s1.isdigit() and s2.isdigit() and d1.isdigit(): if int(s1) <= int(c) and int(s1) >= 1 : if int(s2) <= int(f) and int(s2) >= 1 : if int(d1) <= int(c) and int(d1) >= 1 : f1 = int(s1) c1 = int(s2) elementos = int(d1) aux = matriz.Search(f1,c1) i = 0 j = 0 t = 1 aun1 = aux if c1+elementos <= (int(c)+1) and f1+elementos <= (int(f)+1): while j < elementos: aux = aun1 while i < t: aux.dato = '*' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 t = t + 1 aun1 = aun1.abajo tamaño = 25 t1 = auxiliar.Pintando() t2 = matriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Triangulo Rectangulo",font=("Lucida Console",10)) im4.place(x=px+390,y=90+alto) windows.destroy() ventana.destroy() texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Agregar Triangulo Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Espacio no disponible - Operacion : Agregar Triangulo Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error Espacio no disponible") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de matriz - Operacion : Agregar Triangulo Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede numero de tamaño de matriz - Operacion : Agregar Triangulo Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz c:1") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede numero de tamaño de matriz - Operacion : Agregar Triangulo Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz f:1") else: ventanaEmergente("Error Ingrese solo Numero") texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Ingrese solo numeros - Operacion : Agregar Triangulo Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) def agregarV(ventana,windows,s1,s2,d1,f,c,matriz): auxiliar = copy.deepcopy(matriz) if s1.isdigit() and s2.isdigit() and d1.isdigit(): if int(s1) <= int(c) and int(s1) >= 1 : if int(s2) <= int(f) and int(s2) >= 1 : if int(d1) <= int(f) and int(d1) >= 1 : f1 = int(s1) c1 = int(s2) elementos = int(d1) aux = matriz.Search(f1,c1) i = 0 if f1+elementos <= int(f)+1: while i < elementos: aux.dato = '*' i = i + 1 aux = aux.abajo elif f1-elementos >= 0: while i < elementos: aux.dato = '*' i = i + 1 aux = aux.arriba else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Elementos no cabe en matriz - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Elementos no cabe en matriz") tamaño = 25 t1 = auxiliar.Pintando() t2 = matriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Agregar Linea Vertical",font=("Lucida Console",10)) im4.place(x=px+390,y=90+alto) windows.destroy() ventana.destroy() texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Agregar Linea Vertical - Matriz Usada: "+matriz.primero.nombre log.append(texto) else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Agregar Linea Vertical - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error 1numero de elementos excede tamaño de matriz") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Agregar Linea Vertical - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero de columnas excede tamaño de matriz ") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Agregar Linea Vertical - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero de filas excede tamaño de matriz ") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Ingrese solo Numeros - Operacion : Agregar Linea Vertical - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error Ingrese solo Numero") def guardarA(ventana,windows,s1,s2,d1,d2,f,c,matriz): global x1,x2,y1,y2,filas,columnas,elementos auxiliar = copy.deepcopy(matriz) if s1.isdigit() and s2.isdigit() and d1.isdigit() and d2.isdigit(): if int(s1) <= int(c) and int(s1) >= 1 : if int(s2) <= int(f) and int(s2) >= 1 : if int(d1) <= int(c) and int(d1) >= 1 : if int(d2) <= int(f) and int(d2) >= 1 : f1 = int(s1) c1 = int(s2) f2 = int(d1) c2 = int(d2) if f1 <= f2: #siguiente if c1 <= c2: #abajo aux = matriz.Search(f1,c1) avanzax = c2-c1 avanzay = f2-f1 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '*' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.abajo elif c1 > c2: #abajo aux = matriz.Search(f2,c2) avanzax = c1-c2 avanzay = f2-f1 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '*' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.arriba elif f2 <= f1: #siguiente if c1 <= c2: #abajo aux = matriz.Search(f1,c1) avanzax = c2-c1 avanzay = f1-f2 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '*' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.arriba elif c1 > c2: #abajo aux = matriz.Search(f2,c2) avanzay = f1-f2 avanzax = c1-c2 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '*' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.abajo tamaño = 25 t1 = auxiliar.Pintando() t2 = matriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Rectangulo",font=("Lucida Console",10)) im4.place(x=px+390,y=90+alto) windows.destroy() ventana.destroy() texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Agregar Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Añadir Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz c:2") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Añadir Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz f:2") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Añadir Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz c:1") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Añadir Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz f:1") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Solo tiene que añadir numeros - Operacion : Añadir Rectangulo - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error Ingrese solo Numero") def agregarH(ventana,windows,s1,s2,d1,f,c,matriz): auxiliar = copy.deepcopy(matriz) if s1.isdigit() and s2.isdigit() and d1.isdigit(): if int(s1) <= int(c) and int(s1) >= 1 : if int(s2) <= int(f) and int(s2) >= 1 : if int(d1) <= int(c) and int(d1) >= 1 : f1 = int(s1) c1 = int(s2) elementos = int(d1) aux = matriz.Search(f1,c1) i = 0 if c1+elementos <= int(c)+1: while i < elementos: aux.dato = '*' i = i + 1 aux = aux.siguiente elif c1-elementos<=0: while i < elementos: aux.dato = '*' i = i + 1 aux = aux.atras else: ventanaEmergente("Elementos no cabe en matriz") texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Elementos no cabe en matriz - Operacion : Agregar Linea Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) tamaño = 25 t1 = auxiliar.Pintando() t2 = matriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Agregar Linea Horinzontal",font=("Lucida Console",10)) im4.place(x=px+390,y=90+alto) windows.destroy() ventana.destroy() texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Agregar linea Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Agregar Linea Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero de elementos excede tamaño de matriz") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Agregar Linea Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero de columnas excede tamaño de matriz ") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Agregar Linea Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero de filas excede tamaño de matriz ") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Ingrese solo numeros - Operacion : Agregar Linea Horizontal - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error Ingrese solo Numero") def guardar(ventana,windows,s1,s2,d1,d2,f,c,matriz): global x1,x2,y1,y2,filas,columnas,elementos auxiliar = copy.deepcopy(matriz) if s1.isdigit() and s2.isdigit() and d1.isdigit() and d2.isdigit(): if int(s1) <= int(c) and int(s1) >= 1 : if int(s2) <= int(f) and int(s2) >= 1 : if int(d1) <= int(c) and int(d1) >= 1 : if int(d2) <= int(f) and int(d2) >= 1 : f1 = int(s1) c1 = int(s2) f2 = int(d1) c2 = int(d2) if f1 <= f2: #siguiente if c1 <= c2: #abajo aux = matriz.Search(f1,c1) avanzax = c2-c1 avanzay = f2-f1 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '-' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.abajo elif c1 > c2: #abajo aux = matriz.Search(f2,c2) avanzax = c1-c2 avanzay = f2-f1 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '-' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.arriba elif f2 <= f1: #siguiente if c1 <= c2: #abajo aux = matriz.Search(f1,c1) avanzax = c2-c1 avanzay = f1-f2 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '-' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.arriba elif c1 > c2: #abajo aux = matriz.Search(f2,c2) avanzay = f1-f2 avanzax = c1-c2 i = 0 j = 0 aun1 = aux while j <= avanzay: aux = aun1 while i <= avanzax: aux.dato = '-' aux = aux.siguiente i = i + 1 j = j + 1 i = 0 aun1 = aun1.abajo tamaño = 25 t1 = auxiliar.Pintando() t2 = matriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 400 or ancho >= 300: while alto>= 380 or ancho >= 300 : tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) ancho = 0.83*float(tamaño)*float(matriz.primero.c) px = (300-ancho)/2 im1 = Label(raiz,text=t1,font=("Lucida Console",int(tamaño))) im1.place(x=px,y=90) im3 = Label(raiz,text="Imagen Original",font=("Lucida Console",10)) im3.place(x=px+30,y=90+alto) px1 = ((300-ancho)/2)+340 im2 = Label(raiz,text=t2,font=("Lucida Console",int(tamaño))) im2.place(x=px1,y=90) im4 = Label(raiz,text="Eliminado",font=("Lucida Console",10)) im4.place(x=px+390,y=90+alto) texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Operacion: Limpiar Zona - Matriz Usada: "+matriz.primero.nombre log.append(texto) windows.destroy() ventana.destroy() else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Limpiar Zona - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz Y:2") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Limpiar Zona - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz X:2") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Limpiar Zona - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz Y:1") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Excede tamaño de Matriz - Operacion : Limpiar Zona - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error numero excede tamaño de matriz X:1") else: texto = time.strftime('%Y/%m/%d - %H:%M:%S', time.localtime())+" - "+ "Error: Solo Numeros - Operacion : Limpiar Zona - Matriz Usada: "+matriz.primero.nombre log.append(texto) ventanaEmergente("Error Ingrese solo Numero") def verImagen(combo): img = combo.get() if img == 'Seleccione Imagen': ventanaEmergente("Porfavor Seleccione una Imagen") else: tamaño = 25 aux = listaImagenes.BuscarMatriz(img) matriz = aux.matriz imagen = Tk() imagen.title("Imagen") imagen.configure(bg="#2D9AB7") texto = matriz.Pintando() ancho = 0.83*float(tamaño)*float(matriz.primero.c) alto = 1.36*float(tamaño)*float(matriz.primero.f) if alto >= 700: while alto>= 700: tamaño = tamaño-0.3 alto = 1.36*float(tamaño)*float(matriz.primero.f) x_ventana = raiz.winfo_screenwidth() // 2 - int(ancho) // 2 y_ventana = raiz.winfo_screenheight() // 2 - int(alto) // 2 posicion = str(int(ancho)) + "x" + str(int(alto)) + "+" + str(x_ventana) + "+" + str(y_ventana) imagen.geometry(posicion) lb2 = Label(imagen,text=texto,fg="#FFFFFF",bg="#2D9AB7",font=("Lucida Console",int(tamaño))) lb2.place(x=0,y=0) imagen.mainloop() # limite = Label(windows,text="|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n|\n",font=("Lucida Console",20)).place(x=345,y=20) #limite1 = Label(windows,text="-------------------------------------------------------------------",font=("Lucida Console",20)).place(x=0,y=30) def documento(): path = 'ensayo.pdf' subprocess.Popen([path], shell=True) def ayuda(): ayuda = Tk() ayuda.title("Ayuda") ancho_ventana = 403 alto_ventana = 160 ayuda.configure(bg="#B3B3B3") x_ventana = raiz.winfo_screenwidth() // 2 - ancho_ventana // 2 y_ventana = raiz.winfo_screenheight() // 2 - alto_ventana // 2 posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(x_ventana) + "+" + str(y_ventana) ayuda.geometry(posicion) b1 = Button(ayuda,text="Datos del Desarrollador",command=datos,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",17)) b1.place(x=30,y=30) b2 = Button(ayuda,text="Documentacion",command=documento,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",17)) b2.place(x=100,y=90) ayuda.mainloop() def datos(): dato = Tk() dato.title("Datos del desarrolador") tk = Label(dato,text="Edwin Estuardo Reyes Reyes \n201709015\n 4to Semestre ",bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",17)) tk.place(x=10,y=30) ancho_ventana = 390 alto_ventana = 120 dato.configure(bg="#2D9AB7") x_ventana = raiz.winfo_screenwidth() // 2 - ancho_ventana // 2 y_ventana = raiz.winfo_screenheight() // 2 - alto_ventana // 2 posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(x_ventana) + "+" + str(y_ventana) dato.geometry(posicion) def graphi(): g = Digraph('unix', filename='Imagenes Cargadas en sistema',node_attr={'color': 'lightblue2', 'style': 'filled'}) aux = listaImagenes.primero texto = "nombre "+aux.nombre+" fila "+aux.fila+" columna "+aux.columna g.edge('Lista de Imagenes',texto) while aux.siguiente != None: g.edge("nombre "+aux.nombre+" fila "+aux.fila+" columna "+aux.columna,"nombre "+aux.siguiente.nombre+" fila "+aux.siguiente.fila+" columna "+aux.siguiente.columna) aux = aux.siguiente g.view() raiz = Tk() raiz.title("Principal") ancho_ventana = 650 alto_ventana = 460 raiz['bg'] = '#B3B3B3' x_ventana = raiz.winfo_screenwidth() // 2 - ancho_ventana // 2 y_ventana = raiz.winfo_screenheight() // 2 - alto_ventana // 2 posicion = str(ancho_ventana) + "x" + str(alto_ventana) + "+" + str(x_ventana) + "+" + str(y_ventana) raiz.geometry(posicion) tamaño = 17 raiz.iconbitmap("codificacion.ico") botonCargar = Button(raiz,text="Cargar Archivo",command=carga,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",tamaño)) botonCargar.place(x=10,y=20) botonOperacion = Button(raiz,text="Operaciones",command=operaciones,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",tamaño)) botonOperacion.place(x=233,y=20) botonReporte = Button(raiz,text="Reporte",command=reporte,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",tamaño)) botonReporte.place(x=420,y=20) botonAyuda = Button(raiz,text="Ayuda",command=ayuda,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",tamaño)) botonAyuda.place(x=550,y=20) botonA = Button(raiz,text=" ",command=graphi,bg = "#2D9AB7",fg = "#FFFFFF",font=("Lucida Console",5)) botonA.place(x=0,y=0) raiz.mainloop()
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,942
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/NodoLista.py
class NodoLista(): def __init__(self,matriz,nombre,fila,columna): self.matriz = matriz self.nombre = nombre self.fila = fila self.columna = columna self.siguiente = None self.atras = None
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,943
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/Matriz.py
from Nodo import Nodo from ListaDoble import ListaDoble from NodoMatriz import NodoMatriz from NodoEncabezado import NodoEncabezado class Matriz(): def __init__(self,nombre,f,c): listaDeListas = ListaDoble() listaDeColumna = ListaDoble() self.primero = Nodo(nombre,listaDeListas,listaDeColumna,f,c) def Search(self,fila,columna): fil = self.primero.fila.Buscar(fila).Nodo col = self.primero.columna.Buscar(columna).Nodo while col != None: while fil != None: if fil == col: return fil else: fil = fil.siguiente fil = self.primero.fila.Buscar(fila).Nodo col = col.abajo def Agregar(self,fila,columna,valor): nodoMatriz = NodoMatriz(valor,fila,columna) if self.primero.fila.ExisteNodo(fila,"fila") == False and self.primero.columna.ExisteNodo(columna,"Columna") == False: #si existe e nodoCabezacolumna = NodoEncabezado(columna) nodoCabezafila = NodoEncabezado(fila) nodoCabezacolumna.Nodo = nodoMatriz nodoCabezafila.Nodo = nodoMatriz self.primero.fila.Agregar(nodoCabezafila) self.primero.columna.Agregar(nodoCabezacolumna) elif self.primero.fila.ExisteNodo(fila,"fila") and self.primero.columna.ExisteNodo(columna,"columna") == False: #si existe el no aux = self.primero.fila.Buscar(fila) aux1 = aux.Nodo nodoCabezacolumna = NodoEncabezado(columna) nodoCabezacolumna.Nodo = nodoMatriz self.primero.columna.Agregar(nodoCabezacolumna) while aux1.siguiente != None: aux1 = aux1.siguiente aux1.siguiente = nodoMatriz nodoMatriz.atras = aux1 elif self.primero.fila.ExisteNodo(fila,"fila") == False and self.primero.columna.ExisteNodo(columna,"columna"): #si existe el nodo aux = self.primero.columna.Buscar(columna) aux1 = aux.Nodo nodoCabezaFila = NodoEncabezado(fila) nodoCabezaFila.Nodo = nodoMatriz self.primero.fila.Agregar(nodoCabezaFila) while aux1.abajo != None: aux1 = aux1.abajo aux1.abajo = nodoMatriz nodoMatriz.arriba = aux1 else: auxiliar = self.primero.fila.Buscar(fila) aux1 = auxiliar.Nodo while aux1.siguiente != None: aux1 = aux1.siguiente aux1.siguiente = nodoMatriz nodoMatriz.atras = aux1 aux = self.primero.columna.Buscar(columna) au = aux.Nodo while au.abajo != None: au = au.abajo au.abajo = nodoMatriz nodoMatriz.arriba = au def Pintando(self): au = self.primero.fila.primero texto = '' while(au != None): auxiliar = au.Nodo while(auxiliar != None): texto = texto + auxiliar.dato auxiliar = auxiliar.siguiente au = au.siguiente texto = texto + '\n' return texto def Print(self): print(self.primero.nombre) print(" c ",end="") aux = self.primero.columna.primero while (aux != None): print(str(aux.identificador)+" ", end="") aux = aux.siguiente print("") au = self.primero.fila.primero while(au != None): print(str(au.identificador)+" ", end = "") auxiliar = au.Nodo while(auxiliar != None): print(auxiliar.dato+" ", end = "") auxiliar = auxiliar.siguiente au = au.siguiente print("") def get_Primero(self): return self.primero def Imprimir(self,posicion,identificador): if posicion == 'fila': auxiliar = self.primero.fila.Buscar(identificador) aux = auxiliar.Nodo print("Fila "+str(identificador)+": ") while aux != None: print(aux.dato+" ", end = "") aux = aux.siguiente elif posicion == 'columna': auxiliar = self.primero.columna.Buscar(identificador) aux = auxiliar.Nodo print("Columna "+str(identificador)+": ") while aux != None: print(aux.dato+" ", end = "") aux = aux.abajo print("")
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,944
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/prueba.py
import subprocess path = 'indexx.pdf' subprocess.Popen([path], shell=True)
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,945
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/NodoEncabezado.py
class NodoEncabezado(): def __init__(self,identificador): self.identificador = identificador self.siguiente = None self.atras = None self.Nodo = None
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,946
EstuardoReyes/IPC2_Proyecto2_201709015
refs/heads/main
/Ventana.py
from tkinter import Tk, Label, Button class Main: def __init__(self, master): self.master = master master.title("Una simple interfaz gráfica") self.etiqueta = Label(master, text="Esta es la primera ventana!") self.etiqueta.pack() self.botonSaludo = Button(master, text="Saludar", command=self.saludar) self.botonSaludo.pack() self.botonCerrar = Button(master, text="Cerrar", command=master.quit) self.botonCerrar.pack() def saludar(self): print("¡Hey!") root = Tk() miVentana = VentanaEjemplo(root) root.mainloop()
{"/main.py": ["/Matriz.py", "/NodoLista.py"], "/Matriz.py": ["/Nodo.py", "/NodoMatriz.py", "/NodoEncabezado.py"]}
23,947
venieri/cancan
refs/heads/master
/videopoker/views.py
import random import logging import pickle from django import forms from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic import TemplateView def build_bid_select_field(max_amount, default = 10): bids = list(filter(lambda x: x <= max_amount, [1,5,10,20,50,100,500,1000,5000])) if bids: default = min(default, max(bids)) #print default, bids else: default = 0 print(max_amount, default, list(zip(bids, bids))) return forms.TypedChoiceField(coerce=int, initial=default, choices = zip(bids, bids)) def build_bid_select_field(max_amount, default = 10): bids = list(filter(lambda x: x <= max_amount, [1,5,10,20,50,100,500,1000,5000])) if bids: default = min(default, max(bids)) #print default, bids else: default = 0 print('build_bid_select_field', max_amount, default, list(zip(bids, bids))) return forms.TypedChoiceField(coerce=int, initial=default, choices = zip(bids, bids)) def get_form_class(request): class BidForm(forms.Form): bid = build_bid_select_field(request.user.account.bankroll) return BidForm from utils.cards import Deck, Hand, multiples log = logging.getLogger(__name__) ODDS=(('no hand', 0), ('Low Pair', 0), ('Jacks High', 1), ('Two Pairs', 2), ('3 of a Kind', 3), ('Straight', 4), ('Flush', 6), ('Full House',9), ('4 of a Kind',25), ('Straight Flush',50), ('Royal Flush',250)) START_MESSAGE="Welcome to Jacks High" DRAW_MESSAGE="Go on draw your next cards" BUSTED_MESSAGE="Sorry, you're BUSTED!" WON_MESSAGE="<br>Wow You've won %.0f" LOST_MESSAGE="Sorry you lost, try another hand?" def deal(): deck = Deck() deck.suffle() hand = Hand() for card in range(5): hand.take(deck.deal()) print('deal', [(card.open, card.ordinal) for card in hand]) return deck, hand decorators = [never_cache, login_required] @method_decorator(decorators, name='dispatch') class JHPoker(TemplateView): template_name = "jhpoker.html" def post(self, request): winnings = 0 bid = 0 account = request.user.account message = '' action = 'DEAL' current_state = request.session.get('next_state', 'start') form = get_form_class(request)(request.POST) print('state', current_state) print('form.is_valid()', form.is_valid()) if form.is_valid(): if current_state == 'start': deck, hand = deal() request.session['next_state'] = 'delt' message = "Choose your bid and click on deal" action = 'DEAL' elif current_state == 'delt': bid = form.cleaned_data['bid'] hand = Hand.from_json(request.session['hand']) deck = Deck.from_json(request.session['deck']) log.debug('delt %s', current_state) request.user.account.bid('jackpot', bid) for card in range(5): hand[card].show() print('delt', [(card.open, card.ordinal) for card in hand]) request.session['hand'] = hand.to_json() request.session['deck'] = deck.to_json() request.session['next_state'] = 'drawn' message = "Choose which cards to keep and click on deal" action = 'DRAW' elif current_state == 'drawn': print(request.POST) request.session['next_state'] = 'delt' bid = form.cleaned_data['bid'] hand = Hand.from_json(request.session['hand']) deck = Deck.from_json(request.session['deck']) for card in range(5): if 'holdcard-%d' % card not in request.POST: hand[card] = deck.deal().show() print('holdcard-%d' % card, 'holdcard-%d' % card not in request.POST, hand[card]) print('drawn', [(card.open, card.ordinal) for card in hand]) score = scorer(hand) handname, odds = ODDS[score] winnings = odds * bid request.user.account.win('vpoker', winnings, bid) message = handname if odds: message += WON_MESSAGE % winnings elif request.user.account.bankroll > 1: message = LOST_MESSAGE else: message = BUSTED_MESSAGE deck_1, hand_1 = deal() request.session['hand'] = hand_1.to_json() request.session['deck'] = deck_1.to_json() action = 'DEAL' params = dict( action=action, hand=hand, current_state=current_state, next_state=request.session['next_state'], account=request.user.account, message=message, bid=bid, winnings=winnings, form=form) return render(request, "jhpoker.html", params) def get(self, request): winnings = 0 bid = 0 message = '' action = 'DEAL' current_state = 'start' log.debug('start %s', current_state) form = get_form_class(request)() print(form) deck, hand = deal() request.session['hand'] = hand.to_json() request.session['deck'] = deck.to_json() message = "Choose your bid and click on deal" request.session['next_state'] = 'delt' action = 'DEAL' params = dict( action = action, hand = request.session['hand'], current_state = current_state, next_state = request.session['next_state'], account = request.user.account, message = message, bid = bid, winnings = winnings, form = form) return render(request, "jhpoker.html", params) def jhi_Poker_scorer(hand): log.debug('scoring %s', hand.show()) values = [card.value for card in hand] suites = [card.suite for card in hand] smax = max(suites) smin = min(suites) size = len(hand) flush = 0 straight = 0 vmax = max(values) vmin = min(values) vdiff = vmax - vmin + 1 score = 0 # print ' is straight ? %d == %d ' % (vdiff , size) if vdiff == size: # straight # print 'straight' straight = 1 elif vmin == 1 and vmax == 13: # good chance royal straight svalues = values svalues.sort() # print 'svalues', svalues svalues[0] = 14 vmax = max(svalues) vdiff = vmax - min(svalues) + 1 if vdiff == size: straight = 1 if straight: score = 5 # print ' is flush ? %d == %d ' % (smin , smax) if smax == smin: # flush flush = 1 if straight: if vmax == 14: score = 10 else: score = 9 else: score = 6 log.debug('hjiPokerScorer-score %s', score) mscore = 0 if score < 9: # print 'check for multiples' mscore = multiples(hand) log.debug('hjiPokerScorer-score %s', mscore) if mscore > 0: score = mscore elif score > 0: hand.cards = map(hold, hand) return score def multiples2(hand): i = 0 pairs = {} score = 0 size = len(hand.cards) for i in range(size - 1): for j in range(i, size): if i != j and hand.cards[i].value == hand.cards[j].value: hand.cards[i].state = 9 hand.cards[j].state = 9 if pairs.has_key(hand.cards[i].value): pairs[hand.cards[i].value] = pairs[hand.cards[i].value] + 1 else: pairs[hand.cards[i].value] = 1 # print pairs npairs = len(pairs) if npairs: series = [] for p in pairs.keys(): series.append(p) # return (series, pairs) # now jh specific ascore = {1: 1, 2: 4, 3: 4, 6: 8} a = series[0] # print series number = pairs[a] score = ascore[number] if number == 1: if a > 10 or a == 1: score = 2 if npairs == 2: bscore = {1: 3, 3: 7} b = series[1] number = pairs[b] if number == 1: if score == 4: score = 7 else: score = 3 elif number == 3: score = 7 return score def hold(card): card.setState(9) return card def scorer(hand): log.debug('scoring %s', hand.show()) values = [card.value for card in hand] suites = [card.suite for card in hand] smax = max(suites) smin = min(suites) size = len(hand) flush = 0 straight = 0 vmax = max(values) vmin = min(values) vdiff = vmax - vmin + 1 score = 0 # print ' is straight ? %d == %d ' % (vdiff , size) if vdiff == size: # straight # print 'straight' straight = 1 elif vmin == 1 and vmax == 13: # good chance royal straight svalues = values svalues.sort() # print 'svalues', svalues svalues[0] = 14 vmax = max(svalues) vdiff = vmax - min(svalues) + 1 if vdiff == size: straight = 1 if straight: score = 5 # print ' is flush ? %d == %d ' % (smin , smax) if smax == smin: # flush flush = 1 if straight: if vmax == 14: score = 10 else: score = 9 else: score = 6 log.debug('hjiPokerScorer-score %s', score) mscore = 0 if score < 9: # print 'check for multiples' mscore = multiples(hand) log.debug('hjiPokerScorer-mscore %s', mscore) if mscore > 0: score = mscore elif score > 0: hand.cards = map(hold, hand) return score def jhPokerScorer(hand): values = hand.values() # print values suites = hand.suites() smax = max(suites) smin = min(suites) size = len(hand.cards) flush = 0 straight = 0 vmax = max(values) vmin = min(values) vdiff = vmax - vmin + 1 score = 0 # print ' is straight ? %d == %d ' % (vdiff , size) if vdiff == size: # straight # print 'straight' straight = 1 elif vmin == 1 and vmax == 13: # good chance royal straight svalues = values svalues.sort() # print 'svalues', svalues svalues[0] = 14 vmax = max(svalues) vdiff = vmax - min(svalues) + 1 if vdiff == size: straight = 1 if straight: score = 5 # print ' is flush ? %d == %d ' % (smin , smax) if smax == smin: # flush flush = 1 if straight: if vmax == 14: score = 10 else: score = 9 else: score = 6 mscore = 0 if score < 9: # print 'check for multiples' mscore = multiples(hand) if mscore > 0: score = mscore elif score > 0: hand.cards = map(hold, hand.cards) return score def holdOn(state): if state == 9: return "CHECKED" return ""
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,948
venieri/cancan
refs/heads/master
/accounts/templatetags/casino_tags.py
''' Created on Oct 24, 2011 @author: tvassila ''' import time #=============================================================================== # import copy # from django.template import TemplateSyntaxError, Node, Variable, Library # from django.utils.datastructures import SortedDict #=============================================================================== from django.template import Library from cancan import settings register = Library() @register.simple_tag(takes_context=True) def get_settings(context, key): context[key] = getattr(settings, key,'COuKOU-%s' % key) return '' @register.filter def split(str): return str.split(",") @register.simple_tag def test_tag(): return "<span>" + "</span><span>".join(["one", "two", "three"])+"</span>" #=============================================================================== # def get_fieldset(parser, token): # try: # name, fields, as_, variable_name, from_, form = token.split_contents() # except ValueError: # raise TemplateSyntaxError('bad arguments for %r' % token.split_contents()[0]) # return FieldSetNode(fields.split(','), variable_name, form) # # get_fieldset = register.tag(get_fieldset) # # class FieldSetNode(Node): # def __init__(self, fields, variable_name, form_variable): # print fields # print 'form.fields', form_variable.fields # self.fields = fields # self.variable_name = variable_name # self.form_variable = form_variable # # def render(self, context): # form = Variable(self.form_variable).resolve(context) # new_form = copy.copy(form) # new_form.fields = SortedDict([(key, form.fields[key]) for key in self.fields]) # context[self.variable_name] = new_form # return u'' #===============================================================================
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,949
venieri/cancan
refs/heads/master
/cancan/urls.py
"""cancan URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('', views.Doorway.as_view(), name="doorway"), path('membership_agreement/', views.MembershipAgreement.as_view(), name="membership_agreement"), path('join/', views.Join.as_view(), name="join"), path('sign_in/', views.SignIn.as_view(), name="sign_in"), path('mainhall/', views.Mainhall.as_view(), name="mainhall"), path('games/', views.Games.as_view(), name="games"), path('manager/', views.Manager.as_view(), name="manager"), path('private/', views.Mainhall.as_view(), name="private"), path('pit/', views.Pit.as_view(), name="pit"), path('arcade/', views.Arcade.as_view(), name="arcade"), path('exit/', views.Mainhall.as_view(), name="exit"), path('baccarra/', views.Mainhall.as_view(), name="baccarra"), path('bjack/', views.Mainhall.as_view(), name="bjack"), path('craps/', views.Mainhall.as_view(), name="craps"), path('videopoker/', include('videopoker.urls')), path('jackpot/', include('jackpot.urls')), path('roulette/', include('roulette.urls')), path('accounts/', include('accounts.urls')), path('admin/', admin.site.urls), ]
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,950
venieri/cancan
refs/heads/master
/accounts/migrations/0003_auto_20200102_1847.py
# Generated by Django 3.0.1 on 2020-01-02 18:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('accounts', '0002_account_score'), ] operations = [ migrations.RenameField( model_name='account', old_name='address', new_name='wallet', ), migrations.AddField( model_name='account', name='addreed_to_rules', field=models.BooleanField(default=True), ), ]
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,951
venieri/cancan
refs/heads/master
/accounts/urls.py
from django.urls import path from . import views urlpatterns = [ path('cashier/', views.Cashier.as_view(), name='cashier'), path('transactions/', views.Transactions.as_view(), name='transactions'), path('buy/', views.Buy.as_view(), name='buy'), ]
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,952
venieri/cancan
refs/heads/master
/accounts/models.py
from django.db import models # Create your models here. from django.contrib.auth.models import User class Account(models.Model): class Meta: permissions = ( ("play", "Can play in the casino"), ) OPENING_BALANCE = 5000 # This field is required. user = models.OneToOneField(User, on_delete=models.CASCADE) wallet = models.TextField(blank=True) agreed_to_rules = models.BooleanField(default=True) bankroll = models.FloatField(default=OPENING_BALANCE) bids = models.FloatField(default=0) won = models.FloatField(default=0) score = models.FloatField(default=0) @classmethod def open(cls, email, username, password, **kwa): user = User.objects.create_user(username, email, password) account = user.get_profile() AccountLine(entry_type=('accounted opened with %f' % account.bankroll), account=account, amount=account.bankroll, bankroll=account.bankroll).save() return account def bid(self, game, amount): self.bankroll -= amount self.bids += amount self.score = self.won / self.bids AccountLine.objects.create(entry_type='%s bid %.0f' % (game, amount), account=self, amount=-amount, bankroll=self.bankroll) self.save() return self def win(self, game, amount, bid, bid_returned=0): message = '%s bid %.0f, won %.0f' % (game, bid, amount) if bid_returned: message += '+%f' % bid_returned self.bankroll += bid_returned self.won += amount self.bankroll += amount self.score = self.won / self.bids AccountLine.objects.create(entry_type=message, account=self, amount=amount, bankroll=self.bankroll).save() self.save() return amount def buy(self, amount): self.bankroll += amount AccountLine(entry_type='bought', account=self, amount=amount, bankroll = self.bankroll).save() self.save() return self class AccountLine(models.Model): account = models.ForeignKey(Account, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True, auto_created=True) entry_type = models.CharField(max_length=100) amount = models.FloatField(default=0) bankroll = models.FloatField()
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,953
venieri/cancan
refs/heads/master
/accounts/views.py
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache from django.views.generic import TemplateView from django.views.generic.list import ListView from django.shortcuts import render from django.http import HttpResponseRedirect from django import forms from django.urls import reverse from . import models decorators = [never_cache, login_required] @method_decorator(decorators, name='dispatch') class Cashier(TemplateView): template_name = "cashier.html" @method_decorator(decorators, name='dispatch') class Transactions(ListView): template_name = "transactions.html" model = models.AccountLine paginate_by = 10 @method_decorator(decorators, name='dispatch') class Buy(TemplateView): template_name = "buy.html" class BuyForm(forms.Form): VALUES = [10, 20, 50, 100, 500, 1000, 5000] amount = forms.TypedChoiceField(coerce=int, choices=zip(VALUES, VALUES)) def get(self, request): form = self.BuyForm() return render(request, "buy.html", {'form':form}) def post(self, request): form = self.BuyForm(request.POST) if form.is_valid(): amount = form.cleaned_data['amount'] request.user.account.buy(amount).save() return HttpResponseRedirect(reverse('cashier'))
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,954
venieri/cancan
refs/heads/master
/cancan/views.py
import random from django.http import HttpResponseRedirect from django.shortcuts import render from django.views.generic import TemplateView from accounts.models import Account from django import forms from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.urls import reverse from copy import deepcopy from django.contrib.auth import login from django.contrib.auth.views import LoginView class JoinForm(UserCreationForm): error_css_class = 'is-danger' xrequired_css_class = 'ui-state-highlight' email = forms.EmailField(required=False) agreed_to_rules = forms.BooleanField(required=True) wallet = forms.CharField(widget=forms.Textarea, required=False, help_text='enter where you want the check sent to...') def save(self, commit=True): user = super(JoinForm, self).save() account = Account.objects.create(user=user) account.agreed_to_rules = self.cleaned_data['agreed_to_rules'] account.wallet = self.cleaned_data['wallet'] if commit: user.save() account.save() return user def required(self): return self.subform(('username', 'password1', 'password2')) def optional(self): return self.subform(('wallet')) def subform(self, fieldset=()): form = deepcopy(self) form.fields = dict([(key, self.fields[key]) for key in fieldset]) return form class Doorway(TemplateView): template_name = "doorway.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pot'] = random.randrange(1000,5000) context['top10'] = [account for account in Account.objects.all().order_by('score')] return context class Mainhall(TemplateView): template_name = "mainhall.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['pot'] = random.randrange(1000,5000) context['top10'] = [account for account in Account.objects.all().order_by('score')] return context class Games(TemplateView): template_name = "games.html" class Pit(TemplateView): template_name = "pit.html" class Arcade(TemplateView): template_name = "arcade.html" class Manager(TemplateView): template_name = "manager.html" class MembershipAgreement(TemplateView): template_name = "join.html" def get(self, request): return render(request, "agreement.html", {}) class Join(TemplateView): template_name = "join.html" def get(self, request): return render(request, "join.html", { 'form': JoinForm()}) def post(self, request): form = JoinForm(request.POST) if form.is_valid(): user = form.save() login(request, user) return HttpResponseRedirect(reverse('mainhall')) return render(request, 'join.html', {'form': form}) class SignIn(LoginView): template_name = "signin.html"
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,955
venieri/cancan
refs/heads/master
/roulette/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.Spin.as_view(), name='roulette'), ]
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,956
venieri/cancan
refs/heads/master
/jackpot/views.py
import random from django.http import HttpResponseRedirect from django.shortcuts import render from django.views.generic import TemplateView from accounts.models import Account from django import forms from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.urls import reverse from copy import deepcopy from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect from django.views.decorators.cache import never_cache def build_bid_select_field(max_amount, default = 10): bids = list(filter(lambda x: x <= max_amount, [1,5,10,20,50,100,500,1000,5000])) if bids: default = min(default, max(bids)) #print default, bids else: default = 0 print(max_amount, default, list(zip(bids, bids))) return forms.TypedChoiceField(coerce=int, initial=default, choices = zip(bids, bids)) fruit_odds = { 'eye': [0.0, 0.04, 0], # 'eye' :[0.0, 0.02, 0], 'seven': [0.1, 0.25, 0], # 'seven':[0.1, 0.25, 0], 'cherry': [0.25, 0.45, 0], # [0.25, 0.45, 0], 'hand': [0.6, 0.75, 0], 'fish': [0.75, 0.8, 0], 'grape': [0.8, 0.95, 0], 'diamond': [0.95, 1.0, 0]} payout = { 'eye eye eye': 250, 'seven seven seven': 30, 'cherry cherry cherry': 15, 'hand hand hand': 10, 'grape grape grape': 10, 'diamond diamond diamond': 10, 'cherry cherry ANY': 3} def get_fruit(fruits): fruit = None while not fruit: randval = random.random() for fruit in fruit_odds: odds = fruit_odds[fruit] if odds[0] <= randval < odds[1]: fruit_odds[fruit][2] = fruit_odds[fruit][2] + 1 break else: fruit = 'fish' if fruit in fruits: fruit = None return fruit def get_different_fruit(fruit): for key in fruit_odds.keys(): if key != fruit: return key def spin_wheel(): midf = get_fruit(()) topf = get_fruit((midf,)) # if midf != 'fish' else ()) botf = get_fruit((midf, topf)) # if topf != 'fish' else (midf)) return dict(top=topf, mid=midf, bottom=botf) def calc_score(left, middle, right): line = "%s %s %s" % (left, middle, right) if line in payout: return payout[line], line # 'three %s' % middle else: score = 0 if left == 'cherry': score += 1 if middle == 'cherry': score += 1 if right == 'cherry': score += 1 if score == 2: return payout['cherry cherry ANY'], line # 'two cherries' return 0, line # 'nothing' decorators = [never_cache, login_required] @method_decorator(decorators, name='dispatch') class Jackpot(TemplateView): template_name = "join.html" def post(self, request): account = request.user.account form = self.get_form_class(request)(request.POST) left_wheel = spin_wheel() middle_wheel = spin_wheel() right_wheel = spin_wheel() if form.is_valid(): bid = form.cleaned_data['bid'] if account.bankroll >= bid: account.bid('jackpot', bid) winnings = 0 score, fruit = calc_score( left=left_wheel['mid'], middle=middle_wheel['mid'], right=right_wheel['mid'] ) if score > 0.0: winnings = score * bid account.win('jackpot', winnings, bid) message = '%s, You Won $%d!!' % (fruit, winnings) state = 'won' else: message = '%s, Too bad, try again' % fruit state = 'lost' params = self.get_params(request, self.get_form_class(request)(), bid) params['left_wheel'] = left_wheel params['middle_wheel'] = middle_wheel params['right_wheel'] = right_wheel params['winnings'] = winnings params['state'] = state params['message'] = message return render(request, "jackpot.html", params) return render(request, "jackpot.html", self.get_params(request, self.get_form_class(request))) def get(self, request): return render(request, "jackpot.html", self.get_params(request, self.get_form_class(request)())) def get_form_class(self, request): class BidForm(forms.Form): bid = build_bid_select_field(request.user.account.bankroll) return BidForm def get_params(self, request, form, bid=0): return { 'state': 'nobid', 'account': request.user.account, 'message': 'Spin to Win', 'left_wheel': spin_wheel(), 'middle_wheel': spin_wheel(), 'right_wheel': spin_wheel(), 'bid': 0, 'winnings': 0, 'form': form }
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,957
venieri/cancan
refs/heads/master
/accounts/admin.py
from django.contrib import admin import logging logger = logging.getLogger(__name__) from django.contrib import admin, messages from . import models class AccountLineInline(admin.TabularInline): model = models.AccountLine extra = 0 list_filter = ['status'] search_fields = ['entry_type', 'amount'] date_hierarchy = 'timestamp' list_display = [ 'account', 'timestamp', 'entry_type', 'amount', 'bankroll' ] class AccountAdmin(admin.ModelAdmin): list_display =[ 'user', 'bankroll', 'bids', 'won'] # list_filter = ['status'] search_fields = ['status', 'user'] inlines = (AccountLineInline,) admin.site.register(models.Account, AccountAdmin)
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,958
venieri/cancan
refs/heads/master
/utils/cards.py
import logging log = logging.getLogger(__name__) from random import shuffle, randint class Card: def __init__(self, ordinal=0, value=0, suite=0, open=0): self.ordinal = ordinal self.value = value self.suite = suite self.open = open and 1 or 0 def hide(self): self.open = 0 return self def show(self): self.open = 1 return self def score(self, scorer): return scorer(self.value, self.ordinal) def __str__(self): return "%d" % (self.open and self.ordinal or 0) def to_json(self): return vars(self) @classmethod def from_json(cls, json): return cls(**json) class CardList(object): def __init__(self, *cards): self.cards = list(cards) def __getitem__(self, index): return self.cards[index] def __setitem__(self, index, card): self.cards[index] = card return self def __repr__(self): return self.cards.__repr__() def __len__(self): return len(self.cards) def to_json(self): return [card.to_json() for card in self.cards] @classmethod def from_json(cls, json): obj = cls() obj.cards = [Card.from_json(card) for card in json] return obj def debug(self): return str( [("%d %s" % (card.value, {0: 'b', 1: 'd', 2: 'c', 3: 'h', 4: 's'}[card.suite])) for card in self.cards]) class Deck(CardList): CARDvalues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] CARDsuites = [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4] def __init__(self, size=52): super(Deck, self).__init__() self.cards.extend([Card(card, self.CARDvalues[card], self.CARDsuites[card]) for card in range(1, 53)]) def suffle(self): shuffle(self.cards) return self def cut_deck(self, position=0): if not position: position = randint(1, len(self.cards) + 1) self.cards = self.cards[position:] + self.cards[:position] return self def deal(self): card = self.cards[0] self.cards = self.cards[1:] return card class Shoe(Deck): def __init__(self, deck=None, cut=None, multiple=1): super(Shoe, self).__init__() if not deck: deck = Deck() self.cards.extend(deck.cards * multiple) self.cut = cut if cut else len(self) class Hand(CardList): def take(self, card): self.cards.append(card) return self def show(self): return str([("%d %s" % (card.value, {0: 'b', 1: 'd', 2: 'c', 3: 'h', 4: 's'}[card.suite])) for card in self]) def multiples(hand): i = 0 pairs = {} score = 0 size = len(hand) for i in range(size - 1): for j in range(i, size): if i != j and hand[i].value == hand[j].value: hand[i].state = 9 hand[j].state = 9 if hand[i].value in pairs: pairs[hand[i].value] = pairs[hand[i].value] + 1 else: pairs[hand[i].value] = 1 log.debug('multiples-pairs %s', pairs) npairs = len(pairs) if npairs: series = [] for p in pairs.keys(): series.append(p) # return (series, pairs) # now jh specific ascore = {1: 1, 2: 4, 3: 4, 6: 8} a = series[0] log.debug('multiples-series %s', series) number = pairs[a] score = ascore[number] if number == 1: if a > 10 or a == 1: score = 2 if npairs == 2: bscore = {1: 3, 3: 7} b = series[1] number = pairs[b] if number == 1: if score == 4: score = 7 else: score = 3 elif number == 3: score = 7 log.debug('multiples-score %s', score) return score def hold(card): card.state = 9 return card
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,959
venieri/cancan
refs/heads/master
/jackpot/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.Jackpot.as_view(), name='jackpot'), ]
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,960
venieri/cancan
refs/heads/master
/cancan/forms.py
''' Created on Oct 21, 2011 @author: tvassila ''' from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import authenticate, login from django.http import HttpResponseRedirect from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect from django.core.urlresolvers import r from django.utils.copycompat import deepcopy from django.utils.datastructures import SortedDict from accounts.models import Account class BuyForm(forms.Form): VALUES = [10, 20, 50, 100, 500, 1000, 5000] amount = forms.TypedChoiceField(coerce=int, choices=zip(VALUES, VALUES)) class SigninForm(AuthenticationForm): pass class RulesForm(forms.Form): pass class JoinForm(UserCreationForm): error_css_class = 'ui-state-error' xrequired_css_class = 'ui-state-highlight' first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) email = forms.EmailField(required=False) # referrer = forms.CharField( required=False, widget=forms.HiddenInput()) pay = forms.CharField(required=False, help_text='enter the names you want yours winnings cheque made out to.') address = forms.CharField(widget=forms.Textarea, required=False, help_text='enter where you want the check sent to...') def save(self, commit=True): print self.cleaned_data['first_name'], self.cleaned_data['username'] user = super(JoinForm, self).save() user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] Account.objects.create(user=user) user.get_profile().pay = self.cleaned_data['pay'] user.get_profile().address = self.cleaned_data['address'] if commit: user.save() user.get_profile().save() return user def required(self): return self.subform(('username', 'password1', 'password2')) def optional(self): return self.subform(('email', 'first_name', 'last_name', 'address')) def subform(self, fieldset=()): form = deepcopy(self) form.fields = SortedDict([(key, self.fields[key]) for key in fieldset]) return form class JoinWizard(FormWizard): def done(self, request, form_list): if not form_list: return HttpResponseRedirect(reverse('bounce')) form = form_list[1] if form.is_valid(): user = form.save() user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) login(request, user) return HttpResponseRedirect(reverse('mainhall')) def get_template(self, step): if step == 0: return 'rules.html' return 'join.html' @method_decorator(csrf_protect) def __callx__(self, request, *args, **kwargs): if request.POST and request.POST.get('cancel'): return self.done(request, []) return super(JoinWizard, self).__call__(request, *args, **kwargs)
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,961
venieri/cancan
refs/heads/master
/videopoker/apps.py
from django.apps import AppConfig class VideopokerConfig(AppConfig): name = 'videopoker'
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
23,962
venieri/cancan
refs/heads/master
/roulette/views.py
from django.shortcuts import render # Create your views here. ''' Created on Oct 27, 2011 @author: tvassila ''' # Create your views here. import logging, json, time logger = logging.getLogger(__name__) from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_protect from django.views.decorators.cache import never_cache from django import forms import random thousands = lambda x: ((x*4//5)//1000) fivehundreds = lambda x:((x-thousands(x)*1000)*3//4)//500 hundreds = lambda x:((x-thousands(x)*1000 - fivehundreds(x)*500)*4//5)//100 fifties = lambda x:((x-thousands(x)*1000 - fivehundreds(x)*500 - hundreds(x)*100)*2//3)//50 twenties = lambda x:((x-thousands(x)*1000 - fivehundreds(x)*500 - hundreds(x)*100-fifties(x)*50)*3//4)//20 tens = lambda x:((x-thousands(x)*1000 - fivehundreds(x)*500 - hundreds(x)*100-fifties(x)*50-twenties(x)*20))//10 def bankroll(amount, dominations=((1000,thousands), (500,fivehundreds), (100, hundreds), (50, fifties), (20, twenties), (10, tens))): chips=[] amount = int(amount) for value,func in dominations: f = func x = func(amount) chips += [value]* x return chips class ChipStack(list): def __init__(self, bid, chips): super(self, ChipStack).__init__(chips) self.bid = bid START_MESSAGE = "Welcome to The Table" BUST_MESSAGE = "Sorry, you're BUSTED!" WON_MESSAGE = "Congratulations, You've won %.0f" LOST_MESSAGE = "Place your bets" def spin_ball(): return random.choice((0, 32, 15, 19, 4, 21, 2, 25, 17, 34, 6, 27, 13, 36, 11, 8, 23, 10, 5, 24, 16, 33, 1, 20, 14, 31, 9, 22, 18, 29, 7, 28, 12, 35, 3, 26)) from django.views.generic import TemplateView _bankroll = 100000 class BidForm(forms.Form): chips = forms.TextInput() decorators = [never_cache, login_required] @method_decorator(decorators, name='dispatch') class Spin(TemplateView): template_name = "roulette.html" def get(self, request): return render(request, "roulette.html", {'ball': spin_ball(), 'chips': [dict(id='chip-%d' % i, value=value, state='start') for i, value in enumerate(bankroll(request.user.account.bankroll))], 'form': BidForm(), 'payout_js': json.dumps([]), 'payout': []} ) def post(self, request): ball = spin_ball() form = BidForm(request.POST) if form.is_valid() and _bankroll > 0: chips = request.POST.get('chips') # print chips chips = json.loads(chips) if chips else [] # print 'CHIPS IN', chips total_bid, total_won, total_lost, winning_bids, winStack, loosingBids = croupierCollect(ball, chips, odds, table) # account.bid('roulette', total_bid) if total_won: message = WON_MESSAGE % total_won logger.debug('before wonOnMany') # account.win('roulette', total_won + winning_bids, total_bid) logger.debug('before won flash') elif 10 > 1: #account.bankroll > 1: message = LOST_MESSAGE logger.debug('before lost flash') else: message = BUST_MESSAGE logger.debug('before lost flash') payout = croupierPayout(winStack) params = {'payout_js': json.dumps(payout), 'payout': payout, 'bid': total_bid, 'won': total_won, 'winningBids': winning_bids, 'loosingBids': loosingBids, } return render(request, "roulette.html", {'ball': spin_ball(), 'chips': [dict(id='chip-%d' % i, value=value, state='start') for i, value in enumerate(bankroll(10000))], 'form': BidForm(), 'payout_js': json.dumps([]), 'payout': []} ) @login_required @csrf_protect @never_cache def spin(request): class BidForm(forms.Form): chips = forms.TextInput() account = request.user.get_profile() message = 'Spin to Win' ball = spin_ball() print 'BALL', table[ball] params = {} if request.method == 'GET': print 'spin GET' chips = [dict(id='chip-%d' % i, value=value, state='start') for i, value in enumerate(bankroll(account.bankroll))] elif request.method == 'POST': try: print 'spin POST' form = BidForm(request.POST) if form.is_valid() and account.bankroll > 0: chips = request.POST.get('chips') # print chips chips = json.loads(chips) if chips else [] # print 'CHIPS IN', chips total_bid, total_won, total_lost, winning_bids, winStack, loosingBids = croupierCollect(ball, chips, odds, table) account.bid('roulette', total_bid) if total_won: message = WON_MESSAGE % total_won logger.debug('before wonOnMany') account.win('roulette', total_won + winning_bids, total_bid) logger.debug('before won flash') elif account.bankroll > 1: message = LOST_MESSAGE logger.debug('before lost flash') else: message = BUST_MESSAGE logger.debug('before lost flash') payout = croupierPayout(winStack) print 'PAYOUT', payout params = {'payout_js': json.dumps(payout), 'payout': payout, 'bid': total_bid, 'won': total_won, 'winningBids': winning_bids, 'loosingBids': loosingBids, } except: logger.exception("ROULETTE Failed %s" % params) print "-" * 40 chips = [dict(id='chip-%d' % i, value=value, state='start') for i, value in enumerate(bankroll(account.bankroll))] form = BidForm() # print params # print message # print account.bankroll # print 'CHIPS OUT', chips values = {'ball': ball, 'colour_call': table[ball][1][1], 'ball_call': table[ball][1][0], 'account': account, 'message': message, 'chips': chips, 'form': form, 'payout_js': json.dumps([]), 'payout': []} values.update(params) # print values return render_to_response('roulette.html', values, context_instance=RequestContext(request)) odds = {'Zero': 35, '1': 35, '2': 35, '3': 35, '4': 35, '5': 35, '6': 35, '7': 35, '8': 35, '9': 35, '10': 35, '11': 35, '12': 35, '13': 35, '14': 35, '15': 35, '16': 35, '17': 35, '18': 35, '19': 35, '20': 35, '21': 35, '22': 35, '23': 35, '24': 35, '25': 35, '26': 35, '27': 35, '28': 35, '29': 35, '30': 35, '31': 35, '32': 35, '33': 35, '34': 35, '35': 35, '36': 35, '1to3': 11, '4to6': 11, '7to9': 11, '10to12': 11, '13to15': 11, '16to18': 11, '19to21': 11, '22to24': 11, '25to27': 11, '28to30': 11, '31to33': 11, '34to36': 11, '1to34': 2, '2to35': 2, '3to36': 2, '1doz': 2, '2doz': 2, '3doz': 2, 'Red': 1, 'Black': 1, 'even': 1, 'odd': 1, '1to18': 1, '19to36': 1} tableODDS = 0 tableWINNERS = 1 tableNAME = 0 tableCOLOUR = 1 table = [ (35.0, ['Zero', 'Green']), (35.0, ['1', 'Red', '1to18', 'odd', '1to3', '1to34', '1doz']), (35.0, ['2', 'Black', '1to18', 'even', '1to3', '2to35', '1doz']), (35.0, ['3', 'Red', '1to18', 'odd', '1to3', '3to36', '1doz']), (35.0, ['4', 'Black', '1to18', 'even', '4to6', '1to34', '1doz']), (35.0, ['5', 'Red', '1to18', 'odd', '4to6', '2to35', '1doz']), (35.0, ['6', 'Black', '1to18', 'even', '4to6', '3to36', '1doz']), (35.0, ['7', 'Red', '1to18', 'odd', '7to9', '1to34', '1doz']), (35.0, ['8', 'Black', '1to18', 'even', '7to9', '2to35', '1doz']), (35.0, ['9', 'Red', '1to18', 'odd', '7to9', '3to36', '1doz']), (35.0, ['10', 'Black', '1to18', 'even', '10to12', '1to34', '1doz']), (35.0, ['11', 'Black', '1to18', 'odd', '10to12', '2to35', '1doz']), (35.0, ['12', 'Red', '1to18', 'even', '10to12', '3to36', '1doz']), (35.0, ['13', 'Black', '1to18', 'odd', '13to15', '1to34', '2doz']), (35.0, ['14', 'Red', '1to18', 'even', '13to15', '2to35', '2doz']), (35.0, ['15', 'Black', '1to18', 'odd', '13to15', '3to36', '2doz']), (35.0, ['16', 'Red', '1to18', 'even', '16to18', '1to34', '2doz']), (35.0, ['17', 'Black', '1to18', 'odd', '16to18', '2to35', '2doz']), (35.0, ['18', 'Red', '1to18', 'even', '16to18', '3to36', '2doz']), (35.0, ['19', 'Red', '19to36', 'odd', '19to21', '1to34', '2doz']), (35.0, ['20', 'Black', '19to36', 'even', '19to21', '2to35', '2doz']), (35.0, ['21', 'Red', '19to36', 'odd', '19to21', '3to36', '2doz']), (35.0, ['22', 'Black', '19to36', 'even', '22to24', '1to34', '2doz']), (35.0, ['23', 'Red', '19to36', 'odd', '22to24', '2to35', '2doz']), (35.0, ['24', 'Black', '19to36', 'even', '22to24', '3to36', '2doz']), (35.0, ['25', 'Red', '19to36', 'odd', '25to27', '1to34', '3doz']), (35.0, ['26', 'Black', '19to36', 'even', '25to27', '2to35', '3doz']), (35.0, ['27', 'Red', '19to36', 'odd', '25to27', '3to36', '3doz']), (35.0, ['28', 'Black', '19to36', 'even', '28to30', '1to34', '3doz']), (35.0, ['29', 'Black', '19to36', 'odd', '28to30', '2to35', '3doz']), (35.0, ['30', 'Red', '19to36', 'even', '28to30', '3to36', '3doz']), (35.0, ['31', 'Black', '19to36', 'odd', '31to33', '1to34', '3doz']), (35.0, ['32', 'Red', '19to36', 'even', '31to33', '2to35', '3doz']), (35.0, ['33', 'Black', '19to36', 'odd', '31to33', '3to36', '3doz']), (35.0, ['34', 'Red', '19to36', 'even', '34to36', '1to34', '3doz']), (35.0, ['35', 'Black', '19to36', 'odd', '34to36', '2to35', '3doz']), (35.0, ['36', 'Red', '19to36', 'even', '34to36', '3to36', '3doz']), (11.0, ['1to3', 'Green']), (11.0, ['4to6', 'Green']), (11.0, ['7to9', 'Green']), (11.0, ['10to12', 'Green']), (11.0, ['13to15', 'Green']), (11.0, ['16to18', 'Green']), (11.0, ['19to21', 'Green']), (11.0, ['22to24', 'Green']), (11.0, ['25to27', 'Green']), (11.0, ['28to30', 'Green']), (11.0, ['31to33', 'Green']), (11.0, ['34to36', 'Green']), (2.0, ['1to34', 'Green']), (2.0, ['2to35', 'Green']), (2.0, ['3to36', 'Green']), (2.0, ['1doz', 'Green']), (2.0, ['2doz', 'Green']), (2.0, ['3doz', 'Green']), (1.0, ['Red', 'Red']), (1.0, ['Black', 'Black']), (1.0, ['even', 'Green']), (1.0, ['odd', 'Green']), (1.0, ['1to18', 'Green']), (1.0, ['19to36', 'Green'])] import time, random def croupierCollect(ball, chips, odds, table): total_bid = 0 total_won = 0 total_lost = 0 winStack = [] loosingBids = [] winning_bids = 0 for chip in chips: bid_split = len(chip['bids']) bid_lost = 0 if bid_split: wins = [] for bid in chip['bids']: bid_part = chip['value'] / bid_split if bid in table[ball][1]: print bid_split, chip['value'] won = bid_part * odds[bid] winning_bids += bid_part wins.append((chip, won, bid_part)) else: bid_lost += bid_part won = sum([value for id, value, _ in wins]) if wins: winStack.append((chip, won - bid_lost, chip['value'] / bid_split)) else: chip['state'] = 'LOST' total_won += won total_bid += chip['value'] total_lost += bid_lost return total_bid, total_won, total_lost, winning_bids, winStack, loosingBids def croupierPayout(winningBids): newChips = [] i = 0 for chip, won, bid_part in winningBids: for value in payout(won, chip['value']): newChips.append({ 'id': '%d-%d' % (time.time(), i), 'bids': chip['bids'], 'state': 'WON', 'top': int(chip['top']) + i, 'left': int(chip['left']) + i, 'value': value }) i += 1 return newChips def payout(amount, bid=100): chips = [] amount = int(amount) for dom in 1000, 500, 100, 50, 20, 10: if dom < amount or dom == bid: chips += [dom] * (amount // dom) amount -= dom * (amount // dom) if amount < 10: break return chips
{"/videopoker/views.py": ["/utils/cards.py"], "/cancan/views.py": ["/accounts/models.py"], "/jackpot/views.py": ["/accounts/models.py"], "/cancan/forms.py": ["/accounts/models.py"]}
24,003
Sirtsu55/Rocket-car
refs/heads/master
/drone.py
import pygame from pygame.sprite import Sprite import random class Drone(): def __init__(self, settings, screen): '''make a drone and then spawn it at the top''' self.screen = screen self.settings = settings #load the drone self.image = pygame.image.load('img\drone.png') self.rect = self.image.get_rect() self.screen_rect = self.screen.get_rect() self.rect.centery = self.screen_rect.top self.rect.centerx = random.randint(0, self.settings.screen_w) self.y = float(self.rect.centery) self.x = float(self.rect.centerx) def bounce_and_down(self,settings): if self.y <= settings.screen_h: self.y += +settings.drone_speed #MAKE THE DRONE BOUNCE AND GO SIDEWAYS if self.x <= settings.screen_w : self.x += settings.drone_s_speed if self.x >=settings.screen_w: settings.drone_s_speed = -settings.drone_s_speed self.x += settings.drone_s_speed if self.x <= 0: settings.drone_s_speed = -settings.drone_s_speed self.x += settings.drone_s_speed def update(self, settings): # MAKE THE DRONE GO DOWN Drone.bounce_and_down(self, settings) self.rect.centery = int(self.y) self.rect.centerx = int(self.x) def blitme(self): '''draw the drone''' self.screen.blit(self.image, self.rect)
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,004
Sirtsu55/Rocket-car
refs/heads/master
/button.py
import pygame.font import pygame class Button(): def __init__(self,settings, screen, msg): pygame.init() """make a button to start the game""" self.screen = screen self.settings = settings self.screen_rect = screen.get_rect() self.width, self.height = 200, 50 self.b_colour = self.settings.bg_colour self.txt_colour = (0, 255,0) self.font = pygame.font.SysFont('calibri', 48) self.rect = pygame.Rect(0,0, self.width, self. height) self.rect.center = self.screen_rect.center self.show_msg(msg) def show_msg(self, msg): self.msg_img = self.font.render(msg, True,self.txt_colour, self.b_colour) self.msg_img_rect = self.msg_img.get_rect() self.msg_img_rect.center = self.rect.center def draw_button(self): #draw a button self.screen.fill(self.b_colour, self.rect) self.screen.blit(self.msg_img, self.msg_img_rect)
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,005
Sirtsu55/Rocket-car
refs/heads/master
/functions.py
import sys import pygame import random from bullet import Bullet from drone import Drone from car import Car from points import PointButton def collision(bullets, drones, settings, car): for bullet in bullets: bullet.collision_bullet(drones, settings, bullets) for drone in drones: car.collision_car(drones, bullets) def update_drones(drones, settings): for drone in drones: drone.update(settings) drone.blitme() def make_drones(settings, drones, screen): for drone in drones: if drones[-1].rect.centery >= 200 : create_drone(settings, screen, drones) def remove_and_speedup_drone(settings, screen, drones): for drone in drones: if drone.y >= settings.screen_h: drones.remove(drone) settings.drone_speed += settings.speed_up settings.drone_s_speed += settings.speed_up settings.lives -= 1 def create_drone(settings, screen, drones): drone = Drone(settings, screen) drones.append(drone) def fire_bullets(settings, screen, car, bullets): for bullet in bullets.copy(): if bullet.rect.bottom <=0: bullets.remove(bullet) def make_bullets(settings, screen, car, bullets): if len(bullets) < settings.max_bullets: new_bullet = Bullet(settings, screen, car) bullets.add(new_bullet) def draw_bullets(bullets): for bullet in bullets.sprites(): bullet.draw_bullet() def quit(event): if event.type == pygame.QUIT: #exit the game sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: sys.exit() def check_play_button(stats, play_button, mouse_x, mouse_y): if play_button.rect.collidepoint(mouse_x, mouse_y): stats.active = True pygame.mouse.set_visible(False) def keydown(event, settings, screen ,car,car2, bullets, stats): #keydown events if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: car.moving_right = True elif event.key == pygame.K_LEFT: car.moving_left = True elif event.key == pygame.K_UP: car.moving_up = True elif event.key == pygame.K_DOWN: car.moving_down = True elif event.key == pygame.K_SPACE: #make a new bullet and add it into the bullets Group make_bullets(settings, screen, car, bullets) if stats.two_player: if event.key == pygame.K_d: car2.moving_right = True elif event.key == pygame.K_a: car2.moving_left = True elif event.key == pygame.K_w: car2.moving_up = True elif event.key == pygame.K_s: car2.moving_down = True elif event.key == pygame.K_LALT: #make a new bullet and add it into the bullets Group make_bullets(settings, screen, car2, bullets) def keyup(event, settings, screen, car, car2, bullets): #key up events if event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: car.moving_right = False elif event.key == pygame.K_LEFT: car.moving_left = False elif event.key == pygame.K_UP: car.moving_up = False elif event.key == pygame.K_DOWN: car.moving_down = False if event.key == pygame.K_d: car2.moving_right = False elif event.key == pygame.K_a: car2.moving_left = False elif event.key == pygame.K_w: car2.moving_up = False elif event.key == pygame.K_s: car2.moving_down = False def check_events(settings, screen ,car, car2 , bullets, stats, play_button): for event in pygame.event.get(): quit(event) if event.type == pygame.KEYDOWN: keydown(event, settings, screen, car, car2, bullets, stats) elif event.type == pygame.KEYUP: keyup(event, settings, screen, car, car2, bullets) if event.type == pygame.MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame.mouse.get_pos() check_play_button(stats, play_button, mouse_x, mouse_y) def screen_update(d_settings, screen, car, car2, line, bullets, drones, stats, play_button, points): screen.fill(d_settings.bg_colour) points = PointButton(d_settings, screen, ' HP: '+str(d_settings.lives)) points.draw_points() if stats.active == False: car.draw() line.draw_line() play_button.draw_button() pygame.display.flip() if stats.two_player: car2.draw() if stats.active: car.draw() line.draw_line() update_drones(drones, d_settings) remove_and_speedup_drone(d_settings, screen, drones) #draw all the bullets on the screen draw_bullets(bullets) pygame.display.flip()
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,006
Sirtsu55/Rocket-car
refs/heads/master
/car2.py
import pygame import time from stats import Stats class Car2(): def __init__(self, settings, screen): '''Car class and its start''' self.screen = screen self.settings = settings #load the car file self.image = pygame.image.load('img\car.png') self.car_rect = self.image.get_rect() self.screen_rect = screen.get_rect() # start a car at the bottom of the screen self.car_rect.centerx = self.screen_rect.centerx - 20 self.car_rect.centery = self.screen_rect.bottom self.car_rect.bottom = self.screen_rect.bottom #convert the centerx to a float to get accurate measurements self.centerx = float(self.car_rect.centerx) self.centery = float(self.car_rect.centery) #movement flags self.moving_left = False self.moving_right = False self.moving_up = False self.moving_down = False def update(self): if self.moving_right and self.car_rect.right < self.screen_rect.right: self.centerx += self.settings.speed if self.moving_left and self.car_rect.left > 0: self.centerx -= self.settings.speed if self.moving_up and self.car_rect.top > 400: self.centery -= self.settings.speed if self.moving_down and self.car_rect.bottom < 600: self.centery += self.settings.speed self.car_rect.centerx = self.centerx self.car_rect.centery = self.centery def draw(self): """Draw the ship at its current location.""" self.screen.blit(self.image, self.car_rect) def collision_car(self, drones, bullets): stats = Stats(self.settings, drones, bullets) for drone in drones: if self.car_rect.colliderect(drone): stats.settings.lives -= 1 time.sleep(self.settings.sleep_time) drones.remove(drone)
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,007
Sirtsu55/Rocket-car
refs/heads/master
/settings.py
class Settings(): def __init__(self): '''settings for the game''' # screen settings self.screen_w = 1000 #screen width self.screen_h = 600 #screen height self.bg_colour = (60,60,60) self.speed = 1 self.b_speed = 5 self.bullet_w = 40 self.bullet_h = 10 self.bullet_colour = 255, 0, 0 self.max_bullets = 2 self.drone_speed = 0.03 self.drone_s_speed = 0.5 self.speed_up = 0.01 self.lives = 5 self.points = 0 self.sleep_time = 0.3 self.points_earn = 1000 self.level_up_scale = 1.5 self.level_up = [i * (self.points_earn * 10 * self.level_up_scale) for i in range(1,11)]
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,008
Sirtsu55/Rocket-car
refs/heads/master
/line.py
import pygame class Line(): def __init__(self, screen): '''a class for line''' self.screen = screen self.image = pygame.image.load('img\line.png') self.rect = self.image.get_rect() self.screen_rect = self.screen.get_rect() self.rect.centery = self.screen_rect.centery + 100 self.rect.right = self.screen_rect.right def draw_line(self): self.screen.blit(self.image, self.rect.center)
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,009
Sirtsu55/Rocket-car
refs/heads/master
/stats.py
import sys class Stats(): """a class whre all the game stats will be""" def __init__(self, settings, drones, bullets): self.settings = settings self.bullets = bullets self.drones = drones self.settings = settings self.active = False self.two_player = False def reset(self): if self.settings.lives == 0: self.bullets.remove() for drone in self.drones: self.drones.remove(drone) self.active = False
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,010
Sirtsu55/Rocket-car
refs/heads/master
/bullet.py
import pygame from pygame.sprite import Sprite from stats import Stats class Bullet(Sprite): def __init__(self, settings, screen, car): '''a bullet that is fired from the car''' super().__init__() self.screen = screen #make a Bullet self.rect = pygame.Rect(0, 0,settings.bullet_w, settings.bullet_h) self.rect.centerx = car.car_rect.centerx self.rect.top = car.car_rect.top #store the bullets position as a float(decimal value) self.y = float(self.rect.y) self.colour = settings.bullet_colour self.speed = settings.b_speed def update(self): #update the decimal point of the bullet self.rect.y -= self.speed #update the pos of the bullet self.recty = self.y def draw_bullet(self): pygame.draw.rect(self.screen, self.colour, self.rect) def collision_bullet(self, drones, settings, bullets): stats = Stats(settings, drones, bullets) for drone in drones: if self.rect.colliderect(drone): level_up(settings) drones.remove(drone) def level_up(settings): settings.drone_speed += settings.speed_up settings.drone_s_speed += settings.speed_up settings.points += int(settings.points_earn) settings.speed += settings.speed_up settings.points = int(settings.points) if settings.points in settings.level_up: settings.lives += 1 settings.points_earn *= settings.level_up_scale
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,011
Sirtsu55/Rocket-car
refs/heads/master
/game.py
import pygame import functions as f from settings import Settings from car import Car from line import Line from pygame.sprite import Group from stats import Stats from car2 import Car2 from button import Button from points import PointButton def run_game(): d_settings = Settings() screen = pygame.display.set_mode((d_settings.screen_w, d_settings.screen_h)) screen.fill(d_settings.bg_colour) car = Car(d_settings, screen) car2 = Car2(d_settings, screen) line = Line(screen) bullets = Group() drones = [] stats = Stats(d_settings, drones, bullets) play_button = Button(d_settings, screen, 'start') pygame.init() points = PointButton(d_settings, screen, d_settings.points) #making a Car pygame.display.set_caption('Rocket Car') while True: f.check_events(d_settings, screen, car,car2, bullets, stats, play_button) if not stats.active: pygame.mouse.set_visible(True) d_settings = Settings() screen = pygame.display.set_mode((d_settings.screen_w, d_settings.screen_h)) screen.fill(d_settings.bg_colour) car = Car(d_settings, screen) car2 = Car2(d_settings, screen) line = Line(screen) bullets = Group() drones = [] stats = Stats(d_settings, drones, bullets) play_button = Button(d_settings, screen, 'start') f.screen_update(d_settings, screen, car, car2, line, bullets, drones, stats, play_button, points) if stats.active: f.make_drones(d_settings, drones, screen) if stats.two_player: f.collision(bullets, drones, d_settings, car2) if len(drones) < 1: f.create_drone(d_settings, screen, drones) f.collision(bullets, drones, d_settings, car) car.update() car2.update() bullets.update() stats.reset() # delete the old bullets f.fire_bullets(d_settings, screen,car, bullets) f.screen_update(d_settings, screen, car, car2, line, bullets, drones, stats, play_button, points) run_game()
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,012
Sirtsu55/Rocket-car
refs/heads/master
/points.py
import pygame import pygame.font class PointButton(): pygame.init() '''points counter''' def __init__(self, settings, screen, points): self.screen = screen self.settings = settings self.screen_rect = self.screen.get_rect() self.width, self.height = 200, 20 self.b_colour = self.settings.bg_colour self.txt_colour = (0,0,0) self.font = pygame.font.SysFont('calibri', 30) self.rect = pygame.Rect(0,0, self.width, self.height) self.rect.top = self.screen_rect.top self.rect.left = self.screen_rect.left self.show_points(points, self.settings) def show_points(self, points, settings): point_num = "{:,}".format(int(settings.points)) points = ' points: '+str(point_num) + str(points) self.points_img = self.font.render(str(points), True,self.txt_colour, self.b_colour) self.points_rect = self.points_img.get_rect() self.points_rect.center = self.rect.center def draw_points(self): self.screen.fill(self.b_colour, self.rect) self.screen.blit(self.points_img, self.points_rect)
{"/functions.py": ["/bullet.py", "/drone.py", "/points.py"], "/car2.py": ["/stats.py"], "/bullet.py": ["/stats.py"], "/game.py": ["/functions.py", "/settings.py", "/line.py", "/stats.py", "/car2.py", "/button.py", "/points.py"]}
24,030
Hcode4/pythonEveryDay
refs/heads/master
/OpFactory.py
import SpliteColumn import WriteExcel def op_factory(filePath): opType = input("请输入操作类型: \n 1. 按照某一列数据切割多行\n") opType = int(opType) if opType == 1: a = input("输入需要按某一列分行的列数,从0开始计数\n") a = int(a) b = input("输入间隔方式,如,等 注意中英文\n") tables = SpliteColumn.read_excel(filePath, a, b) print('读取成功') WriteExcel.writeExcel(tables, filePath, len(tables), len(tables[0])) input('回车键退出 ') tables = SpliteColumn.read_excel(filePath, a, b) print('读取成功') WriteExcel.writeExcel(tables, filePath, len(tables), len(tables[0]))
{"/OpFactory.py": ["/SpliteColumn.py", "/WriteExcel.py"], "/ReadExcel.py": ["/OpFactory.py"]}
24,031
Hcode4/pythonEveryDay
refs/heads/master
/SpliteColumn.py
# -*- coding: utf-8 -*- import xlrd import copy def read_excel(excelPath, splitCols, splitePattern): tables = [] # 打开文件 workbook = xlrd.open_workbook(excelPath) # sheet索引从0开始 sheet = workbook.sheet_by_index(0) for rown in range(sheet.nrows): array = [""] * sheet.ncols for ncol in range(sheet.ncols): array[ncol] = sheet.cell_value(rown, ncol) if splitCols != -1 and splitCols < sheet.ncols and array[splitCols].find(splitePattern) > 0: arraySplit = array[splitCols].split(",") for spliteIndex in range(len(arraySplit)): arrayCopy = copy.copy(array) arrayCopy[splitCols] = arraySplit[spliteIndex] tables.append(arrayCopy) else: tables.append(array) return tables
{"/OpFactory.py": ["/SpliteColumn.py", "/WriteExcel.py"], "/ReadExcel.py": ["/OpFactory.py"]}
24,032
Hcode4/pythonEveryDay
refs/heads/master
/ReadExcel.py
# -*- coding: utf-8 -*- import OpFactory if __name__ == '__main__': # 读取Excel filePath = input("输入文件路径, 请将\\ 改为 / 如 C:/Users/16146/Desktop/test.xls\n") OpFactory.op_factory(filePath)
{"/OpFactory.py": ["/SpliteColumn.py", "/WriteExcel.py"], "/ReadExcel.py": ["/OpFactory.py"]}
24,033
Hcode4/pythonEveryDay
refs/heads/master
/WriteExcel.py
import xlwt def writeExcel(table, localPath, numberCount, numberRange): workbook = xlwt.Workbook(localPath) # 在文件中创建一个名为TEST的sheet,不加名字默认为sheet1 worksheet = workbook.add_sheet("deal") for columnIndex in range(numberCount): for rangeIndex in range(numberRange): worksheet.write(columnIndex, rangeIndex, table[columnIndex][rangeIndex]) workbook.save(localPath) print("写入成功")
{"/OpFactory.py": ["/SpliteColumn.py", "/WriteExcel.py"], "/ReadExcel.py": ["/OpFactory.py"]}
24,047
ailling/webtest
refs/heads/master
/tests/compat.py
# -*- coding: utf-8 -*- import sys try: # py < 2.7 import unittest2 as unittest except ImportError: import unittest try: unicode() except NameError: u = str b = bytes else: def b(value): return str(value) def u(value): if isinstance(value, unicode): return value return unicode(value, 'utf-8') if sys.version_info[:1] < (2, 6): def assertIn(self, x, y, c=None): assert x in y unittest.TestCase.assertIn = assertIn
{"/tests/test_cookie.py": ["/tests/compat.py"]}
24,048
ailling/webtest
refs/heads/master
/tests/test_cookie.py
import webtest from webob import Request from tests.compat import unittest from webtest.compat import to_bytes def cookie_app(environ, start_response): req = Request(environ) status = "200 OK" body = '<html><body><a href="/go/">go</a></body></html>' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ] if req.path_info != '/go/': headers.extend([ ('Set-Cookie', 'spam=eggs'), ('Set-Cookie', 'foo="bar;baz"'), ]) start_response(status, headers) return [to_bytes(body)] def cookie_app2(environ, start_response): status = to_bytes("200 OK") body = '' headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ('Set-Cookie', 'spam=eggs'), ('Set-Cookie', 'foo="bar;baz"'), ] start_response(status, headers) return [to_bytes(body)] def cookie_app3(environ, start_response): status = to_bytes("200 OK") body = 'Cookie: %(HTTP_COOKIE)s' % environ headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(body))), ] start_response(status, headers) return [to_bytes(body)] class TestCookies(unittest.TestCase): def test_cookies(self): app = webtest.TestApp(cookie_app) self.assertTrue(not app.cookies, 'App should initially contain no cookies') app.get('/') cookies = app.cookies self.assert_(cookies, 'Response should have set cookies') self.assertEqual(cookies['spam'], 'eggs') self.assertEqual(cookies['foo'], 'bar;baz') def test_preserve_cookies(self): app = webtest.TestApp(cookie_app) res = app.get('/') self.assert_(app.cookies) res.click('go') self.assert_(app.cookies) def test_cookies2(self): app = webtest.TestApp(cookie_app) self.assertTrue(not app.cookies, 'App should initially contain no cookies') app.get('/') self.assert_(app.cookies, 'Response should have set cookies') self.assertIn(app.cookies['spam'], 'eggs') self.assertIn(app.cookies['foo'], 'bar;baz') def test_send_cookies(self): app = webtest.TestApp(cookie_app3) self.assertTrue(not app.cookies, 'App should initially contain no cookies') resp = app.get('/', headers=[('Cookie', 'spam=eggs')]) self.assertFalse(bool(app.cookies), 'Response should not have set cookies') resp.mustcontain('Cookie: spam=eggs')
{"/tests/test_cookie.py": ["/tests/compat.py"]}
24,050
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/urls.py
from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('users', views.UserViewSet) router.register('foods', views.FoodViewSet) app_name = "movies" # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('api/', include(router.urls)), path('api/search_food_api', views.search_food_api, name='search_food_api'), path('', views.index, name='index'), path('login/', views.login, name='login'), path('logout/', views.logout, name='logout'), path('search_food/', views.search_food, name='search_food'), path('validate_login/', views.validate_login, name='validate_login'), path('register/', views.register, name='register'), path('save_user/', views.save_user, name='save_user'), path('detail/<int:food_id>', views.detail, name='detail'), path('add_food/', views.add_food, name='add_food'), path('save_food', views.save_food, name='save_food'), path('delete/<int:food_id>', views.delete_food, name='delete_food'), path('edit/<int:food_id>', views.edit_food, name='edit_food'), path('update/<int:food_id>', views.update_food, name='update_food'), ]
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,051
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/admin.py
from django.contrib import admin from .models import Food, User admin.site.register(Food) admin.site.register(User)
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,052
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/migrations/0003_auto_20190628_1742.py
# Generated by Django 2.1.7 on 2019-06-28 12:12 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('myapp', '0002_food_user_id'), ] operations = [ migrations.RemoveField( model_name='user', name='birth_year', ), migrations.AddField( model_name='user', name='password', field=models.CharField(default=django.utils.timezone.now, max_length=255), preserve_default=False, ), ]
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,053
yashmahes/AppyHigh
refs/heads/master
/appyhigh/common/validations.py
import re from datetime import date from common.messages import PASSWORD_VALIDATE, EMAIL_EXIST_MESSAGE, EMAIL_NOT_EXIST_MESSAGE from django.forms.utils import ValidationError from myapp.models import User, Food def validate_password(password): if len(password) < 7: raise ValidationError(PASSWORD_VALIDATE) def validate_email(email): user = User.objects.filter(email=email.lower()) # user = db.user.find({'email': email.lower()}) if user.count() > 0: raise ValidationError(EMAIL_EXIST_MESSAGE) def validate_forgot_password_email(email): user = User.objects.filter(email=email.lower()) if user.count() == 0: raise ValidationError(EMAIL_NOT_EXIST_MESSAGE) def is_alphabate(value): if re.match('^[a-zA-Z ]*$', value): return True else: raise ValidationError("Please insert alphabets only") def check_dob(value): born = value today = date.today() if born >= today: raise ValidationError( "Ensure that birth date should be less than today's date") else: return True def validate_phone_number(phone_number): if len(phone_number) > 10 or len(phone_number) < 8: raise ValidationError( 'Make sure that phone number consist of either 8 or 10 digits')
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,054
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/views.py
from rest_framework import viewsets from .serializers import UserSerializer, FoodSerializer, RegisterSerializer, LoginSerializer from .models import User, Food from django.shortcuts import render, get_list_or_404, get_object_or_404, redirect from .forms import FoodForm, SearchFoodForm, LoginForm, RegisterForm from rest_framework.response import Response from rest_framework import status from rest_framework.decorators import api_view def login(request): form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def register(request): form = RegisterForm() return render(request, 'movies/register.html', {'form': form}) class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class FoodViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Food.objects.all() serializer_class = FoodSerializer def index(request): # movies = Movie.objects.all() # movies = Movie.objects.filter(release_year=1984) # movies = Movie.objects.get(id=1) if request.session.get('loggedin_user_id'): data = Food.objects.all() user_id = request.session.get('loggedin_user_id') user = User.objects.get(id=user_id) return render(request, 'movies/index.html', {'data': data, 'user': user}) else: form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def detail(request, food_id): if request.session.get('loggedin_user_id'): data = get_object_or_404(Food, id=food_id) return render(request, 'movies/detail.html', {'data': data}) else: form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def add_food(request): if request.session.get('loggedin_user_id'): form = FoodForm() return render(request, 'movies/add.html', {'form': form}) else: form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def save_food(request): if request.session.get('loggedin_user_id'): if request.method == 'POST': form = FoodForm(request.POST) if form.is_valid(): # form.save() a = Food() print(form.cleaned_data) a.name = form.cleaned_data['name'] a.carbohydrates_amount = form.cleaned_data['carbohydrates_amount'] a.fats_amount = form.cleaned_data['fats_amount'] a.proteins_amount = form.cleaned_data['proteins_amount'] a.user_id = request.session.get('loggedin_user_id') a.save() data = Food.objects.all() user_id = request.session.get('loggedin_user_id') user = User.objects.get(id=user_id) return render(request, 'movies/index.html', {'data': data, 'user': user}) else: form = FoodForm() return render(request, 'movies/add.html', {'form': form}) else: form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def edit_food(request, food_id): if request.session.get('loggedin_user_id'): data = Food.objects.get(id=food_id) return render(request, 'movies/edit.html', {'data': data}) else: form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def update_food(request, food_id): a = Food.objects.get(id=food_id) print(request.POST) form = FoodForm(request.POST) data = Food.objects.all() if form.is_valid(): print(form.cleaned_data) a.name = form.cleaned_data['name'] a.carbohydrates_amount = form.cleaned_data['carbohydrates_amount'] a.fats_amount = form.cleaned_data['fats_amount'] a.proteins_amount = form.cleaned_data['proteins_amount'] a.user_id = request.session.get('loggedin_user_id') a.save() data = Food.objects.all() user_id = request.session.get('loggedin_user_id') user = User.objects.get(id=user_id) return render(request, 'movies/index.html', {'data': data, 'user': user}) return render(request, 'movies/edit.html', {'data': data}) def delete_food(request, food_id): if request.session.get('loggedin_user_id'): m = get_object_or_404(Food, id=food_id) m.delete() data = Food.objects.all() user_id = request.session.get('loggedin_user_id') user = User.objects.get(id=user_id) return render(request, 'movies/index.html', {'data': data, 'user': user}) else: form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def logout(request): request.session['loggedin_user_id'] = None form = LoginForm() return render(request, 'movies/login.html', {'form': form}) def search_food(request): food_name = request.GET.get("fname") data = get_object_or_404(Food, name=food_name) return render(request, 'movies/detail.html', {'data': data}) @api_view(['GET']) def search_food_api(request): food_name = request.GET.get("fname") food_data = get_object_or_404(Food, name=food_name) serializer = FoodSerializer(data=food_data) response_object = {} response_object['name'] = food_data.name response_object['carbohydrates_amount'] = food_data.carbohydrates_amount response_object['fats_amount'] = food_data.fats_amount response_object['proteins_amount'] = food_data.proteins_amount return Response({'data': response_object}, status=status.HTTP_200_OK) def validate_login(request): form = LoginForm(request.POST) if form.is_valid(): print(form.cleaned_data) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = User.objects.filter(username=username, password=password) if user: request.session['loggedin_user_id'] = user[0].id data = Food.objects.all() user_id = request.session.get('loggedin_user_id') user = User.objects.get(id=user_id) return render(request, 'movies/index.html', {'data': data, 'user': user}) else: return render(request, 'movies/login.html', {'form': form}) return render(request, 'movies/login.html', {'form': form}) def register(request): form = RegisterForm() return render(request, 'movies/register.html', {'form': form}) def save_user(request): form = RegisterForm(request.POST) if form.is_valid(): print(form.cleaned_data) user = User() user.fullname = form.cleaned_data['fullname'] user.email = form.cleaned_data['email'] user.password = form.cleaned_data['password'] user.username = user.email user.save() form = LoginForm() return render(request, 'movies/login.html', {'form': form}) form = RegisterForm() return render(request, 'movies/register.html', {'form': form})
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,055
yashmahes/AppyHigh
refs/heads/master
/appyhigh/common/messages.py
REQUIRED = "This field is required" REGISTERED_SUCCESSFULLY = "Registered Successfully" EMAIL_VALID = "Please enter a valid email" PASSWORD_VALIDATE = "The password must be 7 to 12 characters long" EMAIL_EXIST_MESSAGE = "This email is already registered" INVALID_DETAIL = "Please provide valid credentials" ACCESS_TOKEN_EXPIRED = 'Your access token has been expired' REFRESH_TOKEN_EXPIRED = 'Your refresh token has been expired' EMAIL_NOT_EXIST_MESSAGE = 'This email does not exist'
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,056
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/models.py
from django.db import models # Create your models here. class Food(models.Model): name = models.CharField(max_length=255) carbohydrates_amount = models.IntegerField() fats_amount = models.IntegerField() proteins_amount = models.IntegerField() user_id = models.IntegerField() def __str__(self): return self.name class User(models.Model): fullname = models.CharField(max_length=255) email = models.EmailField() username = models.CharField(max_length=255) password = models.CharField(max_length=255) def __str__(self): return self.fullname
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,057
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/serializers.py
from rest_framework import serializers from common.messages import REQUIRED, EMAIL_VALID from common.validations import validate_password, validate_email, validate_forgot_password_email, validate_phone_number from django.contrib.auth.hashers import make_password from .models import User, Food class RegisterSerializer(serializers.Serializer): fullname = serializers.CharField( max_length=50, error_messages={'blank': REQUIRED}) email = serializers.EmailField(max_length=30, error_messages={'blank': REQUIRED, 'invalid': EMAIL_VALID}, validators=[validate_email]) password = serializers.CharField(max_length=12, error_messages={ 'blank': REQUIRED}, validators=[validate_password]) access_token = serializers.CharField(max_length=255, default="") def validate(self, attrs): attrs['email'] = attrs['email'].lower() return attrs class LoginSerializer(serializers.Serializer): email = serializers.EmailField( error_messages={'blank': REQUIRED, 'invalid': EMAIL_VALID}) password = serializers.CharField(max_length=12, error_messages={ 'blank': REQUIRED}, validators=[validate_password]) def validate(self, attrs): attrs['email'] = attrs['email'].lower() return attrs class ForgotPasswordSerializer(serializers.Serializer): email = serializers.EmailField(error_messages={ 'blank': REQUIRED, 'invalid': EMAIL_VALID}, validators=[validate_forgot_password_email]) class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('fullname', 'birth_year', 'email', 'username') class FoodSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Food fields = ('name', 'carbohydrates_amount', 'fats_amount', 'proteins_amount')
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,058
yashmahes/AppyHigh
refs/heads/master
/appyhigh/myapp/forms.py
from .models import Food from django import forms class FoodForm(forms.Form): name = forms.CharField(max_length=255) carbohydrates_amount = forms.IntegerField() fats_amount = forms.IntegerField() proteins_amount = forms.IntegerField() class SearchFoodForm(forms.Form): food_name = forms.CharField(max_length=100) class LoginForm(forms.Form): username = forms.CharField(max_length=100) password = forms.CharField(max_length=100) class RegisterForm(forms.Form): fullname = forms.CharField(max_length=255) email = forms.EmailField() password = forms.CharField(max_length=255)
{"/appyhigh/myapp/admin.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/views.py": ["/appyhigh/myapp/serializers.py", "/appyhigh/myapp/models.py", "/appyhigh/myapp/forms.py"], "/appyhigh/myapp/serializers.py": ["/appyhigh/myapp/models.py"], "/appyhigh/myapp/forms.py": ["/appyhigh/myapp/models.py"]}
24,062
nmtsylla/touba_fact
refs/heads/master
/blog/models.py
#-*-coding: utf-8-* from django.db import models from django.contrib.auth.models import User # Create your models here. class Profil(models.Model): user = models.OneToOneField(User) def __unicode__(self): return "Profil: {0}".format(self.user.username) class Categorie(models.Model): nom_categorie = models.CharField(max_length=20) def __unicode__(self): return u"%s" % self.nom_categorie class Article(models.Model): titre = models.CharField(max_length=100) auteur = models.CharField(max_length=42) contenu = models.TextField(null=True) source = models.CharField(max_length=50) date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de publication") categorie = models.ForeignKey(Categorie) def __unicode__(self): return u"%s" % self.titre
{"/blog/views.py": ["/blog/models.py", "/blog/forms.py"]}
24,063
nmtsylla/touba_fact
refs/heads/master
/blog/views.py
#-*-coding:utf-8-* # Create your views here. from django.shortcuts import render, get_object_or_404, HttpResponseRedirect, render_to_response from datetime import datetime from blog.models import Article from blog.forms import ContactForm, ArticleForm, LoginForm from django.contrib.auth import authenticate, login, logout from django.core.urlresolvers import reverse from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.template.context import RequestContext def homepage(request): return render(request, 'blog/homepage.html', {'current_date': datetime.now()}) def list_facts(request): articles = Article.objects.all() paginator = Paginator(articles, 10) page = request.GET.get('page') try: show_lines = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. show_lines = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. show_lines = paginator.page(paginator.num_pages) #return render(request, 'blog/facts.html', {'articles': articles}) return render_to_response('blog/facts.html', RequestContext(request, { 'articles': show_lines })) def view_fact(request, id_fact): article = get_object_or_404(Article, id=id_fact) return render(request, 'blog/fact.html', {'article': article}) def mouridisme(request): return render(request, 'blog/mouridisme.html') def about(request): pass def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): sujet = form.cleaned_data['sujet'] message = form.cleaned_data['message'] envoyeur = form.cleaned_data['envoyeur'] renvoi = form.cleaned_data['renvoi'] return HttpResponseRedirect('/blog/') else: form = ContactForm() return render(request, 'blog/contact.html', {'title': 'Contacter nous!', 'form': form}) def add(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): titre = form.cleaned_data['titre'] auteur = form.cleaned_data['auteur'] contenu = form.cleaned_data['contenu'] categorie = form.cleaned_data['categorie'] form.save() return HttpResponseRedirect('/blog/facts') else: form = ArticleForm() return render(request, 'blog/add_fact.html', {'title': 'Ajouter !', 'form': form}) def connexion(request): error = False if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user: login(request, user) else: error = True else: form = LoginForm() return render(request, 'blog/login.html', locals()) def deconnexion(request): logout(request) return redirect(reverse(connexion))
{"/blog/views.py": ["/blog/models.py", "/blog/forms.py"]}
24,064
nmtsylla/touba_fact
refs/heads/master
/blog/forms.py
#-*-coding:utf-8-* from django import forms from models import Article class ContactForm(forms.Form): sujet = forms.CharField(max_length=100, label="Sujet:", required=True) message = forms.CharField(widget=forms.Textarea, label="Message:", required=True) envoyeur = forms.EmailField(label="Votre adresse mail:", required=True) renvoi = forms.BooleanField(help_text="Cochez si vous souhaitez obtenir une copie du mail envoyé.", required=False) class ArticleForm(forms.ModelForm): class Meta: model = Article class LoginForm(forms.Form): username = forms.CharField(max_length=35, label='Username: ') password = forms.CharField(label='Password: ', widget=forms.PasswordInput)
{"/blog/views.py": ["/blog/models.py", "/blog/forms.py"]}
24,065
nmtsylla/touba_fact
refs/heads/master
/blog/urls.py
from django.conf.urls import patterns, url __author__ = 'nmtsylla' urlpatterns = patterns('blog.views', url(r'^$', 'homepage'), url(r'^login/$', 'connexion'), url(r'^logout/$', 'deconnexion'), url(r'^add_fact/$', 'add'), url(r'about/$', 'about'), url(r'mouridisme/$', 'mouridisme'), url(r'contact/$', 'contact'), url(r'fact/(?P<id_fact>\d+)$', 'view_fact'), url(r'facts/$', 'list_facts'), url(r'facts/(?P<year>\d{4})/(?P<month>\d{2})/$', 'list_facts'), )
{"/blog/views.py": ["/blog/models.py", "/blog/forms.py"]}
24,086
sumitsk/HER
refs/heads/master
/model.py
import torch.nn as nn import torch import torch.nn.functional as F def weights_init(m): classname = m.__class__.__name__ if classname.find('Conv') != -1 or classname.find('Linear') != -1: nn.init.xavier_normal_(m.weight.data) # nn.init.orthogonal_(m.weight.data) if m.bias is not None: m.bias.data.fill_(0) class Actor(nn.Module): def __init__(self, input_size, out_size, max_u=1.0): super().__init__() hidden_size = 256 self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, hidden_size) self.out = nn.Linear(hidden_size, out_size) self.max_u = max_u self.apply(weights_init) def forward(self, s): x = F.relu(self.fc1(s)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) return self.max_u * torch.tanh(self.out(x)) class Critic(nn.Module): def __init__(self, input_size): super().__init__() hidden_size = 256 self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, hidden_size) self.out = nn.Linear(hidden_size, 1) self.apply(weights_init) def forward(self, s, a): x = torch.cat([s,a], -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = F.relu(self.fc3(x)) return self.out(x)
{"/main.py": ["/utils.py", "/arguments.py", "/learner.py", "/policy.py"], "/policy.py": ["/model.py", "/replay_buffer.py", "/her.py", "/normalizer.py", "/utils.py"]}