index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
37,253
halliganbs/candida_project
refs/heads/main
/join.py
''' Joined on WELLID for experiment data and meta data 7000x files: Image_Metadata_WellID Stock_Plate7000x files: COORDINATE ''' import pandas as pd # data = pd.read_csv('data/70003.csv') # compounds = pd.read_csv('data/Stock_Plate70003.csv') # change WellID to be WellID # data_temp = data.rename(columns={'Image_Metadata_WellID': 'WellID'}) # compounds_temp = data.rename(columns={'COORDINATE' : 'WellID'}) # df = data_temp.join(compounds_temp) # df = data.join(compounds.set_index('COORDINATE'), on='Image_Metadata_WellID') # print(df['COMPOUND_NAME']) # for name in df['COMPOUND_NAME']: # if name == '\\s': # print('missing') # print(df.head()) # print("\n") # print(data.shape) # df.to_csv(path_or_buf='temp.csv', index=False) def join(meta, instrument, metaID='COORDINATE', instID='Image_Metadata_WellID'): data = pd.read_csv(instrument, sep='\t') compounds = pd.read_csv(meta) df = data.join(compounds.set_index(metaID), on=instID) return df # DATA_PATH = 'data/instrument/' # META_PATH = 'out/' # JOIN_PATH = 'joined/' # PLATE = '70012.csv' # joined = join(meta=META_PATH+'Stock_Plate'+PLATE, instrument=DATA_PATH+PLATE) # joined.to_csv(JOIN_PATH+PLATE, index=False)
{"/clean.py": ["/search.py", "/join.py", "/find.py"], "/data_explorer.py": ["/find.py", "/join.py"], "/find.py": ["/search.py"]}
37,254
halliganbs/candida_project
refs/heads/main
/find.py
''' Find missing compound names ''' import pandas as pd import numpy as np from progress.bar import Bar import requests from search import get_name # reads in csv, finds missing, returns both def find_missing(csv, col='COMPOUND_NAME'): df = pd.read_csv(csv) # df['COMPOUND_NAME'] = None missing = np.where(pd.isnull(df['COMPOUND_NAME'])) return df, missing # df, miss = find_missing('data/meta/Stock_Plate70010.csv') # cat_num = df.loc[miss,'CATALOG'] # bar = Bar("Getting Names", max=len(cat_num)) # names = [] # for c in cat_num: # names.append(get_name(c)) # bar.next() # bar.finish() # print(names)
{"/clean.py": ["/search.py", "/join.py", "/find.py"], "/data_explorer.py": ["/find.py", "/join.py"], "/find.py": ["/search.py"]}
37,255
Foxgeek36/web_frame_server
refs/heads/master
/app_dr/views_err.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/11/30 @Author : fls @Contact : fls@darkripples.com @Desc : darkripples总平台相关-通用异常func @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/11/30 10:20 fls 1.0 create """ from django.http import JsonResponse from jwt.exceptions import PyJWTError from ez_utils.models import ResModel400, ResModel404, ResModel500 from ez_utils import fls_log flog = fls_log(handler_name="") def handler_500(exception, req=None): """ 定义异常时的返回值 > 通过urls.py指定handler500的话,只需exception参数; > 通过中间件dr_middleware.py拦截到的异常,会有req信息 """ import traceback flog.log_error(traceback.format_exc()) print('>>>>>>handler_500>>>>>>>', exception, "|", type(exception)) # 默认返回值Response ret = ResModel500() if isinstance(exception, PyJWTError): # jwt校验token无效,不在具体区分详细的异常类型了 ret.code = ret.ResCode.need_login ret.msg = "TOKEN无效" return JsonResponse(ret.to_dic()) def handler_400(request, exception): """ 定义400状态的返回值 """ ret = ResModel400() print('>>>>>>>>>>>handler_400') return JsonResponse(ret.to_dic()) def handler_404(request, exception): """ 定义404状态的返回值 """ ret = ResModel404() print('>>>>>>>>>>>handler_404') return JsonResponse(ret.to_dic())
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,256
Foxgeek36/web_frame_server
refs/heads/master
/conf/__init__.py
from .configs_dev import * #from .configs import *
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,257
Foxgeek36/web_frame_server
refs/heads/master
/app_dr/views.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/09/02 @Author : fls @Contact : fls@darkripples.com @Desc : darkripples总平台相关-通用views @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/09/02 11:41 fls 1.0 create 2019/11/22 10:27 fls 1.1 加入djangorestframework-jwt相关,并初始化测试代码 2019/11/29 15:51 fls 2.0 去除测试代码,增加通用文件上传api """ from django.http import JsonResponse from ez_utils.models import ResModel def index(req): """ 2017/05/29 fls frist coming """ ret = ResModel() ret.msg = '欢迎dr' ret.code = ret.ResCode.succ return JsonResponse(ret.to_dic())
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,258
Foxgeek36/web_frame_server
refs/heads/master
/app_dr/migrations/0001_initial.py
# Generated by Django 2.2.1 on 2019-11-11 05:42 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='DrVisitorInfo', fields=[ ('id', models.CharField(db_column='id', max_length=40, primary_key=True, serialize=False, verbose_name='id')), ('add_time', models.DateTimeField(blank=True, null=True, verbose_name='添加时间')), ('app_name', models.CharField(blank=True, max_length=40, verbose_name='子系统模块名')), ('visitor_type', models.CharField(blank=True, choices=[('read', '阅读')], max_length=10, verbose_name='访客类型')), ('link_id', models.CharField(blank=True, max_length=40, verbose_name='关联id')), ('visitor_ip', models.CharField(blank=True, max_length=20, verbose_name='访问者ip')), ('visitor_lat', models.CharField(blank=True, max_length=30, verbose_name='访问者纬度')), ('visitor_lng', models.CharField(blank=True, max_length=30, verbose_name='访问者经度')), ('visitor_city', models.CharField(blank=True, max_length=30, verbose_name='访问者城市')), ('visitor_addr', models.TextField(blank=True, null=True, verbose_name='访问者位置描述')), ('cnt_ipstack', models.IntegerField(default=0, verbose_name='解析次数_ipstack')), ], options={ 'db_table': 'dr_visitor_info', }, ), ]
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,259
Foxgeek36/web_frame_server
refs/heads/master
/app_blog/views.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/8/30 @Author : fls @Contact : fls@darkripples.com @Desc : blog相关 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/8/30 14:53 fls 1.0 create """ import traceback from django.http import JsonResponse from django.views.decorators.http import require_GET from django.apps import apps from ez_utils.models import ResPageModel, ResModel from ez_utils import connection, get_ip from ez_utils import fls_log flog = fls_log(handler_name="app_blog.views") from .models import SQL_DIC_TYPE, SQL_DIC_BLOG, SQL_DIC_PARAM from app_dr.dr_utils import add_visitor, req_invalid_check from conf import PAGE_DEFAULT_LIMIT, SET_TITLE_CMD @require_GET def indexList(req): """ 2019/08/30 fls 查询blog列表 :param req: request :return: """ ret = ResPageModel() ret.msg = req_invalid_check(req) if ret.msg: # 请求合法性校验不通过 ret.code = ret.ResCode.fail ret.data = [] return JsonResponse(ret.to_dic()) blog_type = req.GET.get('type', '') ret.page = req.GET.get('page', '1') ret.limit = req.GET.get('limit', PAGE_DEFAULT_LIMIT) # todo 权限level的控制 # 采用源生sql,方便where条件和分页,后期计划加入用户表的关联查询 sql = "select a.{table1_id},a.{table1_title},b.{table2_type_name},a.{table1_tags},a.{table1_notes},a.{table1_aname}," \ "to_char(a.{table1_atime}, 'yyyy-mm-dd hh24:mi:ss') as {table1_atime}, a.{table1_rlevel},a.{table1_rcnt} " \ "from {table1} a, {table2} b where a.{table1_type_id}=b.{table2_type_id} and a.{table1_rcnt}>=0".format( **SQL_DIC_BLOG) sql_count = "select count(1) as cnt " \ "from {table1} a, {table2} b where a.{table1_type_id}=b.{table2_type_id} and {table1_rcnt}>=0".format( **SQL_DIC_BLOG) # 查询条件 par_dic = {} if blog_type: # 类型 sql += " and a.{table1_type_id}=%(blog_type)s".format(**SQL_DIC_BLOG) sql_count += " and a.{table1_type_id}=%(blog_type)s".format(**SQL_DIC_BLOG) par_dic['blog_type'] = blog_type # 排序 sql += " order by a.{table1_atime} desc ".format(**SQL_DIC_BLOG) with connection() as con: rs = con.execute_sql(sql_count, par_dic) ret.rsCount = rs[0].cnt # dicorobj需为dict ret.data = con.execute_sql(sql, par_dic, dicorobj="dict", page=ret.page, limit=ret.limit) ret.code = ret.ResCode.succ return JsonResponse(ret.to_dic()) @require_GET def contentDetail(req, id): """ 查询blog明细 :param req: request :param id: id :return: """ ret = ResModel() ret.msg = req_invalid_check(req) # 浏览者信息 v_cnt = 0 try: ip = get_ip(req) v_cnt = add_visitor(ip, apps.get_app_config('app_blog').name, 'read', id) except: flog.log_error("记录访客信息失败:%s", traceback.format_exc()) if ret.msg: # 请求合法性校验不通过 ret.code = ret.ResCode.fail ret.data = {} return JsonResponse(ret.to_dic()) ret.code = ret.ResCode.succ # todo 权限level的控制 # 为了统一,驼峰命名,采用原生sql with connection() as con: rs = con.execute_sql( "select {table1_id},{table1_title},{table1_content},{table1_rcnt}," \ "to_char({table1_atime}, 'yyyy-mm-dd hh24:mi:ss') as {table1_atime},{table1_notes},{table1_bgurl},{table1_rlevel} " \ "from {table1} where {table1_id}=%(id)s and {table1_rcnt}>=0".format(**SQL_DIC_BLOG), {"id": id}, dicorobj="dict") if rs: ret.data = rs[0] if v_cnt == 1: con.execute_sql( "update {table1} set {table1_rcnt}={table1_rcnt}+1 where {table1_id}=%(id)s".format(**SQL_DIC_BLOG), {"id": id}) else: ret.data = {} return JsonResponse(ret.to_dic()) @require_GET def typeList(req): """ 查询blog类别 :param req: request :return: """ ret = ResModel() ret.msg = req_invalid_check(req) if ret.msg: # 请求合法性校验不通过 ret.code = ret.ResCode.fail ret.data = [] return JsonResponse(ret.to_dic()) ret.code = ret.ResCode.succ with connection() as con: ret.data = con.execute_sql( "select {table2_type_id}, {table2_type_name} " "from {table2} order by convert_to({table2_type_name} , 'GB18030') asc".format(**SQL_DIC_TYPE), dicorobj="dict") return JsonResponse(ret.to_dic()) @require_GET def titleValue(req): """ 查询副标题参数 :param req: request :return: """ ret = ResModel() ret.msg = req_invalid_check(req) if ret.msg: # 请求合法性校验不通过 ret.code = ret.ResCode.fail ret.data = {} return JsonResponse(ret.to_dic()) ret.code = ret.ResCode.succ with connection() as con: rs = con.execute_sql("select {table1_value} from {table1} where {table1_code}=%(p)s ".format(**SQL_DIC_PARAM), {'p': SET_TITLE_CMD}, dicorobj="dict") ret.data = rs[0] if rs else {} return JsonResponse(ret.to_dic())
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,260
Foxgeek36/web_frame_server
refs/heads/master
/app_blog/migrations/0001_initial.py
# Generated by Django 2.2.1 on 2019-11-11 05:42 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='BlogContent', fields=[ ('id', models.CharField(db_column='id', max_length=40, primary_key=True, serialize=False, verbose_name='id')), ('title', models.CharField(blank=True, db_column='title', db_index=True, max_length=50, verbose_name='标题')), ('title_notes', models.CharField(blank=True, max_length=100, null=True, verbose_name='摘要描述')), ('blog_type', models.CharField(blank=True, db_index=True, max_length=2, verbose_name='类别')), ('blog_tags', models.TextField(blank=True, db_index=True, verbose_name='标签')), ('content', models.TextField(blank=True, verbose_name='内容')), ('read_level', models.IntegerField(default=0, verbose_name='阅读级别')), ('read_cnt', models.IntegerField(default=0, verbose_name='阅读量')), ('bg_url', models.TextField(blank=True, null=True, verbose_name='背景图')), ('auth_account', models.CharField(blank=True, max_length=50, verbose_name='作者用户名')), ('auth_name', models.CharField(blank=True, max_length=50, verbose_name='作者姓名')), ('add_time', models.DateTimeField(blank=True, null=True, verbose_name='添加时间')), ('upd_time', models.DateTimeField(blank=True, null=True, verbose_name='修改时间')), ], options={ 'db_table': 'blog_content', }, ), migrations.CreateModel( name='BlogParam', fields=[ ('param_code', models.CharField(db_column='param_code', max_length=30, primary_key=True, serialize=False, verbose_name='code')), ('param_name', models.TextField(blank=True, verbose_name='名称')), ('param_value', models.TextField(blank=True, null=True, verbose_name='参数值')), ('param_notes', models.TextField(blank=True, null=True, verbose_name='备注')), ], options={ 'db_table': 'blog_param', }, ), migrations.CreateModel( name='BlogType', fields=[ ('type_id', models.CharField(db_column='type_id', max_length=2, primary_key=True, serialize=False, verbose_name='type_id')), ('type_name', models.CharField(blank=True, choices=[('fx', '分享'), ('zz', '转载'), ('bj', '笔记'), ('gw', '感悟')], db_index=True, max_length=10, verbose_name='类别')), ], options={ 'db_table': 'blog_type', }, ), ]
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,261
Foxgeek36/web_frame_server
refs/heads/master
/app_blog/urls.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/8/30 @Author : fls @Contact : fls@darkripples.com @Desc : blog相关 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/8/30 14:53 fls 1.0 create """ from django.urls import path from .views import indexList, contentDetail, typeList, titleValue from django.apps import apps # 不可删除 app_name = apps.get_app_config('app_blog').name urlpatterns = [ path(r'indexList/', indexList), path(r'contentDetail/<str:id>', contentDetail), path(r'typeList/', typeList), path(r'titleValue/', titleValue), ]
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,262
Foxgeek36/web_frame_server
refs/heads/master
/app_dr/dr_utils.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/09/15 @Author : fls @Contact : fls@darkripples.com @Desc : darkripples总平台相关-应用内utils @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/09/15 08:43 fls 1.0 create """ import re import uuid from django.conf import settings from django.utils import timezone from conf import REQ_HEADER_PWD from ez_utils import connection, after_seconds, is_internal_ip, get_ip, fls_log from .models import SQL_DIC_VISITOR, DrVisitorInfo flog = fls_log(handler_name="app_dr.dr_utils") def add_visitor(ip, app_type, visitor_type, link_id): """ 添加到访客记录 :param ip: 同ip,5分钟内,只记录一次 :param app_type: :param visitor_type: :param link_id: 关联的id,可以不关联到业务表,用于记录访客随便输入的id :return: """ with connection() as con: rs = con.execute_sql( "SELECT count(1) as cnt FROM {table1} " \ "WHERE {table1_ip} = %(ip)s and {table1_atime}>=%(time)s and {table1_linkid}=%(link_id)s".format( **SQL_DIC_VISITOR), {'ip': ip, 'time': after_seconds(seconds=-1 * 5 * 60), 'link_id': link_id}) if not rs or rs[0].cnt == 0: # 若登记过该ip,则获取它的信息 cnt_ipstack = 0 visitor_lat = '' visitor_lng = '' if is_internal_ip(ip) or '127.0.0.1' == ip: # 内网ip,免解析 cnt_ipstack = -1 else: rs_over = con.execute_sql( "SELECT {table1_lat},{table1_lng} FROM {table1} " \ "WHERE {table1_ip} = %(ip)s and {table1_lat} is not null and {table1_lat}!='' limit 1".format( **SQL_DIC_VISITOR), {'ip': ip}, hump=False) if rs_over and rs_over[0]: cnt_ipstack = -1 visitor_lat = rs_over[0][SQL_DIC_VISITOR["table1_lat"]] visitor_lng = rs_over[0][SQL_DIC_VISITOR["table1_lng"]] # 登记信息 DrVisitorInfo.objects.create(id=str(uuid.uuid1()).replace('-', ''), visitor_ip=ip, add_time=timezone.now(), app_name=app_type, visitor_type=visitor_type, link_id=link_id, cnt_ipstack=cnt_ipstack, visitor_lat=visitor_lat, visitor_lng=visitor_lng) return 1 return 0 def req_invalid_check(req): """ request合法性校验 :param req: :return: 校验通过return '',否则return错误信息 """ flag = "" if req.META.get("HTTP_DR_DEBUG") == REQ_HEADER_PWD: # 测试时,传递该密参,不进行校验 return flag # 其他情况,校验header中的参数 ip = get_ip(req) if req.META.get("HTTP_TOKEN") is None: flag = 1 allowed_hosts = settings.ALLOWED_HOSTS referer_rule = r'//(.*?)/' referer_rs = re.findall(referer_rule, req.META.get("HTTP_REFERER", "")) if (not referer_rs) or (referer_rs[0] not in allowed_hosts): flag = 1 # origin_rs = req.META.get("HTTP_ORIGIN", "").split("//") # if (len(origin_rs) < 2) or (origin_rs[1] not in allowed_hosts): # flag = 1 if flag: flag = f"当前客户端外网IP:{ip}.请斟酌调取本接口" return flag
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,263
Foxgeek36/web_frame_server
refs/heads/master
/conf/configs_dev.py
# coding:utf8 # todo 需自己设置***的参数 HOST = '***' PORT = 5432 USER = '***' PWD = '***' DBNAME = '***' DB_TYPE = 'postgresql' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': DBNAME, # Or path to database file if using sqlite3. 'USER': USER, # Not used with sqlite3. 'PASSWORD': PWD, # Not used with sqlite3. 'HOST': HOST, # Set to empty string for localhost. Not used with sqlite3. 'PORT': PORT, # Set to empty string for default. Not used with sqlite3. } } SET_TITLE_CMD = "***" # redis REDIS_PWD = '***' REDIS_PORT = 6379 # Email设置 EMAIL_HOST_USER = '***@darkripples.com' # 我的邮箱帐号 EMAIL_HOST_PASSWORD = '***' # 授权码 # 分页相关 PAGE_DEFAULT_LIMIT = 10 # 每页条数 # 防爬处理.header校验码.DR-DEBUG=校验码才行 REQ_HEADER_PWD = '***'
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,264
Foxgeek36/web_frame_server
refs/heads/master
/darkripples/settings.py
# coding:utf8 """ Django settings for darkripples project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os, sys # Build paths inside the project like this: os.path.join(BASE_DIR, ...) # web root BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # now root BASEPATH = os.path.split(__file__)[0] STATICPATH = os.path.join(BASE_DIR, 'static') CACHE_DIR = os.path.join(BASE_DIR, 'tmp') LOGS_DIR = os.path.join(BASE_DIR, 'logs') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ao)k*rjqle#h)@1w1-so%-jbxs4*u7lw(&*ex(k)3b+nwo@6n1' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # because of Nginx,so,this settings may be CAN'T WORK ALLOWED_HOSTS = ['127.0.0.1', '192.168.0.105', 'www.darkripples.com', 'localhost'] # 设置请求是否允许携带Cookie,必须和xhrFields: {withCredentials: true,}同时使用 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True # 允许所有的请求头 from corsheaders.defaults import default_headers # 跨域相关配置 CORS_ALLOW_HEADERS = list(default_headers) + [ 'Token', 'Content-Type' ] # 跨域源的白名单,需要跨域的源设置在这里 # CORS_ORIGIN_WHITELIST = ['*'] # 指定哪些方法可以发送跨域请求 CORS_ALLOW_METHODS = ('DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # django-cors-headers 跨域相关 'corsheaders', 'app_blog', 'app_dr', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # 跨域:注意顺序,必须放在CommonMiddleware之上 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] MIDDLEWARE += [ # 自定义的中间件.必须放在最后 'darkripples.middleware.dr_middleware.DRMiddleware', ] ROOT_URLCONF = 'darkripples.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(STATICPATH, 'tmpl')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'darkripples.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ TIME_ZONE = 'Asia/Shanghai' LANGUAGE_CODE = 'zh_Hans' LANGUAGE_CODE = 'zh-hans' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(BASE_DIR, 'static'), ) # 设置项是否开启URL访问地址后面不为/跳转至带有/的路径 APPEND_SLASH = True # 定时任务crontab的字符集 CRONTAB_COMMAND_PREFIX = 'LANG_ALL=zh_cn.UTF-8' sys.path.insert(0, os.path.join(BASEPATH)) from conf import DATABASES
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,265
Foxgeek36/web_frame_server
refs/heads/master
/app_dr/urls.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/09/02 @Author : fls @Contact : fls@darkripples.com @Desc : darkripples总平台相关 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/09/02 11:41 fls 1.0 create """ from django.urls import path from django.apps import apps from .views import index # 不可删除 app_name = apps.get_app_config('app_dr').name urlpatterns = [ path(r'index/', index), ]
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,266
Foxgeek36/web_frame_server
refs/heads/master
/darkripples/middleware/dr_middleware.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/11/15 @Author : fls @Contact : fls@darkripples.com @Desc : darkripples-中间件 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/11/15 14:24 fls 1.0 create """ import traceback from jwt.exceptions import PyJWTError from django.utils.deprecation import MiddlewareMixin from django.http import JsonResponse from django.apps import apps from ez_utils import fls_log, match_url from ez_utils.models import ResModel flog = fls_log(handler_name="") def check_token(req_token): """ 校验token :param req_token: :return: """ if not req_token: ret = ResModel() ret.code = ret.ResCode.need_login ret.msg = "" return JsonResponse(ret.to_dic()) from rest_framework_jwt.settings import api_settings jwt_decode_handler = api_settings.JWT_DECODE_HANDLER try: # {'user_id': 'a', 'username': 'fls',} jwt_decode_handler(req_token) except: ret = ResModel() ret.code = ret.ResCode.need_login ret.msg = "无效的token" return JsonResponse(ret.to_dic()) return None class DRMiddleware(MiddlewareMixin): """ 中间件类 """ def process_request(self, request): """ 请求前调用,不可return :param request: """ print('>>>>process_request>>>>>>') # request.META['DR_PAR1'] = 9 # 请求路径.如/app_dr/index/ fpath = request.get_full_path() need_check_token = False for c in apps.get_app_configs(): if not c.name.startswith('app_'): continue if 'check_token_url_list' not in dir(c): continue for check_u in c.check_token_url_list: # todo 匹配方式需再详尽测试 if match_url(fpath, check_u): need_check_token = True break if need_check_token: # 校验token req_token = request.META.get('HTTP_TOKEN') ret_check = check_token(req_token) if ret_check is not None: return ret_check def process_response(self, request, response): """ view处理后调用,必须return 若有process_exception,则走完异常处理后再来到此处 :param request: :param response: :return: """ return response def process_exception(self, request, exception): """ 视图函数发生异常时调用 :param request: :param exception: :return: """ flog.log_error(traceback.format_exc()) print('>>>>>>process_exception>>>>>>>', exception, "|", type(exception)) # 默认返回值Response ret = ResModel() ret.code = ret.ResCode.err ret.msg = "系统应用异常" if isinstance(exception, PyJWTError): # jwt校验token无效,不在具体区分详细的异常类型了 ret.code = ret.ResCode.need_login ret.msg = "TOKEN无效" return JsonResponse(ret.to_dic())
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,267
Foxgeek36/web_frame_server
refs/heads/master
/ez_utils/file_utils.py
#!/usr/bin/env python # coding:utf8 """ @Time : 2019/5/18 @Author : fls @Contact : fls@darkripples.com @Desc : fls易用性utils-文件相关utils @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 2019/5/18 11:41 fls 1.0 create """ import base64 import glob import os def read_in_chunks(file_path: str, chunk_size=1024 * 1024): """ Lazy function (generator) to read a file piece by piece. """ file_object = open(file_path, 'rb') while True: chunk_data = file_object.read(chunk_size) if not chunk_data: break yield chunk_data def walk_dir(file_path: str, include_dir=True): """ loop dir """ ret = [] for root, dirs, files in os.walk(file_path, topdown=True): for name in files: # 文件 ret.append(os.path.join(root, name)) if include_dir: for name in dirs: # 文件夹 ret.append(os.path.join(root, name)) return ret def glob_dir(file_path: str): """ loop file """ return glob.glob(file_path) def save_img_base64(file_path: str, img_64: str): """ base64字符串保存为图片 :param file_path: 图片保存的完整路径 :param img_64: :return: """ imagedata = base64.b64decode(img_64) file = open(file_path, "wb") file.write(imagedata) file.close() def help(num='①'): print(num + "关于文件操作") print("\t" + read_in_chunks.__doc__)
{"/conf/__init__.py": ["/conf/configs_dev.py"], "/app_blog/views.py": ["/app_dr/dr_utils.py", "/conf/__init__.py"], "/app_blog/urls.py": ["/app_blog/views.py"], "/app_dr/dr_utils.py": ["/conf/__init__.py"], "/darkripples/settings.py": ["/conf/__init__.py"], "/app_dr/urls.py": ["/app_dr/views.py"]}
37,277
daisySSSS/basic_algo
refs/heads/master
/test_binary_search.py
from binary_search import BinarySearchTree bst = BinarySearchTree() bst.insert(4) bst.insert(7) bst.insert(6) bst.insert(3) bst.insert(5) bst.insert(2) print('The binary search tree is:') bst.print_tree() print('The maximum value in the tree is:') print(bst.max().val) print('The minimum value in the tree is:') print(bst.min().val) print('The successor of 3 is:') print(bst.successor(bst.search(3)).val) print('The successor of 4 is:') print(bst.successor(bst.search(4)).val) bst.delete(bst.search(4)) print('The successor of 3 after deleting 4 is:') print(bst.successor(bst.search(3)).val)
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,278
daisySSSS/basic_algo
refs/heads/master
/sort.py
INF = 1E4 class Sort: def _exchange(self, nums, i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp def _partition(self, nums, start, end): x = nums[end] # pivot i = start - 1 j = start - 1 for v in nums[start:end]: j += 1 # points to the current num if v <= x: i += 1 # points to the last checked num that is smaller or equal to the pivot self._exchange(nums, i, j) i += 1 self._exchange(nums, i, end) return i def quick_sort(self, nums, start, end): # worst case time complexity O(n^2) # best case time complexity O(nlogn) if start < end: q = self._partition(nums, start, end) self.quick_sort(nums, start, q-1) self.quick_sort(nums, q+1, end) def _max_heapify(self, nums, i): # time complexity O(logn) left = 2*i + 1 right = 2*(i + 1) largest = i if left < self._heap_size and nums[left] > nums[i]: largest = left if right < self._heap_size and nums[right] > nums[largest]: largest = right if largest != i: self._exchange(nums, i, largest) self._max_heapify(nums, largest) def _build_heap(self, nums): # time complexity O(n) self._heap_size = len(nums) for i in reversed(range(int(len(nums)/2.))): self._max_heapify(nums, i) def heap_sort(self, nums): # time complexity: O(nlogn) # Space complexity: O(1) # sort inplace self._build_heap(nums) for i in reversed(range(1, len(nums))): self._exchange(nums, i, 0) self._heap_size -= 1 self._max_heapify(nums, 0) def priority_queue_increase_key(self, nums, i, key): if key <= nums[i]: return False else: nums[i] = key parent = int((i-1)/2.) while i and nums[parent] < nums[i]: self._exchange(nums, parent, i) i = parent parent = int((i-1)/2.) def priority_queue_heap_extract_maximum(self, nums): if self._heap_size < 1: return False max_heap = nums[0] nums[0] = nums[self._heap_size-1] self._heap_size -= 1 self._max_heapify(nums, 0) return max_heap def priority_queue_heap_max(self, nums): if self._heap_size < 1: return False return nums.pop(0) def priority_queue_insert(self, nums, key): self._heap_size += 1 nums.append(-INF) self.priority_queue_increase_key(nums, self._heap_size-1, key) def count_sort(self, nums): mi = min([x[0] for x in nums]) ma = max([x[0] for x in nums]) cnt = dict() for i in range(mi, ma+1): cnt[i] = 0 for i in nums: cnt[i[0]] += 1 prv = -1 for i in range(mi, ma+1): cnt[i] += prv prv = cnt[i] lnums = len(nums) result = [None]*lnums attached = [None]*lnums for v in reversed(nums): result[cnt[v[0]]] = v[0] attached[cnt[v[0]]] = v[1] cnt[v[0]] -= 1 return result, attached def _split(self, num): return [int(i) for i in str(num)] def radix_sort(self, nums): splited_num = [self._split(num) for num in nums] cnt_num = [len(x) for x in splited_num] max_cnt = max(cnt_num) splited_num = [[0]*(max_cnt-len(x))+x for x in splited_num] cnt = max_cnt-1 idx = list(range(len(nums))) while cnt >= 0: num_to_sort = [(splited_num[i][cnt], i) for i in idx] _, idx = self.count_sort(num_to_sort) cnt -= 1 return [nums[i] for i in idx] # def bucket_sort(self, nums): # def bubble_sort(): # def insertion_sort():
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,279
daisySSSS/basic_algo
refs/heads/master
/test_graph.py
from graph import Graph import logging print('='*15) print('Initializing Graph') g = Graph() g.print_graph() print('='*15) print('Adding Edges to Graph') g.add_edge(0, 1, 1) g.add_edge(0, 2, 3) g.add_edge(2, 4, 7) g.add_edge(4, 5, 1) g.add_edge(5, 3, 1) g.add_edge(1, 3, 7) g.add_edge(1, 6, 6) g.add_edge(6, 3, 2) g.add_edge(1, 0, 3) g.add_edge(4, 1, 5) g.print_graph() print('='*15) bfs_order = g.bfs(0) print('BFS search') print(bfs_order) print('='*15) topological_sort, dfs_order = g.dfs() print('DFS search') print(dfs_order) print('DAG? %d' % g.dag) if g.dag: print('Topological sort') print(topological_sort) print('='*15) g.shortest_path_bellman_ford(0) print('='*15) g.shortest_path_dijkstra(0) print('='*15) g.strongly_connected_component() print('='*15) print('Initializing Graph') g = Graph(undirected=1) print('='*15) print('Adding Edges to Graph') g.add_edge(0, 1, 1) g.add_edge(0, 2, 3) g.add_edge(2, 4, 7) g.add_edge(4, 5, 1) g.add_edge(5, 3, 1) g.add_edge(1, 3, 7) g.add_edge(1, 6, 6) g.add_edge(6, 3, 2) print('='*15) mst_parent, total_weight = g.mst_prim() print('Minimum spanning tree with Prim algorithm') print(mst_parent) print('Total weight: %d' % total_weight) print('='*15) mst_parent, total_weight = g.mst_kruskal() print('Minimum spanning tree with Kruskal algorithm') print(mst_parent) print('Total weight: %d' % total_weight)
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,280
daisySSSS/basic_algo
refs/heads/master
/red_black_tree.py
from binary_search_tree import BinarySearchTree class RedBlackTreeNode(): def __init__(self, val = None, left = None, right = None, parent = None, color = 'black'): self.val = val self.left = left self.right = right self.parent = parent self.color = color def is_redblacktree(x): if not x: return True if x.root.color != 'black': print('property 2 not satisfied. (root not black)') return False stack = [[x.root, 1]] black_height_list = [] while stack: node, black_height = stack.pop() if node.val == None: if node.color == 'black': black_height_list.append(black_height) else: print('property 3 not satisfied. (leaf not black.)') return False else: if node.color not in ['red', 'black']: print('property 1 not satisfied. (only red and black allowed)') return False if node.color=='red': if node.left and node.left.color != 'black': print('property 4 not satisfied. (red parent has black children)') return False if node.right and node.right.color != 'black': print('property 4 not satisfied. (red parent has black children)') return False if node.left: if node.left.color == 'black': stack.append([node.left, black_height+1]) else: stack.append([node.left, black_height]) if node.right: if node.right.color == 'black': stack.append([node.right, black_height+1]) else: stack.append([node.right, black_height]) if not node.left and not node.right: print('property 3 not satisfied. (leaf not black.)') return False if len(set(black_height_list))!=1: print(black_height_list) print('property 5 not satisfied. (equal black height for all branches)') return False return True def is_equal_tree(x,y): if not x and not y: return True elif (x and not y) or (y and not x): return False stack_x = [x] stack_y = [y] flag = 0 while stack_x and stack_y: x = stack_x.pop() y = stack_y.pop() if x.val != y.val: flag = 1 break if x.right and y.right: stack_x.append(x.right) stack_y.append(y.right) elif (x.right and not y.right) or (not x.right and y.right): flag = 1 break if x.left and y.left: stack_x.append(x.left) stack_y.append(y.left) elif (x.left and not y.left) or (not x.left and y.left): flag = 1 break if flag: return False else: return True class RedBlackTree(BinarySearchTree): def __init__(self, root=None): self.root = root self.nil = RedBlackTreeNode() self.root.parent = self.nil def _left_rotate(self, x): y = x.right x.right = y.left if is_equal_tree(y.left,self.nil): y.left.parent = x y.parent = x.parent if is_equal_tree(x.parent,self.nil): self.root = y elif is_equal_tree(x,x.parent.left): x.parent.left = y else: is_equal_tree(x.parent.right,y) y.left = x x.parent = y def _right_rotate(self, x): y = x.left x.left = y.right if y.right != self.nil: y.right.parent = x y.parent = x.parent if x.parent == self.nil: self.root = y elif x == x.parent.left: x.parent.left = y else: x.parent.right = y y.right = x x.parent = y return y def _insert_fixup(self, z): while z.parent.color == 'red': if z.parent == z.parent.parent.left: y = z.parent.parent.right if y.color == 'red': z.parent.color = 'black' y.color = 'black' z.parent.parent.color = 'red' z = z.parent.parent elif z == z.parent.right: z = z.parent self._left_rotate(z) else: z.parent.color = 'black' z.parent.parent.color = 'red' self._right_rotate(z.parent.parent) else: y = z.parent.parent.left if y.color == 'red': z.parent.color = 'black' y.color = 'black' z.parent.parent.color = 'red' z = z.parent.parent elif z == z.parent.left: z = z.parent self._right_rotate(z) else: z.parent.color = 'black' z.parent.parent.color = 'red' self._left_rotate(z.parent.parent) def insert(self, z): x = self.root y = self.nil while not is_equal_tree(x,self.nil): y = x if z.val < x.val: x = x.left else: x = x.right if is_equal_tree(y,self.nil): self.root = z elif z.val < y.val: y.left = z else: y.right = z z.left = self.nil z.right = self.nil z.color = 'red' z.parent = y self._insert_fixup(z)
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,281
daisySSSS/basic_algo
refs/heads/master
/test_RedBlackTree.py
import pytest from red_black_tree import RedBlackTreeNode, RedBlackTree, is_equal_tree, is_redblacktree def getTree1(): # Tree 1 # 1 # / \ # 0 3 # / \ # 2 4 x = RedBlackTreeNode(val=1) y = RedBlackTreeNode(val=3, color='red') x.left = RedBlackTreeNode(val=0) x.left.left = RedBlackTreeNode() x.left.right = RedBlackTreeNode() x.right = y y.parent = x y.left = RedBlackTreeNode(val=2) y.right = RedBlackTreeNode(val=4) y.left.left = RedBlackTreeNode() y.left.right = RedBlackTreeNode() y.right.left = RedBlackTreeNode() y.right.right = RedBlackTreeNode() tree = RedBlackTree(root=x) return tree def getTree2(): # Tree2 # 3 # / \ # 1 4 # / \ # 0 2 x = RedBlackTreeNode(val=1, color='red') y = RedBlackTreeNode(val=3) x.left = RedBlackTreeNode(val=0) x.right = RedBlackTreeNode(val=2) x.left.left = RedBlackTreeNode() x.left.right = RedBlackTreeNode() x.right.left = RedBlackTreeNode() x.right.right = RedBlackTreeNode() y.right = RedBlackTreeNode(val=4) y.right.left = RedBlackTreeNode() y.right.right = RedBlackTreeNode() y.left = x x.parent = y tree = RedBlackTree(root=y) return tree def getTree3(): # Tree3 # 5 # / # 1 # / \ # 0 3 # / \ # 2 4 root = RedBlackTreeNode(val = 5) x = RedBlackTreeNode(val=1) y = RedBlackTreeNode(val=3, color='red') root.left = x x.parent = root x.left = RedBlackTreeNode(val=0) x.left.left = RedBlackTreeNode() x.left.right = RedBlackTreeNode() x.right = y y.parent = x y.left = RedBlackTreeNode(val=2) y.left.left = RedBlackTreeNode() y.left.right = RedBlackTreeNode() y.right = RedBlackTreeNode(val=4) y.right.left = RedBlackTreeNode() y.right.right = RedBlackTreeNode() tree = RedBlackTree(root=root) return tree def getTree4(): # Tree4 # 5 # / # 3 # / \ # 1 4 # / \ # 0 2 root = RedBlackTreeNode(val=5) x = RedBlackTreeNode(val=1,color='red') y = RedBlackTreeNode(val=3) root.left = y y.parent = root x.left = RedBlackTreeNode(val=0) x.right = RedBlackTreeNode(val=2) x.left.left = RedBlackTreeNode() x.left.right = RedBlackTreeNode() x.right.left = RedBlackTreeNode() x.right.right = RedBlackTreeNode() y.right = RedBlackTreeNode(val=4) y.right.left = RedBlackTreeNode() y.right.right = RedBlackTreeNode() y.left = x x.parent = y tree = RedBlackTree(root=root) return tree def test_is_equal_tree(): x = RedBlackTreeNode(val=1) y = RedBlackTreeNode(val=1) assert is_equal_tree(x,y)==True def test_is_equal_tree_with_branch(): x = RedBlackTreeNode(val=1) y = RedBlackTreeNode(val=3) x.left = RedBlackTreeNode(val=0) x.right = y y.parent = x y.left = RedBlackTreeNode(val=2) y.right = RedBlackTreeNode(val=4) assert is_equal_tree(x,y)==False def test_is_equal_tree_nil(): assert is_equal_tree(RedBlackTreeNode(),RedBlackTreeNode()) def test_left_rotate(): tree1 = getTree1() tree2 = getTree2() tree1._left_rotate(tree1.root) assert is_equal_tree(tree1.root,tree2.root) def test_left_rotate_not_from_root(): tree3 = getTree3() tree4 = getTree4() tree3._left_rotate(tree3.root.left) assert is_equal_tree(tree3.root,tree4.root) def test_right_rotate(): tree1 = getTree1() tree2 = getTree2() tree2._right_rotate(tree2.root) assert is_equal_tree(tree1.root,tree2.root) def test_right_rotate_not_from_root(): tree3 = getTree3() tree4 = getTree4() tree4._right_rotate(tree4.root.left) assert is_equal_tree(tree3.root,tree4.root) def test_is_redblacktree(): tree = getTree3() assert is_redblacktree(tree) def test_insert_black_parent(): tree = getTree1() assert is_redblacktree(tree.insert(RedBlackTreeNode(val=1.5))) def test_insert_red_parent(): tree = getTree1() assert is_redblacktree(tree.insert(RedBlackTreeNode(val=0.5))) def test_insert_red_parent(): tree = getTree1() assert is_redblacktree(tree.insert(RedBlackTreeNode(val=-0.5)))
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,282
daisySSSS/basic_algo
refs/heads/master
/test_tree_tranverse.py
from tree_tranverse import Tree, inorder_tranverse_recursive,inorder_tranverse_iterative,preorder_tranverse_recursive,preorder_tranverse_iterative,postorder_tranverse_recursive,postorder_tranverse_iterative root = Tree(value=0) root.left = Tree(value=1) root.right = Tree(value=2) root.left.left = Tree(value=3) root.left.right = Tree(value=4) root.right.left = Tree(value=5) root.right.right = Tree(value=6) print(inorder_tranverse_recursive(root)==inorder_tranverse_iterative(root)) print(preorder_tranverse_recursive(root)==preorder_tranverse_iterative(root)) print(postorder_tranverse_recursive(root)==postorder_tranverse_iterative(root))
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,283
daisySSSS/basic_algo
refs/heads/master
/tree_tranverse.py
class Tree: def __init__(self, left=None, right=None, value=None): self.left = left self.right = right self.value = value def inorder_tranverse_recursive(root): if root.left: inorder_tranverse_recursive(root.left) print(root.value) if root.right: inorder_tranverse_recursive(root.right) def inorder_tranverse_iterative(root): node = root stack = [] while 1: if node: stack.append(node) node = node.left elif stack: node = stack.pop() print(node.value) node = node.right else: break def preorder_tranverse_recursive(root): print(root.value) if root.left: preorder_tranverse_recursive(root.left) if root.right: preorder_tranverse_recursive(root.right) def preorder_tranverse_iterative(root): node = root stack = [] while 1: if node: print(node.value) stack.append(node) node = node.left elif stack: node = stack.pop() node = node.right else: break def postorder_tranverse_recursive(root): if root.left: postorder_tranverse_recursive(root.left) if root.right: postorder_tranverse_recursive(root.right) print(root.value) def postorder_tranverse_iterative(root): node = root stack = [] while 1: if node: stack.append(node) stack.append(node) node = node.left elif stack: node = stack.pop() if stack and stack[-1]==node: node = node.right else: print(node.value) node=None else: break
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,284
daisySSSS/basic_algo
refs/heads/master
/test_sort.py
from sort import Sort s = Sort() nums = [134,13,15,15,64,14,73,42,14,82] s.quick_sort(nums, 0, len(nums)-1) print('='*15) print('Result from quick sort') print(nums) nums = [134,13,15,15,64,14,73,42,14,82] s = Sort() s.heap_sort(nums) print('='*15) print('Result from heap sort') print(nums) nums = [] s = Sort() s._build_heap(nums) s.priority_queue_insert(nums, 100) s.priority_queue_insert(nums, 134) s.priority_queue_insert(nums, 33) s.priority_queue_insert(nums, 1345) s.priority_queue_insert(nums, 1) s.priority_queue_insert(nums, 10) print('='*15) print('Result for priority queue insert') print(nums) max_heap = s.priority_queue_heap_extract_maximum(nums) print('='*15) print('Result for priority queue extract maximum') print(max_heap) print(nums) nums = [134,13,15,15,64,14,73,42,14,82] count_sort, idx = s.count_sort([(x, i) for i, x in enumerate(nums)]) print('='*15) print('Result for count sort') print(count_sort) nums = [134,13,15,15,64,14,73,42,14,82] radix_sort = s.radix_sort(nums) print('='*15) print('Result for radix sort') print(radix_sort)
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,285
daisySSSS/basic_algo
refs/heads/master
/binary_search_tree.py
# binary_search_tree # median class Node(): def __init__(self, val, left = None, right = None, parent = None): self.val = val self.left = left self.right = right self.parent = parent class BinarySearchTree(): def __init__(self, root=None): self.root = root def print_tree(self): x = self.root queue = [x] while queue: cur = queue.pop(0) tmp = [] if cur.left: queue.append(cur.left) tmp.append(cur.left.val) else: tmp.append('nil') if cur.right: queue.append(cur.right) tmp.append(cur.right.val) else: tmp.append('nil') print(cur.val, tmp) def search(self, num): x = self.root while x: if num < x.val: x = x.left elif num == x.val: return x else: x = x.right def insert(self, num): x = self.root y = None while x: if num < x.val: y = x x = x.left else: y = x x = x.right if not y: self.root = Node(num) else: if num < y.val: y.left = Node(num) y.left.parent = y else: y.right = Node(num) y.right.parent = y def successor(self, x): if not x: x = self.root if x.right: return self.min(x.right) else: y = x.parent while y and x == y.right: x = y y = x.parent return y def delete(self, x): if not x.left: self.transplant(x,x.right) if not x.right: self.transplant(x, x.left) else: y = self.min(x.right) if x.right != y: self.transplant(y, y.right) y.right = x.right y.right.parent = y self.transplant(x, y) y.left = x.left y.left.parent = y def transplant(self, x, y): if x.parent == None: self.root = y elif x == x.parent.right: x.parent.right = y else: x.parent.left = y if y != None: y.parent = x.parent def min(self, x=None): if not x: x = self.root while x.left: x = x.left return x def max(self, x=None): if not x: x = self.root while x.right: x = x.right return x
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,286
daisySSSS/basic_algo
refs/heads/master
/graph.py
from collections import defaultdict import heapq INF = 1E4 class Graph: def __init__(self, undirected=False): self.graph = defaultdict(dict) # dictionary containing adjacency List self.V = set() self.undirected = undirected def add_edge(self, u, v, w): if self.undirected: self.graph[u][v] = w self.graph[v][u] = w else: self.graph[u][v] = w self.V.add(u) self.V.add(v) def print_graph(self): print(self.graph) def bfs(self, src): # Time complexity O(E+V) # Space complexity O(V) stack = [src] visited = dict() bfs_order = [] for i in self.V: visited[i] = 0 while stack: cur = stack.pop(0) bfs_order.append(cur) visited[cur] = 1 for i in self.graph[cur]: if not visited[i]: stack.append(i) visited[cur] = 2 return bfs_order def _dfs_visit(self, graph, v, visited, topological_sort, dfs_order): visited[v] = 1 dfs_order.append(v) for i in graph[v]: if visited[i] == 1: self.dag = 0 if not visited[i]: visited, topological_sort, dfs_order = self._dfs_visit( graph, i, visited, topological_sort, dfs_order) visited[v] = 2 topological_sort.insert(0, v) return visited, topological_sort, dfs_order # Time complexity O(E+V) def dfs(self): visited = dict() dfs_order = [] topological_sort = [] self.dag = 1 for i in self.V: visited[i] = 0 for i in self.V: if not visited[i]: visited, topological_sort, dfs_order = self._dfs_visit( self.graph, i, visited, topological_sort, dfs_order) return topological_sort, dfs_order def mst_kruskal(self): # time complexity O(ElogV). mst_set = dict() # for each node in the graph, the set it belongs to. node_sets = dict() # for each set, the list of all the nodes. mst_parent = defaultdict(list) # The parent of each node. for i in self.V: mst_set[i] = i node_sets[i] = [i] self.E = [] for i in self.graph: for j in self.graph[i]: self.E.append((self.graph[i][j], i, j)) self.E.sort() total_weight = 0 for e in self.E: old_set = mst_set[e[2]] new_set = mst_set[e[1]] if old_set != new_set: for i in node_sets[old_set]: mst_set[i] = new_set node_sets[new_set].append(i) del node_sets[old_set] mst_parent[e[2]].append(e[1]) total_weight += e[0] return mst_parent, total_weight def _exchange(self, nums, i, j): tmp = nums[i] nums[i] = nums[j] nums[j] = tmp def mst_prim(self): src = 1 h = [] mst_tree = self._initialize_single_source(src) visited = [src] for i in self.graph[src]: heapq.heappush(h, (self.graph[src][i], src, i)) total_weight = 0 while h: weight, parent, cur = heapq.heappop(h) if cur not in visited: mst_tree[cur]['parent'] = parent visited.append(cur) total_weight += weight for i in self.graph[cur]: if i not in visited: heapq.heappush(h, (self.graph[cur][i], cur, i)) return mst_tree, total_weight def _initialize_single_source(self, src): shortest_path = defaultdict(dict) for i in self.V: shortest_path[i]['weight'] = INF shortest_path[i]['parent'] = None shortest_path[src]['weight'] = 0 return shortest_path def _relax(self, start, end): if self.graph[start][end] + self.shortest_path[start]['weight'] < self.shortest_path[end]['weight']: self.shortest_path[end]['weight'] = self.graph[start][end] + \ self.shortest_path[start]['weight'] self.shortest_path[end]['parent'] = start def shortest_path_bellman_ford(self, src): # Complexity Bellman_ford O(VE) # Complexity Bellman_ford DAG O(V+E) # TO-DO: determine if it is a DAG self.shortest_path = self._initialize_single_source(src) if self.dag: topological_sort, _ = self.dfs() for i in topological_sort: for v in self.graph[i]: self._relax(i, v) else: for i in self.V: for start in self.graph: for end in self.graph[start]: self._relax(start, end) print('Shortest path with Bellman-ford algorithm.') print(self.shortest_path) def shortest_path_dijkstra(self, src): # Time complexity: O(VlogV+E) self.shortest_path = self._initialize_single_source(src) h = [] visited = [] for i in self.V: heapq.heappush(h, (self.shortest_path[i]['weight'], i)) while h: weight, cur = heapq.heappop(h) visited.append(cur) for i in self.graph[cur]: if i not in visited: h.remove((self.shortest_path[i]['weight'], i)) self._relax(cur, i) heapq.heappush(h, (self.shortest_path[i]['weight'], i)) print('Shortest path with Dijktra algorithm') print(self.shortest_path) def _transpose(self, graph): graph_transposed = defaultdict(dict) for i in self.graph: for j in self.graph[i]: graph_transposed[j][i] = self.graph[i][j] return graph_transposed def strongly_connected_component(self): topological_sort, _ = self.dfs() graph_transposed = self._transpose(self.graph) visited = dict() for i in self.V: visited[i] = 0 cnt = 0 for i in topological_sort: if not visited[i]: visited, topological_sort_node, _ = self._dfs_visit( graph_transposed, i, visited, [], []) print('Nodes in strongly connected component %d:' % cnt) print(topological_sort_node) cnt += 1
{"/test_graph.py": ["/graph.py"], "/red_black_tree.py": ["/binary_search_tree.py"], "/test_RedBlackTree.py": ["/red_black_tree.py"], "/test_tree_tranverse.py": ["/tree_tranverse.py"], "/test_sort.py": ["/sort.py"]}
37,288
ellipsistechnology/intro-to-python
refs/heads/master
/TestPart3.py
#!/usr/bin/env python3 import subprocess import TestFile import os def test(script): if not script: return False, "Error: Script not given." else: # Test file structure: fileResult, fileMessage = TestFile.testFile(script) if not fileResult: return fileResult, fileMessage # Part 3 - Test 1: Creates a file with the count of monkeys: subprocess.check_output(['python', script]) if not os.path.exists("monkeys.txt"): return False, "Part 2 - Test 1 FAIL: File named monkeys.txt not found." else: data = open("monkeys.txt", encoding="utf-8").read() expected = "3 monkeys found." if data.strip() != expected: return False, "Part 2 - Test 1 FAIL: expected '%s', got '%s'" % (expected, data) os.remove("monkeys.txt") return True, "OK"
{"/TestPart3.py": ["/TestFile.py"], "/TestPart2.py": ["/TestFile.py"], "/TestPart1.py": ["/TestFile.py"], "/testAll.py": ["/TestPart1.py", "/TestPart2.py", "/TestPart3.py"]}
37,289
ellipsistechnology/intro-to-python
refs/heads/master
/TestPart2.py
#!/usr/bin/env python3 import subprocess import TestFile def test(script): if not script: return False, "Error: Script not given." else: # Test file structure: fileResult, fileMessage = TestFile.testFile(script) if not fileResult: return fileResult, fileMessage # Test the file includes a the printThing function: f = open(script, encoding='utf-8') file_string = f.read() if "def printThing(x, thing):" not in file_string: return False, "Fail: Program does not include the printThing(x, thing) function definition." # Part 1 - Test 1: With no parameters prints "Error: Need more arguments.": result = subprocess.check_output(['python', script]) output = result.decode("utf-8") expected = "Error: Need more arguments." if output.strip() != expected: return False, "Part 2 - Test 1 FAIL: expected '%s', got '%s'" % (expected, output) # Part 2 - Test 2: With one parameter prints a list of numbers: result = subprocess.check_output(['python', script, "5"]) output = result.decode("utf-8") expected = ["1\n2\n3\n4\n5", "1\r\n2\r\n3\r\n4\r\n5", "1\n\r2\n\r3\n\r4\n\r5"] if output.strip() != expected[0] and output.strip() != expected[1] and output.strip() != expected[1]: return False, "Part 2 - Test 2 FAIL: expected '%s', got '%s'" % (expected, output) # Part 2 - Test 3: With two parameter prints a list of numbered things: result = subprocess.check_output(['python', script, "5", "carrot"]) output = result.decode("utf-8") expected = ["5 carrots\n4 carrots\n3 carrots\n2 carrots\n1 carrot", "5 carrots\r\n4 carrots\r\n3 carrots\r\n2 carrots\r\n1 carrot", "5 carrots\n\r4 carrots\n\r3 carrots\n\r2 carrots\n\r1 carrot"] if output.strip() != expected[0] and output.strip() != expected[1] and output.strip() != expected[2]: return False, "Part 2 - Test 3 FAIL: expected '%s', got '%s'" % (expected, output) return True, "OK"
{"/TestPart3.py": ["/TestFile.py"], "/TestPart2.py": ["/TestFile.py"], "/TestPart1.py": ["/TestFile.py"], "/testAll.py": ["/TestPart1.py", "/TestPart2.py", "/TestPart3.py"]}
37,290
ellipsistechnology/intro-to-python
refs/heads/master
/TestPart1.py
#!/usr/bin/env python3 import subprocess import TestFile TEST_NAME = "Ben" TEST_NAMES = ['Ben', 'Bob', 'Bill'] def test(script): if not script: return False, "Error: Script not given." else: # Test file structure: fileResult, fileMessage = TestFile.testFile(script) if not fileResult: return fileResult, fileMessage # Part 1 - Test 1: With no parameters prints "Hello world!: result = subprocess.check_output(['python', script]) output = result.decode("utf-8") expected = "Hello world!" if output.strip() != expected: return False, "Part 1 - Test 1 FAIL: expected '%s', got '%s'" % (expected, output) # Part 1 - Test 2: Prints one name: result = subprocess.check_output(['python', script, TEST_NAME]) output = result.decode("utf-8") expected = "Hello %s!" % TEST_NAME if output.strip() != expected: return False, "Part 1 - Test 2 FAIL: expected '%s', got '%s'" % (expected, output) # Part 1 - Test 3: Prints multiple names: result = subprocess.check_output(['python', script] + TEST_NAMES) output = result.decode("utf-8") expected = "Hello %s!Hello %s!Hello %s!" % (TEST_NAMES[0], TEST_NAMES[1], TEST_NAMES[2]) if output.strip().replace("\n", "").replace("\r", "") != expected: return False, "Part 1 - Test 3 FAIL: expected '%s', got '%s'" % (expected, output) return True, "OK"
{"/TestPart3.py": ["/TestFile.py"], "/TestPart2.py": ["/TestFile.py"], "/TestPart1.py": ["/TestFile.py"], "/testAll.py": ["/TestPart1.py", "/TestPart2.py", "/TestPart3.py"]}
37,291
ellipsistechnology/intro-to-python
refs/heads/master
/TestFile.py
import re import os def testByRegex(regex, test_str): # print("testing %s: found %d" % (regex, len(re.findall(regex, test_str, re.MULTILINE)))) return re.findall(regex, test_str, re.MULTILINE) def testFile(fileName): if not os.path.exists(fileName): return False, "FAIL: Script %s does not exist." % fileName f = open(fileName, encoding="utf-8") file_string = f.read() if len(testByRegex("((?<!\\s)^(#!/usr/bin/env python3)$)", file_string)) == 0: return False, "FAIL: File %s does not start with #!/usr/bin/env python3" % fileName if len(testByRegex("^#.*\\w.+$", file_string)) < 2: return False, "FAIL: File %s does not include enough comments" % fileName return True, "OK"
{"/TestPart3.py": ["/TestFile.py"], "/TestPart2.py": ["/TestFile.py"], "/TestPart1.py": ["/TestFile.py"], "/testAll.py": ["/TestPart1.py", "/TestPart2.py", "/TestPart3.py"]}
37,292
ellipsistechnology/intro-to-python
refs/heads/master
/testAll.py
#!/usr/bin/env python3 import os import TestPart1 import TestPart2 import TestPart3 import importlib.util REPORT_FILE = "marks.csv" def test(dir): if dir.endswith("__pycache__"): return print("Testing %s" % dir) # Check that all required files exist and run tests: idPath = os.path.join(dir, "id.py") if not os.path.exists(idPath): print("Error: File %s not found" % idPath) return spec = importlib.util.spec_from_file_location("module.name", idPath) idModule = importlib.util.module_from_spec(spec) spec.loader.exec_module(idModule) id, name, cohort = idModule.id() if not id or not name or cohort not in ["Electrical", "Communications"]: print("Error: Invalid (id, name, cohort) = (%s, %s, %s)" % id, name, cohort) return part1Path = os.path.join(dir, "Part1.py") if not os.path.exists(part1Path): result1, message1 = False, "Error: File %s not found" % part1Path else: result1, message1 = TestPart1.test(part1Path) part2Path = os.path.join(dir, "Part2.py") if not os.path.exists(part2Path): result2, message2 = False, "Error: File %s not found" % part2Path else: result2, message2 = TestPart2.test(part2Path) part3Path = os.path.join(dir, "Part3.py") if not os.path.exists(part3Path): result3, message3 = False, "Error: File %s not found" % part3Path else: result3, message3 = TestPart3.test(part3Path) # Update report: report = open(REPORT_FILE, "a") report.write( "%s, 1,%s,%s\n" % (id, "PASS" if result1 else "FAIL", message1.replace("\n", "")) ) report.write( "%s, 2,%s,%s\n" % (id, "PASS" if result2 else "FAIL", message2.replace("\n", "")) ) report.write( "%s, 3,%s,%s\n" % (id, "PASS" if result3 else "FAIL", message3.replace("\n", "")) ) report.close() # Enpty report file fisrt: report = open(REPORT_FILE, "w") report.write("ID, Part, Result, Message\n") report.close() # Test all scripts in all subdirs of assignments: # r=root, d=directories, f = files for r, d, f in os.walk("assignments"): for dir in d: test(os.path.join(r, dir))
{"/TestPart3.py": ["/TestFile.py"], "/TestPart2.py": ["/TestFile.py"], "/TestPart1.py": ["/TestFile.py"], "/testAll.py": ["/TestPart1.py", "/TestPart2.py", "/TestPart3.py"]}
37,293
vlrizkidz93/king-bot
refs/heads/master
/src/village.py
from .utils import log from .util_game import close_modal from .custom_driver import client from enum import Enum class building(Enum): smithy = 13 headquarter = 15 rallypoint = 16 market = 17 barracks = 19 academy = 22 residence = 25 def open_village(browser: client, id: int) -> None: index = id # check selected village ul = browser.find("//div[contains(@class, 'villageListDropDown')]") ul = ul.find_element_by_xpath(".//ul") lis = ul.find_elements_by_xpath(".//li") classes = lis[index].get_attribute("class") if "selected" in classes: return btn = browser.find("//a[@id='villageOverview']") browser.click(btn, 1) table = browser.find("//table[contains(@class, 'villagesTable')]/tbody") villages = table.find_elements_by_xpath(".//tr") tds = villages[index].find_elements_by_xpath(".//td") link = tds[0].find_element_by_xpath(".//a") browser.click(link, 1) close_modal(browser) def open_city(browser: client) -> None: btn = browser.find("//a[@id='optimizly_mainnav_village']") classes = btn.get_attribute("class") if "active" in classes: return browser.click(btn, 1) def open_resources(browser: client) -> None: btn = browser.find("//a[@id='optimizly_mainnav_resources']") classes = btn.get_attribute("class") if "active" in classes: return browser.click(btn, 1) def open_building(browser: client, building: int) -> None: # todo open by slot id img = browser.find("//img[@id='buildingImage{}']".format(building)) browser.click(img, 1) def open_building_type(browser: client, b_type: building) -> None: view = browser.find("//div[@id='villageView']") locations = view.find_elements_by_xpath(".//building-location") for loc in locations: classes = loc.get_attribute("class") if "free" not in classes: img = loc.find_element_by_xpath(".//img") classes = img.get_attribute("class") class_list = classes.split(" ") for c in class_list: if c == "buildingId{}".format(b_type.value): browser.click(img) return def open_map(browser: client) -> None: map_button = browser.find("//a[contains(@class, 'navi_map bubbleButton')]") browser.click(map_button, 1)
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,294
vlrizkidz93/king-bot
refs/heads/master
/src/slot.py
from .utils import log from .custom_driver import client from selenium.webdriver.remote import webelement def find_slot(browser: client, id: int) -> webelement: el_list = browser.driver.find_elements_by_xpath( "//div[contains(@class, 'buildingStatus location{}')]".format(id) ) for element in el_list: c = element.get_attribute("class") classes = c.split(" ") for cla in classes: if cla == "location{}".format(id): return element
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,295
vlrizkidz93/king-bot
refs/heads/master
/src/celebration.py
import time from .utils import log, parse_time_to_seconds from .custom_driver import client, use_browser from .util_game import close_modal, open_village_overview, overview def celebration_thread( browser: client, villages: list, celebration_type: int, interval: int ) -> None: # init delay time.sleep(2) while True: sleep_time = interval remaining_time = manage_celebration(browser, villages, celebration_type) if remaining_time < interval: sleep_time = remaining_time + 5 time.sleep(sleep_time) @use_browser def manage_celebration(browser: client, villages: list, celebration_type: int) -> int: available_villages = get_available_villages(browser, villages) for village in available_villages: start_celebration(browser, village, celebration_type) lowest_time = -1 remaining_time_list = get_celebration_times(browser, villages) for time in remaining_time_list: seconds = parse_time_to_seconds(time) if lowest_time == -1: lowest_time = seconds continue if seconds < lowest_time: lowest_time = seconds return lowest_time def get_available_villages(browser: client, villages: list) -> list: open_village_overview(browser, overview.culture_points) tab_content = browser.find("//div[contains(@class, 'tabCulturePoints')]") table = tab_content.find_element_by_xpath( ".//table[contains(@class, 'villagesTable')]/tbody" ) trs = table.find_elements_by_xpath(".//tr") available_villages = [] for village in villages: if len(trs) <= village: log(f"couldn't access village: {village}") continue # village is available span = trs[village].find_elements_by_xpath(".//td")[2] span = span.find_element_by_xpath(".//span") ngif = span.get_attribute("ng-if") if "== 0" in ngif: available_villages.append(village) return available_villages def start_celebration(browser: client, village: int, celebration_type: int) -> None: open_village_overview(browser, overview.culture_points) tab_content = browser.find("//div[contains(@class, 'tabCulturePoints')]") table = tab_content.find_element_by_xpath( ".//table[contains(@class, 'villagesTable')]/tbody" ) trs = table.find_elements_by_xpath(".//tr") if len(trs) <= village: log(f"couldn't access village: {village}") return # village is available span = trs[village].find_elements_by_xpath(".//td")[2] span = span.find_element_by_xpath(".//span") ngif = span.get_attribute("ng-if") if "== 0" not in ngif: log(f"can't start celebration in village: {village}") return # start celebrating atag = span.find_element_by_xpath(".//a") browser.click(atag, 1) if celebration_type == 1: # TODO select big celebration here pass button = browser.find("//button[contains(@clickable, 'startCelebration')]") btnClasses = button.get_attribute("class") if "disabled" in btnClasses: log(f"not enough resources to start celebration in village: {village}") close_modal(browser) return browser.click(button, 1) close_modal(browser) def get_celebration_times(browser: client, villages: list) -> list: open_village_overview(browser, overview.culture_points) tab_content = browser.find("//div[contains(@class, 'tabCulturePoints')]") table = tab_content.find_element_by_xpath( ".//table[contains(@class, 'villagesTable')]/tbody" ) trs = table.find_elements_by_xpath(".//tr") sleep_time_list = [] for village in villages: if len(trs) <= village: log(f"couldn't access village: {village}") continue # village is available span = trs[village].find_elements_by_xpath(".//td")[2] span = span.find_element_by_xpath(".//span") ngif = span.get_attribute("ng-if") if "> 0" in ngif: span = span.find_element_by_xpath(".//span") time = span.get_attribute("innerHTML") sleep_time_list.append(time) return sleep_time_list
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,296
vlrizkidz93/king-bot
refs/heads/master
/src/dodge_attack.py
from .custom_driver import client, use_browser import time from random import randint from .utils import log from .village import open_village, open_city, open_building from .farming import send_farm from .util_game import ( close_modal, shortcut, open_shortcut, check_resources, old_shortcut, ) from .settings import settings import json def check_for_attack_thread( browser: client, village: int, interval: int, units: list, target: list, save_resources: bool, units_train: list, ) -> None: time.sleep(randint(0, 10)) if save_resources: with open(settings.units_path, "r") as f: content = json.load(f) while True: sleep_time = interval attack_time = check_for_attack(browser, village) if attack_time: timelist = attack_time.split(":") countdown = ( int(timelist[0]) * 60 * 60 + int(timelist[1]) * 60 + int(timelist[0]) ) save_send_time = 10 * 60 if countdown < save_send_time: # send units away unit_dict = {} # fill the dict, -1 means send all units for unit in units: unit_dict[int(unit)] = -1 send_farm( browser=browser, village=village, units=unit_dict, x=int(target[0]), y=int(target[1]), ) log("units sent to rescue") if save_resources: save_resources_gold(browser, units_train, content) sleep_time = save_send_time # sleep at least until attack is over elif countdown > sleep_time + save_send_time: # do nothing and wait for next waking up pass else: # wake up before attack so the countdown will be smaller than save_send_time sleep_time = countdown - (save_send_time - 10) pass # log("checking for attacks going to sleep") time.sleep(sleep_time) @use_browser def check_for_attack(browser: client, village: int) -> str: # log("checking for incoming attacks...") open_village(browser, village) movements = browser.find("//div[@id='troopMovements']") ul = movements.find_element_by_xpath(".//ul") lis = ul.find_elements_by_xpath(".//li") for li in lis: classes = li.get_attribute("class") if "incoming_attacks" in classes: cd = li.find_element_by_xpath(".//div[@class='countdown']") countdown = cd.get_attribute("innerHTML") log("incoming attack in {} !".format(countdown)) return countdown return "" @use_browser def save_resources(browser: client, threshold: list) -> None: open_shortcut(browser, shortcut.barrack) el = browser.find("//div[@class='modalContent']") max_button = el.find_element_by_xpath( ".//div[@class='iconButton maxButton clickable']" ) browser.click(max_button, 1) browser.sleep(1) train_button = browser.find("//button[contains(@class, 'animate footerButton')]") browser.click(train_button, 1) close_modal(browser) # put resource left to market based on threshold browser.sleep(1) resource = check_resources(browser) foo = 0 open_shortcut(browser, shortcut.marketplace) browser.sleep(1) el = browser.find("//div[@class='modalContent']") sell_tab = el.find_element_by_xpath( ".//a[contains(@class, 'naviTabSell clickable')]" ) browser.click(sell_tab, 1) merchant = el.find_element_by_xpath(".//div[@class='marketplaceHeaderGroup']") merchant = merchant.find_element_by_xpath(".//div[@class='circle']/span") merchant = int(merchant.get_attribute("innerHTML")) browser.sleep(1) if merchant > 0: for res_name in resource.keys(): if resource[res_name] >= threshold[foo]: offering = browser.find("//div[@class='offerBox']") offering = offering.find_element_by_xpath( ".//div[@class='resourceFilter filterBar']" ) offering_type = offering.find_elements_by_xpath( ".//a[contains(@class, 'filter iconButton')]" ) browser.click(offering_type[foo], 1) input_offering = browser.find( "//input[@id='marketNewOfferOfferedAmount']" ) input_offering.click() input_offering.send_keys("1000") browser.sleep(1) searching = browser.find("//div[@class='searchBox']") searching = searching.find_element_by_xpath( ".//div[@class='resourceFilter filterBar']" ) searching_type = searching.find_elements_by_xpath( ".//a[contains(@class, 'filter iconButton')]" ) browser.click(searching_type[(foo + 1) % 2], 1) input_searching = browser.find( "//input[@id='marketNewOfferSearchedAmount']" ) input_searching.click() input_searching.send_keys("2000") browser.sleep(1) while resource[res_name] >= threshold[foo] and merchant > 0: sell_btn = browser.find( "//button[contains(@class, 'createOfferBtn')]" ) browser.click(sell_btn, 1) resource[res_name] -= 1000 merchant -= 1 browser.sleep(1) foo += 1 browser.sleep(1) close_modal(browser) @use_browser def save_resources_gold(browser: client, units_train: list, content: dict) -> None: tribe_id = browser.find('//*[@id="troopsStationed"]//li[contains(@class, "tribe")]') tribe_id = tribe_id.get_attribute("tooltip-translate") units_cost = [] # resources cost for every unit in units_train total_units_cost = [] # total resources cost for every unit in units_train training_queue: dict = {} # dict for training queue for tribe in content["tribe"]: if tribe_id in tribe["tribeId"]: for unit in tribe["units"]: if unit["unitId"] in units_train: units_cost.append(unit["trainingCost"]) training_cost = sum(unit["trainingCost"].values()) total_units_cost.append(training_cost) # initializing training_queue training_queue[unit["unitTrain"]] = {} training_queue[unit["unitTrain"]][unit["unitId"]] = 0 resources = check_resources(browser) total_resources = sum(resources.values()) # training amount distributed by: equal resources consumption per unit type training_amount = [] # amount of troop for training for cost in total_units_cost: train_amount = total_resources // (len(units_train) * cost) training_amount.append(train_amount) # fetching training_amount to training_queue _iter = (x for x in training_amount) # generator of training_amount for unit_train in training_queue: for unit_id in training_queue[unit_train]: training_queue[unit_train][unit_id] = next(_iter) total_training_cost = [] # amount of troop * units_cost _iter = (x for x in training_amount) # generator of training_amount for unit_cost in units_cost: amount = next(_iter) temp = {} # temporary dict for _keys, _values in unit_cost.items(): temp[_keys] = _values * amount total_training_cost.append(temp) wood, clay, iron = 0, 0, 0 for resource in total_training_cost: wood += resource["wood"] clay += resource["clay"] iron += resource["iron"] _resource = (x for x in (wood, clay, iron)) # generator of resources # NPC the resources through the marketplace open_shortcut(browser, shortcut.marketplace) npc_tab = browser.find('//*[@id="optimizely_maintab_NpcTrade"]') browser.click(npc_tab, 1) market_content = browser.find('//div[contains(@class, "marketContent npcTrader")]') trs = market_content.find_elements_by_xpath('.//tbody[@class="sliderTable"]/tr') browser.sleep(1) for tr in trs[:-2]: input = tr.find_element_by_xpath(".//input") browser.sleep(0.5) input.clear() browser.sleep(1.5) input.send_keys(next(_resource)) browser.sleep(1.5) lock = tr.find_element_by_xpath('.//div[@class="lockButtonBackground"]') browser.sleep(1.5) browser.click(lock, 1) browser.sleep(1.5) convert_button = market_content.find_element_by_xpath( './/div[@class="merchantBtn"]/button' ) browser.click(convert_button, 1) # close marketplace close_modal(browser) # Start training troops for unit_train in training_queue: old_shortcut(browser, unit_train) for unit_id in training_queue[unit_train]: # click picture based unit_id unit_type = "unitType{}".format(unit_id) image_troop = browser.find( "//div[@class='modalContent']//img[contains(@class, '{}')]".format( unit_type ) ) browser.click(image_troop, 1) # input amount based training_queue[unit_train][unit_id] input_troop = browser.find('//div[@class="inputContainer"]') input_troop = input_troop.find_element_by_xpath("./input").send_keys( training_queue[unit_train][unit_id] ) browser.sleep(1.5) # click train button train_button = browser.find( "//button[contains(@class, 'animate footerButton')]" ) browser.click(train_button, 1) browser.sleep(1.5) browser.sleep(1) close_modal(browser)
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,297
vlrizkidz93/king-bot
refs/heads/master
/src/util_game.py
from .custom_driver import client from .utils import log from enum import Enum def close_modal(browser: client) -> None: el = browser.find("//div[@class='modalContent']") el = el.find_element_by_xpath(".//a[@class='closeWindow clickable']") browser.click(el) def close_welcome_screen(browser: client) -> None: wc = browser.find("//div[contains(@class, 'welcomeScreen')]") log("closing welcome-screen") el = wc.find_element_by_xpath(".//a[@class='closeWindow clickable']") browser.click(el) def check_resources(browser: client) -> dict: resources_list = ["wood", "clay", "iron", "crop"] resources = {} for res in resources_list: find_resources = browser.find("//div[@class='stockContainer {0}']".format(res)) find_resources = find_resources.find_element_by_xpath( ".//div[contains(@class, 'progressbar')]" ) value = int(find_resources.get_attribute("value")) resources[res] = value return resources class shortcut(Enum): marketplace = 0 barrack = 1 stable = 2 workshop = 3 def open_shortcut(browser: client, sc: shortcut) -> None: shortcut_link = browser.find("//div[@id='quickLinks']") shortcut_link = shortcut_link.find_element_by_xpath( ".//div[contains(@class, 'slotWrapper')]" ) link = shortcut_link.find_elements_by_xpath( ".//div[contains(@class, 'slotContainer')]" ) browser.click(link[sc.value], 1) class overview(Enum): overview = "optimizely_maintab_Overview" resources = "optimizely_maintab_Resources" warehouse = "optimizely_maintab_Store" culture_points = "optimizely_maintab_CulturePoints" units = "optimizely_maintab_Troops" oases = "optimizely_maintab_Oases" def open_village_overview(browser: client, tab: overview) -> None: btn = browser.find("//a[@id='villageOverview']") browser.click(btn, 1) navi_tab = browser.find(f"//a[@id='{tab.value}']") classes = navi_tab.get_attribute("class") if "inactive" in classes: browser.click(tab, 2) def old_shortcut(browser: client, shortcut: str) -> None: shortcut_dict = {"marketplace": 0, "barrack": 1, "stable": 2, "workshop": 3} shortcut_link = browser.find("//div[@id='quickLinks']") shortcut_link = shortcut_link.find_element_by_xpath( ".//div[contains(@class, 'slotWrapper')]" ) link = shortcut_link.find_elements_by_xpath( ".//div[contains(@class, 'slotContainer')]" ) browser.click(link[shortcut_dict[shortcut.lower()]], 1)
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,298
vlrizkidz93/king-bot
refs/heads/master
/src/account.py
from .utils import log from .custom_driver import client, use_browser @use_browser def login(browser: client, gameworld: str, email: str, password: str) -> None: world = gameworld browser.get("https://kingdoms.com/com") loginButton = browser.find("//span[text()='Login']", 1) browser.click(loginButton, 2) el = browser.find("//iframe[@class='mellon-iframe']", 2) browser.driver.switch_to.frame(el) el = browser.find("//iframe", 2) browser.driver.switch_to.frame(el) browser.find("//input[@name='email']").send_keys(email) pw = browser.find("//input[@name='password']") pw.send_keys(password) pw.submit() browser.sleep(3) check_notification(browser) # login to gameworld browser.find( "//span[contains(text(), '{}')]/following::button[@type='button']".format(world) ).click() log("login successful") browser.sleep(8) def check_notification(browser: client) -> None: try: browser.find("//body[contains(@class, 'modal-open')]") log("closing notification-modal") btn_close = browser.find("//button[@class='close']") browser.click(btn_close, 1) except: pass
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,299
vlrizkidz93/king-bot
refs/heads/master
/src/train_troops.py
from .custom_driver import client, use_browser import time import json from .utils import log from .util_game import close_modal, check_resources, old_shortcut from .village import open_village, open_city from .settings import settings def train_troops_thread( browser: client, village: int, units: list, interval: int ) -> None: # init delay time.sleep(2) with open(settings.units_path, "r") as f: content = json.load(f) while True: # log("start training troops.") if not start_training(browser, village, units, content): log("village is too low of resources.") # log("finished training troops.") time.sleep(interval) @use_browser def start_training( browser: client, village: int, units_train: list, content: dict ) -> bool: open_village(browser, village) open_city(browser) tribe_id = browser.find('//*[@id="troopsStationed"]//li[contains(@class, "tribe")]') tribe_id = tribe_id.get_attribute("tooltip-translate") units_cost = [] # resources cost for every unit in units_train total_units_cost_wood = [] # total wood cost for every unit in units_train total_units_cost_clay = [] # total clay cost for every unit in units_train total_units_cost_iron = [] # total iron cost for every unit in units_train training_queue: dict = {} # dict for training queue for tribe in content["tribe"]: if tribe_id in tribe["tribeId"]: for unit in tribe["units"]: if unit["unitId"] in units_train: units_cost.append(unit["trainingCost"]) training_cost_wood = unit["trainingCost"]["wood"] training_cost_clay = unit["trainingCost"]["clay"] training_cost_iron = unit["trainingCost"]["iron"] total_units_cost_wood.append(training_cost_wood) total_units_cost_clay.append(training_cost_clay) total_units_cost_iron.append(training_cost_iron) # initializing training_queue training_queue[unit["unitTrain"]] = {} training_queue[unit["unitTrain"]][unit["unitId"]] = {} training_queue[unit["unitTrain"]][unit["unitId"]]["amount"] = 0 training_queue[unit["unitTrain"]][unit["unitId"]]["name"] = unit[ "unitName" ] resources = check_resources(browser) # training amount distributed by: less resources consumption per unit type training_amount = [] # less posible amount of troop for training training_amount_wood = [] training_amount_clay = [] training_amount_iron = [] for cost in total_units_cost_wood: train_amount = resources["wood"] // (len(units_train) * cost) training_amount_wood.append(train_amount) for cost in total_units_cost_clay: train_amount = resources["clay"] // (len(units_train) * cost) training_amount_clay.append(train_amount) for cost in total_units_cost_iron: train_amount = resources["iron"] // (len(units_train) * cost) training_amount_iron.append(train_amount) # get the minimum possible troops to train training_amount = list( map(min, training_amount_wood, training_amount_clay, training_amount_iron) ) if sum(training_amount) == 0: return False # fetching training_amount to training_queue _iter = (x for x in training_amount) # generator of training_amount for unit_train in training_queue: for unit_id in training_queue[unit_train]: training_queue[unit_train][unit_id]["amount"] = next(_iter) total_training_cost = [] # amount of troop * units_cost _iter = (x for x in training_amount) # generator of training_amount for unit_cost in units_cost: amount = next(_iter) temp = {} # temporary dict for _keys, _values in unit_cost.items(): temp[_keys] = _values * amount total_training_cost.append(temp) # Start training troops index = 0 for unit_train in training_queue: old_shortcut(browser, unit_train) for unit_id in training_queue[unit_train]: # input amount based training_queue[unit_train][unit_id] input_amount = training_queue[unit_train][unit_id]["amount"] input_name = training_queue[unit_train][unit_id]["name"] if input_amount == 0: continue # Skip empty amount log( "training {} units of type {}".format(input_amount, input_name) + " with a cost of wood:{}, clay:{}, iron:{}".format( total_training_cost[index]["wood"], total_training_cost[index]["clay"], total_training_cost[index]["iron"], ) ) # click picture based unit_id unit_type = "unitType{}".format(unit_id) image_troop = browser.find( "//div[@class='modalContent']//img[contains(@class, '{}')]".format( unit_type ) ) browser.click(image_troop, 1) input_troop = browser.find('//div[@class="inputContainer"]') input_troop = input_troop.find_element_by_xpath("./input") input_troop.click() input_troop.send_keys(input_amount) browser.sleep(1.5) # click train button train_button = browser.find( "//button[contains(@class, 'animate footerButton')]" ) browser.click(train_button, 1) browser.sleep(1.5) index += 1 browser.sleep(1) close_modal(browser) return True
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,300
vlrizkidz93/king-bot
refs/heads/master
/src/master_builders.py
from .custom_driver import client, use_browser from .village import open_village, open_city, open_resources from .utils import log, parse_time_to_seconds from .util_game import close_modal from .settings import * import time import json import os import re def master_builder_thread( browser: client, village: int, file_name: str, interval: int ) -> None: default_interval = interval with open(settings.buildings_path, "r") as f: content = json.load(f) buildings = [x for x in content["buildings"]] file_path = os.path.join(BASE_DIR, "assets", file_name) # BASE_DIR come from settings.py while True: with open(file_path, "r") as f: content = json.load(f) queues = [x for x in content["queues"]] construct_slot, queue_slot = check_building_queue(browser, village) if queues and (construct_slot or queue_slot): while construct_slot or queue_slot: queues = master_builder(browser, village, queues, buildings) construct_slot, queue_slot = check_building_queue(browser, village) if not queue_slot: break if not queues: break with open(file_path, "w") as f: f.write('{"queues":') f.write(json.dumps(queues, indent=4)) f.write("}") interval, can_finish_earlier = check_queue_times( browser, village, default_interval ) time.sleep(interval) if can_finish_earlier: five_mins(browser, village) else: construct_slot, queue_slot = check_building_queue(browser, village) if not construct_slot: interval, can_finish_earlier = check_queue_times( browser, village, default_interval ) time.sleep(interval) if can_finish_earlier: five_mins(browser, village) elif not queues: log("Queues is empty, please add queue to {}".format(file_name)) log(time.strftime("%H:%M")) time.sleep(default_interval) else: time.sleep(default_interval) @use_browser def master_builder( browser: client, village: int, queues: list, buildings: list ) -> list: open_village(browser, village) tribe_id = browser.find('//*[@id="troopsStationed"]//li[contains(@class, "tribe")]') tribe_id = tribe_id.get_attribute("tooltip-translate") if "Tribe_1" in tribe_id: new_queues = roman_constructor(browser, village, queues, buildings) return new_queues elif ( "Village" in queues[0]["queueLocation"] and "Construct" in queues[0]["queueType"] ): new_queues = master_constructor(browser, queues, buildings) return new_queues elif ( "Village" in queues[0]["queueLocation"] and "Upgrade" in queues[0]["queueType"] ): open_city(browser) time.sleep(1) found = False for building in buildings: if queues[0]["queueBuilding"] in building["buildingName"]: building_id = building["buildingId"] found = True break if not found: log("buildingId not found, remove it from queues.") new_queues = queues[1:] return new_queues building_img = browser.find( '//img[contains(@class, "{}")]/following::span'.format(building_id) ) building_status = building_img.find_element_by_xpath( './/div[contains(@class, "buildingStatus")]' ) color = building_status.find_element_by_xpath( './/div[contains(@class, "colorLayer")]' ).get_attribute("class") new_queues = check_color(browser, village, color, building_status, queues) return new_queues elif "Resources" in queues[0]["queueLocation"]: open_resources(browser) time.sleep(1) location_id = queues[0]["queueBuilding"] building_location = browser.find( '//building-location[@class="buildingLocation {}"]'.format(location_id) ) building_status = building_location.find_element_by_xpath( './/div[contains(@class, "buildingStatus")]' ) color = building_status.find_element_by_xpath( './/div[contains(@class, "colorLayer")]' ).get_attribute("class") new_queues = check_color(browser, village, color, building_status, queues) open_city(browser) return new_queues else: return queues @use_browser def check_queue_times(browser: client, village: int, default_interval: int) -> tuple: open_village(browser, village) notepad = browser.find('//a[@id="notepadButton"]') construct_slot, queue_slot = check_building_queue(browser, village) if construct_slot: return default_interval, False # writedown the time building_queue_container = browser.find( '//div[contains(@class, "buildingQueueContainer queueContainer")]' ) divs = building_queue_container.find_elements_by_xpath("./div") for div in divs: the_class = div.get_attribute("drop-class") if not the_class: continue else: if "noDrop" in the_class: browser.click(div, 1) inner_box = browser.find('//div[@class="detailsInnerBox"]') details_contents = inner_box.find_elements_by_xpath( './div[contains(@class, "detailsContent")]' ) times = [] finish_earlier = [] for details_content in details_contents: details_info = details_content.find_element_by_xpath( './div[contains(@class, "detailsInfo")]' ) details_time = details_info.find_element_by_xpath( './div[@class="detailsTime"]' ) span = details_time.find_element_by_xpath("./span") the_time = span.get_attribute("innerHTML") times.append(the_time) details_button = details_content.find_element_by_xpath( './div[contains(@class, "detailsButtonContainer")]' ) button = details_button.find_element_by_xpath("./button") the_class = button.get_attribute("class") if "disabled" in the_class: finish_earlier.append(False) else: finish_earlier.append(True) break else: continue # parse time to seconds browser.hover(notepad) times_in_seconds = [] for time in times: time_in_seconds = parse_time_to_seconds(time) times_in_seconds.append(time_in_seconds) if len(times_in_seconds) > 1: if times_in_seconds[0] < times_in_seconds[1]: if times_in_seconds[0] < 300 and finish_earlier[0]: return 1, True elif times_in_seconds[0] > 300 and finish_earlier[0]: return times_in_seconds[0] - 298, True else: return times_in_seconds[0], False elif times_in_seconds[0] > times_in_seconds[1]: if times_in_seconds[1] < 300: return 1, True else: return times_in_seconds[1] - 298, True else: if times_in_seconds[1] < 300: return 1, True else: return times_in_seconds[1] - 298, True else: if times_in_seconds[0] < 300 and finish_earlier[0]: return 1, True elif times_in_seconds[0] > 300 and finish_earlier[0]: return times_in_seconds[0] - 298, True elif not finish_earlier[0]: return times_in_seconds[0] + 1, False return 1, True @use_browser def check_building_queue(browser: client, village: int) -> tuple: open_village(browser, village) # check how much construction slot that empty empty_construct_slot = 0 construction_container = browser.find('//div[@class="constructionContainer"]') building_queue_slots = construction_container.find_elements_by_xpath("./div") for building_queue_slot in building_queue_slots: the_class = building_queue_slot.get_attribute("class") if "paid" in the_class: continue empty_construct_slot += 1 # check how much queue slot that empty empty_queue = 0 builder_container = browser.find('//div[@class="masterBuilderContainer"]') queue_slots = builder_container.find_elements_by_xpath("./div") for queue_slot in queue_slots: the_class = queue_slot.get_attribute("class") if "empty" not in the_class or "locked" in the_class: continue empty_queue += 1 return empty_construct_slot, empty_queue @use_browser def master_constructor(browser: client, queues: list, buildings: list) -> list: open_city(browser) time.sleep(1) base_url = browser.current_url() location_slots = browser.finds('//building-location[contains(@class, "free")]') if len(location_slots) < 1: log("no free slot for construc the building.") new_queues = queues[1:] return new_queues the_class = location_slots[0].get_attribute("class") base_url += "/location:" base_url += re.findall("\d+", the_class)[0] base_url += "/window:building" browser.get(base_url) time.sleep(3.5) found = False for building in buildings: if queues[0]["queueBuilding"] in building["buildingName"]: building_type = building["buildingType"] found = True break if not found: log("buildingType not found, remove it from queues.") new_queues = queues[1:] return new_queues modal_content = browser.find('//div[@class="modalContent"]') pages = modal_content.find_element_by_xpath('.//div[contains(@class, "pages")]') pages_class = pages.get_attribute("class") found = False if "ng-hide" in pages_class: building_img = modal_content.find_elements_by_xpath(".//img") for img in building_img: the_class = img.get_attribute("class") if building_type in the_class: browser.click(img, 1) found = True break else: pages = pages.find_elements_by_xpath("./div") for page in pages[2:-1]: building_img = modal_content.find_elements_by_xpath(".//img") for img in building_img: the_class = img.get_attribute("class") if building_type in the_class: browser.click(img, 1) found = True break if found: break browser.click(pages[-1], 1.3) if not found: log("building image not found.") close_modal(browser) new_queues = queues[1:] return new_queues buttons = modal_content.find_elements_by_xpath( './/button[contains(@class, "startConstruction")]' ) for button in buttons: the_class = button.get_attribute("class") if "ng-hide" not in the_class: if "disable" in the_class: tooltip = button.get_attribute("tooltip-translate-switch") if "Requirements" in tooltip: log("requirements not fulfilled.") close_modal(browser) new_queues = queues[1:] return new_queues else: log("building queue full.") close_modal(browser) return queues else: browser.click(button, 1.3) log("constructing..") new_queues = queues[1:] return new_queues return new_queues @use_browser def check_color( browser: client, village: int, color: str, building_status, queues: list ) -> list: notepad = browser.find('//a[@id="notepadButton"]') if "possible" in color: # green browser.click_v2(building_status, 1) browser.hover(notepad, 1) log("upgrading..") new_queues = queues[1:] return new_queues if "notNow" in color: # green / yellow construct_slot, queue_slot = check_building_queue(browser, village) if queue_slot: browser.click_v2(building_status, 1) browser.hover(notepad, 1) log("queue building..") new_queues = queues[1:] return new_queues else: return queues if "notAtAll" in color: # grey log("grey, removing from queue.") new_queues = queues[1:] return new_queues if "maxLevel" in color: # blue log("blue, removing from queue.") new_queues = queues[1:] return new_queues return new_queues def roman_constructor( browser: client, village: int, queues: list, buildings: list ) -> list: temp_dict = {x: y for x, y in enumerate(queues)} new_dict = {x: y for x, y in enumerate(queues)} for index, queue in temp_dict.items(): if "Village" in queue["queueLocation"] and "Construct" in queue["queueType"]: temp_queues = [queue] new_queues = master_constructor(browser, temp_queues, buildings) if not new_queues: del new_dict[index] construct_slot, queue_slot = check_building_queue(browser, village) if not construct_slot and not queue_slot: break elif "Village" in queue["queueLocation"] and "Upgrade" in queue["queueType"]: open_city(browser) time.sleep(1) for building in buildings: if queue["queueBuilding"] in building["buildingName"]: building_id = building["buildingId"] break building_img = browser.find( '//img[contains(@class, "{}")]/following::span'.format(building_id) ) building_status = building_img.find_element_by_xpath( './/div[contains(@class, "buildingStatus")]' ) color = building_status.find_element_by_xpath( './/div[contains(@class, "colorLayer")]' ).get_attribute("class") temp_queues = [queue] new_queues = check_color( browser, village, color, building_status, temp_queues ) if not new_queues: del new_dict[index] construct_slot, queue_slot = check_building_queue(browser, village) if not construct_slot and not queue_slot: break elif "Resources" in queue["queueLocation"]: open_resources(browser) time.sleep(1) location_id = queue["queueBuilding"] building_location = browser.find( '//building-location[@class="buildingLocation {}"]'.format(location_id) ) building_status = building_location.find_element_by_xpath( './/div[contains(@class, "buildingStatus")]' ) color = building_status.find_element_by_xpath( './/div[contains(@class, "colorLayer")]' ).get_attribute("class") temp_queues = [queue] new_queues = check_color( browser, village, color, building_status, temp_queues ) if not new_queues: del new_dict[index] construct_slot, queue_slot = check_building_queue(browser, village) if not construct_slot and not queue_slot: open_city(browser) break new_queue = [x for x in new_dict.values()] return new_queue def five_mins(browser: client, village: int) -> None: notepad = browser.find('//a[@id="notepadButton"]') construct_slot, queue_slot = check_building_queue(browser, village) if construct_slot: browser.hover(notepad) return building_queue_container = browser.find( '//div[contains(@class, "buildingQueueContainer queueContainer")]' ) divs = building_queue_container.find_elements_by_xpath("./div") for div in divs: the_class = div.get_attribute("drop-class") if not the_class: continue else: if "noDrop" in the_class: browser.click(div, 1) inner_box = browser.find('//div[@class="detailsInnerBox"]') details_contents = inner_box.find_elements_by_xpath( './div[contains(@class, "detailsContent")]' ) for details_content in details_contents: details_button = details_content.find_element_by_xpath( './div[contains(@class, "detailsButtonContainer")]' ) button = details_button.find_element_by_xpath("./button") the_class = button.get_attribute("class") if "disabled" in the_class or "premium" in the_class: continue else: try: voucher = button.find_element_by_xpath( './/span[@class="price voucher"]' ) except: browser.click(button, 1) else: continue break else: continue
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,301
vlrizkidz93/king-bot
refs/heads/master
/start.py
from src import king_bot, settings import sys # these could be read in via arguments, file or login manually - read documentation gameworld = "com3" # choose uppercase (exact world name) - optional email = "vlrizkidz93@tuta.io" # optional password = "melodies" # optional proxy = "" # optional # increase the number if your internet connecion is slow settings.browser_speed = 1.0 kingbot = king_bot( email=email, password=password, gameworld=gameworld, proxy=proxy, start_args=sys.argv, debug=True, ) # place your actions below # kingbot.start_adventures(1000) kingbot.robber_hideout(village=0, interval=600, units={4: 100, 10: -1}) kingbot.robber_camp(village=0, interval=600, units={4: 100, 10: -1})
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,302
vlrizkidz93/king-bot
refs/heads/master
/src/farming.py
from .custom_driver import client, use_browser from .settings import settings import time from .utils import log, check_for_lines from .village import open_building, open_city, open_village from .util_game import close_modal import schedule from threading import Thread from random import randint def start_farming_thread( browser: client, village: int, farmlists: list, interval: int ) -> None: # todo exit when in beginners protection time.sleep(randint(0, 10)) # starting sleep timer while True: start_farming(browser, village, farmlists) time.sleep(interval + randint(0, 10)) # randomize intervals @use_browser def start_farming(browser: client, village: int, farmlists: list) -> None: # log("farming thread in village {} waking up".format(village)) open_village(browser, village) open_city(browser) open_building(browser, 32) browser.sleep(1) tab = browser.find("//a[contains(@class, 'tab naviTabFarmList')]") browser.click(tab, 1) table = browser.find("//div[@class='farmList']") table = browser.find(".//table[contains(@class, 'farmListsOverviewTable')]") lists = table.find_elements_by_xpath(".//tbody") for i in farmlists: cb = lists[i].find_element_by_xpath(".//input[@type='checkbox']") # cb.send_keys(Keys.SPACE) browser.click(cb) browser.sleep(0.5) btn = browser.find("//button[contains(@class, 'startRaid')]") browser.click(btn, 1) log("farmlists: {} sent in village: {}".format(str(farmlists), str(village))) close_modal(browser) # log("farming thread in village {} sleeping".format(village)) def sort_danger_farms_thread( browser: client, farmlists: list, to_list: int, red: bool, yellow: bool, interval: int, ) -> None: time.sleep(randint(0, 10)) # random sleeping at start while True: sort_danger_farms(browser, farmlists, to_list, red, yellow) time.sleep(interval + randint(0, 10)) # randomized intervals @use_browser def sort_danger_farms( browser: client, farmlists: list, to_list: int, red: bool, yellow: bool ) -> None: # log("sorting farms started...") open_city(browser) open_building(browser, 32) browser.sleep(1) tab = browser.find("//a[contains(@class, 'tab naviTabFarmList')]") browser.click(tab, 1) table = browser.find("//div[@class='farmList']") table = browser.find(".//table[contains(@class, 'farmListsOverviewTable')]") lists = table.find_elements_by_xpath(".//tbody") for i in farmlists: # opens farmlist cb = lists[i].find_element_by_xpath(".//td[contains(@class, 'clickable')]") browser.click(cb) tbody = browser.find("//div[@class='listDetail']") tbody = tbody.find_element_by_xpath(".//tbody") trs = tbody.find_elements_by_xpath(".//tr") for tr in trs: tds = tr.find_elements_by_xpath(".//td") try: icon = tds[6].find_element_by_xpath(".//i") translate = icon.get_attribute("tooltip-translate") if translate != "Notification_1": movefarm = False if translate == "Notification_2": # farm is yellow if yellow == True: movefarm = True elif translate == "Notification_3": # farm is red if red == True: movefarm = True if movefarm == True: # move the farm browser.hover(tds[1]) if to_list == -1: add = tds[9].find_element_by_xpath( ".//div[contains(@clickable, 'deleteEntry')]" ) browser.click(add, 1) else: add = tds[9].find_element_by_xpath( ".//div[contains(@clickable, 'farmListAdd')]" ) browser.click(add, 1) inner = browser.find("//div[@class='farmListInner']") movelists = inner.find_element_by_xpath( ".//div[contains(@class, 'list')]" ) # todo test this !! # move to new list browser.hover(movelists[to_list]) browser.click(movelists[to_list]) browser.sleep(1) # remove from current list browser.hover(movelists[i]) browser.click(movelists[i]) browser.sleep(1) modal = browser.find( "//div[contains(@class, 'farmListAdd')]" ) closemodal = modal.find_element_by_xpath( ".//a[contains(@class, 'closeWindow')]" ) browser.click(closemodal, 2) log("moved or deleted farm") except: # farm never got sent pass # press back button btnback = browser.find("//div[@class='back clickable']") browser.click(btnback, 1) close_modal(browser) # log("sorting farms going to sleep") def start_custom_farmlist_thread( browser: client, reload: bool, interval: int = 60 ) -> None: # thread that executes jobs Thread(target=run_jobs).start() jobs: list = [] # current jobs while True: job_dict = check_for_lines(path=settings.farmlist_path, current_lines=jobs) # remove jobs that are not present anymore for rem_job in job_dict["remove"]: schedule.clear(rem_job) jobs.remove(rem_job) # add new jobs for add_job in job_dict["add"]: args = add_job.split(";") units = args[4] unit_list = units.split(",") unit_dict = {} for i in range(0, len(unit_list), 2): unit_dict[int(unit_list[i])] = int(unit_list[i + 1]) # shedule task schedule.every(int(args[2])).seconds.do( send_farm, browser=browser, x=args[0], y=args[1], village=args[3], units=unit_dict, ).tag(add_job) jobs.append(add_job) log("job " + add_job + " started") browser.use() for add_job in job_dict["add"]: args = add_job.split(";") units = args[4] unit_list = units.split(",") unit_dict = {} for i in range(0, len(unit_list), 2): unit_dict[int(unit_list[i])] = int(unit_list[i + 1]) # send one time at start send_farm( browser=browser, x=args[0], y=args[1], village=args[3], units=unit_dict ) browser.done() if not reload: break time.sleep(interval) @use_browser def send_farm(browser: client, village: int, x: int, y: int, units: dict) -> None: # log("sending units to: ({}/{}) ...".format(x, y)) open_village(browser, int(village)) open_city(browser) open_building(browser, 32) btn = browser.find("//button[contains(@class, 'sendTroops')]") browser.click(btn, 2) input = browser.find("//div[@class='modalContent']") input = input.find_element_by_xpath(".//input[contains(@class, 'targetInput')]") input.send_keys("({}|{})".format(x, y)) browser.sleep(1) btn = browser.find("//div[contains(@class, 'clickableContainer missionType4')]") browser.click(btn) input = browser.find("//tbody[contains(@class, 'inputTroops')]/tr") input = input.find_elements_by_xpath(".//td") units_sent = False if -1 in units: # send all units, max count log("send all units max count...") for inp in input: inp = inp.find_element_by_xpath(".//input") dis = inp.get_attribute("disabled") if not dis: inp.click() number = inp.get_attribute("number") inp.send_keys(number) units_sent = True else: # send value amount of units with index key for key, value in units.items(): inp = input[int(key)].find_element_by_xpath(".//input") # check if the field is disabled dis = inp.get_attribute("disabled") if not dis: # gets max available troop count number = inp.get_attribute("number") units_to_send = int(value) # send all units if value is -1 if units_to_send == -1: units_to_send = int(number) else: if int(number) < units_to_send: # send max value if there arent enough units to send units_to_send = number inp.click() inp.send_keys(units_to_send) units_sent = True if not units_sent: log("no units got sent...") close_modal(browser) return browser.sleep(1) btn = browser.find("//button[contains(@class, 'next clickable')]") browser.click(btn, 1) btn = browser.find("//button[contains(@class, 'sendTroops clickable')]") browser.click(btn, 1) log("units sent to: ({}/{}).".format(x, y)) def run_jobs(): while True: schedule.run_pending() time.sleep(1)
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,303
vlrizkidz93/king-bot
refs/heads/master
/src/gamestate.py
from .custom_driver import client from .slot import find_slot from .utils import log from util_game import close_modal def load_slot_data(browser: client, id: int) -> dict: el = find_slot(browser, id) templvl = el.find_element_by_class_name("buildingLevel") lvl = templvl.get_attribute("innerHTML") temp_upgrade = el.find_element_by_xpath( ".//div[contains(@class, 'colorLayer')]" ).get_attribute("class") if "possible" in temp_upgrade: upgradable = True return {"lvl": lvl, "upgradeable": upgradable} def init_villages(browser: client) -> list: villages: list = [] btn = browser.find("//a[@id='villageOverview']") browser.click(btn, 1) table = browser.find("//table[contains(@class, 'villagesTable')]/tbody") villages = table.find_elements_by_xpath(".//tr") for vil in villages: tds = vil.find_elements_by_xpath(".//td") name = tds[0].find_element_by_xpath(".//a").get_attribute("innerHTML") # villages.append( # village(browser, name, villages.index(vil))) # log("village {} added".format(name)) close_modal(browser) return villages def checkBuildingSlot(browser: client): slots = browser.driver.find_elements_by_xpath( "//div[@class='masterBuilderContainer']/div[contains(@class, 'buildingQueueSlot')]" ) freeSlots = 0 locked = False for slot in slots: if locked: break classes = slot.get_attribute("class").split(" ") for c in classes: if "empty" == c: freeSlots += 1 if "locked" == c: locked = True break return freeSlots class slot: def __init__(self, id: int): self.id = id self.upgradable = False self.field = id < 19 self.lvl = -1 class village: def __init__(self, name: str, index: int): self.slots = [] self.name = name self.index = index # 1-18 = ress # 19-40 = city class gameworld: def __init__(self, world: str): self.world = world.lower() # init self.villages = []
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,304
vlrizkidz93/king-bot
refs/heads/master
/setup.py
from setuptools import setup __version__ = "0.0.1" __author__ = "Felix Breuer" requirements = [ "selenium", "typing", "schedule", "fake_useragent", "chromedriver-py==2.38", ] description = "Travian Kingdoms automation bot." setup( name="king-bot", version=__version__, author=__author__, author_email="f.breuer94@gmail.com", url="https://github.com/breuerfelix/king-bot", description=description, install_requires=requirements, include_package_data=True, )
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,305
vlrizkidz93/king-bot
refs/heads/master
/src/upgrade.py
from .custom_driver import client, use_browser from .slot import find_slot from .utils import log from .util_game import close_modal import time from random import randint from .village import ( open_building, open_village, open_city, open_building_type, building, ) from datetime import timedelta def upgrade_slot(browser: client, id: int) -> None: el = find_slot(browser, id) el = el.find_element_by_xpath(".//div[contains(@class, 'clickable')]") browser.click(el, 1) browser.click(el, 1) log("added slot: {} to queue".format(id)) def upgrade_units_smithy_thread( browser: client, village: int, units: list, interval: int ) -> None: time.sleep(randint(0, 10)) while True: sleep_time: int = interval rv = upgrade_units_smithy(browser, village, units) # log("upgrade units in smithy thread going to sleep ...") if rv != -1: if rv is None: log("smithy is busy.") else: sleep_time = rv log( "smithy is busy. going to sleep for " + "{:0>8}".format(str(timedelta(seconds=sleep_time))) + "." ) time.sleep(sleep_time) @use_browser def upgrade_units_smithy(browser: client, village: int, units: list) -> int: # log("upgrade units in smithy thread waking up ...") open_village(browser, village) open_city(browser) open_building_type(browser, building.smithy) smith = browser.find("//div[contains(@class, 'blacksmith')]") carousel = smith.find_element_by_xpath(".//div[@class='carousel']") pages = carousel.find_element_by_xpath(".//div[contains(@class, 'pages')]") classes = pages.get_attribute("class") # todo implement pages pages = "ng-hide" not in classes # true if there are more than one page item_container = carousel.find_element_by_xpath(".//div[@class='items']") items = item_container.find_elements_by_xpath("./*") countdown = "" available_units: dict = {} for item in items: unit = item.find_element_by_xpath(".//div[contains(@class, 'unit')]") classes = unit.get_attribute("class") if "ng-hide" not in classes: # continue because no dummy container # get unit id unit_img = unit.find_element_by_xpath( ".//img[contains(@class, 'itemImage')]" ) unit_id = int(unit_img.get_attribute("data")) item_body = unit.find_element_by_xpath(".//div[@class='itemBody']") # check for progress bar progress_container = item_body.find_element_by_xpath( ".//div[contains(@class, 'progressContainer')]" ) classes = progress_container.get_attribute("class") if "ng-hide" not in classes: # here is a loading bar countdown_div = progress_container.find_element_by_xpath( ".//div[@class='countdown']" ) countdown = countdown_div.get_attribute("innerHTML") # check if unit is locked divs = item_body.find_elements_by_xpath("./*") locked = False for div in divs: classes = div.get_attribute("class") if "lockExplain" in classes: locked = True if not locked: # add to dict available_units[unit_id] = unit_img if countdown: cd_list = countdown.split(":") cd = int(cd_list[0]) * 60 * 60 + int(cd_list[1]) * 60 + int(cd_list[2]) close_modal(browser) log( "upgrade postponed for " + cd_list[0] + " hours " + cd_list[1] + " minutes " + cd_list[2] + " seconds." ) return cd else: for un in units: if un in available_units: browser.click(available_units[un], 1) log( "will try to upgrade unit: " + str(un) + " in village: " + str(village) + "." ) break # click upgrade button improve = browser.find("//button[contains(@clickable, 'research')]") classes = improve.get_attribute("class").split(" ") available = True for c in classes: if c == "disabled": available = False break if available: browser.click(improve, 1) log("upgrade started.") close_modal(browser) return -1
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,306
vlrizkidz93/king-bot
refs/heads/master
/src/__init__.py
from .king_bot import king_bot from .settings import settings
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,307
vlrizkidz93/king-bot
refs/heads/master
/src/adventures.py
from .custom_driver import client, use_browser from threading import Thread import time from .utils import log from .util_game import close_modal def adventures_thread(browser: client, interval: int, health: int) -> None: # init delay time.sleep(2) while True: if check_health(browser, health): if start_adventure(browser, interval): interval = check_adventure_time(browser) else: log("hero is too low for adventures.") time.sleep(interval) @use_browser def start_adventure(browser: client, interval: int) -> bool: # log("adventure thread waking up") heroLinks = browser.find("//div[@class='heroLinks']") a = heroLinks.find_element_by_xpath(".//a[contains(@class, 'adventureLink')]") browser.click(a, 2) el = browser.find("//div[@class='modalContent']") el = el.find_element_by_xpath(".//button") classes = el.get_attribute("class").split(" ") available = True for c in classes: if c == "disabled": available = False break if available: browser.click(el, 2) log("adventure started.") close_modal(browser) return available # log("adventure thread sleeping") @use_browser def check_health(browser: client, health: int) -> bool: hero_stats = browser.find("//div[@class='heroStats']") hero_stats = hero_stats.find_element_by_xpath(".//div[contains(@class, 'health')]") hero_health = int(hero_stats.get_attribute("perc")) return hero_health > health @use_browser def check_adventure_time(browser: client) -> int: movements = browser.find("//div[@id='troopMovements']") ul = movements.find_element_by_xpath(".//ul") lis = ul.find_elements_by_xpath(".//li") for li in lis: classes = li.get_attribute("class") if "outgoing_adventure" in classes: cd = li.find_element_by_xpath(".//div[@class='countdown']") adventure_time = cd.get_attribute("innerHTML") timelist = adventure_time.split(":") countdown = ( ( (int(timelist[0]) * 60 * 60) + (int(timelist[1]) * 60) + int(timelist[2]) ) * 2 ) + 10 break return countdown
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,308
vlrizkidz93/king-bot
refs/heads/master
/src/robber_camps.py
from .custom_driver import client, use_browser from .utils import log from .util_game import close_modal import time from .village import open_village, open_city, open_map def robber_camp_thread( browser: client, village: int, units: dict, interval: int ) -> None: while True: robbers = check_robbers(browser, village) if robbers is None: robbers = [] if len(robbers): for robber in robbers: send_troops(browser, village, robber, units) else: log("there is no Robber Camps right now, will check again later.") time.sleep(interval) @use_browser def send_troops(browser: client, village: int, robber, units: dict) -> None: if robber is None: log("parsing webelement failed") return open_village(browser, village) open_map(browser) browser.hover(robber) browser.hover(robber) robber_name = robber.text browser.click(robber, 2) item_pos1 = browser.find("//div[contains(@class, 'item pos1')]") browser.click(item_pos1, 2) try: error = browser.find("//div[contains(@ng-if, 'error')]") log(robber_name + ": " + error.get_attribute("innerText")) close_modal(browser) open_city(browser) return except: pass raid_button = browser.find( "//div[contains(@class, 'clickableContainer missionType4')]" ) browser.click(raid_button, 2) input = browser.find("//tbody[contains(@class, 'inputTroops')]/tr") input = input.find_elements_by_xpath(".//td") units_sent = False units_total = 0 if -1 in units: # send all units, max count for inp in input: inp = inp.find_element_by_xpath(".//input") dis = inp.get_attribute("disabled") if not dis: inp.click() number = inp.get_attribute("number") inp.send_keys(number) units_sent = True else: # send value amount of units with index key for key, value in units.items(): inp = input[int(key)].find_element_by_xpath(".//input") # check if the field is disabled dis = inp.get_attribute("disabled") if not dis: # gets max available troop count number = inp.get_attribute("number") units_to_send = int(value) # send all units if value is -1 if units_to_send == -1: units_to_send = int(number) else: if int(number) < units_to_send: # send max value if there arent enough units to send units_to_send = number inp.click() inp.send_keys(units_to_send) units_sent = True units_total += units_to_send if not units_sent: log("no units available to sent.") close_modal(browser) open_city(browser) return time.sleep(1) send_button_1 = browser.find("//button[contains(@class, 'next clickable')]") browser.click(send_button_1, 2) send_button_2 = browser.find("//button[contains(@class, 'sendTroops clickable')]") browser.click(send_button_2, 2) log("sent " + str(units_total) + " units to " + robber_name + ".") open_city(browser) @use_browser def check_robbers(browser: client, village: int): open_village(browser, village) map_button = browser.find("//a[contains(@class, 'navi_map bubbleButton')]") browser.click(map_button, 1) overlay_markers = browser.find("//div[@id='overlayMarkers']") divs = overlay_markers.find_elements_by_xpath(".//div") robbers = [] for listed in divs: attribute = listed.get_attribute("class") if "robber" in attribute: span = listed.find_element_by_xpath(".//span") span_attribute = span.get_attribute("class") if "jsVillageType8" in span_attribute: browser.hover(span) browser.hover(span) robbers.append(span) open_city(browser) return robbers
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,309
vlrizkidz93/king-bot
refs/heads/master
/src/utils.py
import datetime import time import threading def log(message: str): print_status(message) def error(message: str): print_status(message, bcolors.FAIL, "ERROR") def warning(message: str): print_status(message, bcolors.WARNING, "WARNING") def info(message: str): print_status(message, bcolors.HEADER, "INFO") def check_for_lines(path: str, current_lines: list) -> dict: lines_to_add: list = [] lines_to_remove: list = [] with open(path, "r") as file: lines = file.read().splitlines() for line in lines: if line not in current_lines: log("new line: " + str(line)) lines_to_add.append(line) for job in current_lines: if job not in lines: log("removed / changed line: " + str(line)) lines_to_remove.append(job) return {"add": lines_to_add, "remove": lines_to_remove} def parse_time_to_seconds(time: str) -> int: """needs hour:minutes:seconds as paramter, returns time in seconds""" timelist = time.split(":") seconds = int(timelist[0]) * 60 * 60 + int(timelist[1]) * 60 + int(timelist[2]) return seconds def print_status(message: str = None, color: str = "\033[92m", status: str = "OK"): output = ( "[" + color + " " + status + " " + bcolors.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S") ) thread_name = threading.current_thread().name if thread_name is not None: output += " [" + bcolors.OKBLUE + thread_name + bcolors.ENDC + "]" if message is not None: output += " " + message print(output) class bcolors: HEADER = "\033[95m" OKBLUE = "\033[94m" OKGREEN = "\033[92m" WARNING = "\033[93m" FAIL = "\033[91m" ENDC = "\033[0m" def disable(self): self.HEADER = "" self.OKBLUE = "" self.OKGREEN = "" self.WARNING = "" self.FAIL = "" self.ENDC = ""
{"/src/village.py": ["/src/utils.py", "/src/util_game.py"], "/src/slot.py": ["/src/utils.py"], "/src/celebration.py": ["/src/utils.py", "/src/util_game.py"], "/src/dodge_attack.py": ["/src/utils.py", "/src/village.py", "/src/farming.py", "/src/util_game.py"], "/src/util_game.py": ["/src/utils.py"], "/src/account.py": ["/src/utils.py"], "/src/train_troops.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/master_builders.py": ["/src/village.py", "/src/utils.py", "/src/util_game.py"], "/start.py": ["/src/__init__.py"], "/src/farming.py": ["/src/utils.py", "/src/village.py", "/src/util_game.py"], "/src/gamestate.py": ["/src/slot.py", "/src/utils.py"], "/src/upgrade.py": ["/src/slot.py", "/src/utils.py", "/src/util_game.py", "/src/village.py"], "/src/adventures.py": ["/src/utils.py", "/src/util_game.py"], "/src/robber_camps.py": ["/src/utils.py", "/src/util_game.py", "/src/village.py"]}
37,318
RoboneClub/Mechabot-Analysis
refs/heads/main
/map.py
""" Created by Mechabot team This function offers to plot a worldmap with the path of the ISS alongside other given points """ from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np import pandas as pd def dms2dd(arr): """ This method returns an array with the Decimal Degree format of an array with points in Degree,Minutes,Seconds format. Input Parameters: arr --> 1 Dimensional array with a list of location points in the DMS format Returned Parameters: result --> 1 Dimensional array with the points of arr in DD format """ result = [] for i in arr: deg, minutes, seconds = i.split(':') result.append((float(deg) + float(minutes)/60 + float(seconds)/(60*60))) return result def plot(x=[],y=[],label=''): """ This Method Plots the Path of the ISS alongside with indicating specific points on the map of longitude x and latitude y parameters. If no paramters were passed theb only the ISS orbit will be plotted. This requires an active internet service to load the World map image on the background of the plot. Input Parameters: x --> 1D array with the Longitude location of the points which will be indicated on map. y --> 1D array with the Latitude location of the points which will be indicated on map. label --> String storing the label that will be added on the map's legend for the points to be plotted. """ '''Importing the cs file''' data=pd.read_csv('data01.csv') '''Getting the Latitude and longitude data of our flight in DMS format''' lat_dms = data.iloc[:,2].values long_dms = data.iloc[:,3].values '''Changing the format from DMS to DD for plotting on the map''' long_dd = dms2dd(long_dms) lat_dd = dms2dd(lat_dms) '''Preparing the grid for the map plot''' m = Basemap(projection='mill', llcrnrlat = -90, urcrnrlat = 90, llcrnrlon = -180, urcrnrlon = 180, resolution = 'c', epsg = 4269) m.drawcoastlines() '''Plotting our path of the ISS orbit''' m.plot(long_dd[0:2562],lat_dd[0:2562],color='yellow', latlon = True,label='ISS orbit') m.plot(long_dd[2562:5019],lat_dd[2562:5019],color='yellow', latlon = True) m.plot(long_dd[5019:],lat_dd[5019:],color='yellow', latlon = True) '''Adding specific points on the map if parameter x,y were passed''' m.scatter(x,y,color='red',s=60, latlon = True,marker='x',label=label) '''Adds the grid for the plot''' m.drawparallels(np.arange(-90,90,10),labels=[True,False,False,False]) m.drawmeridians(np.arange(-180,180,30),labels=[0,0,0,1]) '''Loads the map background image from the online server''' m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels = 2000, verbose= True) '''Adds a title for the plot''' plt.title(' Experiment runtime ISS orbit', fontsize=20) '''Adds a legend for the plot''' plt.legend() plt.show() '''If this module is ran separately it will plot the path of the ISS''' if __name__ == '__main__': plot()
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,319
RoboneClub/Mechabot-Analysis
refs/heads/main
/noise_filtering.py
import numpy as np def noise_filtering(X,Y,Z,sensitivity,frequency,rms): matrix = np.transpose(np.array((X,Y,Z))) #Using the sensor data LSM9DS1 cross_talk = [[1,sensitivity,sensitivity], [sensitivity,1,sensitivity], [sensitivity, sensitivity, 1]] cross_talk = np.linalg.inv(cross_talk) #Crosstalk --> inverse to divide the data on crosstalk noise_rms = rms * frequency**0.5 noise = np.random.randn(len(X),1) * noise_rms """we remove the noise""" matrix = matrix - noise return matrix if __name__ == '__main__': import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('data01.csv') time = data['Time'] MagnX = data.iloc[:,10].values MagnY = data.iloc[:,11].values MagnZ = data.iloc[:,12].values sensitivity = 0.043 #Senstivity according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf frequency = 20 #Frequency according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf rms = 3.2 * 10**-3 #RMS Noise assumtion according to https://www.st.com/resource/en/datasheet/lis3mdl.pdf which is a similar build Magn = noise_filtering(MagnX,MagnY,MagnZ,sensitivity,frequency,rms) """magnetometer x, y, and z readings with reduced noise""" plt.plot(Magn) plt.show()
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,320
RoboneClub/Mechabot-Analysis
refs/heads/main
/magn.py
import numpy as np import pandas as pd def get_resultant(X,Y,Z): """This function gets the resultant magnitudes of three arrays of vector quantities: X, Y, and Z.""" resultant = [] for i in range(len(X)): resultant.append((X[i]**2 + Y[i]**2 + Z[i] **2)**0.5) return resultant def get_mean_3(x, y, z): """This function calculates the mean of three values""" return (x+y+z)/3 def get_mean(arr): """This function uses numpy's mean funtion to calculate the mean of values in an array""" return np.mean(arr) def get_sd(arr): """This function uses numpy's std funtion to calculate the standard deviation of values in an array""" return np.std(arr) def get_magn_history(magn_resultant, decay = 0.0005): """This function simulates Magnetometer readings in the past""" history_magn = [] for i in magn_resultant: arr = [i] for j in range(9): arr.append(arr[j] + arr[j]*decay) history_magn.append(np.flip(arr)) return history_magn def cor(y,z): """This function numpy's correlate function to find correlations between two arrays""" return np.correlate(y,z,mode="full") def sumnomeq(y,k): """This function calculates the sum of all iterations of the nominaor in the autocorrelation formula""" nomeq = [] end = len(y) - k mean = get_mean(y) for i in range(0,end): nomeq.append((y[i] - mean) * ( y[i + k] - mean)) return np.sum(nomeq) def sumdenomeq(y): """This function calculates the sum of all iterations of the denominaor in the autocorrelation formula""" denomeq = [] mean = get_mean(y) end = len(y) - 1 for i in range(0,end): denomeq.append((y[i] - mean)**2) return np.sum(denomeq) def autocor(y): """Autocorrelation of array y""" #Formula from: https://www.itl.nist.gov/div898/handbook/eda/section3/eda35c.htm autocorarr = [] counter = 0 denom = sumdenomeq(y) for i in range (len(y)-1): autocorarr.append((sumnomeq(y,i)/denom)) counter += 1 print(f"Progress of calculating autocorrelation: {counter*100/len(y)}%") return autocorarr if __name__ == '__main__': import matplotlib.pyplot as plt data = pd.read_csv('data01.csv') """imports the data from the csv using pandas library""" """Takes only the time, magnetometer X, Y, and Z readings from the dataset:""" time = data.iloc[:,1].values MagnX = data.iloc[:,10].values MagnY = data.iloc[:,11].values MagnZ = data.iloc[:,12].values plt.plot(np.arange(0,len(MagnX),1),MagnX,label='MagnX') plt.plot(np.arange(0,len(MagnX),1),MagnY,label='MagnY') plt.plot(np.arange(0,len(MagnX),1),MagnZ,label='MagnZ') """plots magnetometer X,Y, and Z readings""" plt.legend() plt.show() """calculates the resultant magnitude of the magnetic field""" Magn_resultant = get_resultant(MagnX,MagnY,MagnZ) """calculates the mean of magnetometer readings""" Magn_mean = get_mean(Magn_resultant) """calculates the standard deviation of magnetometer readings""" Magn_sd = get_sd(Magn_resultant) autocorr_magn = autocor(MagnX)#np.load("autocorrelation_magn.npy",allow_pickle=True) import plot plot.plot_2d(np.arange(0,len(MagnX),1),'record number',[np.append(autocorr_magn,autocorr_magn[-1])],'Autocorrelation',[MagnX],"Magn") plt.plot(np.arange(0,len(MagnX),1),Magn_resultant,label='MagnResultant') plt.plot(np.arange(0,len(MagnX),1),[Magn_mean]*len(MagnX),label='Mean') plt.plot(np.arange(0,len(MagnX),1),[Magn_sd]*len(MagnX),label='Numpy Standard Deviation') """plots resultant magnetometer values, the mean, and the standard deviation""" plt.legend() plt.show() """ fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel('time (s)') ax1.set_ylabel('Magnetic Strength', color=color) ax1.plot(np.arange(0,len(MagnX),1), Magn_resultant, color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel('Auto-correlation', color=color) # we already handled the x-label with ax1 ax2.plot(np.arange(0,len(MagnX),1), auto_correlation, color=color) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.show() """
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,321
RoboneClub/Mechabot-Analysis
refs/heads/main
/graphs.py
"""This script Plots the retrieved data in the CSV using the matplotlib""" import matplotlib.pyplot as plt import pandas as pd import numpy as np """importing data from CSV files""" #importing time, tilt, gyroscope, magnetometer, acceleration, and img values data = pd.read_csv('data01.csv') time = data.iloc[:,1].values tilt = data.iloc[:,4:7].values gyro = data.iloc[:,7:10].values magn = data.iloc[:,10:13].values acc = data.iloc[:,13:].values img = data.iloc[:,-1] """Plotting the rate of capturing the imgaes""" t = [] for i in time: t.append(i.split(":")) start_time = float(t[0][0])*3600 + float(t[0][1])*60 + float(t[0][2]) -1 rate = [] for index in range(len(img)): delta_time = float(t[index][0])*3600 + float(t[index][1])*60 + float(t[index][2]) - start_time rate.append(img[index]/delta_time) plt.title("img rate") plt.plot(time[10:],rate[10:],color = 'blue') plt.scatter(time[10:],rate[10:],color = "red") plt.xlabel("Time") plt.ylabel("Rate of taking images") plt.show() """Plotting the Magnometer readings on 3 seperate plots""" fig, (ax1, ax2,ax3) = plt.subplots(3) fig.suptitle('Magnometer') l1, = ax1.plot(time,magn[:,0],color='r',label="dsads") l2, = ax2.plot(time,magn[:,1],color='b') l3, = ax3.plot(time,magn[:,2],color='g') plt.legend([l1, l2, l3],["MagnX", "MagnY", "MagnZ"]) plt.show() """Plotting the Position readings on 3 seperate plot""" fig, (ax1, ax2,ax3) = plt.subplots(3) fig.suptitle('Tilting') l1, = ax1.plot(time,tilt[:,0],color='r',label="dsads") l2, = ax2.plot(time,tilt[:,1],color='b') l3, = ax3.plot(time,tilt[:,2],color='g') plt.legend([l1, l2, l3],["Pitch", "Roll", "Yaw"]) plt.show() """Plotting the Acceleration readings on 3 seperate plots""" fig, (ax1, ax2,ax3) = plt.subplots(3) fig.suptitle('Accel') l1, = ax1.plot(time,acc[:,0],color='r',label="dsads") l2, = ax2.plot(time,acc[:,1],color='b') l3, = ax3.plot(time,acc[:,2],color='g') plt.legend([l1, l2, l3],["AccX", "AccY", "AccZ"]) plt.show() """Plotting the angular velocity readings on 3 seperate plots""" fig, (ax1, ax2,ax3) = plt.subplots(3) fig.suptitle('Gyro') l1, = ax1.plot(time,gyro[:,0],color='r',label="dsads") l2, = ax2.plot(time,gyro[:,1],color='b') l3, = ax3.plot(time,gyro[:,2],color='g') plt.legend([l1, l2, l3],["GyroX", "GyroY", "GyroZ"]) plt.show() """Plotting the Magnometer readings in a single plot""" plt.title("Magn") plt.plot(time,magn[:,0],color = 'blue',label="x-Magnometer") plt.plot(time,magn[:,1],color = 'red',label="y-Magnometer") plt.plot(time,magn[:,2],color = 'green',label="z-Magnometer") plt.legend() plt.xlabel("Time") plt.ylabel("Magnetic Field") plt.show() """Plotting the angular velocity readings in a single plot""" plt.title("Gyro") plt.plot(time,gyro[:,0],color = 'blue',label="x-Gyro") plt.plot(time,gyro[:,1],color = 'red',label="y-Gyro") plt.plot(time,gyro[:,2],color = 'green',label="z-Gyro") plt.legend() plt.xlabel("Time") plt.ylabel("Gyro") plt.show()
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,322
RoboneClub/Mechabot-Analysis
refs/heads/main
/plot.py
import matplotlib.pyplot as plt def plot_2d(x_axis,x_label,arr1,arr1_label,arr2,arr2_label,title=[""]*20): for m in range(len(arr1)): fig, ax1 = plt.subplots() color = 'tab:red' ax1.set_xlabel(x_label,size=15) ax1.set_ylabel(arr1_label, color=color,size = 15) ax1.plot(x_axis, arr1[m], color=color) ax1.tick_params(axis='y', labelcolor=color) ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis color = 'tab:blue' ax2.set_ylabel(arr2_label, color=color,size=15) # we already handled the x-label with ax1 ax2.plot(x_axis, arr2[m], color=color) ax2.tick_params(axis='y', labelcolor=color) fig.tight_layout() # otherwise the right y-label is slightly clipped plt.title(title[m],size=15,color='green') plt.show()
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,323
RoboneClub/Mechabot-Analysis
refs/heads/main
/experiment-2.py
""" This expirment tests whether or not the magnetic field affects the objects in the LEO by correlating the resultant intensity of the magnetic field with the accelertaion and angular velocity of the ISS """ """ Importing the libraries and the modules """ from datetime import datetime,timedelta import magn import numpy as np import pandas as pd import matplotlib.pyplot as plt import noise_filtering import plot """_______________________ Part 1: Analyzing the IMU sensor data _______________________""" ''' 1-Importing the IMU sensor data ''' #Imports the whole data from the csv using pandas library data = pd.read_csv('data01.csv') #Takes the time, gyroscope, magnometer, and accelerometer X, Y, and Z readings from the dataset: time = data.iloc[:,1].values gyroX = data.iloc[:,7].values gyroY = data.iloc[:,8].values gyroZ = data.iloc[:,9].values magnX = data.iloc[:,10].values magnY = data.iloc[:,11].values magnZ = data.iloc[:,12].values magn_resultant = magn.get_resultant(magnX,magnY,magnZ) accX = data.iloc[:,13].values accY = data.iloc[:,14].values accZ = data.iloc[:,15].values acc_resultant = magn.get_resultant(accX,accY,accZ) ''' 2-Preprocessing the data by applying noise filteration ''' gyro_filtered_matrix = noise_filtering.noise_filtering(gyroX,gyroY,gyroZ,sensitivity = (0.0175), frequency = 476, rms = (3.2 * 10**-3) ) #Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf magn_filtered_matrix = noise_filtering.noise_filtering(magnX,magnY,magnZ,sensitivity = 0.043, frequency = 20, rms = (3.2 * 10**-3) ) #Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf #RMS Noise assumtion according to https://www.st.com/resource/en/datasheet/lis3mdl.pdf which is a similar build acc_filtered_matrix = noise_filtering.noise_filtering(accX,accY,accZ,sensitivity = (0.000244*9.81), frequency = 10, rms = (3.2 * 10**-3) ) #Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf gyroX_filtered = gyro_filtered_matrix[:,0] gyroY_filtered = gyro_filtered_matrix[:,1] gyroZ_filtered = gyro_filtered_matrix[:,2] magn_filtered_resultant = magn.get_resultant(magn_filtered_matrix[:,0],magn_filtered_matrix[:,1],magn_filtered_matrix[:,2]) acc_filtered_resultant = magn.get_resultant(acc_filtered_matrix[:,0],acc_filtered_matrix[:,1],acc_filtered_matrix[:,2]) ''' 3- Calculating the resultant magnitude, the standard deviation, the mean and the autocorrelation of the points for the filtered and unfiltered magnetic field, acceleration, and angular velocity''' gyroX_sd = magn.get_sd(gyroX_filtered) gyroY_sd = magn.get_sd(gyroY_filtered) gyroZ_sd = magn.get_sd(gyroZ_filtered) gyro_sd_mean = magn.get_mean_3(gyroX_sd, gyroY_sd, gyroZ_sd) gyroX_mean = magn.get_mean(gyroX_filtered) gyroY_mean = magn.get_mean(gyroY_filtered) gyroZ_mean = magn.get_mean(gyroZ_filtered) gyro_mean_mean = magn.get_mean_3(gyroX_mean, gyroY_mean, gyroZ_mean) magn_sd = magn.get_sd(magn_filtered_resultant) magn_mean = magn.get_mean(magn_filtered_resultant) magn_autocorrelation = magn.autocor(magn_filtered_resultant) acc_sd = magn.get_sd(acc_filtered_resultant) acc_mean = magn.get_mean(acc_filtered_resultant) acc_autocorrelation = magn.autocor(acc_filtered_resultant) acc_autocorrelation_pure = magn.autocor(acc_resultant) '''4- Plotting the Autocorrelation''' #plots accelerometer data plt.title("Accelerometer Data") plt.xlabel("Reading number") plt.ylabel("Acceleration/g") plt.plot(acc_filtered_resultant,label='AccResultant') plt.plot([acc_mean]*len(accX),label='Mean') plt.plot([acc_sd]*len(accX),label='Standard Deviation') plt.legend() plt.show() plt.plot(acc_autocorrelation, label = "Noise filtered acceleration readings autocorrelation") plt.plot(acc_autocorrelation_pure, label= "Raw acceleration readings autocorrelation") plt.xlabel("Readings number") plt.ylabel("Autocorrelation value") plt.title("Auto correlation of Resultant Acceleration") plt.legend() plt.show() #plots magnetometer data plt.title("Magnetometer Data") plt.ylabel("Magnetic Intensity/µT") plt.xlabel("Reading number") plt.plot(magn_filtered_resultant,label='MagnResultant') plt.plot([magn_mean]*len(magnX),label='Mean') plt.plot([magn_sd]*len(magnX),label='Standard Deviation') plt.legend() plt.show() #plots autocorrelation data plot.plot_2d(np.arange(0,len(magn_filtered_resultant),1),'Reading number',[np.append(magn_autocorrelation,magn_autocorrelation[-1])],'Autocorrelation of magnetic field',[magn_filtered_resultant],"Resultant Magnetic field Intensity/µT") """_______________________ Part 2: Comparing and correlating data ______________________""" '''1- Plotting the correlations ''' magn_acc_cor = magn.cor(magn_filtered_resultant, acc_filtered_resultant) #plots correlation data plt.title("Correlation between Acceleration and Magnetic Intensity") plt.xlabel("Reading number") plt.plot(magn_acc_cor) plt.ylabel("Correlation value") plt.legend() plt.show() magn_gyroX_cor = magn.cor(magn_filtered_resultant, gyroX_filtered) #plots correlation data plt.title("Correlation between Angular velocity in X-axis and Magnetic Intensity") plt.xlabel("Reading number") plt.plot(magn_gyroX_cor) plt.ylabel("Correlation value") plt.legend() plt.show() magn_gyroY_cor = magn.cor(magn_filtered_resultant, gyroY_filtered) #plots correlation data plt.title("Correlation between Angular velocity in Y-axis and Magnetic Intensity") plt.xlabel("Reading number") plt.plot(magn_gyroY_cor) plt.ylabel("Correlation value") plt.legend() plt.show() magn_gyroZ_cor = magn.cor(magn_filtered_resultant, gyroZ_filtered) #plots correlation data plt.title("Correlation between Angular velocity in Z-axis and Magnetic Intensity") plt.xlabel("Reading number") plt.plot(magn_gyroZ_cor) plt.ylabel("Correlation value") plt.legend() plt.show()
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,324
RoboneClub/Mechabot-Analysis
refs/heads/main
/API.py
#https://www.worldweatheronline.com/developer/api/docs/historical-weather-api.aspx import requests import numpy as np from geopy.geocoders import Nominatim from datetime import datetime,timedelta url = "https://api.worldweatheronline.com/premium/v1/past-weather.ashx?" key = "XXXXXXXXXXXXXXXXXXXXXXXX" #Add the API key here def get_weather_data(lat=[],long=[],date=[]): """This function gathers weather data for the corresponding latitude, longitude, and date, for the past 10 years.""" weather_data = [] length = len(lat) counter = 0 for lat,long,date in zip(lat,long,date): this_location_weather = [] #collects the weather data for this location for last 10 years for i in range(10): d = (datetime.strptime(date,'%d/%m/20%y') - timedelta(365*i)).strftime("%d/%m/%Y") try: print("Trying to fetch response.....") response = requests.get(f"{url}key={key}&q={lat},{long}&date={d}&format=json") this_location_weather.append(response.json()['data']) print(f"Fetched weather history data for {lat},{long} on {d}") except: print(f"Failed to retrive data for {lat},{long} on {d}") this_location_weather.append("Failed to retrieve") counter += 1 print(f"API Fetching Progress {counter*100/length}%") weather_data.append(this_location_weather) return weather_data def get_avg_temp(data): """this function gets the average temperatures for each point in the fetched data""" temp_history = [] for point in data: this_point_temp = [] for year_reading in point: this_point_temp.append(int(year_reading['weather'][0]['avgtempC'])) temp_history.append(np.flip(this_point_temp)) return temp_history def get_uv_index(data): """this function gets the average uv index for each point in the fetched data""" uv_index_history = [] for point in data: this_point_temp = [] for year_reading in point: this_point_temp.append(int(year_reading['weather'][0]['uvIndex'])) uv_index_history.append(np.flip(this_point_temp)) return uv_index_history def get_avg_precipitation(data): """this function gets the average precipitation for each point in the fetched data""" precip_history = [] for point in data: this_point_precip = [] for year_reading in point: hourly = [] for hour in year_reading['weather'][0]['hourly']: hourly.append(float(hour['precipMM'])) this_point_precip.append(float(np.average(hourly))) precip_history.append(np.flip(this_point_precip)) return precip_history def get_avg_wind_speed(data): """this function gets the average wind speeds for each point in the fetched data""" wind_speed_history = [] for point in data: this_point_wind_speed = [] for year_reading in point: hourly = [] for hour in year_reading['weather'][0]['hourly']: hourly.append(float(hour['windspeedKmph'])) this_point_wind_speed.append(float(np.average(hourly))) wind_speed_history.append(np.flip(this_point_wind_speed)) return wind_speed_history def get_avg_humidity(data): """this function gets the average humidity for each point in the fetched data""" humidity_history = [] for point in data: this_point_humidity = [] for year_reading in point: hourly = [] for hour in year_reading['weather'][0]['hourly']: hourly.append(float(hour['humidity'])) this_point_humidity.append(float(np.average(hourly))) humidity_history.append(np.flip(this_point_humidity)) return humidity_history def get_location(long,lat): geolocator = Nominatim(user_agent="GoogleV3") locations = [] for i,j in zip(long,lat): location = geolocator.reverse(str(i)+","+str(j)) location = location.address if location != None else 'N/A' locations.append(location) return locations if __name__ == '__main__': lat = [52.509669] long = [13.376294] date = ["01/01/2010"] data = get_weather_data(lat,long,date) print(data[0][0]['weather'][0]['avgtempC']) #prints the average tempereature for 01/01/2010 of the first location print("/n/n//n/n/n\nn\n\n\n\n\n\n\n") print(get_location(lat,long)) #prints the average tempereature for 01/01/2010 of the first location
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,325
RoboneClub/Mechabot-Analysis
refs/heads/main
/experiment-1.py
""" Importing the libraries and the modules """ from datetime import datetime,timedelta import API import magn import map import numpy as np import pandas as pd import matplotlib.pyplot as plt import noise_filtering """_______________________ Part 1: Analyzing the magnometer data _______________________""" ''' 1-Importing the magnometer data ''' #Imports the whole data from the csv using pandas library data = pd.read_csv('data01.csv') #Takes only the time,magnometer X,Y,Z readings from the dataset: time = data.iloc[:,1].values magnX = data.iloc[:,10].values magnY = data.iloc[:,11].values magnZ = data.iloc[:,12].values ''' 2-Preprocessing the data by applying noise filteration ''' magn_filtered_matrix = noise_filtering.noise_filtering(magnX,magnY,magnZ,sensitivity = 0.043, frequency = 20, rms = (3.2 * 10**-3) ) #Senstivity and Frequency are according to https://www.st.com/resource/en/datasheet/lsm9ds1.pdf #RMS Noise assumtion according to https://www.st.com/resource/en/datasheet/lis3mdl.pdf which is a similar build ''' 3- Calculating the resultant magnitude of the magnetic field, the standard deviation,the mean and the auto corelation of the points''' magn_resultant = magn.get_resultant(magn_filtered_matrix[:,0],magn_filtered_matrix[:,1],magn_filtered_matrix[:,2]) magn_sd = magn.get_sd(magn_resultant) magn_mean = magn.get_mean(magn_resultant) magn_autocorrelation = magn.autocor(magn_resultant) #A graph is plotted for the magnetic intensity autocorrelation in expirment 2 '''4- Plotting the graphs ''' plt.title("Magnometer Readings") plt.xlabel("Time") plt.ylabel("Magnetic Intensity/µT") plt.plot(time,magnX,label='MagnX') plt.plot(time,magnY,label='MagnY') plt.plot(time,magnZ,label='MagnZ') plt.legend() plt.show() plt.title("Magnometer Data") plt.xlabel("Time") plt.ylabel("Magnetic Intensity/µT") plt.plot(time,magn_resultant,label='MagnResultant') plt.plot(time,[magn_mean]*len(magnX),label='Mean') plt.plot(time,[magn_sd]*len(magnX),label='Standard Deviation') plt.legend() plt.show() """_______________________ Part 2: Extracting 20 points to preform the research on _______________________""" ''' 0-The chosen points: ''' #Indices of the chosen points: points_of_study = [78, 179, 447, 597, 689, 771, 833, 953, 1037, 1125, 3974, 4037, 4075, 4133, 4155, 4180, 4197, 4234, 4271, 4286] '''1-Extracting the location of these points from the dataset''' long_dms = data.iloc[points_of_study]['Longitude'].values lat_dms = data.iloc[points_of_study]['Latitude'].values #Changing the format of the location longitude and latitude from Degree Minutes Seconds to Decimal Degress long_dd = map.dms2dd(long_dms) lat_dd = map.dms2dd(lat_dms) '''2-Marking the Study Points on the Map''' #map.plot(long_dd,lat_dd,'Study Points') #Getting the image numbers for the images of the chosen locations imgs = data.iloc[points_of_study]['ImgNo'].values print(f"\n \n {'='*100}\n Make sure to Check out images: \n{imgs}\n to see the images corresponding to the chosen points \n{'='*100}\n\n\n\n") '''3-Extract the magnetic field readings corresponding to the chosen indices for the study:''' magn_points_of_study = pd.DataFrame({'col':magn_resultant}).iloc[points_of_study].values.flatten(order='C') '''4-Get the magnometic values history for 10 years of each location ''' #Refrence for decay value: https://www.pnas.org/content/115/20/5111#:~:text=Abstract,since%201600%20or%20even%20earlier. magn_history = magn.get_magn_history(magn_points_of_study,decay = 0.0005) """_______________________ Part 3: Fetching the weather history data for the study points _______________________""" '''Importing the date for the Points''' date = data.iloc[points_of_study]['Date'].values '''1-Downloading the weather data for the last 10 years for each point using the API''' weather_data = API.get_weather_data(lat_dd, long_dd, date) '''1.5-Saving the downloaded data in a numpy file ''' np.save("weather_data.npy",weather_data) #For loading the file: #weather_data = np.load("weather_data.npy",allow_pickle=True) '''2-Extract each variable from the downloaded data''' avg_temp = np.array(API.get_avg_temp(weather_data)) avg_wind_speed = np.array(API.get_avg_wind_speed(weather_data)) avg_uv_index = np.array(API.get_uv_index(weather_data)) avg_precip = np.array(API.get_avg_precipitation(weather_data)) avg_humidity = np.array(API.get_avg_humidity(weather_data)) """Results of Experiment 1.0: ____________ Part 4: Comparing the Magnometer values with the climate of the study points to check general characetistics of magnetic zones __________""" """ This experiment checks for the presence of climate characteristics associated with the magnetic intensity.For example it checks if areas with high magnetic intensities tend to have higher temperatures than other areas with lower magnetic intensities. The experiment scatters each reading of the magnetic field alongside with the climate values from the 20 locations all in one graph. """ #plotting the graphs plt.title("Magnometer - Temperature") plt.scatter(magn_points_of_study,avg_temp[:,0]) plt.ylabel("Average Temperature/ C") plt.xlabel("Magnetic Intensity/µT") plt.show() plt.title("Magnometer - Windspeed") plt.scatter(magn_points_of_study,avg_wind_speed[:,0]) plt.ylabel("Average Wind Speed/ KmHr") plt.xlabel("Magnetic Intensity/µT") plt.show() plt.title("Magnometer - UV index") plt.scatter(magn_points_of_study,avg_uv_index[:,0]) plt.ylabel("Average UV index") plt.xlabel("Magnetic Intensity/µT") plt.show() plt.title("Magnometer - Precipitation") plt.scatter(magn_points_of_study,avg_precip[:,0]) plt.ylabel("Average Precipitation/mm") plt.xlabel("Magnetic Intensity/µT") plt.show() plt.title("Magnometer - Humidity") plt.scatter(magn_points_of_study,avg_humidity[:,0]) plt.ylabel("Average Humidity/%") plt.xlabel("Magnetic Intensity/µT") plt.show() """Results of Experiment 1.5: _______________________ Part 5: Comparing the Magnometer values with the weather history data for each of the study points _______________________""" """ This experiment produces graphs that check for correlations between change in Magnetic field intensity and the change of each of Average Temperature, Wind Speed, UV Index, Precipitation, and Humidty in 20 locations for the past 10 years. Each graph contains the past climate history along side with the magnetic intensity history for Each Location from the 20 Points. """ import plot locations = API.get_location(long_dd,lat_dd) x_axis = np.arange(2012,2022,1) #plotting the graphs plot.plot_2d(x_axis,'Year',avg_temp,'Average Temperature of day',magn_history,'Magnetic field intensity/µT',locations) plot.plot_2d(x_axis,'Year',avg_wind_speed,'Average wind speed',magn_history,'Magnetic field intensity/µT',locations) plot.plot_2d(x_axis,'Year',avg_uv_index,'Average UV index',magn_history,'Magnetic field intensity/µT',locations) plot.plot_2d(x_axis,'Year',avg_precip,'Average precip',magn_history,'Magnetic field intensity/µT',locations) plot.plot_2d(x_axis,'Year',avg_humidity,'Average humidity',magn_history,'Magnetic field intensity/µT',locations)
{"/magn.py": ["/plot.py"], "/experiment-2.py": ["/magn.py", "/noise_filtering.py", "/plot.py"], "/experiment-1.py": ["/API.py", "/magn.py", "/map.py", "/noise_filtering.py", "/plot.py"]}
37,333
Querela/discord-system-observer-bot
refs/heads/master
/discord_system_observer_bot/statsobserver.py
import datetime import typing from base64 import b64encode from collections import defaultdict from functools import lru_cache, partial from io import BytesIO from discord_system_observer_bot.gpuinfo import get_gpus from discord_system_observer_bot.gpuinfo import ( _get_gpu_util, _get_gpu_mem_load, _get_gpu_temp, ) from discord_system_observer_bot.sysinfo import ( _get_loadavg, _get_mem_util, _get_mem_used, ) from discord_system_observer_bot.sysinfo import ( _get_disk_paths, _get_disk_usage, _get_disk_free_gb, ) LimitTypesSetType = typing.Optional[typing.Tuple[str]] # --------------------------------------------------------------------------- @lru_cache(maxsize=1) def has_extra_deps_gpu() -> bool: try: import GPUtil # pylint: disable=import-outside-toplevel,unused-import except ImportError: return False return True @lru_cache(maxsize=1) def has_extra_deps_plot() -> bool: try: import matplotlib # pylint: disable=import-outside-toplevel,unused-import except ImportError: return False return True # --------------------------------------------------------------------------- def collect_stats( include: typing.Set[str] = ("cpu", "disk", "gpu") ) -> typing.Dict[str, typing.Union[float, int]]: stats = dict() stats["_id"] = 0 stats["_datetime"] = int(datetime.datetime.now(datetime.timezone.utc).timestamp()) if "cpu" in include: ( stats["load_avg_1m_perc_percpu"], stats["load_avg_5m_perc_percpu"], stats["load_avg_15m_perc_percpu"], ) = [round(v, 1) for v in _get_loadavg()] stats["mem_util_perc"] = round(_get_mem_util(), 1) stats["mem_used_gb"] = round(_get_mem_used(), 1) if "disk" in include: for dpath in _get_disk_paths(): stats[f"disk_usage_perc:{dpath}"] = round(_get_disk_usage(dpath), 1) stats[f"disk_free_gb:{dpath}"] = round(_get_disk_free_gb(dpath), 1) if "gpu" in include and has_extra_deps_gpu(): for gpu in get_gpus(): stats[f"gpu_util_perc:{gpu.id}"] = round(gpu.load * 100) stats[f"gpu_mem_perc:{gpu.id}"] = round(gpu.memoryUtil * 100, 1) stats[f"gpu_temp:{gpu.id}"] = round(gpu.temperature, 1) stats[f"gpu_mem_used_mb:{gpu.id}"] = int(gpu.memoryUsed) stats[f"gpu_mem_total_mb:{gpu.id}"] = int(gpu.memoryTotal) return stats def stats2rows( stats_list: typing.List[typing.Dict[str, typing.Union[float, int]]] ) -> typing.Optional[typing.Tuple[typing.Tuple[str, typing.List]]]: if not stats_list: return None names = tuple(stats_list[0].keys()) # TODO: need to order by _id/_datetime values? # TODO: filter those values? series = list(zip(*[tuple(s.values()) for s in stats_list])) return tuple(zip(names, series)) def plot_rows( data_series: typing.Tuple[typing.Tuple[str, typing.List]], as_data_uri: bool = True ) -> typing.Optional[typing.Union[str, bytes]]: if not has_extra_deps_plot(): return None # pylint: disable=import-outside-toplevel # import matplotlib.dates as mdates import matplotlib.pyplot as plt # pylint: enable=import-outside-toplevel meta_series = [ds for ds in data_series if ds[0].startswith("_")] data_series = [ds for ds in data_series if not ds[0].startswith("_")] # how many subplots nrows = len(data_series) ncols = 2 # shared x-axis x = [ # pylint: disable=invalid-name datetime.datetime.utcfromtimestamp(v) for n, vs in meta_series if n == "_datetime" for v in vs ] # alternative numeric x-labels # x = [vs for n, vs in meta_series if n == "_id"][0] # pylint: disable=invalid-name # plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M")) # plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1)) # fig, axes = plt.subplots(int((nrows + ncols - 1) / ncols), ncols, sharex=True, figsize=(8, 10)) fig = plt.figure(figsize=(8, 10)) # how many rows / columns, round up plt_layout_fmt = (int((nrows + ncols - 1) / ncols), ncols) # plot series for axis_nr, (name, series) in enumerate(data_series, 1): # get current plot ax = fig.add_subplot(*(plt_layout_fmt + (axis_nr,))) # plot ax.plot(x, series) # set plot title ax.set_title(name) for axis_nr, ax in enumerate(fig.axes, 1): # set x-axis to start with 0 # ax.set_xlim(left=0, right=len(x)) # disable inner x-axis labels # ax.label_outer() # if not ax.is_last_row(): # if axis_nr not in (nrows, nrows - 1): # print(ax.get_title()) # for label in ax.get_xticklabels(which="both"): # label.set_visible(False) # ax.get_xaxis().get_offset_text().set_visible(False) # ax.set_xlabel("") pass plt.gcf().autofmt_xdate() plt.tight_layout() # serialize result bbuf = BytesIO() # https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html fig.savefig(bbuf, format="png") if as_data_uri: data_uri = f"data:image/png;base64,{b64encode(bbuf.getvalue()).decode()}" return data_uri return bbuf.getvalue() # --------------------------------------------------------------------------- class ObservableLimit(typing.NamedTuple): #: visible name of the check/limit/... name: str #: function that returns a numeric value fn_retrieve: typing.Callable[[], float] #: function that get current and threshold value (may be ignored) #: and returns True if current value is ok fn_check: typing.Callable[[float, float], bool] #: unit, str (for visibility purposes, nothing functional, like %, °C, GB) unit: str #: threshold, numeric (for visibility purposes) threshold: float #: message to send if check failed (e. g. resource exhausted) message: str #: badness increment for each failed check, None for default #: can be smaller than threshold to allow for multiple consecutive failed checks #: or same as threshold to immediatly notify badness_inc: typing.Optional[int] = None #: WARNING: currently ignored! (default value of 1 used) #: allows for faster/slower decay of bad status badness_dec: typing.Optional[int] = None #: badness threshold if reached, a message is sent, None for default #: allows for fluctuations until message is sent badness_threshold: typing.Optional[int] = None class BadCounterManager: """Manager that gathers badness values for keys with individual thresholds and increments.""" def __init__( self, default_threshold: int = 3, default_increase: int = 1, default_decrease: int = 1, ): self.bad_counters = defaultdict(int) self.default_increase = default_increase self.default_decrease = default_decrease self.default_threshold = default_threshold def reset(self, name: typing.Optional[str] = None) -> None: """Reset counters etc. to normal/default levels.""" if name is not None: self.bad_counters[name] = 0 else: for name_ in self.bad_counters.keys(): self.bad_counters[name_] = 0 def increase_counter(self, name: str, limit: ObservableLimit) -> bool: """Increse the badness level and return True if threshold reached.""" bad_threshold = ( limit.badness_threshold if limit.badness_threshold is not None else self.default_threshold ) bad_inc = ( limit.badness_inc if limit.badness_inc is not None else self.default_increase ) # increse value self.bad_counters[name] = min(bad_threshold, self.bad_counters[name] + bad_inc) return self.threshold_reached(name, limit) def decrease_counter( self, name: str, limit: typing.Optional[ObservableLimit] = None ) -> bool: """Decrease the badness counter and return True if normal.""" if self.bad_counters[name] > 0: bad_dec = ( limit.badness_dec if limit is not None and limit.badness_dec is not None else self.default_decrease ) self.bad_counters[name] = max(0, self.bad_counters[name] - bad_dec) return self.is_normal(name) def threshold_reached(self, name: str, limit: ObservableLimit) -> bool: """Return True if the badness counter has reached the threshold.""" bad_threshold = ( limit.badness_threshold if limit.badness_threshold is not None else self.default_threshold ) return self.bad_counters[name] >= bad_threshold def is_normal(self, name: str) -> bool: """Return True if the badness counter is zero/normal.""" return self.bad_counters[name] == 0 class NotifyBadCounterManager(BadCounterManager): """Manager that collects badness values and notification statuses.""" def __init__( self, default_threshold: int = 3, default_increase: int = 1, default_decrease: int = 1, ): super().__init__( default_threshold=default_threshold, default_increase=default_increase, default_decrease=default_decrease, ) self.notified = defaultdict(bool) def reset(self, name: typing.Optional[str] = None) -> None: super().reset(name=name) if name is not None: self.notified[name] = False else: for name_ in self.notified.keys(): self.notified[name_] = False def decrease_counter( self, name: str, limit: typing.Optional[ObservableLimit] = None ) -> bool: """Decrease the counter and reset the notification flag if the normal level has been reached. Returns True on change from non-normal to normal (for a one-time notification setup).""" was_normal_before = self.is_normal(name) has_notified_before = self.notified[name] is_normal = super().decrease_counter(name, limit=limit) if is_normal: self.notified[name] = False # return True if changed, else False if it was already normal # additionally require a limit exceeded message to be sent, else ignore the change return was_normal_before != is_normal and has_notified_before def should_notify(self, name: str, limit: ObservableLimit) -> bool: """Return True if a notification should be sent.""" if not self.threshold_reached(name, limit): return False if self.notified[name]: return False return True def mark_notified(self, name: str) -> None: """Mark this counter as already notified.""" self.notified[name] = True # --------------------------------------------------------------------------- def make_observable_limits( include: LimitTypesSetType = ( "cpu", "ram", "disk", "disk_gb", "gpu_load", "gpu_temp", ) ) -> typing.Dict[str, ObservableLimit]: limits = dict() if include is None: # critical: more for early warnings include = ("disk", "disk_gb", "gpu_temp") # more for notification purposes (if free or not) # include += ("cpu", "ram", "gpu_load") if "cpu" in include: limits["cpu_load_5min"] = ObservableLimit( name="CPU Load Avg [5min]", fn_retrieve=lambda: round(_get_loadavg()[1], 1), fn_check=lambda cur, thres: cur < thres, unit="%", threshold=95.0, message="**CPU Load Avg [5min]** is too high! (value: `{cur_value:.1f}%`, threshold: `{threshold:.1f})`", # increase badness level by 2 badness_inc=2, # notify, when badness counter reached 6 badness_threshold=6, ) if "ram" in include: limits["mem_util"] = ObservableLimit( name="Memory Utilisation", fn_retrieve=lambda: round(_get_mem_util(), 1), fn_check=lambda cur, thres: cur < thres, unit="%", threshold=85.0, message="**Memory Usage** is too high! (value: `{cur_value:.1f}%`, threshold: `{threshold:.1f})`", # increase badness level by 1 badness_inc=1, # notify, when badness counter reached 3 badness_threshold=3, ) if "disk" in include or "disk_gb" in include: for i, path in enumerate(_get_disk_paths()): if "disk" in include: limits[f"disk_util_perc{i}"] = ObservableLimit( name=f"Disk Usage: {path}", fn_retrieve=partial(_get_disk_usage, path), fn_check=lambda cur, thres: cur < thres, unit="%", threshold=95.0, message=( f"**Disk Usage for `{path}`** is too high! " "(value: `{cur_value:.1f}%`, threshold: `{threshold:.1f})`" ), # use default increment amount badness_inc=None, # notify immediately badness_threshold=None, ) # TODO: disable the static values test if system has less or not significantly more total disk space if "disk_gb" in include: def _round_get_disk_gree_gb(path): return round(_get_disk_free_gb(path), 1) limits[f"disk_util_gb{i}"] = ObservableLimit( name=f"Disk Space (Free): {path}", fn_retrieve=partial(_round_get_disk_gree_gb, path), fn_check=lambda cur, thres: cur > thres, unit="GB", # currently a hard-coded limit of 30GB (for smaller systems (non-servers) unneccessary?) threshold=30.0, message=( "No more **Disk Space for `{path}`**! " "(value: `{cur_value:.1f}GB`, threshold: `{threshold:.1f})`" ), # use default increment amount badness_inc=None, # notify immediately badness_threshold=None, ) if ("gpu_load" in include or "gpu_temp" in include) and has_extra_deps_gpu(): for gpu in get_gpus(): # NOTE: may be useful if you just want to know when GPU is free for new stuff ... if "gpu_load" in include: limits[f"gpu_util_perc:{gpu.id}"] = ObservableLimit( name=f"GPU {gpu.id} Utilisation", fn_retrieve=partial(_get_gpu_util, gpu.id), fn_check=lambda cur, thres: cur < thres, unit="%", threshold=85, message="**GPU {gpu.id} Utilisation** is working! (value: `{cur_value}%`, threshold: `{threshold})`", # increase by 2, decrease by 1 badness_inc=2, badness_threshold=6, ) limits[f"gpu_mem_perc:{gpu.id}"] = ObservableLimit( name=f"GPU {gpu.id} Memory Utilisation", fn_retrieve=partial(_get_gpu_mem_load, gpu.id), fn_check=lambda cur, thres: cur < thres, unit="%", threshold=85.0, message="**GPU {gpu.id} Memory** is full! (value: `{cur_value:.1f}%`, threshold: `{threshold:.1f})`", # increase by 2, decrease by 1 badness_inc=2, badness_threshold=6, ) if "gpu_temp" in include: limits[f"gpu_util_perc:{gpu.id}"] = ObservableLimit( name=f"GPU {gpu.id} Temperature", fn_retrieve=partial(_get_gpu_temp, gpu.id), fn_check=lambda cur, thres: cur < thres, unit="°C", threshold=90, message="**GPU {gpu.id} Temperature** too high! (value: `{cur_value:.1f}{unit}`, threshold: `{threshold:.1f}{unit})`", # 3 times the charm badness_inc=1, badness_threshold=3, ) return limits # ---------------------------------------------------------------------------
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,334
Querela/discord-system-observer-bot
refs/heads/master
/discord_system_observer_bot/bot.py
import datetime import logging import typing from collections import defaultdict, deque from io import BytesIO import discord from discord.ext import commands, tasks from discord_system_observer_bot.gpuinfo import get_gpu_info from discord_system_observer_bot.statsobserver import collect_stats as _collect_stats from discord_system_observer_bot.statsobserver import stats2rows from discord_system_observer_bot.statsobserver import plot_rows from discord_system_observer_bot.statsobserver import ( has_extra_deps_gpu, has_extra_deps_plot, ) from discord_system_observer_bot.statsobserver import ( make_observable_limits, LimitTypesSetType, NotifyBadCounterManager, ) from discord_system_observer_bot.sysinfo import get_local_machine_name from discord_system_observer_bot.sysinfo import get_cpu_info, get_disk_info from discord_system_observer_bot.utils import make_table, dump_dict_kv LOGGER = logging.getLogger(__name__) # --------------------------------------------------------------------------- # Hack, will not allow multiple instances to be run in threads # Well, should previously have been the same, as the local_machine_name # is always the same. _LOCAL_MACHINE_NAME = get_local_machine_name() def get_name() -> str: """Gets the locally stored "machine" name. Returns ------- str name of the machine the bot runs on """ return _LOCAL_MACHINE_NAME def set_name(name: str) -> None: """Set the local "machine" name. Parameters ---------- name : str the name of the machine/system the bot runs on """ global _LOCAL_MACHINE_NAME # pylint: disable=global-statement # NOTE: using global here is the easiest solution # compared to creating a class for storing and accessing # a single variable ... _LOCAL_MACHINE_NAME = name # --------------------------------------------------------------------------- def make_sysinfo_message( cpu: bool = True, disk: bool = True, gpu: bool = True, name: typing.Optional[str] = None, ) -> str: if name is None: name = get_name() message = f"**Status of `{name}`**\n" message += f"Date: `{datetime.datetime.now()}`\n\n" if cpu: message += "System information:" ret = get_cpu_info() if ret is not None: message += "\n" + ret + "\n" else: message += " N/A\n" if disk: message += "Disk information:" ret = get_disk_info() if ret is not None: message += "\n" + ret + "\n" else: message += " N/A\n" if gpu and has_extra_deps_gpu(): message += "GPU information:" ret = get_gpu_info() if ret is not None: message += "\n" + ret + "\n" else: message += " N/A\n" return message def make_sysinfo_embed( cpu: bool = True, disk: bool = True, gpu: bool = True, name: typing.Optional[str] = None, ) -> discord.Embed: if name is None: name = get_name() embed = discord.Embed(title=f"System Status of `{name}`") # embed.set_thumbnail(url="") # TODO: add "private" logo (maybe as an config option ...) if cpu: embed.add_field( name="System information", value=get_cpu_info() or "N/A", inline=False ) if disk: embed.add_field( name="Disk information", value=get_disk_info() or "N/A", inline=False ) if gpu: embed.add_field( name="GPU information", value=get_gpu_info() or "N/A", inline=False ) embed.set_footer(text=f"Date: {datetime.datetime.now()}") return embed # --------------------------------------------------------------------------- class SelfOrAllName: """Discord Type Converter. Checks whether the local machine name is star '*' or the actual name. If not raise BadArgument to abort subcommand execution.""" def __init__(self, name: str): self._name = name @classmethod async def convert( cls, ctx, argument: str # pylint: disable=unused-argument ) -> "SelfOrAllName": if argument not in ("*", get_name()): raise commands.BadArgument("Not the local machine name or wildcard!") return cls(argument) @property def name(self) -> str: return self._name def __str__(self): return self._name # --------------------------------------------------------------------------- class SystemResourceObserverCog(commands.Cog, name="System Resource Observer"): def __init__(self, bot: "ObserverBot", limits_types: LimitTypesSetType = None): self.bot = bot self.limits = dict() self.bad_checker = NotifyBadCounterManager() self.stats = defaultdict(int) self.init_limits(limits_types=limits_types) def init_limits(self, limits_types: LimitTypesSetType = None): # TODO: pack them in an optional file (like Flask configs) and try to load else nothing. self.limits.update(make_observable_limits(include=limits_types)) def reset_notifications(self): self.bad_checker.reset() @tasks.loop(minutes=5.0) async def observe_system(self): LOGGER.debug("Running observe system task loop ...") async with self.bot.get_channel(self.bot.channel_id).typing(): # perform checks for name, limit in self.limits.items(): try: await self.run_single_check(name, limit) except Exception as ex: # pylint: disable=broad-except LOGGER.debug( f"Failed to evaulate check: {limit.name}, reason: {ex}" ) self.stats["num_checks"] += 1 async def run_single_check(self, name, limit): LOGGER.debug(f"Running check: {limit.name}") cur_value = limit.fn_retrieve() is_ok = limit.fn_check(cur_value, limit.threshold) if not is_ok: # check of limit was "bad", now check if we have to notify someone self.stats["num_limits_reached"] += 1 self.stats[f"num_limits_reached:{name}:{limit.name}"] += 1 # increase badness self.bad_checker.increase_counter(name, limit) if self.bad_checker.should_notify(name, limit): # check if already notified (that limit reached) # even if shortly recovered but not completely, e. g. 3->2->3 >= 3 (thres) <= 0 (not completely reset) await self.send( limit.message.format( cur_value=cur_value, threshold=limit.threshold, unit=limit.unit ) + f" @`{self.bot.local_machine_name}`" ) self.bad_checker.mark_notified(name) self.stats["num_limits_notified"] += 1 else: if self.bad_checker.decrease_counter(name): # get one-time True if changed from non-normal to normal await self.send( f"*{limit.name} has recovered*" f" @`{self.bot.local_machine_name}`" ) self.stats["num_normal_notified"] += 1 @observe_system.before_loop async def before_observe_start(self): LOGGER.debug("Wait for observer bot to be ready ...") await self.bot.wait_until_ready() async def send(self, message): # TODO: send to default channel? channel = self.bot.get_channel(self.bot.channel_id) await channel.send(message) def cog_unload(self): self.observe_system.cancel() # pylint: disable=no-member @commands.group(name="observer", invoke_without_command=False) async def observer_cmd( self, ctx, name: typing.Optional[SelfOrAllName] = SelfOrAllName("*"), ): """Management commands, like start/stop/status ... Optionally supply the name of the local machine to filter command execution. Beware for machine names that are the same as sub command names.""" # if ctx.invoked_subcommand is None: # on invalid name fall back to default ("*"), but no sub-command # await ctx.send(f"Name provided: {name}") # if no name provided or wrong name, it would fall back to # sending help. We would need an additional attribute for checking. # await ctx.send_help(ctx.command) @observer_cmd.error async def observer_cmd_error(self, ctx, error): # seems not to really matter, i think # did not observe any calls to it pass @observer_cmd.command(name="start") @commands.cooldown(1.0, 10.0) async def observer_start(self, ctx): """Starts the background system observer loop.""" # NOTE: check for is_running() only added in version 1.4.0 if self.observe_system.get_task() is None: # pylint: disable=no-member self.observe_system.start() # pylint: disable=no-member await ctx.send(f"Observer started @`{self.bot.local_machine_name}`") else: self.observe_system.restart() # pylint: disable=no-member await ctx.send(f"Observer restarted @`{self.bot.local_machine_name}`") @observer_cmd.command(name="stop") @commands.cooldown(1.0, 10.0) async def observer_stop(self, ctx): """Stops the background system observer.""" self.observe_system.cancel() # pylint: disable=no-member self.reset_notifications() await ctx.send(f"Observer stopped @`{self.bot.local_machine_name}`") def _header_for(self, name: str) -> str: return ( f"**{name} for** `{self.bot.local_machine_name}`" # pylint: disable=no-member f""" [`{"running" if self.observe_system.next_iteration is not None else "stopped"}`]""" "\n" ) @observer_cmd.command(name="status") @commands.cooldown(1.0, 10.0) async def observer_status(self, ctx): """Displays statistics about notifications etc.""" if not self.stats: await ctx.send(f"N/A [`{self.bot.local_machine_name}`] [`not-started`]") return try: # pylint: disable=no-member next_time = self.observe_system.next_iteration - datetime.datetime.now( datetime.timezone.utc ) # pylint: enable=no-member except TypeError: # if stopped, then ``next_iteration`` is None next_time = "?" message = "".join( [ self._header_for("Observer status"), dump_dict_kv(self.stats, wrap_markdown=True), f"\nNext check in `{next_time}`", ] ) await ctx.send(message) @observer_cmd.command(name="dump-badness") @commands.cooldown(1.0, 10.0) async def observer_dump_badness(self, ctx): """Dump current badness values.""" if not self.bad_checker.bad_counters: await ctx.send(f"N/A [`{self.bot.local_machine_name}`] [`not-started`]") return message = "".join( [ self._header_for("Badness values"), # dump_dict_kv(self.bad_checker.bad_counters, wrap_markdown=True), make_table( [ ( v.name, self.bad_checker.bad_counters[k], v.badness_inc, v.badness_dec, v.badness_threshold, self.bad_checker.notified[k], ) for k, v in self.limits.items() ], ("name", "badness", "inc", "dec", "max", "notified"), alignments=("<", ">", ">", ">", ">", ">"), wrap_markdown=True, header_separator=True, column_separators=False, ), ] ) await ctx.send(message) @observer_cmd.command(name="dump-limits") @commands.cooldown(1.0, 10.0) async def observer_dump_limits(self, ctx): """Write out limits.""" def _get_safe_current(limit): try: return limit.fn_retrieve() except: # pylint: disable=bare-except return None message = "".join( [ self._header_for("Limits"), make_table( [ ( limit.name, # lid, "id" _get_safe_current(limit), limit.threshold, limit.unit, self.bad_checker.threshold_reached(lid, limit), self.bad_checker.notified[lid], ) for lid, limit in self.limits.items() ], ("name", "current", "threshold", "unit", "exceed?", "notified"), alignments=("<", ">", ">", "<", ">", ">"), wrap_markdown=True, header_separator=True, column_separators=False, ), ] ) await ctx.send(message) # --------------------------------------------------------------------------- class SystemStatsCollectorCog(commands.Cog, name="System Statistics Collector"): def __init__(self, bot: "ObserverBot"): self.bot = bot # for a total of a week # 10 / 60 how often per minute, # times minutes in hour, hours in day, days in week num = 10 / 60 * 60 * 24 * 7 self.stats = deque(maxlen=round(num)) @tasks.loop(minutes=5.0) async def collect_stats(self): LOGGER.debug("Running collect system stats task loop ...") async with self.bot.get_channel(self.bot.channel_id).typing(): # collect stats try: cur_stats = _collect_stats(include=("cpu", "disk", "gpu")) if self.stats: cur_stats["_id"] = self.stats[-1]["_id"] + 1 self.stats.append(cur_stats) except Exception as ex: # pylint: disable=broad-except LOGGER.debug(f"Failed to collect stats, reason: {ex}") @collect_stats.before_loop async def before_collect_stats_start(self): LOGGER.debug("Wait for observer bot to be ready ...") await self.bot.wait_until_ready() @commands.group(name="collector", invoke_without_command=False) async def collector_cmd( self, ctx, name: typing.Optional[SelfOrAllName] = SelfOrAllName("*"), ): """Management commands, like start/stop/status ... Optionally supply the name of the local machine to filter command execution. Beware for machine names that are the same as sub command names.""" @collector_cmd.command(name="start") @commands.cooldown(1.0, 10.0) async def collector_start(self, ctx): """Starts the background system statistics collector loop.""" # NOTE: check for is_running() only added in version 1.4.0 if self.collect_stats.get_task() is None: # pylint: disable=no-member self.collect_stats.start() # pylint: disable=no-member await ctx.send(f"Collector started @`{self.bot.local_machine_name}`") else: self.collect_stats.restart() # pylint: disable=no-member await ctx.send(f"Collector restarted @`{self.bot.local_machine_name}`") @collector_cmd.command(name="stop") @commands.cooldown(1.0, 10.0) async def collector_stop(self, ctx): """Stops the background system statistics collector.""" self.collect_stats.cancel() # pylint: disable=no-member await ctx.send(f"Collector stopped @`{self.bot.local_machine_name}`") @collector_cmd.command(name="plot") @commands.cooldown(1.0, 10.0) async def collector_plot(self, ctx): """Plots collected stats.""" if not self.stats: await ctx.send(f"N/A @`{self.bot.local_machine_name}`") return if not has_extra_deps_plot(): await ctx.send( f"N/A (missing plotting dependencies) @`{self.bot.local_machine_name}`" ) return series = stats2rows(self.stats) plot_bytes = plot_rows(series, as_data_uri=False) if plot_bytes is None: await ctx.send(f"N/A (empty plot?) @`{self.bot.local_machine_name}`") return dfile = discord.File( BytesIO(plot_bytes), filename=f"plot-{datetime.datetime.now(datetime.timezone.utc)}.png", ) await ctx.send(f"Plot @`{self.bot.local_machine_name}`", file=dfile) # --------------------------------------------------------------------------- class GeneralCommandsCog(commands.Cog, name="General"): def __init__(self, bot: "ObserverBot"): self.bot = bot @commands.command() async def ping(self, ctx): """Standard Ping-Pong latency/is-alive test.""" await ctx.send( f"Pong (latency: {self.bot.latency * 1000:.1f} ms) @`{self.bot.local_machine_name}`" ) @commands.command() async def info(self, ctx): """Query local system information and send it back.""" embed = make_sysinfo_embed(name=self.bot.local_machine_name) await ctx.send(embed=embed) # --------------------------------------------------------------------------- class ObserverBot(commands.Bot): def __init__( self, channel_id: int, *args, name: typing.Optional[str] = None, limits_types: LimitTypesSetType = None, **kwargs, ): super().__init__(*args, **kwargs) self.channel_id = channel_id self.local_machine_name = name or get_name() self.add_cog(GeneralCommandsCog(self)) self.add_cog(SystemResourceObserverCog(self, limits_types=limits_types)) self.add_cog(SystemStatsCollectorCog(self)) async def on_ready(self): LOGGER.info(f"Logged on as {self.user}") LOGGER.debug(f"name: {self.user.name}, id: {self.user.id}") channel = self.get_channel(self.channel_id) LOGGER.info(f"Channel: {channel} {type(channel)} {repr(channel)}") await channel.send( f"Running observer bot on `{self.local_machine_name}`...\n" f"Type `{self.command_prefix}help` to display available commands." ) await self.change_presence(status=discord.Status.idle) async def on_disconnect(self): LOGGER.warning(f"Bot {self.user} disconnected!") # --------------------------------------------------------------------------- def run_observer( token: str, channel_id: int, name: typing.Optional[str] = None, limits_types: LimitTypesSetType = None, ) -> typing.NoReturn: """Starts the observer bot and blocks until finished. Parameters ---------- token : str bot authentiation token channel_id : int Discord channel id name : typing.Optional[str], optional local machine name, used for filtering, by default None limits_types : LimitTypesSetType or typing.Optional[typing.Set[str]], optional Names of limit types that should be observed, None would mean that only critical limits are used, to disable all, use an empty set, by default None """ if name: LOGGER.info(f"Set local machine name to: {name}") set_name(name) observer_bot = ObserverBot( channel_id, name=name, limits_types=limits_types, command_prefix="." ) LOGGER.info("Start observer bot ...") observer_bot.run(token) LOGGER.info("Quit observer bot.") # ---------------------------------------------------------------------------
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,335
Querela/discord-system-observer-bot
refs/heads/master
/setup.py
from setuptools import setup def load_content(filename): with open(filename, "r", encoding="utf-8") as fp: return fp.read() setup( name="discord-system-observer-bot", version="0.0.5", license="MIT License", author="Erik Körner", author_email="koerner@informatik.uni-leipzig.de", description="A Discord bot that observes a local machine, issues warnings and can be queries from Discord chat.", long_description=load_content("README.rst"), long_description_content_type="text/x-rst", url="https://github.com/Querela/discord-system-observer-bot", keywords=["discord", "bot", "system-observer"], classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "License :: OSI Approved :: MIT License", "Operating System :: POSIX", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Topic :: Utilities", ], packages=["discord_system_observer_bot"], python_requires=">=3.6", install_requires=["discord.py", "psutil"], extras_require={ "gpu": ["gputil"], "plot": ["matplotlib"], "dev": ["black", "pylint", "wheel", "twine"], "doc": ["pdoc3"], }, entry_points={ "console_scripts": ["dbot-observe = discord_system_observer_bot.cli:main"] }, )
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,336
Querela/discord-system-observer-bot
refs/heads/master
/discord_system_observer_bot/gpuinfo.py
import typing from discord_system_observer_bot.utils import make_table try: import GPUtil _HAS_GPU = True except ImportError: _HAS_GPU = False # make dummy objects class GPUtil: class GPU: pass def getGPUs(self): return [] # --------------------------------------------------------------------------- def get_gpus() -> typing.List[GPUtil.GPU]: """Return a list of ``GPUtil.GPU`` objects. Empty if none found. Returns ------- typing.List[GPUtil.GPU] List of GPU info objects. Empty if none found. """ return GPUtil.getGPUs() # --------------------------------------------------------------------------- class NoGPUException(Exception): pass def _get_gpu(gpu_id): for gpu in get_gpus(): if gpu.id == gpu_id: return gpu return None def _get_gpu_util(gpu_id): gpu = _get_gpu(gpu_id) if gpu is None: raise NoGPUException() return round(gpu.load * 100) def _get_gpu_mem_load(gpu_id): gpu = _get_gpu(gpu_id) if gpu is None: raise NoGPUException() return round(gpu.memoryUtil * 100, 1) def _get_gpu_temp(gpu_id): gpu = _get_gpu(gpu_id) if gpu is None: raise NoGPUException() return round(gpu.temperature, 1) # --------------------------------------------------------------------------- def get_gpu_info() -> typing.Optional[str]: """Generates a summary about GPU status. Returns ------- typing.Optional[str] ``None`` if no GPU support else a simple markdown formatted string. """ if not _HAS_GPU: return None headers = ("ID", "Util", "Mem", "Temp", "Memory (Used)") # , "Name") rows = list() for gpu in GPUtil.getGPUs(): fields = [ f"{gpu.id}", f"{gpu.load * 100:.0f} %", f"{gpu.memoryUtil * 100:.1f} %", f"{gpu.temperature:.1f} °C", f"{int(gpu.memoryUsed)} / {int(gpu.memoryTotal)} MB", # f"{gpu.name}", ] rows.append(fields) info = make_table(rows, headers) return info # ---------------------------------------------------------------------------
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,337
Querela/discord-system-observer-bot
refs/heads/master
/discord_system_observer_bot/utils.py
import typing def make_table( rows: typing.List, headers: typing.Optional[typing.Set[str]], alignments: typing.Optional[typing.Set[str]] = None, wrap_markdown: bool = True, header_separator: bool = True, column_separators: bool = True, ) -> typing.Optional[str]: # get number of columns if headers: num_columns = len(headers) elif rows: num_columns = len(rows[0]) else: # no headers and no rows, can't output anything return None # check input correct! if rows: assert len({len(row) for row in rows}) == 1, ( "All data rows should have the same number of columns! " f"Got {set(len(row) for row in rows)}" ) if headers and rows: assert len(headers) == len(rows[0]), ( "Number of headers and number of columns in data rows " "should be the same! " f"headers: {len(headers)}, rows[0]: {len(rows[0])}" ) if alignments: assert len(alignments) == num_columns, ( "Number of alignments should match number of data " "columns/headers! " f"alignments: {len(alignments)}, #columns: {num_columns}" ) # compute width of columns column_widths = [ max( len(str(row[field_idx])) for row in [headers or [""] * num_columns] + (rows or []) ) for field_idx in range(num_columns) ] col_sep_str = " | " if column_separators else " " table_strs = list() # header + separator if headers: table_strs.append( # col_sep_str.lstrip() + col_sep_str.join( [ f"{header:{column_width}s}" for header, column_width in zip(headers, column_widths) ] ) # + col_sep_str.rstrip() ) # separator if header_separator: table_strs.append( # col_sep_str.lstrip() + col_sep_str.join(["-" * column_width for column_width in column_widths]) # + col_sep_str.rstrip() ) # data rows if rows: def _get_type_align(field): if isinstance(field, (int, float)): return "numeric", ">" if isinstance(field, (bool)): return "bool", ">" if field is None: return "None", ">" return "str", "<" # check alignments else guess from first line check_each = False if not alignments: # alignments = () # col_types = () check_each = True # for field_idx, field in enumerate(rows[0]): # col_type, alignment = _get_type_align(field) # col_types += col_type # alignments += alignment rows_str = list() for row in rows: cells = list() for field_idx, (field, column_width) in enumerate(zip(row, column_widths)): # if alignments provided, just dump if not check_each: if field is None or isinstance(field, bool): field = str(field) cells.append(f"{field:{alignments[field_idx]}{column_width}}") else: _, alignment = _get_type_align(field) # if col_type != col_types[field_idx]: if field is None or isinstance(field, bool): field = str(field) cells.append(f"{field:{alignment}{column_width}}") rows_str.append( # col_sep_str.lstrip() + col_sep_str.join(cells) # + col_sep_str.rstrip() ) table_strs.extend(rows_str) table_str = "\n".join(table_strs) if wrap_markdown: table_str = "\n".join(["```", table_str, "```"]) return table_str def dump_dict_kv( dict_kv: typing.Dict[str, typing.Any], wrap_markdown: bool = True ) -> typing.Optional[str]: if not dict_kv: return None len_keys = max(len(k) for k in dict_kv.keys()) len_vals = max( len(str(v)) for v in dict_kv.values() if isinstance(v, (int, float, bool)) ) text = "\n".join([f"{k:<{len_keys}} {v:>{len_vals}}" for k, v in dict_kv.items()]) # return text text = make_table( list(dict_kv.items()), None, alignments=("<", ">"), wrap_markdown=wrap_markdown, header_separator=False, column_separators=False, ) return text
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,338
Querela/discord-system-observer-bot
refs/heads/master
/discord_system_observer_bot/sysinfo.py
import os import time import typing from datetime import timedelta import psutil from psutil._common import bytes2human from discord_system_observer_bot.utils import make_table Percentage100Type = float SizeGBType = float # --------------------------------------------------------------------------- def _get_loadavg() -> typing.List[Percentage100Type]: return [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()] def _get_mem_util() -> Percentage100Type: mem = psutil.virtual_memory() return mem.used / mem.total * 100 def _get_mem_used() -> SizeGBType: mem = psutil.virtual_memory() return mem.used / 1024 ** 3 def get_disk_list() -> typing.List: return [ disk for disk in psutil.disk_partitions(all=False) if "loop" not in disk.device and not disk.mountpoint.startswith("/boot") ] def _get_disk_paths() -> typing.List[str]: disks = get_disk_list() paths = [disk.mountpoint for disk in disks] return paths def _get_disk_usage(path: str) -> Percentage100Type: return psutil.disk_usage(path).percent def _get_disk_free_gb(path: str) -> SizeGBType: return psutil.disk_usage(path).free / 1024 ** 3 # --------------------------------------------------------------------------- def get_cpu_info() -> str: meminfo = psutil.virtual_memory() GB_div = 1024 ** 3 # pylint: disable=invalid-name info = ( "```\n" + "\n".join( [ f"Uptime: {timedelta(seconds=int(time.time() - psutil.boot_time()))}", f"CPUs: {psutil.cpu_count()}", f"RAM: {meminfo.total / GB_div:.1f} GB", "", "Load: 1min: {0[0]:.1f}%, 5min: {0[1]:.1f}%, 15min: {0[2]:.1f}%".format( _get_loadavg() ), f"Memory: {(meminfo.used / meminfo.total) * 100:.1f}% [used: {meminfo.used / GB_div:.1f} / {meminfo.total / GB_div:.1f} GB] [available: {meminfo.available / GB_div:.1f} GB]", ] ) + "\n```" ) return info def get_disk_info() -> str: disks = get_disk_list() headers = ("Device", "Mount", "Use", "Total", "Used", "Free") rows = list() for disk in disks: usage = psutil.disk_usage(disk.mountpoint) rows.append( ( disk.device, disk.mountpoint, f"{usage.percent:.1f} %", bytes2human(usage.total), bytes2human(usage.used), bytes2human(usage.free), # disk.fstype, ) ) info = make_table(rows, headers) return info def get_local_machine_name() -> str: return os.uname().nodename # ---------------------------------------------------------------------------
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,339
Querela/discord-system-observer-bot
refs/heads/master
/discord_system_observer_bot/cli.py
import argparse import configparser import logging import os import pathlib import sys from discord_system_observer_bot.bot import run_observer LOGGER = logging.getLogger(__name__) # --------------------------------------------------------------------------- CONFIG_SECTION_NAME = "discord-bot" CONFIG_PATHS = [ pathlib.Path.home() / ".dbot.conf", pathlib.Path.home() / "dbot.conf", pathlib.Path(".") / ".dbot.conf", pathlib.Path(".") / "dbot.conf", pathlib.Path("/etc/dbot.conf"), ] def find_config_file(): for filename in CONFIG_PATHS: if filename.exists(): LOGGER.info(f"Found config file: {filename}") return filename LOGGER.error("Found no configuration file in search path!") return None def load_config_file(filename): config = configparser.ConfigParser() LOGGER.debug(f"Try loading configurations from {filename}") try: config.read(filename) if CONFIG_SECTION_NAME not in config: LOGGER.error(f"Missing configuration section header: {CONFIG_SECTION_NAME}") return None configs = config[CONFIG_SECTION_NAME] return { "token": configs["token"].strip('"'), "channel": int(configs["channel"]), } except KeyError as ex: LOGGER.error(f"Missing configuration key! >>{ex.args[0]}<<") except: # pylint: disable=bare-except LOGGER.exception("Loading configuration failed!") return None def load_config(filename=None, **kwargs): configs = None if filename and os.path.isfile(filename): configs = load_config_file(filename) if configs is None: LOGGER.error("Loading given config file failed! Trying default ones ...") if configs is None: filename = find_config_file() if filename is not None: configs = load_config_file(filename) if configs is None: if "token" not in kwargs or "channel" not in kwargs: raise Exception("No configuration file found!") configs = {**configs, **kwargs} return configs # --------------------------------------------------------------------------- def parse_args(args=None): parser = argparse.ArgumentParser() parser.add_argument("-c", "--config", type=str, default=None, help="Config file") parser.add_argument( "-d", "--debug", action="store_true", help="Enable debug logging" ) parser.add_argument( "-n", "--name", type=str, default=None, help="Local machine name (id)" ) args = parser.parse_args(args) return args def setup_logging(debug=False): if debug: # logging.basicConfig(format="* %(message)s", level=logging.INFO) logging.basicConfig( format="[%(levelname).1s] {%(name)s} %(message)s", level=logging.DEBUG ) logging.getLogger("websockets.protocol").setLevel(logging.WARNING) logging.getLogger("websockets.client").setLevel(logging.WARNING) logging.getLogger("discord.client").setLevel(logging.WARNING) # --------------------------------------------------------------------------- def main(args=None): args = parse_args(args) setup_logging(args.debug) configs = load_config(filename=args.config) LOGGER.debug(f"Run bot with configs: {configs}") try: run_observer(configs["token"], configs["channel"], name=args.name) except: # pylint: disable=bare-except sys.exit(1) LOGGER.info("Done.") # ---------------------------------------------------------------------------
{"/discord_system_observer_bot/statsobserver.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/sysinfo.py"], "/discord_system_observer_bot/bot.py": ["/discord_system_observer_bot/gpuinfo.py", "/discord_system_observer_bot/statsobserver.py", "/discord_system_observer_bot/sysinfo.py", "/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/gpuinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/sysinfo.py": ["/discord_system_observer_bot/utils.py"], "/discord_system_observer_bot/cli.py": ["/discord_system_observer_bot/bot.py"]}
37,340
univ-of-utah-marriott-library-apple/display_manager
refs/heads/stable
/gui.py
#!/usr/bin/env python3 ######################################################################## # Copyright (c) 2018 University of Utah Student Computing Labs. # # All Rights Reserved. # # # # Permission to use, copy, modify, and distribute this software and # # its documentation for any purpose and without fee is hereby granted, # # provided that the above copyright notice appears in all copies and # # that both that copyright notice and this permission notice appear # # in supporting documentation, and that the name of The University # # of Utah not be used in advertising or publicity pertaining to # # distribution of the software without specific, written prior # # permission. This software is supplied as is without expressed or # # implied warranties of any kind. # ######################################################################## # Display Manager, version 1.0.1 # Graphical User Interface import os import tkinter as tk from tkinter import ttk from tkinter import filedialog as tkFileDialog from display_manager import * class App(object): """ The GUI for the user to interact with. """ def __init__(self): self.root = tk.Tk() self.root.title("Display Manager") self.mainFrame = ttk.Frame(self.root) # Set up the window self.mainFrame.grid(column=0, row=0) self.root.columnconfigure(0, weight=1) self.root.rowconfigure(0, weight=1) self.root.geometry("+400+200") # Raw GIF encoding self.logoPic = tk.PhotoImage( data=""" R0lGODlhvAE8APcAAAAAAP///28HFZwAAp0ABfHX2J8AC96gpOKuseW1uLaXmezIyu/P0e/Q0vPe 39nJysJXYcVfaIVCSMhmb895gJBWW9eMk9aLkdiPldeOlNiQltePldeQltqUmuOboZppbeGmq6R5 feKrr+Sus+OtsuOusq2Ii7+kpsixs6EAEaAAD7AnN7MxP7Y4RnopMbk/TL9OWcRcZtODi9iPlteP ltC9v6IAE6IAFaIAFqEAFKEAE6wWK6sYLKsaLqwbLqwcL6MAGqMAGKkNJakQJ6kRKKsTKaoUKqoW K6sXLKwYLa0ZLvns7qUAHaQAG6cII6kOKPDq66gDIqcDIvz09hsZGnd1dv37/Onn6Hl4eXh3eP/+ //j6+uzu7urs7Ojq6uPl5c3Pz/f4+PP09OXm5t3e3s/Q0HKBgN/h4JoAAJcAAAUDAwMCAgYFBQgH BwwLCw4NDSIgIBAPD+HV1RMSEhQTExYVFRkYGOjg4B4dHUVDQygnJyUkJFdVVTMyMi8uLisqKjw7 Ozc2Nvj19YB+flNSUlJRUVBPT01MTEpJSUhHR0A/P/37+/Xz8+/t7efl5ePh4dTS0s3Ly8fFxaup qX9+fn18fHd2dnZ1dXV0dHRzc2xra2hnZ2ZlZWJhYV9eXlxbW1lYWP79/fn4+Pj39+jn5+fm5uXk 5OTj497d3drZ2djX19bV1dDPz87Nzc3MzMnIyMjHx8fGxsPCwry7u7q5ubm4uLi3t7e2tra1tbW0 tLSzs7Cvr6yrq6inp6OioqGgoJ+enp2cnJuampWUlJSTk4yLi4mIiIeGhoWEhISDg/7+/v39/fv7 +/f39/b29vX19fT09PPz8/Dw8O/v7+7u7uzs7Ovr6+np6ePj4+Hh4d/f397e3t3d3dvb29ra2tnZ 2dbW1tXV1dLS0tDQ0M7OzsvLy8TExMPDw8HBwb+/v76+vrKysq6urqysrKurq6ioqKWlpZmZmZeX l5GRkY6OjoqKioGBgXt7e3JycnBwcG5ubmpqamNjYwkJCQEBAf///yH5BAEAAP8ALAAAAAC8ATwA AAj/AAMIHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8ePIEOKHEmypMmTKFOqXMmypcuX MGPKnEmzps2bOHPq3Mmzp8+fQIMKHUq0qEEASI0qXcq0qdOjSZ9KnUq1qkykAKxq3cq1q0asXsOK HUs2ANiyaNOqNXp2rdu3cGu2jUu3rl2Sc+/qNdkABIkSJf6WGAGYMGASIBwIXCJCBOHHgUdILgxi wd6YeS9r/kghzY0goIMAER0atA00BwQuUGGANJDRpEMDSQNjs8vMtnNjlJHDyJHfwIP/HgIEhGoh ToQrR3IkRQzdK3FDnx6R9w4e2Hkgya49CZIixVUP/3GCfTsSJN7Rn0finDpK6e7jK5RxY0f67drP a+dRpInxAAsgt55+56XHQxLtyYdXVEYJIoccgih4k3Xedafffvz5J54T5h144XbeJShhSPD9JIcA AsgxYk3WlXdgfvgl0d9/AXI4YIHraSfiQGGMQU1B0mAjjUDRmBKGQKVQc8Yv0ZyhzzrQ2DOPFQ+V o88tAz1jSinLCKRMKWOMAlEjv3wzERdjMDOQKsAwI44+tpRUokEf1GnnnShAgZAgJoSg4kcnpnhS DXY+wNAJdt4BnXU5ErjfdxoC+ASHjza63o4C0dIPKAWtw4YhAhHSjzEBkONGJ/MAAI8rAIBCCgB1 NP/zUDEAdDIQMW3004tAwvQTxzsQAQOAJwhJEws0An0jDkGG9OPKQPwA8EovAPAjJ4MNoajtttp+ oGdBNaBYAUiB/lnSCdqOq5Ag25prG6P5JVGpdjNuiB+I+iWRHqYBrAMAIgVtA2soy1ABACEBCJsF NcdYow4Amljzhh+yOkRtJgNhgZStASCC1DwQkWJMOQgFMocoAaDTBj4EKQIALAOVg0wYvgBAybVZ PYSiBCf0fIICH0igrQs1FPQAiiGQi6K7I6GrLdMFOb00dJ3h0ASIj+prBBA6oKYaa0EM4YOj3vnA BA60GXTLwQYBAsAVZ8zhRiABUALAOapQ4s05EFv/E0cfyqBDCCCgPPvKJuFQUk8AueSxDz7+YDLQ PlToAUcA0sQRCB30BADPIYBskk0AuGxChj7xFPPOOZvQYkwtAShDjyKI4BIAMgC84Yk8hgDgRz5D dgwAyQLNYs8V8ACQDzGA2KNMAPf8co4n4xiThyKd3x4MLPsc0wk7ATyTRSbBHzRnQSh+cJAcFWhb NEE1nPCtR+WeJLUAJijkQrvQdbDCCy3ggX0exQMj/OAFL2BBAgTSgBa04AUrKEJ+yvMdFkCQAmpj W0EwAQAwsAMPfKhDKTrRjwAMAwDA+Ebf/hYAS/RhH3Irxdr2AAB8rA0AeoiDPywxED7oYRNt4IYu /94wiH4kIwCHyAMncMgMWv0BAFnYXBv0kAUAbCIAhQBAH+wAgHl4oh92oMIn+hCHOOzhCgLxGPEC 0AkAoAMXaqCDH/pRwwDowQ1voEMvAMGPQwCAh3N0QxwGgcNSaVFNCDkfQdKXEBRoa34kqZ9JnPYB FEESfjubmm60EIpQMIAIUbgXdpjAgiV0UgsC4WQorAABHRQoO0/AAQKUEYrnFcQWACiEQZLni3zk 4RcAcEcf8hCAVPUiHCv0g0C8AY88AOAd5fDHHNpBij4AoBbL0McfB5KIPbyDDfLAByDWtg+BjAMY fgCAONgBgD/gohRu28QZggGAY5gDAIcIwBfegP8HSPjBDmOwQvLwwQxbqnEg2jSHLvyRB1Fsww5v AEcWOTGOADQjHfZggx6kAQoAfGIcYUgEAKQhrHgoRJEDYWRCQoCi/JlEkudC0dEEcAKEtM8FToOa bQpABCno6z6knEJCIJCCCWLnCTZYIEIeBqqCQIINfABEFR7Rhk24wR4BqAcAjrnCQDCDGHGAgzWD cc9PBCAabYDD89oBAMkJJBB7MMUf8qAHYyBTEwHQhxv2kE5z7AIApArAH/rBhQDUzBipyl4e1lCL QFDBGQFgayUI4rFWDCQfADCHv44hED4AgBaIUMMpAsANQLjBD3T4wyk6ug1eASAenVADKU6KLYb/ qHRPQhNAhATyoEtCQQ4neMBuB3IHOSgqAIJ4wAlQcNyCwJS4yj0B0x7UXIL8FkIJcVoAhOaC9aGo Z5q0LnCDO9yBPChCyQ3uJQnioJ4JNyHtVS9v5bDeANxBudgtiIP+BIX41XciDRhCFLCjL+2QcglD deWLjoqDESQEmMSaBSsGsgw/vMENvrAjHdwAO2Ns9a5+OwQ6AACIALDzF/e0lTTq8IYxBMDDPBSI 5QKQCaRsIxs1HLG17PEydi5OFH94w+iAWY+asSwAe3DDK/wwByoB8xKUBYAqEJpZXQCAEwLxgxpY kYh+cCMAIrXdHvDgCM9OOQDVqAMc7NDUhKBU/yC3RYjT3heA7w6ET9yqwHAr+QFBVHJbFahuAJ77 gP1tywWGEkhuyysQluo2uygKgCMFQOeBOBoKOSUI+7hFU/SlSAHcCgGj7/DnbSngICgwtLYUwK5O E6TQ3DJBeQPl56dpJMA+7RAPDjzUFOjrlU+4QQkOUo9CcDEdKqTDNAbSxuEFwGV2+BGPfyGOWl0D AIqYBQAC4YtAvHbEugxAtEJHB4gJxBluqIPnAHA5cHiUFwcLBh7uNgmbBUAUButGAIQBgEtI4w0A oMcmasUMa+YBHKwAwBzwAdlnk9gQgCiGJtzI1jbsw7OEYMYTweHwehwDAHjAhh8rKhAOAoAXC/95 c50FoD6FBKqmcHZ1ANonrnTttpISyK0AdE5pTYfX0eJS9Z8mjQL9tlQh2hXE/iRQECgcPdMCuV/O tVX0lAqA5lfv1qu3NXU7E6TUO++W1wViAm1JoNQSGG6gsC6ojDSgp/cZZSkTjJ/8xHLYBnFZHW7W jTrkAVkC6cUc8hCNANhjDlgOgDzesAtvzOEe1dCDIZphjzbsoRNU8MUr6KAPgVwhi3ioxB+yIJBq zDUAj1AEZ7+BB35EwxNt8EMn6BALW7yBGAFghiL0cIYAuCMOk41FH/zRBn5UIwCT4OKuolWH4PED D3iggxo4cQw6uGIderDEvBFhigDkAQ76Lsf/H9iQCEQA4hGaoMKZA8AqPQDezbVdSJy9K4CkxRzm d2hphKBQdlELpNQV8CeCIDXNBVP59wHmMmn2p3Q7VxCTplMDoV0BUHZtJxCgJihQZ18uIAGJNmg7 s0gogmgCIQiOZi6CUAESQGd3sD/dFYEhSGc1oGowFwAzFQLzM2ku5YHiIoAa8UlSYCHnwWsI0UqV kgR3dxDScAY/IhDTcCQE0YReMg1dkntcwAzLMA2ioAzQUHio9yPREAZWIA1OKBDZICvQ0HDLwAgV MxBayIXa8AyYswjMUIXnBg1dwgzUsIbc4GIDQQ3Z0HCPcA0D0QzQ8AzPAA1hIArSYAVbgCzO/9B7 dTiFzfBlmGMFYRANXaIM2OAJADAMDKFy82cQ+cdyVgdz4SIA1VVdf6ZnznVbzyVo2yUALTiB4TVz DYh0kRYATld/d7Z0UVeL60WB82NrdzZ2yMVoF8hfIchoUGBoMCcIQqMuBOE03xIoLsBoGeGDFZId QngQRPghseRgKyIRBfcvDQGKpOhyKHJq9ycQo/gBsPh/tWhpuaiDEIhcckCBxHV07ogiVQdpAjAQ f/Ytk/Y+Gbg+GSguBtE+Obg+pzh0/ohqXjdTHTgQuwhzgcKOHeGDHiIvSNCNBvGNHRJs4jiOEWEG ZuAQ6NhyCXGKMzh2WOcCIYAC5fVnCPGQvP9Vi4KAAh+gatpCEDe1WxeIjVFTjzPFjty1WwcZADUQ AjwXXutIJ+k4EA/glJz2JxcYjy/3iyx3J3YSlfb4EW8nBTliYHM3hApGIEdYEEuAARmgATRAAxzA ARqgAXQJlxwQl3Ypl3NJlxtgl30ZmHUJmHlpl3WZl3NZl3wZl3GZmIlJmHO5AY15l4P5l4FJlzSg mIbZl3BJmJl5mJyJmXf5mBswl3xJl5jZASDgAZgpA4phPvGnEKFYEH/WXGPHJz5JNAI5la3Yc2HJ W0+5LZjkm/tjf7gYkAORlEfpghUIBWDHLeZijPLIkiTIacToaAnhdfdjnen4XBsxlmX5kWf/6Y06 UClIQJIGsQQZYAEzQAMz8J7wGZft2Z6MOZ/ueZ/1WZ/vKZ/uCZ/2uZ+M2Z/6OaD8KZ8Aip8Iup/z SZ8KeqAJep8MGqD6GZ8z0AEdIKCumUixmZ28aRCTxpIrN4PmdQJYd1yVNIvgokmS1IzfNT8SOBD7 My6nWJFyVo+ShiKEYknMaS65ZQIFCJUyt5ss+WfwWIxt5zRa6XVE9yBM2qTH5Z092FMEEoTjGZLl uR7egZ4mSSIbihCzKRAsWoEh2kheV5sHQYG7JUkfWhAXyKYocgcsxXSHYqOtllvGGQBQN4ppN5zR GaTTCabL6HNtN1P/OI1eFyiFihBQmo1w/3chu1alBfGNGLKWW/oRKylnhtaQY8pb1dVq7EikBrF2 5qVJTlOR0Gijupg+0lmjyDkQFFiLUJeRtAmkIvqnOqiRZKdJLOoCgjaKrsaA19h0rDaqYroRnxQF v4YfQMACChEBKpAj8hJseEcQVvAN3tAFqtANosAFDccFcBgk3+CE0bCEz1ANiMSEQ8IFoxAN1tCH 0dAMpKAK0rAM1vANKCMQVhAOaGSuVxAO1zAG4WAK7SoQY3CvAXAF20CJz1CvrRUAYWANsmIF1eAM 2qAK1cANqnCuAiENhXVWx/ceXXoQO9ikwKVzd9qON+oC5kKB71Nq3jIQMRhekjRT1PmqUv/5SA3x ov34gYbadnXasxW4qnxmdcEqEJNWgZPmAjSpi6mmLTM4aYFGlUtXjfN4awLWIeghBCsgAxpwAV77 tRuwAS3wg+hhdzgwrQNxDeywDvigC+sgDVlgDgJhD+5wO/KAC3z4DpMVALEwD2GQCXzIC/AQAJVg C9cACl+2DMdwDetACbXwDV6ABbOADKsQANaAC7egDs1wCZBQDrkwCPOwC69QCXIrDvMAhwFwDrhg DvBADMqwDZowC+yAMtHACZbFDPMgC+pwC/jADu4giPUwsL1wMwFQC251EujInSFYqyh7gbLYkyH4 LZVUATR3dtsiopJ0qrIYAlZJcwYxU7z/mLOoGgB/Vml4Gl5/JpMm0D4016fMO7QW2C3rm3UCUKjO G2vGCHTWqy05uKgYwZFG5QNFQABoMAAGfMAF7AQ/wB0MhrYCoSbNEGPQQzLKYAztEADJIAsEsQtY FQCs8AsBAAqEsGyzsA4YbML6AAwBwCbI54kBUApYJQ+TVQ4YEwDLcA/kIBD0ULcBYA6SswvYIBDn gAwDoQnBwAxQZsMCoQnhIBDBULktVHjLUA15AD79QsSpew8pkbzWKQEK8F9jd4pc11x8VmuHRqMG +JQmAKW5RaMAaRDhUrQ7emfPqWc4WopSSZ1AJy4MWKtywHNKu6kDcbRDU6j+exEMIARk/ytK2aEe FIS1E0QEOiACCDEGWCAGAnEPw1AG4qAJtBAAxUAP5cCF64DF45BhsCAPnCIOtnMMudDDV7QOJKML WGAO1gANg0AN5wAzYbAJnVc3JEcPgysQ8XAPEyYQl8DDARAJnEAN+ZAOOSwQ+cBxARAM3hAA0IAF QRwAkgAPR1S8m+AK5DAPxIu8IRuqJEtdDNFb1oUCPiNo8HsHPYMCOrVfjDZe0oWP+fV1svgQ17U+ sHhdo+bOwTVf88POBVFcggYFBF0DEVJc9XVfzAWo9WsQ/eUz78Ve5yWWOcAEFRIjBCQv8oIhP6Uf QoAGDjwQpHAPmFw3tzAN0mAPugDKxP/QCowgEO5gyioMLMdwD6oQCy/2ynklC7agJrpQCZJADaKA Bb+wtwHgDIYAMvYQzMOMeoZQPvtQ1a2AD84cC+QwhfpwzQljJs9wD0EcBsVgC6BwzblQCVxADbtQ ziahcicBvySxi7haFjN1jyyxCDJAAE4w0hME0kYl0iLdA0aABhGAYAdxDVhQMfcACToMPsfwCgRR DuUUALIALMGgw4oAM64sEO+ACGI9CcIgEKSQDM0wDEc0hfjQDMmwLAEgzH1oCVQiELnABwMxDO3A DFhQEJqQDrFDD0PSDFnQfeXgDtAwD8XQL4sTAK8wCFt8zixh102jo1yxkwjxZ0QJEzL/YABC4B2C 3cj3Ut7ZYQQDEAGohBDa8AlBzAyc8Mkt1NlZYA+zAMUBEA/AkA7vQArYgAUNlw8mjA8ZFgBjoAn3 6gvxzQrYwAntWgWiyw7qIAtWwAnCDT0uTFqewIfEXAzpgA512w2fMLACAQv2vQ7nIBDU4AlNjAwV 5QieoLZ4FQC6wA8auyA5UxPWHRIMCKJa0T595qbhOyED4AQ+8GsMbCDm0SHoHQEL4QyoUHhWkA0f iw3tSgrhMA7l48HkMCTSsA0GizJWfhDTAA7kcAXMsA1cmArW0Apntg1LaApoJBDQoOYFEQ6sINbR sA3vR7Dl0LD3ZufccK+PMA3ToA0q/r4Ntz3X1L0SO94RclADKJBbfO0UgSKLCiDpCpBbLvBfMiED aCAEPvAiSy7SjcIDSpDYTl6pI0HXJvHoHHG/mqoVf8ydEhCPLFLk6fHR+XIviI0GMUAlj/AIrA4S rl4S8WO+HaEA+/MBzMsVTVm9H7C0PSEDA0AABpDt2r7t204AaRABoRAAZ4AM/V3sHnHs5t4/EDAB 7N7u7u7uMYBBAsEN9tALo5PuG4Hu+I7vzKAN22BL+44R+h7wBF/wFTHwBp/wCp9yjb7wDv/wDJ/j ED/xFP+JDV/xGL/wCJ/xHF+pG9/xID8iHx/yJO8eI1/yKJ/yKr/yLN/yLv/yEx8QADs= """ ) self.imageLabel = ttk.Label(self.mainFrame, image=self.logoPic) self.imageLabel.grid(column=0, row=0, columnspan=8) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=9, columnspan=8, sticky=tk.EW) # Display selection ttk.Label(self.mainFrame, text="Display:").grid(column=0, row=10, sticky=tk.E) self.displayDict = {} self.displayDropdown = ttk.Combobox(self.mainFrame, width=32, state="readonly") self.displayDropdown.grid(column=1, row=10, columnspan=6, sticky=tk.EW) ttk.Button(self.mainFrame, text="Refresh", command=self.__reloadDisplay).grid(column=7, row=10, sticky=tk.E) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=19, columnspan=8, sticky=tk.EW) # Mode selection ttk.Label(self.mainFrame, text="Resolution:").grid(column=0, row=20, sticky=tk.E) self.modeDict = {} self.modeDropdown = ttk.Combobox(self.mainFrame, width=64, state="readonly") self.modeDropdown.grid(column=1, row=20, columnspan=7, sticky=tk.EW) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=29, columnspan=8, sticky=tk.EW) # Rotate menu ttk.Label(self.mainFrame, text="Rotate:").grid(column=0, row=30, sticky=tk.E) self.rotateSlider = tk.Scale(self.mainFrame, orient=tk.HORIZONTAL, width=32, from_=0, to=270, resolution=90) self.rotateSlider.grid(column=1, row=30, columnspan=7, sticky=tk.EW) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=39, columnspan=8, sticky=tk.EW) # Brightness menu ttk.Label(self.mainFrame, text="Brightness:").grid(column=0, row=40, sticky=tk.E) self.brightnessSlider = tk.Scale(self.mainFrame, orient=tk.HORIZONTAL, width=32, from_=0, to=100) self.brightnessSlider.grid(column=1, row=40, columnspan=7, sticky=tk.EW) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=49, columnspan=8, sticky=tk.EW) # Underscan menu ttk.Label(self.mainFrame, text="Underscan:").grid(column=0, row=50, sticky=tk.E) self.underscanSlider = tk.Scale(self.mainFrame, orient=tk.HORIZONTAL, width=32, from_=0, to=100) self.underscanSlider.grid(column=1, row=50, columnspan=7, sticky=tk.EW) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=59, columnspan=8, sticky=tk.EW) # Mirroring menu ttk.Label(self.mainFrame, text="Mirror Display:").grid(column=0, row=60, sticky=tk.E) self.mirrorEnabled = tk.BooleanVar() self.mirrorEnabled.set(False) self.mirrorDropdown = ttk.Combobox(self.mainFrame, width=32, state="readonly") self.mirrorDropdown.grid(column=1, row=60, columnspan=6, sticky=tk.EW) self.mirrorCheckbox = ttk.Checkbutton(self.mainFrame, text="Enable", variable=self.mirrorEnabled) self.mirrorCheckbox.grid(column=7, row=60, sticky=tk.E) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=69, columnspan=8, sticky=tk.EW) # Set/build script menu ttk.Button(self.mainFrame, text="Set Display", command=self.setDisplay).grid(column=0, row=70, sticky=tk.E) ttk.Button(self.mainFrame, text="Build Script", command=self.buildScript).grid(column=7, row=70, sticky=tk.E) ttk.Separator(self.mainFrame, orient=tk.HORIZONTAL).grid(row=79, columnspan=8, sticky=tk.EW) def __displaySelectionInit(self): """ Add all connected displays to self.displayDropdown. """ displayStrings = [] for display in getAllDisplays(): displayID = str(display.displayID) self.displayDict[displayID] = display displayStrings.append(displayID + " (Main Display)" if display.isMain else displayID) self.displayDropdown["values"] = displayStrings self.displayDropdown.current(0) self.displayDropdown.bind("<<ComboboxSelected>>", lambda event: self.__reloadDisplay()) def __modeSelectionInit(self): """ Add all the DisplayModes of the currently selected display to self.modeDropdown. """ # Add self.display's DisplayModes to self.modeDropdown in reverse sorted order sortedModeStrings = [] for mode in sorted(self.display.allModes, reverse=True): modeString = mode.__str__() self.modeDict[modeString] = mode sortedModeStrings.append(modeString) self.modeDropdown["values"] = sortedModeStrings # Set the default mode to the current mode, if possible currentModeString = self.display.currentMode.__str__() if currentModeString in self.modeDropdown["values"]: self.modeDropdown.current(self.modeDropdown["values"].index(currentModeString)) else: self.modeDropdown.current(0) def __rotateSelectionInit(self): """ Set self.rotateSlider's value to that of the currently selected display, and deactivates said slider if the rotation of this display can't be set. """ if self.display.rotation is not None: rotation = self.display.rotation self.rotateSlider.set(rotation) self.rotateSlider.configure(state=tk.NORMAL) else: self.rotateSlider.set(0) self.rotateSlider.configure(state=tk.DISABLED) def __brightnessSelectionInit(self): """ Set self.brightnessSlider's value to that of the currently selected display, and deactivates said slider if the brightness of this display can't be set. """ if self.display.brightness is not None: brightness = self.display.brightness * 100 self.brightnessSlider.set(brightness) self.brightnessSlider.configure(state=tk.NORMAL) else: self.brightnessSlider.set(0.0) self.brightnessSlider.configure(state=tk.DISABLED) def __underscanSelectionInit(self): """ Sets self.underscanSlider's value to that of the currently selected display, and deactivates said slider if the underscan of this display can't be set. """ if self.display.underscan is not None: underscan = abs(self.display.underscan - 1) * 100 self.underscanSlider.set(underscan) self.underscanSlider.configure(state=tk.NORMAL) else: self.underscanSlider.set(0.0) self.underscanSlider.configure(state=tk.DISABLED) def __mirrorSelectionInit(self): """ Show the other available displays to mirror. """ otherDisplayIDs = [] for display in self.displayDict.values(): displayID = str(display.displayID) if displayID != str(self.display.displayID): otherDisplayIDs.append(displayID + " (Main Display)" if display.isMain else displayID) if otherDisplayIDs: # if there are other displays to mirror self.mirrorDropdown["values"] = otherDisplayIDs self.mirrorDropdown.current(0) else: # there is only one display self.mirrorDropdown["values"] = ["None"] self.mirrorDropdown.current(0) self.mirrorEnabled.set(False) self.mirrorDropdown.configure(state=tk.DISABLED) self.mirrorCheckbox.configure(state=tk.DISABLED) @property def display(self): """ :return: The currently selected Display. """ displayID = re.search(r"^[0-9]*", self.displayDropdown.get()).group() return self.displayDict[displayID] @property def mode(self): """ :return: The currently selected DisplayMode. """ modeString = self.modeDropdown.get() return self.modeDict[modeString] @property def rotation(self): """ :return: The currently selected brightness. """ if self.rotateSlider.get(): return int(self.rotateSlider.get()) else: return 0 @property def brightness(self): """ :return: The currently selected brightness. """ if self.brightnessSlider.get(): return float(self.brightnessSlider.get()) / 100 else: return 0 @property def underscan(self): """ :return: The currently selected underscan. """ if self.underscanSlider.get(): return float(self.underscanSlider.get() / 100) else: return 0 @property def mirror(self): """ :return: The currently selected display to mirror. """ if "None" not in self.mirrorDropdown["values"]: mirrorID = re.search(r"^[0-9]*", self.mirrorDropdown.get()).group() return self.displayDict[mirrorID] else: return None def setDisplay(self): """ Set the Display to the currently selected settings. """ self.__generateCommands().run() self.__reloadDisplay() def buildScript(self): """ Build a script with the currently selected settings and save it where the user specifies. """ # Ask the user where to store the file f = tkFileDialog.asksaveasfile( mode='w', initialdir=os.getcwd(), defaultextension='.sh', initialfile="set", ) if f is not None: # if the user didn't cancel f.write("#!/bin/sh\n\ndisplay_manager.py") for command in self.__generateCommands().commands: f.write(" " + command.__str__()) f.close() def __generateCommands(self): """ :return: A CommandList with all the currently selected commands """ # These commands are always available commands = [ Command( verb="res", width=self.mode.width, height=self.mode.height, refresh=self.mode.refresh, scope=self.display, ), Command( verb="mirror", subcommand="enable" if self.mirrorEnabled.get() else "disable", source=self.mirror if self.mirrorEnabled.get() else None, scope=self.display, ), ] # Add these commands if and only if they're available to this Display rotate = Command( verb="rotate", angle=self.rotation, scope=self.display, ) brightness = Command( verb="brightness", brightness=self.brightness, scope=self.display, ) underscan = Command( verb="underscan", underscan=self.underscan, scope=self.display, ) if self.display.rotation is not None: commands.append(rotate) if self.display.brightness is not None: commands.append(brightness) if self.display.underscan is not None: commands.append(underscan) return CommandList(commands) def __reloadDisplay(self): """ Reloads data-containing elements. """ self.__modeSelectionInit() self.__rotateSelectionInit() self.__brightnessSelectionInit() self.__mirrorSelectionInit() self.__underscanSelectionInit() self.mirrorEnabled.set(False) # resets every time the display is switched def start(self): """ Open the GUI. """ self.__displaySelectionInit() self.__reloadDisplay() self.root.mainloop() def main(): view = App() view.start() if __name__ == "__main__": main()
{"/gui.py": ["/display_manager.py"], "/display_manager.py": ["/display_manager_lib.py"]}
37,341
univ-of-utah-marriott-library-apple/display_manager
refs/heads/stable
/display_manager.py
#!/usr/bin/env python3 ######################################################################## # Copyright (c) 2018 University of Utah Student Computing Labs. # # All Rights Reserved. # # # # Permission to use, copy, modify, and distribute this software and # # its documentation for any purpose and without fee is hereby granted, # # provided that the above copyright notice appears in all copies and # # that both that copyright notice and this permission notice appear # # in supporting documentation, and that the name of The University # # of Utah not be used in advertising or publicity pertaining to # # distribution of the software without specific, written prior # # permission. This software is supplied as is without expressed or # # implied warranties of any kind. # ######################################################################## # Display Manager, version 1.0.1 # Command-Line Interface # Programmatically manages Mac displays. # Can set screen resolution, refresh rate, rotation, brightness, underscan, and screen mirroring. import sys # Collect command-line arguments import re # Parse command-line input import collections # Special collections are required for CommandList from display_manager_lib import * # The Display Manager Library class CommandSyntaxError(Exception): """ Raised if commands have improper syntax (e.g. wrong number of arguments, arguments in wrong place, invalid (sub)command(s), etc.) """ def __init__(self, message, verb=None): """ :param verb: The type of command that raised this exception :param message: Description of what went wrong """ self.message = message self.verb = verb Exception.__init__(self, self.message) class CommandValueError(Exception): """ Raised if a command's arguments have unexpected values (e.g. values are incorrect type, values are outside expected range, etc.) """ def __init__(self, message, verb=None): """ :param verb: The type of command that raised this exception :param message: Description of what went wrong """ self.message = message self.verb = verb Exception.__init__(self, self.message) class CommandExecutionError(Exception): """ Raised if commands could not be executed (usually due to a DisplayError) """ def __init__(self, message, command=None): """ :param command: The Command which raised this exception :param message: Description of what went wrong """ self.message = message self.command = command Exception.__init__(self, self.message) class Command(object): """ Represents a user-requested command to Display Manager """ def __init__(self, **kwargs): """ :param kwargs: Includes verb ("command type"), subcommand, scope, and misc. Command values verb: string in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"] subcommand: string scope: Display(s) width: int height: int refresh: int hidpi: int (0 -> all; 1 -> no HiDPI; 2 -> only HiDPI) angle: int brightness: float underscan: float source: Display """ # Determine verb if "verb" in kwargs: if kwargs["verb"] in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"]: self.verb = kwargs["verb"] else: raise CommandSyntaxError("\"{}\" is not a valid command".format(kwargs["verb"])) else: self.verb = None # Determine subcommand, scope self.subcommand = kwargs["subcommand"] if "subcommand" in kwargs else None if "scope" in kwargs: if isinstance(kwargs["scope"], list): self.scope = kwargs["scope"] elif isinstance(kwargs["scope"], AbstractDisplay): self.scope = [kwargs["scope"]] else: self.scope = None else: self.scope = None # Determine values self.width = int(kwargs["width"]) if "width" in kwargs else None self.height = int(kwargs["height"]) if "height" in kwargs else None self.refresh = int(kwargs["refresh"]) if "refresh" in kwargs else None # For HiDPI: # 0: fits HiDPI or non-HiDPI # 1: fits only non-HiDPI # 2: fits only HiDPI self.hidpi = int(kwargs["hidpi"]) if "hidpi" in kwargs else None self.angle = int(kwargs["angle"]) if "angle" in kwargs else None self.brightness = float(kwargs["brightness"]) if "brightness" in kwargs else None self.underscan = float(kwargs["underscan"]) if "underscan" in kwargs else None self.source = kwargs["source"] if "source" in kwargs else None # Make sure IOKit is ready for use in any/all commands getIOKit() # "Magic" methods def __str__(self): # A list to contain strings of all the arguments in the command stringList = [self.verb] # Determine subcommand if self.subcommand: stringList.append(self.subcommand) # Determine value if self.verb == "res": if self.width and self.height: # can also be set by subcommand=highest stringList.append(self.width) stringList.append(self.height) elif self.verb == "rotate": stringList.append(self.angle) elif self.verb == "brightness": stringList.append(self.brightness) elif self.verb == "underscan": stringList.append(self.underscan) elif self.verb == "mirror" and self.subcommand == "enable": stringList.append(self.source.tag) # Determine options if self.verb == "show" or self.verb == "res": if self.hidpi == 1: stringList.append("no-hidpi") elif self.hidpi == 2: stringList.append("only-hidpi") if self.verb == "res": if self.refresh: stringList.append("refresh {}".format(self.refresh)) # Determine scope if self.scope: if len(self.scope) == len(getAllDisplays()): stringList.append("all") else: for display in sorted(self.scope): stringList.append(display.tag) # Default scope else: if ( self.verb == "res" or self.verb == "rotate" or self.verb == "brightness" or self.verb == "underscan" ): stringList.append("main") elif ( self.verb == "show" or (self.verb == "mirror" and self.subcommand == "disable") ): stringList.append("all") # Convert everything to a string so it can be joined for i in range(len(stringList)): stringList[i] = str(stringList[i]) return " ".join(stringList) def __eq__(self, other): def safeScopeCheckEquals(a, b): """ Check whether two Commands' scopes are equal in a None-safe way :param a: The first Command :param b: The second Command :return: Whether the two scopes are equal """ if a.scope and b.scope: return set(a.scope) == set(b.scope) else: return a.scope == b.scope if isinstance(other, self.__class__): return all([ isinstance(other, self.__class__), self.verb == other.verb, self.subcommand == other.subcommand, safeScopeCheckEquals(self, other), self.width == other.width, self.height == other.height, self.refresh == other.refresh, self.hidpi == other.hidpi, self.angle == other.angle, self.brightness == other.brightness, self.underscan == other.underscan, self.source == other.source, ]) else: return NotImplemented def __ne__(self, other): if isinstance(other, self.__class__): return not self.__eq__(other) else: return NotImplemented def __lt__(self, other): if self.__eq__(other): return False else: return self.__str__().lower() < self.__str__().lower() def __gt__(self, other): if self.__eq__(other): return False else: return self.__str__().lower() > self.__str__().lower() def __hash__(self): return hash(self.__str__()) # Run (and its handlers) def run(self): """ Runs the command this Command has stored """ try: if self.verb == "help": self.__handleHelp() elif self.verb == "show": self.__handleShow() elif self.verb == "res": self.__handleRes() elif self.verb == "rotate": self.__handleRotate() elif self.verb == "brightness": self.__handleBrightness() elif self.verb == "underscan": self.__handleUnderscan() elif self.verb == "mirror": self.__handleMirror() except DisplayError as e: raise CommandExecutionError(e.message, command=self) def __handleHelp(self): """ Shows the user usage information (either for a specific verb, or general help) """ helpTypes = { "usage": "\n".join([ "usage: display_manager.py <command>", "", "COMMANDS (required)", " help Show help information about a command", " show Show current/available display configurations", " res Manage display resolution", " brightness Manage display brightness", " rotate Manage display rotation", " underscan Manage display underscan", " mirror Manage screen mirroring", ]), "help": "\n".join([ "usage: display_manager.py help <command>", "", "COMMANDS (required)", " help Show help information about a command", " show Show current/available display configurations", " res Manage display resolution and refresh rate", " brightness Manage display brightness", " rotate Manage display rotation", " underscan Manage display underscan", " mirror Manage screen mirroring", ]), "show": "\n".join([ "usage: display_manager.py show [subcommand] [options] [scope...]", "", "SUBCOMMANDS (optional)", " current (default) Show the current display configuration", " default Apple's recommended default configuration", " highest Show the highest available configuration", " available Show all available configurations", "", "OPTIONS (optional; only applies to \"available\")", " no-hidpi Don\'t show HiDPI resolutions", " only-hidpi Only show HiDPI resolutions", "", " (Note: by default, both HiDPI and non-HiDPI resolutions are shown)", "", "SCOPE (optional)", " main Perform this command on the main display", " ext<N> Perform this command on external display number <N>", " all (default) Perform this command on all connected displays", ]), "res": "\n".join([ "usage: display_manager.py res <resolution> [refresh] [options] [scope...]", "", "RESOLUTION (required)", " default Apple's recommended default configuration", " highest Set the display to the highest available configuration", " <width> <height> Width and height (in pixels)", " (Note: width and height must be separated by at least one space)", "", "REFRESH (not used by \"default\" or \"highest\" resolution; optional otherwise)", " <refresh> Refresh rate (in Hz)", " (Note: if refresh rate is not specified, it will default to a rate that is " "available at the desired resolution, if possible)", "", "OPTIONS (optional)", " no-hidpi Don\'t set to HiDPI resolutions", " only-hidpi Only set to HiDPI resolutions", "", " (Note: by default, both HiDPI and non-HiDPI resolutions are shown)", "", "SCOPE (optional)", " main (default) Perform this command on the main display", " ext<N> Perform this command on external display number <N>", " all Perform this command on all connected displays", ]), "rotate": "\n".join([ "usage: display_manager.py rotate <angle> [scope...]", "", "ANGLE (required)", " <angle> Desired display rotation; must be a multiple of 90", "", "SCOPE (optional)", " main (default) Perform this command on the main display", " ext<N> Perform this command on external display number <N>", " all Perform this command on all connected displays", ]), "brightness": "\n".join([ "usage: display_manager.py brightness <brightness> [scope...]", "", "BRIGHTNESS (required)", " <brightness> A number between 0 and 1 (inclusive); " "0 is minimum brightness, and 1 is maximum brightness", "", "SCOPE (optional)", " main (default) Perform this command on the main display", " ext<N> Perform this command on external display number <N>", " all Perform this command on all connected displays", ]), "underscan": "\n".join([ "usage: display_manager.py underscan <underscan> [scope...]", "", "UNDERSCAN (required)", " <underscan> A number between 0 and 1 (inclusive); " "0 is minimum underscan, and 1 is maximum underscan", "", "SCOPE (optional)", " main (default) Perform this command on the main display", " ext<N> Perform this command on external display number <N>", " all Perform this command on all connected displays", ]), "mirror": "\n".join([ "usage: display_manager.py mirror enable <source> <target...>", " or: display_manager.py mirror disable [scope...]", "", "SUBCOMMANDS (required)", " enable Set <target> to mirror <source>", " disable Disable mirroring on <scope>", "", "SOURCE/TARGET(S) (not used by \"disable\"; required for \"enable\")", " source The display which will be mirrored by the target(s); " "must be a single element of <SCOPE> (see below); cannot be \"all\"", " target(s) The display(s) which will mirror the source; " "must be an element of <SCOPE> (see below)", "", "SCOPE", " main The main display", " ext<N> External display number <N>", " all (default scope for \"disable\")", " For <enable>: all connected displays besides <source>; only available to <target>", " For <disable>: all connected displays", ])} if self.subcommand in helpTypes: print(helpTypes[self.subcommand]) else: print(helpTypes["usage"]) def __handleShow(self): """ Shows the user information about connected displays """ for i, display in enumerate(self.scope): # Always print display identifier print("display \"{0}\":".format(display.tag)) if self.subcommand == "current": current = display.currentMode print(current.bigString) if display.rotation is not None: print("rotation: {}".format(display.rotation)) if display.brightness is not None: print("brightness: {:.2f}".format(display.brightness)) if display.underscan is not None: print("underscan: {:.2f}".format(display.underscan)) if display.mirrorSource is not None: print("mirror of: {}".format(display.mirrorSource.tag)) elif self.subcommand == "default": default = display.defaultMode if default: print(default.bigString) elif self.subcommand == "highest": highest = display.highestMode(self.hidpi) if highest: print(highest.bigString) elif self.subcommand == "available": # Categorize modes by type, in order current = None default = None hidpi = [] lodpi = [] for mode in sorted(display.allModes, reverse=True): if mode == display.currentMode: current = mode # Note: intentionally left "if" instead of "elif"; mode can be both current and default if mode.isDefault: default = mode if mode.hidpi: hidpi.append(mode) if not mode.hidpi: lodpi.append(mode) if current: print("\n".join([ " current mode:", " {}".format(current.littleString), ])) if default: print("\n".join([ " default mode:", " {}".format(default.littleString), ])) if hidpi: print( " HiDPI modes:" ) for mode in hidpi: print( " {}".format(mode.littleString) ) if lodpi: print( " non-HiDPI modes:" ) for mode in lodpi: print( " {}".format(mode.littleString) ) # Leave an empty line between displays if i < len(self.scope) - 1: print("") def __handleRes(self): """ Sets the display to the correct DisplayMode. """ for display in self.scope: if self.subcommand == "default": default = display.defaultMode display.setMode(default) elif self.subcommand == "highest": highest = display.highestMode(self.hidpi) display.setMode(highest) else: closest = display.closestMode(self.width, self.height, self.refresh, self.hidpi) display.setMode(closest) def __handleRotate(self): """ Sets display rotation. """ for display in self.scope: display.setRotate(self.angle) def __handleBrightness(self): """ Sets display brightness """ for display in self.scope: display.setBrightness(self.brightness) def __handleUnderscan(self): """ Sets or shows a display's underscan settings. """ for display in self.scope: display.setUnderscan(self.underscan) def __handleMirror(self): """ Enables or disables mirroring between two displays. """ if self.subcommand == "enable": source = self.source for target in self.scope: target.setMirrorSource(source) elif self.subcommand == "disable": for target in self.scope: # If display is a mirror of another display, disable mirroring between them if target.mirrorSource is not None: target.setMirrorSource(None) class CommandList(object): """ Holds one or more "Command" instances, and allows smart simultaneous execution """ def __init__(self, commands=None): """ :param commands: A single Command, a list of Commands, or a CommandList """ # self.commands is a list that contains all the raw commands passed in to self.addCommand self.commands = [] # self.commandDict will consist of displayID keys corresponding to commands for that display self.commandDict = {} if commands: if isinstance(commands, Command): self.addCommand(commands) elif isinstance(commands, list): for command in commands: self.addCommand(command) elif isinstance(commands, CommandList): for command in commands.commands: self.addCommand(command) # "Magic" methods def __eq__(self, other): if isinstance(other, self.__class__): return set(self.commands) == set(other.commands) else: return NotImplemented def __ne__(self, other): if isinstance(other, self.__class__): return set(self.commands) != set(other.commands) else: return NotImplemented def __hash__(self): h = 0 for command in self.commands: h = h | command.__str__() return hash(h) # Command interfacing def addCommand(self, command): """ :param command: The Command to add to this CommandList """ # Break "command" into each individual action it will perform # on each individual display in its scope, and add those actions # to commandDict, according to their associated display if command.scope: if len(command.scope) == len(getAllDisplays()): if "all" in self.commandDict: self.commandDict["all"].append(command) else: self.commandDict["all"] = [command] else: for display in command.scope: if display.tag in self.commandDict: self.commandDict[display.tag].append(command) else: self.commandDict[display.tag] = [command] # If there is no scope, there will be only one action. # In this case, we simply add the command to key "None". # Note: this should only be possible with verb="help", since every # other verb has a default scope else: if None in self.commandDict: self.commandDict[None].append(command) else: self.commandDict[None] = [command] self.commands.append(command) def run(self): """ Runs all stored Commands in a non-interfering fashion """ for displayTag in self.commandDict: # Commands for this particular display displayCommands = self.commandDict[displayTag] # Group commands by subcommand. Must preserve ordering to avoid interfering commands verbGroups = collections.OrderedDict([ ("help", []), ("mirror", []), ("rotate", []), ("res", []), ("underscan", []), ("brightness", []), ("show", []), ]) for command in displayCommands: verbGroups[command.verb].append(command) # Run commands by subcommand for verb in verbGroups: # Commands for this display, of this subcommand commands = verbGroups[verb] if len(commands) > 0: # Multiple commands of these types will undo each other. # As such, just run the most recently added command (the last in the list) if ( verb == "help" or verb == "rotate" or verb == "res" or verb == "brightness" or verb == "underscan" ): try: commands[-1].run() except DisplayError as e: raise CommandExecutionError(e.message, commands[-1]) # "show" commands don't interfere with each other, so run all of them elif verb == "show": for command in commands: try: command.run() except DisplayError as e: raise CommandExecutionError(e.message, command) # "mirror" commands are the most complicated to deal with elif verb == "mirror": command = commands[-1] if command.subcommand == "enable": display = getDisplayFromTag(displayTag) # The current Display that the above "display" is mirroring currentMirror = display.mirrorSource # Become a mirror of most recently requested display mirrorDisplay = command.source # If display is not a mirror of any other display if currentMirror is None: try: display.setMirrorSource(mirrorDisplay) except DisplayError as e: raise CommandExecutionError(e.message, command) # The user requested that this display mirror itself, or that it mirror a display # which it is already mirroring. In either case, nothing should be done elif display == currentMirror or currentMirror == mirrorDisplay: pass # display is already a mirror, but not of the requested display else: # First disable mirroring, then enable it for new mirror display.setMirrorSource(None) display.setMirrorSource(mirrorDisplay) try: display.setMirrorSource(None) display.setMirrorSource(mirrorDisplay) except DisplayError as e: raise CommandExecutionError(e.message, command) elif command.subcommand == "disable": try: command.run() except DisplayError as e: raise CommandExecutionError(e.message, command) def getDisplayFromTag(displayTag): """ Returns a Display for "displayTag" :param displayTag: The display tag to find the Display of :return: The Display which displayTag refers to """ if displayTag == "main": return getMainDisplay() elif displayTag == "all": return getAllDisplays() elif re.match(r"^ext[0-9]+$", displayTag): # Get all the external displays (in order) externals = sorted(getAllDisplays()) for display in externals: if display.isMain: externals.remove(display) break # Get the number in displayTag externalNum = int(displayTag[3:]) if externalNum > len(externals) - 1: # There aren't enough displays for this externalNumber to be valid raise CommandValueError("There is no display \"{}\"".format(displayTag)) else: # 0 < externalNum < len(externals) - 1 means valid tag # ("0 < externalNum" known from re.match(r"^ext[0-9]+$") above) return externals[externalNum] # Note: no need for final "else" here, because getDisplayFromTag will only # be passed regex matches for "main|all|ext[0-9]+", because these are the only # arguments added to "scopeTags" def getCommand(commandString): """ Converts the commandString into a Command :param commandString: the string to convert :return: The Command represented by "commandString" """ if not commandString: return None # Individual words/values in the command words = commandString.split() # Determine verb, and remove it from words verb = words.pop(0) # Determine scope, and remove it from words scopePattern = r"^(main|ext[0-9]+|all)$" scopeTags = [] # Iterate backwards through the indices of "words" for i in range(len(words) - 1, -1, -1): if re.match(scopePattern, words[i]): # If this scope tag is at the end of the list if words[i] == words[-1]: scopeTags.append(words.pop(i)) # This scope tag is in the wrong place else: raise CommandSyntaxError("Invalid placement of {}".format(words[i]), verb=verb) # Determine positionals (all remaining words) positionals = words attributesDict = { "verb": verb, "subcommand": None, "scope": None, "width": None, "height": None, "refresh": None, "hidpi": None, "angle": None, "brightness": None, "underscan": None, "source": None, } if verb == "help": if len(positionals) == 0: # Default (sub)command subcommand = "usage" elif len(positionals) == 1: if positionals[0] in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"]: subcommand = positionals[0] # Invalid (sub)command else: raise CommandValueError("\"{}\" is not a valid command".format(positionals[0]), verb=verb) # Too many arguments else: raise CommandSyntaxError("Help commands can only have one argument", verb=verb) attributesDict["subcommand"] = subcommand elif verb == "show": # Determine HiDPI settings hidpi = 0 for positional in positionals: if positional == "no-hidpi": # If HiDPI hasn't been set to the contrary setting if hidpi != 2: hidpi = 1 # doesn't match HiDPI positionals.remove(positional) else: raise CommandValueError("Cannot specify both \"no-hidpi\" and \"only-hidpi\"", verb=verb) elif positional == "only-hidpi": # If HiDPI hasn't been set to the contrary setting if hidpi != 1: hidpi = 2 # only matches HiDPI positionals.remove(positional) else: raise CommandValueError("Cannot specify both \"no-hidpi\" and \"only-hidpi\"", verb=verb) if len(positionals) == 0: # Default subcommand subcommand = "current" elif len(positionals) == 1: if positionals[0] in ["current", "default", "highest", "available"]: subcommand = positionals[0] # Invalid subcommand else: raise CommandValueError("\"{}\" is not a valid subcommand".format(positionals[0]), verb=verb) # Too many arguments else: raise CommandSyntaxError("Show commands can only have one subcommand", verb=verb) # Determine scope if len(scopeTags) > 0: if "all" in scopeTags: scope = getAllDisplays() else: scope = [] for scopeTag in scopeTags: scope.append(getDisplayFromTag(scopeTag)) else: # Default scope scope = getAllDisplays() attributesDict["subcommand"] = subcommand attributesDict["hidpi"] = hidpi attributesDict["scope"] = scope elif verb == "res": # Determine HiDPI settings hidpi = 0 for positional in positionals: if positional == "no-hidpi": # If HiDPI hasn't been set to the contrary setting if hidpi != 2: hidpi = 1 # doesn't match HiDPI positionals.remove(positional) else: raise CommandValueError("Cannot specify both \"no-hidpi\" and \'only-hidpi\"", verb=verb) elif positional == "only-hidpi": # If HiDPI hasn't been set to the contrary setting if hidpi != 1: hidpi = 2 # only matches HiDPI positionals.remove(positional) else: raise CommandValueError("Cannot specify both \"no-hidpi\" and \'only-hidpi\"", verb=verb) if len(positionals) == 0: raise CommandSyntaxError("Res commands must specify a resolution", verb=verb) # case: "default"/"highest" elif len(positionals) == 1: if positionals[0] in ["default", "highest"]: subcommand = positionals[0] else: raise CommandValueError( "Res commands must either specify both width and height or use the \"highest\" keyword", verb=verb ) attributesDict["subcommand"] = subcommand attributesDict["hidpi"] = hidpi # cases: ("default"/"highest", refresh) or (width, height) elif len(positionals) == 2: # case: ("default"/"highest", refresh) if positionals[0] in ["default", "highest"]: subcommand = positionals[0] try: refresh = int(positionals[1]) except ValueError: raise CommandValueError("\"{}\" is not a valid refresh rate", verb=verb) if refresh < 0: raise CommandValueError("Refresh rate must be positive", verb=verb) attributesDict["subcommand"] = subcommand attributesDict["refresh"] = refresh attributesDict["hidpi"] = hidpi # case: (width, height) else: # Try to parse positionals as integers wh = [] for i in range(len(positionals)): try: wh.append(int(positionals[i])) except ValueError: wh.append(None) width, height = wh # Neither width nor height were integers (and thus invalid pixel counts) if width is None and height is None: raise CommandValueError( "Neither \"{}\" nor \"{}\" are valid widths or heights".format( positionals[0], positionals[1]), verb=verb ) # width was invalid elif width is None: raise CommandValueError( "\"{}\" is not a valid width".format(positionals[0]), verb=verb ) # height was invalid elif height is None: raise CommandValueError( "\"{}\" is not a valid height".format(positionals[1]), verb=verb ) # no negative dimensions if width < 0 or height < 0: raise CommandValueError( "Width and height must be positive", verb=verb ) attributesDict["width"] = width attributesDict["height"] = height attributesDict["hidpi"] = hidpi # case: (width, height, refresh) elif len(positionals) == 3: # Try to parse width, height, and refresh as integers whr = [] for i in range(len(positionals)): try: whr.append(int(positionals[i])) except ValueError: whr.append(None) width, height, refresh = whr # Nothing was an integer if width is None and height is None and refresh is None: raise CommandValueError( "\"{}\"x\"{}\" is not a valid resolution, and \"{}\" is not a valid refresh rate".format( positionals[0], positionals[1], positionals[2]), verb=verb ) # Neither width nor height were integers elif width is None or height is None: raise CommandValueError( "\"{}\"x\"{}\" is not a valid resolution".format( positionals[0], positionals[1]), verb=verb ) # refresh was not an integer elif refresh is None: raise CommandValueError( "\"{}\" is not a valid refresh rate".format(positionals[2]), verb=verb ) # no negative dimensions or rate if width < 0 or height < 0 or refresh < 0: raise CommandValueError( "Width, height, and refresh rate must be positive", verb=verb ) attributesDict["width"] = width attributesDict["height"] = height attributesDict["refresh"] = refresh attributesDict["hidpi"] = hidpi else: raise CommandSyntaxError( "Too many arguments supplied for the res command", verb=verb ) # Determine scope if len(scopeTags) > 0: if "all" in scopeTags: scope = getAllDisplays() else: scope = [] for scopeTag in scopeTags: scope.append(getDisplayFromTag(scopeTag)) else: # Default scope scope = getMainDisplay() attributesDict["scope"] = scope elif verb == "rotate": if len(positionals) == 0: raise CommandSyntaxError("Rotate commands must specify an angle", verb=verb) elif len(positionals) == 1: try: angle = int(positionals[0]) # Rotation must be multiple of 90 if angle % 90 != 0: raise CommandValueError("\"{}\" is not a multiple of 90".format(positionals[0]), verb=verb) # Couldn't convert to int except ValueError: raise CommandValueError("\"{}\" is not a multiple of 90".format(positionals[0]), verb=verb) # Too many arguments else: raise CommandSyntaxError("Rotate commands can only have one argument", verb=verb) # Determine scope if len(scopeTags) > 0: if "all" in scopeTags: scope = getAllDisplays() else: scope = [] for scopeTag in scopeTags: scope.append(getDisplayFromTag(scopeTag)) else: # Default scope scope = getMainDisplay() attributesDict["angle"] = angle attributesDict["scope"] = scope elif verb == "brightness": if len(positionals) == 0: raise CommandSyntaxError("Brightness commands must specify a brightness value", verb=verb) elif len(positionals) == 1: try: brightness = float(positionals[0]) # Brightness must be between 0 and 1 if brightness < 0 or brightness > 1: raise CommandValueError( "\"{}\" is not a number between 0 and 1 (inclusive)".format(positionals[0]), verb=verb ) # Couldn't convert to float except ValueError: raise CommandValueError( "\"{}\" is not a number between 0 and 1 (inclusive)".format(positionals[0]), verb=verb ) # Too many arguments else: raise CommandSyntaxError("Brightness commands can only have one argument", verb=verb) # Determine scope if len(scopeTags) > 0: if "all" in scopeTags: scope = getAllDisplays() else: scope = [] for scopeTag in scopeTags: scope.append(getDisplayFromTag(scopeTag)) else: # Default scope scope = getMainDisplay() attributesDict["brightness"] = brightness attributesDict["scope"] = scope elif verb == "underscan": if len(positionals) == 0: raise CommandSyntaxError("Underscan commands must specify an underscan value", verb=verb) elif len(positionals) == 1: try: underscan = float(positionals[0]) # Underscan must be between 0 and 1 if underscan < 0 or underscan > 1: raise CommandValueError( "\"{}\" is not a number between 0 and 1 (inclusive)".format(positionals[0]), verb=verb ) # Couldn't convert to float except ValueError: raise CommandValueError( "\"{}\" is not a number between 0 and 1 (inclusive)".format(positionals[0]), verb=verb ) # Too many arguments else: raise CommandSyntaxError("underscan commands can only have one argument", verb=verb) # Determine scope if len(scopeTags) > 0: if "all" in scopeTags: scope = getAllDisplays() else: scope = [] for scopeTag in scopeTags: scope.append(getDisplayFromTag(scopeTag)) else: # Default scope scope = getMainDisplay() attributesDict["underscan"] = underscan attributesDict["scope"] = scope elif verb == "mirror": if len(positionals) == 0: raise CommandSyntaxError("Mirror commands must specify a subcommand", verb=verb) # elif len(positionals) == 1: subcommand = positionals.pop(0) if subcommand == "enable": if len(positionals) == 0: if len(scopeTags) < 2: raise CommandSyntaxError( "Mirror enable commands require at least one source and one target display", verb=verb ) else: # For "enable" subcommand, first element in scope is source, and the rest are targets # Since we parsed "scope" in reverse order, source will be last source = getDisplayFromTag(scopeTags.pop(-1)) # Cannot mirror from more than one display if isinstance(source, list): if len(source) > 1: raise CommandValueError( "The source for mirror enable cannot be \"all\"", verb=verb ) # Determine target(s) if "all" in scopeTags: targets = getAllDisplays() else: targets = [] for scopeTag in scopeTags: targets.append(getDisplayFromTag(scopeTag)) attributesDict["subcommand"] = subcommand attributesDict["source"] = source attributesDict["scope"] = targets else: raise CommandValueError( "\"{}\" is not a valid source or target".format(positionals[0]), verb=verb ) elif subcommand == "disable": if len(positionals) == 0: # Determine scope if len(scopeTags) > 0: if "all" in scopeTags: scope = getAllDisplays() else: scope = [] for scopeTag in scopeTags: scope.append(getDisplayFromTag(scopeTag)) else: # Default scope scope = getAllDisplays() attributesDict["subcommand"] = subcommand attributesDict["scope"] = scope else: raise CommandValueError( "\"{}\" is not a valid scope".format(positionals[0]), verb=verb ) else: raise CommandValueError("\"{}\" is not a valid subcommand".format(subcommand), verb=verb) emptyKeys = [key for key in attributesDict if attributesDict[key] is None] for emptyKey in emptyKeys: attributesDict.pop(emptyKey) return Command(**attributesDict) def parseCommands(commandStrings): """ :param commandStrings: The string to get Commands from :return: Commands contained within the string """ # Empty string if not commandStrings: raise CommandSyntaxError("An empty string is not a valid command") # Make sure all of the commands are in ASCII if not all(ord(c) < 128 for c in commandStrings): raise CommandSyntaxError("Commands cannot include non-ASCII characters") # The types of commands that can be issued verbPattern = r"help|show|res|brightness|rotate|underscan|mirror" # Pattern for finding multiple commands commandPattern = r"((?:{0}).*?)(?:(?: (?={0}))|\Z)".format(verbPattern) # Make sure the command starts with a valid verb firstWord = commandStrings.split()[0] firstWordMatch = re.match("^(" + verbPattern + ")$", firstWord) if not firstWordMatch: raise CommandSyntaxError("\"{}\" is not a valid type of command".format(firstWord), verb=firstWord) # Get all the individual commands if "help" not in commandStrings: commandStrings = re.findall(commandPattern, commandStrings) # Cannot run more than one command if one of them is a "help" command else: # The whole command will be interpreted as a single help command if firstWord == "help": commandStrings = [commandStrings] # The help command isn't even the first command else: raise CommandSyntaxError("Cannot run multiple commands if one of them is \"help\"", verb="help") # Make the CommandList from the given command strings commands = CommandList() for commandString in commandStrings: command = getCommand(commandString) if command: commands.addCommand(command) return commands def main(): # Attempt to parse the commands try: commands = parseCommands(" ".join(sys.argv[1:])) except (CommandSyntaxError, CommandValueError) as e: if e.verb: if e.verb in ["help", "show", "res", "brightness", "rotate", "underscan", "mirror"]: # Show proper usage information for the attempted command Command(verb="help", subcommand=e.verb).run() print("") print("Error in {} command:".format(e.verb)) print(e.message) else: print("Error: {}".format(e.message)) raise SystemExit() # Command successfully parsed else: try: commands.run() except CommandExecutionError as e: print("Error: {}".format(e.message)) raise SystemExit() if __name__ == "__main__": main()
{"/gui.py": ["/display_manager.py"], "/display_manager.py": ["/display_manager_lib.py"]}
37,342
univ-of-utah-marriott-library-apple/display_manager
refs/heads/stable
/display_manager_lib.py
#!/usr/bin/python3 ######################################################################## # Copyright (c) 2018 University of Utah Student Computing Labs. # # All Rights Reserved. # # # # Permission to use, copy, modify, and distribute this software and # # its documentation for any purpose and without fee is hereby granted, # # provided that the above copyright notice appears in all copies and # # that both that copyright notice and this permission notice appear # # in supporting documentation, and that the name of The University # # of Utah not be used in advertising or publicity pertaining to # # distribution of the software without specific, written prior # # permission. This software is supplied as is without expressed or # # implied warranties of any kind. # ######################################################################## # Display Manager, version 1.0.2 # Python Library # Programmatically manages Mac displays. # Can set screen resolution, refresh rate, rotation, brightness, underscan, and screen mirroring. import sys # make decisions based on system configuration import warnings # control warning settings for import abc # allows use of abstract classes import objc # access Objective-C functions and variables import CoreFoundation # work with Objective-C data types import Quartz # work with system graphics # Configured for global usage; otherwise, must be re-instantiated each time it is called iokit = None class DisplayError(Exception): """ Raised if a display cannot perform the requested operation (or access the requested property) (e.g. does not have a matching display mode, display cannot modify this setting, etc.) """ pass class AbstractDisplay(object): """ Abstract representation which display_manager_lib.Display will inherit from. Included for unit testing purposes """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self, displayID): self.displayID = displayID # "Magic" methods def __eq__(self, other): if isinstance(other, self.__class__): return self.displayID == other.displayID else: return NotImplemented def __ne__(self, other): if isinstance(other, self.__class__): return self.displayID != other.displayID else: return NotImplemented def __lt__(self, other): return self.displayID < other.displayID def __gt__(self, other): return self.displayID > other.displayID def __hash__(self): # Actually just returns self.displayID, as self.displayID is int; # hash() is called for consistency and compatibility return hash(self.displayID) # General properties @abc.abstractproperty def isMain(self): pass @abc.abstractproperty def tag(self): pass # Mode properties and methods @abc.abstractproperty def currentMode(self): pass @abc.abstractproperty def allModes(self): pass @abc.abstractmethod def highestMode(self, hidpi): pass @abc.abstractmethod def closestMode(self, width, height, refresh, hidpi): pass @abc.abstractmethod def setMode(self, mode): pass # Rotation properties and methods @abc.abstractproperty def rotation(self): pass @abc.abstractmethod def setRotate(self, angle): pass # Brightness @abc.abstractproperty def brightness(self): pass @abc.abstractmethod def setBrightness(self, brightness): pass # Underscan @abc.abstractproperty def underscan(self): pass @abc.abstractmethod def setUnderscan(self, underscan): pass # Mirroring @abc.abstractproperty def mirrorSource(self): pass @abc.abstractmethod def setMirrorSource(self, mirrorDisplay): pass class Display(AbstractDisplay): """ Virtual representation of a physical display. Contains properties regarding display information for a given physical display, along with a few useful helper functions to configure the display. """ def __init__(self, displayID): """ :param displayID: The DisplayID of the display to manipulate """ # Make sure displayID is actually a display (error, allDisplayIDs, count) = Quartz.CGGetOnlineDisplayList(32, None, None) # max 32 displays if displayID not in allDisplayIDs or error: raise DisplayError("Display with ID \"{}\" not found".format(displayID)) # Sets self.displayID to displayID super(Display, self).__init__(displayID) # iokit is required for several Display methods getIOKit() # General properties @property def tag(self): """ :return: The display tag for this Display """ if self.isMain: return "main" # is external display else: # Get all the external displays (in order) externals = sorted(getAllDisplays()) for display in externals: if display.isMain: externals.remove(display) break for i in range(len(externals)): if self == externals[i]: return "ext" + str(i) @property def isMain(self): """ :return: Boolean for whether this Display is the main display """ return Quartz.CGDisplayIsMain(self.displayID) @property def isHidpi(self): """ :return: Whether this display can be set to HiDPI resolutions """ # Check if self.allModes has any HiDPI modes for mode in self.allModes: if mode.hidpi: return True # None of self.allModes were HiDPI return False # Helper methods, properties @property def __servicePort(self): """ :return: The integer representing this display's service port. """ return Quartz.CGDisplayIOServicePort(self.displayID) @staticmethod def __rightHidpi(mode, hidpi): """ Evaluates whether the mode fits the user's HiDPI specification. :param mode: The mode to be evaluated. :param hidpi: HiDPI code. 0 returns everything, 1 returns only non-HiDPI, and 2 returns only HiDPI. :return: Whether the mode fits the HiDPI description specified by the user. """ if ( (hidpi == 0) # fits HiDPI or non-HiDPI (default) or (hidpi == 1 and not mode.hidpi) # fits only non-HiDPI or (hidpi == 2 and mode.hidpi) # fits only HiDPI ): return True else: return False # Mode properties and methods @property def currentMode(self): """ :return: The current Quartz "DisplayMode" interface for this display. """ return DisplayMode(Quartz.CGDisplayCopyDisplayMode(self.displayID)) @property def defaultMode(self): for mode in self.allModes: if mode.isDefault: return mode # No default mode was found return None @property def allModes(self): """ :return: All possible Quartz "DisplayMode" interfaces for this display. """ # TO-DO: This needs to be revisited modes = [] # options forces Quartz to show HiDPI modes options = {Quartz.kCGDisplayShowDuplicateLowResolutionModes: True} for modeRef in Quartz.CGDisplayCopyAllDisplayModes(self.displayID, options): modes.append(DisplayMode(modeRef)) # Eliminate all duplicate modes, including any modes that duplicate "default" uniqueModes = set(modes) defaultMode = None # Find default mode for mode in uniqueModes: if mode.isDefault: defaultMode = mode if defaultMode: # If there are any duplicates of defaultMode, remove them (and not defaultMode) for mode in modes: if all([ defaultMode.width == mode.width, defaultMode.height == mode.height, defaultMode.refresh == mode.refresh, defaultMode.hidpi == mode.hidpi, not mode.isDefault, ]): try: uniqueModes.remove(mode) except KeyError: pass return list(uniqueModes) def highestMode(self, hidpi=0): """ :param hidpi: HiDPI code. 0 returns everything, 1 returns only non-HiDPI, and 2 returns only HiDPI. :return: The Quartz "DisplayMode" interface with the highest display resolution for this display. """ highest = None for mode in self.allModes: if highest: if mode > highest and self.__rightHidpi(mode, hidpi): highest = mode else: # highest hasn't been set yet, so anything is the highest highest = mode if highest: return highest else: if hidpi == 1: raise DisplayError( "Display \"{}\" cannot be set to any non-HiDPI resolutions".format(self.tag)) elif hidpi == 2: raise DisplayError( "Display \"{}\" cannot be set to any HiDPI resolutions".format(self.tag)) else: raise DisplayError( "Display \"{}\"\'s resolution cannot be set".format(self.tag)) def closestMode(self, width, height, refresh=0, hidpi=0): """ :param width: Desired width :param height: Desired height :param refresh: Desired refresh rate :param hidpi: HiDPI code. 0 returns everything, 1 returns only non-HiDPI, and 2 returns only HiDPI :return: The closest Quartz "DisplayMode" interface possible for this display. """ # Which criteria does it match (in addition to width and height)? both = [] # matches HiDPI and refresh onlyHidpi = [] # matches HiDPI onlyRefresh = [] # matches refresh for mode in self.allModes: if mode.width == width and mode.height == height: if self.__rightHidpi(mode, hidpi) and mode.refresh == refresh: both.append(mode) elif self.__rightHidpi(mode, hidpi): onlyHidpi.append(mode) elif mode.refresh == refresh: onlyRefresh.append(mode) # Return the nearest match, with HiDPI matches preferred over refresh matches for modes in [both, onlyHidpi, onlyRefresh]: if modes: return modes[0] raise DisplayError( "Display \"{}\" cannot be set to {}x{}".format(self.tag, width, height) ) def setMode(self, mode): """ :param mode: The Quartz "DisplayMode" interface to set this display to. """ (error, configRef) = Quartz.CGBeginDisplayConfiguration(None) if error: raise DisplayError( "Display \"{}\"\'s resolution cannot be set to {}x{} at {} Hz".format( self.tag, mode.width, mode.height, mode.refresh)) error = Quartz.CGConfigureDisplayWithDisplayMode(configRef, self.displayID, mode.raw, None) if error: Quartz.CGCancelDisplayConfiguration(configRef) raise DisplayError( "Display \"{}\"\'s resolution cannot be set to {}x{} at {} Hz".format( self.tag, mode.width, mode.height, mode.refresh)) Quartz.CGCompleteDisplayConfiguration(configRef, Quartz.kCGConfigurePermanently) # Rotation properties and methods @property def rotation(self): """ :return: Rotation of this display, in degrees. """ return int(Quartz.CGDisplayRotation(self.displayID)) def setRotate(self, angle): """ :param angle: The angle of rotation. """ # see: https://opensource.apple.com/source/IOGraphics/IOGraphics-406/IOGraphicsFamily/IOKit/graphics/ # IOGraphicsTypes.h for angle codes (kIOScaleRotate{0, 90, 180, 270}). # Likewise, see .../IOKit/graphics/IOGraphicsTypesPrivate.h for rotateCode (kIOFBSetTransform) swapAxes = 0x10 invertX = 0x20 invertY = 0x40 angleCodes = { 0: 0, 90: (swapAxes | invertX) << 16, 180: (invertX | invertY) << 16, 270: (swapAxes | invertY) << 16, } rotateCode = 0x400 # If user enters inappropriate angle, we should quit if angle % 90 != 0: raise ValueError("Can only rotate by multiples of 90 degrees.") options = rotateCode | angleCodes[angle % 360] # Actually rotate the screen error = iokit["IOServiceRequestProbe"](self.__servicePort, options) if error: raise DisplayError("Cannot manage rotation on display \"{}\"".format(self.tag)) # Brightness properties and methods @property def brightness(self): """ :return: Brightness of this display, from 0 to 1. """ service = self.__servicePort (error, brightness) = iokit["IODisplayGetFloatParameter"](service, 0, iokit["kDisplayBrightness"], None) if error: return None else: return brightness def setBrightness(self, brightness): """ :param brightness: The desired brightness, from 0 to 1. """ error = iokit["IODisplaySetFloatParameter"](self.__servicePort, 0, iokit["kDisplayBrightness"], brightness) if error: if self.isMain: raise DisplayError("Cannot manage brightness on display \"{}\"".format(self.tag)) else: raise DisplayError( "Display \"{}\"\'s brightness cannot be set.\n" "External displays may not be compatible with Display Manager. " "Try setting manually on device hardware.".format(self.tag)) # Underscan properties and methods @property def underscan(self): """ :return: Display's active underscan setting, from 1 (0%) to 0 (100%). (Yes, it doesn't really make sense to have 1 -> 0 and 0 -> 100, but it's how IOKit reports it.) """ (error, underscan) = iokit["IODisplayGetFloatParameter"]( self.__servicePort, 0, iokit["kDisplayUnderscan"], None) if error: return None else: # IOKit handles underscan values as the opposite of what makes sense, so I switch it here. # e.g. 0 -> maximum (100%), 1 -> 0% (default) return float(abs(underscan - 1)) def setUnderscan(self, underscan): """ :param underscan: Underscan value, from 0 (no underscan) to 1 (maximum underscan). """ # IOKit handles underscan values as the opposite of what makes sense, so I switch it here. # e.g. 0 -> maximum (100%), 1 -> 0% (default) underscan = float(abs(underscan - 1)) error = iokit["IODisplaySetFloatParameter"](self.__servicePort, 0, iokit["kDisplayUnderscan"], underscan) if error: raise DisplayError("Cannot manage underscan on display \"{}\"".format(self.tag)) # Mirroring properties and methods @property def mirrorSource(self): """ Checks whether self is mirroring another display :return: The Display that self is mirroring; if self is not mirroring any display, returns None """ # The display which self is mirroring masterDisplayID = Quartz.CGDisplayMirrorsDisplay(self.displayID) if masterDisplayID == Quartz.kCGNullDirectDisplay: # self is not mirroring any display return None else: return Display(masterDisplayID) def setMirrorSource(self, mirrorDisplay): """ :param mirrorDisplay: The Display which this Display will mirror. Input a NoneType to stop mirroring. """ (error, configRef) = Quartz.CGBeginDisplayConfiguration(None) if error: raise DisplayError( "Display \"{}\" cannot be set to mirror display \"{}\"".format(self.tag, mirrorDisplay.tag)) # Will be passed a None mirrorDisplay to disable mirroring. Cannot mirror self. if mirrorDisplay is None or mirrorDisplay.displayID == self.displayID: Quartz.CGConfigureDisplayMirrorOfDisplay(configRef, self.displayID, Quartz.kCGNullDirectDisplay) else: Quartz.CGConfigureDisplayMirrorOfDisplay(configRef, self.displayID, mirrorDisplay.displayID) Quartz.CGCompleteDisplayConfiguration(configRef, Quartz.kCGConfigurePermanently) class AbstractDisplayMode(object): """ Abstract representation which display_manager_lib.DisplayMode will inherit from. Included for unit testing purposes """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def __init__(self, mode): self.raw = mode # "Magic" methods def __eq__(self, other): if isinstance(other, self.__class__): return all([ self.width == other.width, self.height == other.height, self.refresh == other.refresh, self.hidpi == other.hidpi, self.isDefault == other.isDefault, ]) else: return NotImplemented def __ne__(self, other): if isinstance(other, self.__class__): return not self.__eq__(other) else: return NotImplemented def __lt__(self, other): return self.width * self.height < other.width * other.height def __gt__(self, other): return self.width * self.height > other.width * other.height def __hash__(self): return hash((self.width, self.height, self.refresh, self.hidpi, self.isDefault)) # General properties @abc.abstractproperty def width(self): pass @abc.abstractproperty def height(self): pass @abc.abstractproperty def refresh(self): pass @abc.abstractproperty def hidpi(self): pass @abc.abstractproperty def isDefault(self): pass class DisplayMode(AbstractDisplayMode): """ Represents a DisplayMode as implemented in Quartz.CoreGraphics """ def __init__(self, mode): if not isinstance(mode, Quartz.CGDisplayModeRef): raise DisplayError("\"{}\" is not a valid Quartz.CGDisplayModeRef".format(mode)) # sets self.raw to mode super(DisplayMode, self).__init__(mode) self.__width = int(Quartz.CGDisplayModeGetWidth(mode)) self.__height = int(Quartz.CGDisplayModeGetHeight(mode)) self.__refresh = int(Quartz.CGDisplayModeGetRefreshRate(mode)) maxWidth = Quartz.CGDisplayModeGetPixelWidth(mode) # the maximum display width for this display maxHeight = Quartz.CGDisplayModeGetPixelHeight(mode) # the maximum display width for this display self.__hidpi = (maxWidth != self.width and maxHeight != self.height) # if they're the same, mode is not HiDPI # General properties @property def littleString(self): return "resolution: {width}x{height}, refresh rate: {refresh}, HiDPI: {hidpi}".format(**{ "width": self.width, "height": self.height, "refresh": self.refresh, "hidpi": self.hidpi, }) @property def bigString(self): return "\n".join([ "resolution: {}x{}".format(self.width, self.height), "refresh rate: {}".format(self.refresh), "HiDPI: {}".format(self.hidpi), ]) @property def width(self): return self.__width @property def height(self): return self.__height @property def refresh(self): return self.__refresh @property def hidpi(self): return self.__hidpi @property def isDefault(self): """ :return: Whether this DisplayMode is the display's default mode """ # CGDisplayModeGetIOFlags returns a hexadecimal number representing the DisplayMode's flags # the "default" flag is 0x4, which means that said number's binary representation must have # a '1' in the third-to-last position for it to be the default return bin(Quartz.CGDisplayModeGetIOFlags(self.raw))[-3] == '1' def getMainDisplay(): """ :return: The main Display. """ return Display(Quartz.CGMainDisplayID()) def getAllDisplays(): """ :return: A list containing all currently-online displays. """ (error, displayIDs, count) = Quartz.CGGetOnlineDisplayList(32, None, None) # max 32 displays if error: raise DisplayError("Could not retrieve displays list") displays = [] for displayID in displayIDs: displays.append(Display(displayID)) return sorted(displays) def getIOKit(): """ This handles the importing of specific functions and variables from the IOKit framework. IOKit is not natively bridged in PyObjC, so the methods must be found and encoded manually to gain their functionality in Python. :return: A dictionary containing several IOKit functions and variables. """ global iokit # IOKit may have already been instantiated, in which case, nothing needs to be done if not iokit: # PyObjC sometimes raises compatibility warnings in macOS 10.14 relating to parts of IOKit that # Display Manager doesn't use. Thus, such warnings will be temporarily ignored warnings.simplefilter("ignore") # The dictionary which will contain all of the necessary functions and variables from IOKit iokit = {} # Retrieve the IOKit framework iokitBundle = objc.initFrameworkWrapper( "IOKit", frameworkIdentifier="com.apple.iokit", frameworkPath=objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"), globals=globals() ) # The IOKit functions to be retrieved functions = [ ("IOServiceGetMatchingServices", b"iI@o^I"), ("IODisplayCreateInfoDictionary", b"@II"), ("IODisplayGetFloatParameter", b"iII@o^f"), ("IODisplaySetFloatParameter", b"iII@f"), ("IOServiceRequestProbe", b"iII"), ("IOIteratorNext", b"II"), ] # The IOKit variables to be retrieved variables = [ ("kIODisplayNoProductName", b"I"), ("kIOMasterPortDefault", b"I"), ("kIODisplayOverscanKey", b"*"), ("kDisplayVendorID", b"*"), ("kDisplayProductID", b"*"), ("kDisplaySerialNumber", b"*"), ] # Load functions from IOKit.framework into our iokit objc.loadBundleFunctions(iokitBundle, iokit, functions) # Bridge won't put straight into iokit, so globals() objc.loadBundleVariables(iokitBundle, globals(), variables) # Move only the desired variables into iokit for var in variables: key = "{}".format(var[0]) if key in globals(): iokit[key] = globals()[key] # A few IOKit variables that have been deprecated, but whose values # still work as intended in IOKit functions iokit["kDisplayBrightness"] = CoreFoundation.CFSTR("brightness") iokit["kDisplayUnderscan"] = CoreFoundation.CFSTR("pscn") # Stop ignoring warnings now that we've finished with PyObjC warnings.simplefilter("default") return iokit
{"/gui.py": ["/display_manager.py"], "/display_manager.py": ["/display_manager_lib.py"]}
37,343
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/migrations/0006_auto_20161011_1633.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-11 15:33 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hotels', '0005_auto_20161011_1613'), ] operations = [ migrations.RemoveField( model_name='hotel', name='notes', ), migrations.AddField( model_name='hotel', name='chambres', field=models.PositiveIntegerField(default=100), ), migrations.AddField( model_name='hotel', name='note', field=models.DecimalField(decimal_places=1, default=5, max_digits=2), ), migrations.AlterField( model_name='hotel', name='description', field=models.TextField(), ), ]
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,344
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/flights/models.py
from django.db import models '''classe de gestion des Vols ''' class Vol(models.Model): numero = models.CharField(max_length=255) depart = models.DateField() arrivee = models.DateField() origine = models.CharField(max_length=255) destination = models.CharField(max_length=255) modele = models.CharField(max_length=255) def __str__(self): return self.numero
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,345
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/migrations/0003_auto_20161011_1519.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-11 14:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hotels', '0002_hotel_description'), ] operations = [ migrations.AlterField( model_name='hotel', name='description', field=models.CharField(max_length=255, null=True), ), ]
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,346
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/admin.py
from django.contrib import admin # Register your models here. # Register your models here. #admin.site from hotels.models import Hotel,Chambre,Client,Reservation admin.site.register(Hotel) admin.site.register(Chambre) admin.site.register(Client) admin.site.register(Reservation)
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,347
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/views.py
from django.contrib.auth.decorators import login_required from django.shortcuts import render # Create your views here. from django.utils.decorators import method_decorator from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from hotels.models import Hotel,Reservation,Client def index(request): hotels = Hotel.objects.filter(etoiles__gt=2,description__icontains='ville').order_by('nom') hotels = Hotel.objects.order_by('nom') data = { 'hotels' : hotels, 'title': 'liste des hotels', } return render(request , 'index.html',data) class HotelList(ListView): model = Hotel class HotelCreate(CreateView): model = Hotel fields = ['nom','description','etoiles'] success_url = '/hotels' class HotelUpdate(UpdateView): model = Hotel fields = ['nom','description','etoiles'] success_url = '/hotels' class HotelDetail(DetailView): model = Hotel fields = ['nom','description','etoiles'] class HotelDelete(DeleteView): model = Hotel fields = ['nom','description','etoiles'] success_url = '/hotels' def reservations(request): reservations = Reservation.objects.all() data = { 'reservations' : reservations, 'title': 'liste des reservations', } return render(request , 'reservations.html',data) class ReservationList(ListView): model = Reservation class ReservationCreate(CreateView): model = Reservation fields = ['hotel','client','date_reservation'] success_url = '/reservations' class ReservationUpdate(UpdateView): model = Reservation fields = ['hotel','client','date_reservation'] success_url = '/reservations' class ReservationDetail(DetailView): model = Reservation fields = ['hotel','client','date_reservation'] class ReservationDelete(DeleteView): model = Reservation fields = ['hotel','client','date_reservation'] success_url = '/reservations'
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,348
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/migrations/0005_auto_20161011_1613.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-11 15:13 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hotels', '0004_hotel_etoiles'), ] operations = [ migrations.AddField( model_name='hotel', name='actif', field=models.BooleanField(default=True), ), migrations.AddField( model_name='hotel', name='date_creation', field=models.DateField(null=True), ), migrations.AddField( model_name='hotel', name='notes', field=models.DecimalField(decimal_places=1, max_digits=2, null=True), ), migrations.AddField( model_name='hotel', name='ville', field=models.CharField(max_length=255, null=True), ), ]
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,349
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/bookings/urls.py
"""bookings URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from django.contrib.auth import views from hotels import views as hv from flights import views as fv urlpatterns = [ url(r'^admin/', admin.site.urls), # url(r'^hotels$',hv.index), url(r'^hotels$', hv.HotelList.as_view(), name="hotels-list"), url(r'^hotels/(?P<pk>\d+)$', hv.HotelDetail.as_view(), name="hotel-detail"), url(r'^hotel/create$', hv.HotelCreate.as_view(), name="hotel-create"), url(r'^hotel/update/(?P<pk>\d+)$', hv.HotelUpdate.as_view(), name="hotel-update"), url(r'^hotel/delete/(?P<pk>\d+)$', hv.HotelDelete.as_view(), name="hotel-delete"), url(r'^vols$', fv.index), url(r'^reservations$', hv.ReservationList.as_view(), name="reservations-list"), url(r'^reservations/(?P<pk>\d+)$', hv.ReservationDetail.as_view(), name="reservation-detail"), url(r'^reservation/create$', hv.ReservationCreate.as_view(), name="reservation-create"), url(r'^reservation/update/(?P<pk>\d+)$', hv.ReservationUpdate.as_view(), name="reservation-update"), url(r'^reservation/delete/(?P<pk>\d+)$', hv.ReservationDelete.as_view(), name="reservation-delete"), url(r'^login/$', views.login,{'template_name': 'registration/login.html'}, name="login"), url(r'^logout/$', views.logout, {'template_name': 'registration/logged_out.html'},name="logout"), ]
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,350
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/migrations/0004_hotel_etoiles.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-11 14:34 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hotels', '0003_auto_20161011_1519'), ] operations = [ migrations.AddField( model_name='hotel', name='etoiles', field=models.PositiveIntegerField(default=4), ), ]
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,351
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/hotels/models.py
from django.db import models '''classe de gestion des hotes ''' class Hotel(models.Model): nom = models.CharField(max_length=255) description = models.TextField() etoiles = models.PositiveIntegerField(default=4) chambres = models.PositiveIntegerField(default=100) ville = models.CharField(max_length=255, null=True) note= models.DecimalField(decimal_places=1, max_digits=2, default=5) date_creation= models.DateField(null = True) actif = models.BooleanField(default=True) clients = models.ManyToManyField('Client',through='Reservation') def __str__(self): return self.nom ''' classe de gestion des chambres''' class Chambre(models.Model): numero = models.CharField(max_length=5) diponibilite = models.BooleanField(default=True) hotel = models.ForeignKey(Hotel) def __str__(self): return self.numero class Client(models.Model): nom = models.CharField(max_length=255) def __str__(self): return self.nom class Reservation(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE) hotel = models.ForeignKey(Hotel,on_delete=models.CASCADE) date_reservation = models.DateField()
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,352
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/flights/views.py
from django.shortcuts import render # Create your views here. from flights.models import Vol def index(request): vols = Vol.objects().all data = { 'vols': vols, 'title':'liste des vols' } return render(request , 'vols.html',data)
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,353
Raouf-Hammami-27/Bookings-Django
refs/heads/master
/flights/admin.py
from django.contrib import admin from flights.models import Vol admin.site.register(Vol)
{"/hotels/admin.py": ["/hotels/models.py"], "/hotels/views.py": ["/hotels/models.py"], "/flights/views.py": ["/flights/models.py"], "/flights/admin.py": ["/flights/models.py"]}
37,354
tsprouse/NS18a-abinit
refs/heads/master
/tbme.py
fspnum=open('nucleispnumbers.dat','r') ftbme=open('nucleitwobody.dat','r') w=0.0 # oscillator freq. (don't know value, so I can't do this yet!) m=0.0 # mass of nucleon (unknown units, so I can't do this yet!) import kinematic import numpy as np from util import hat spnum = [] invspnum = dict() i=0 for l in fspnum: tup= (int(l.split()[1]),int(l.split()[2]),int(l.split()[3]),int(l.split()[4]),int(l.split()[5]), 2*int(l.split()[1])+int(l.split()[2])) spnum.append(tup) invspnum[tup]=i i=i+1 # for key in invspnum: # print invspnum[key],key # define a basis for a given N=N1+N2, for Mj1+Mj2=0 class deuteron: tbme=None tbhash=list() dim=0 def __init__(self, nm): for s1 in spnum: for s2 in spnum: log=True # boolean algebra var. log = log and (s1[3]+s2[3]==0) # Check that Mj=0 (fix direction) log = log and (s1[4]+s2[4]==0) # Check that Mt=0 (fix to deuteron nucleus) log = log and (spnum.index(s1)<=spnum.index(s2)) # Fix phase of antisymmetrized states log = log and (s1[5]+s2[5]<=nm) # Check N1+N2<=Nmax log = log and (s1[1]+s2[1])%2 == nm%2 # check that g=Nmax%2 if log: self.tbhash.append(tuple([spnum.index(s1),spnum.index(s2)])) # If all above are true, add to 2-body basis print "deuteron 2-b basis initialized to space of dimension: ",len(self.tbhash), ' for N2,max= ',nm # Print diagnostic info self.dim = len(self.tbhash) self.tbme = [[0.0 for x in xrange(self.dim)] for y in xrange(self.dim)] # allocate Hamiltonian for l in ftbme: a,b,c,d,en = l.split()[0:5] b1 = (int(a)-1, int(b)-1) # bra b2 = (int(c)-1, int(d)-1) # ket if b1 in self.tbhash and b2 in self.tbhash: tbme = float(en) self.tbme[self.tbhash.index(b1)][self.tbhash.index(b2)] = tbme ftbme.close() for x in xrange(self.dim): for y in xrange(self.dim): self.tbme[x][y]+=self.kin2bme(x,y) def kin2bme(self,x,y): x1=spnum[self.tbhash[x][0]] x2=spnum[self.tbhash[x][1]] y1=spnum[self.tbhash[y][0]] y2=spnum[self.tbhash[y][1]] res = 0.0 if x1==y1 and y2[1:5]==x2[1:5]: res+=1/hat(x2[1])*kinematic.tkrme(x2[0],x2[1],y2[0],y2[1]) if x2==y2 and y1[1:5]==x1[1:5]: res+=1/hat(x1[1])*kinematic.tkrme(x1[0],x1[1],y1[0],y1[1]) return res def solve(self): np.savetxt('matrix.txt', self.tbme) print(self.tbhash) eigval,eigvec = np.linalg.eigh(np.array(self.tbme)) for e in eigval: print e b=deuteron(2) b.solve()
{"/kinematic.py": ["/util.py"]}
37,355
tsprouse/NS18a-abinit
refs/heads/master
/util.py
def phase(l): return (-1)**(l) def hat(j): return (2.*j+1.)**0.5
{"/kinematic.py": ["/util.py"]}
37,356
tsprouse/NS18a-abinit
refs/heads/master
/abinit.py
fspnum='nucleispnumbers.dat' ftbme='nucleitwobody.dat' import kinematic import numpy as np from util import hat import copy class sp_state: def __init__(self): self.n = 0 self.N = 0 self.m = 0 self.j = 0 self.l = 0 self.tz = 0 def read(self,l): self.n = int(l.split()[1]) self.l = int(l.split()[2]) self.j = float(l.split()[3])/2.0 self.m = float(l.split()[4])/2.0 self.tz = float(l.split()[5])/2.0 self.N = 2*self.n+self.l class spnum: def __init__(self): self.spec = list() f = open(fspnum) for l in f: b=sp_state() b.read(l) self.spec.append(b) f.close() class nb_state: def __init__(self): self.null = False self.phase = 1 self.spec = list() def a(self,ind): if len(self.spec) == 0 or self.null: self.null = True elif ind in self.spec: i = self.spec.index(ind) self.phase = self.phase*((-1)**(i)) self.spec.remove(ind) else: self.null = True def adag(self,ind): if len(self.spec)== 0 and not self.null: self.spec.append(ind) elif ind in self.spec or self.null: self.null = True else: for i in xrange(len(self.spec)): if ind < self.spec[i]: self.spec.insert(i,ind) self.phase = self.phase*((-1)**i) return self.spec.append(ind) self.phase = self.phase*((-1)**(len(self.spec)-1)) def fix(self): self.null = False self.phase = 1 self.save = tuple(self.spec) self.rep = set(self.save) def reset(self): self.null = False self.phase = 1 self.spec = list(self.save) def ip(bra,ket): if bra.null or ket.null: return 0.0 elif bra.spec == ket.spec: return bra.phase*ket.phase else: return 0.0 class nb_basis: def __init__(self, sp): self.spec = list() self.sp = sp def build(self,z,a,nmax,m,p): print "Building basis" self.z = z self.a = a self.nmax = nmax self.m = m self.p = p g = gen(len(self.sp.spec),a) pf = True self.rep = set() while pf: ts = (frozenset(g.vec)) if len(ts) == self.a: self.rep.add(ts) pf = g.nxt() for r in self.rep: if self.check(r): nb = nb_state() for x in r: nb.adag(x) nb.fix() self.spec.append(nb) print len(self.spec) print len(self.rep) def check(self,tup): m = 0 z = 0 n = 0 for x in tup: m+=self.sp.spec[x].m n+=self.sp.spec[x].N if self.sp.spec[x].tz<0: z+=1 if m==self.m and n <= self.nmax and z==self.z and n%2==self.p: # for x in tup: print self.sp.spec[x].n, self.sp.spec[x].l,self.sp.spec[x].j, self.sp.spec[x].m, self.sp.spec[x].N # print '' return True else: return False class gen: def __init__(self,splen,a): self.splen = splen self.a = a self.vec = [0 for x in xrange(a)] def nxt(self): for x in xrange(self.a): if self.vec[x] < self.splen-1: self.vec[x] = self.vec[x]+1 # print self.vec return True else: self.vec[x] = 0 return False class tbint: def __init__(self): print "Reading interaction table" self.spec=dict() f = open(ftbme) for l in f: bra1 = int(l.split()[0])-1 bra2 = int(l.split()[1])-1 ket1 = int(l.split()[2])-1 ket2 = int(l.split()[3])-1 val = float(l.split()[4]) self.spec[(bra1,bra2,ket1,ket2)] = val class hamiltonian: def __init__(self,bas,v): self.basis = bas self.v = v self.spec = [[0.0 for x in xrange(len(self.basis.spec))] for x in xrange(len(self.basis.spec))] print "Adding interaction terms" for xx in xrange(len(self.basis.spec)): for yy in xrange(len(self.basis.spec)): x = copy.deepcopy(self.basis.spec[xx]) y = copy.deepcopy(self.basis.spec[yy]) diff = x.rep.difference(y.rep) if len(diff)<=2: for a in x.rep: for b in x.rep: for g in y.rep: for d in y.rep: if (a,b,g,d) in self.v.spec: y.a(g) y.a(d) y.adag(b) y.adag(a) self.spec[xx][yy]+=ip(y,x)*0.25*self.v.spec[(a,b,g,d)] y.reset() x.reset() print "Adding Kinetic terms" for xx in xrange(len(self.basis.spec)): for yy in xrange(len(self.basis.spec)): x = copy.deepcopy(self.basis.spec[xx]) y = copy.deepcopy(self.basis.spec[yy]) diff = x.rep.difference(y.rep) if len(diff)<=1: for a in x.rep: for b in y.rep: y.a(b) y.adag(a) self.spec[xx][yy]+=ip(y,x)*KinMatEl(self.basis.sp.spec[a],self.basis.sp.spec[b]) y.reset() x.reset() np.savetxt('matrix_abinit.txt', self.spec) print "Solving" self.eigval,self.eigvec = np.linalg.eigh(np.array(self.spec)) print "GS binding energy of nucleus Z=%d A=%d: %f MeV" % (self.basis.z,self.basis.a,self.eigval[0]) for x in self.eigval[1:]: if x < 0: print "Excited state at energy %f MeV" % (x) # for i in xrange(len(self.basis.spec)): # print self.spec[i][i], self.basis.spec[i] def KinMatEl(bra,ket): if bra.j==ket.j and bra.m==ket.m and bra.tz==ket.tz and bra.l == ket.l: return 1./hat(ket.j)*kinematic.tkrme(bra.n,bra.l,ket.n,ket.l) else: return 0.0 this = spnum() that = nb_basis(this) that.build(2,4,3,0,0) these = tbint() those = hamiltonian(that,these) this = spnum() that = nb_basis(this) that.build(1,2,3,0,0) these = tbint() those = hamiltonian(that,these) #end
{"/kinematic.py": ["/util.py"]}
37,357
tsprouse/NS18a-abinit
refs/heads/master
/kinematic.py
from util import phase, hat def rme_bdag(n1, l1, n2, l2): if abs(l2-l1) != 1: return 0. N1 = 2*n1+l1 N2 = 2*n2+l2 if N1==N2+1 and l1==l2+1: res = ((l2+1.)*(N2+l2+3.))**0.5 elif N1==N2+1 and l1==l2-1: res = ((l2*(N2-l2+2.)))**0.5 else: res = 0.0 return res def rme_b(n1,l1,n2,l2): if abs(l2-l1) != 1: return 0. N1 = 2*n1+l1 N2 = 2*n2+l2 if N1==N2-1 and l1==l2+1: res = ((l2+1.)*(N2-l2))**0.5 elif N1==N2-1 and l1==l2-1: res = ((l2*(N2+l2+1.)))**0.5 else: res = 0.0 return res def tkrme(n1,l1,n2,l2): res = -2.5 / hat(l1) bdbd = 0. bbd = 0. bb = 0. bdb = 0. # QMN = n l j mj tz # Only loop over n and l if l1 != l2: return 0. for dn in [-2, -1, 0, 1, 2]: n = n2 + dn if n < 0: continue for dl in [-1, 1]: l = l2 + dl if l < 0: continue #bdbd += phase(l-l1)*rme_bdag(n1,l1,n,l)*rme_bdag(n,l,n2,l2) bdbd += rme_bdag(n1,l1,n,l)*rme_bdag(n,l,n2,l2) bbd += rme_b(n1,l1,n,l)*rme_bdag(n,l,n2,l2) bb += rme_b(n1,l1,n,l)*rme_b(n,l,n2,l2) bdb += rme_bdag(n1,l1,n,l)*rme_b(n,l,n2,l2) res = res*(bdbd + bb - bbd - bdb) return res
{"/kinematic.py": ["/util.py"]}
37,358
raunaqjain/facerecog
refs/heads/master
/dataset_validation.py
import torchvision.datasets as dset import torchvision.transforms as transforms from torch.utils.data import DataLoader import torch import torchvision from utils import imshow from dataset_generator import SiameseNetworkDataset, Config def main(): folder_dataset = dset.ImageFolder(root=Config.training_dir) siamese_dataset = SiameseNetworkDataset(imageFolderDataset=folder_dataset, transform=transforms.Compose([transforms.Resize((100,100)), transforms.ToTensor() ]) ,should_invert=False) vis_dataloader = DataLoader(siamese_dataset, shuffle=True, num_workers=8, batch_size=8) dataiter = iter(vis_dataloader) example_batch = next(dataiter) concatenated = torch.cat((example_batch[0],example_batch[1]),0) print(example_batch[2].numpy()) imshow(torchvision.utils.make_grid(concatenated)) print ("Checking of visualization done.") if __name__ == "__main__": main()
{"/dataset_validation.py": ["/utils.py", "/dataset_generator.py"], "/testing.py": ["/dataset_generator.py", "/utils.py"], "/training.py": ["/utils.py", "/dataset_generator.py"]}
37,359
raunaqjain/facerecog
refs/heads/master
/testing.py
from siamese_network import SiameseNetwork, ContrastiveLoss from dataset_generator import SiameseNetworkDataset, Config from torch.autograd import Variable from utils import imshow, show_plot, save_checkpoint from torchvision import models import torch import torchvision import torchvision.datasets as dset import torchvision.transforms as transforms from torch.utils.data import DataLoader import numpy as np import torch.nn.functional as F import argparse from PIL import Image import PIL.ImageOps import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt def main(): parser = argparse.ArgumentParser() parser.add_argument('-img', type=str, default='test.jpg') # parser.add_argument('-ques', type=str, default='What vechile is in the picture?') args = parser.parse_args() img = args.img folder_dataset_test = dset.ImageFolder(root=Config.testing_dir) siamese_dataset = SiameseNetworkDataset(imageFolderDataset=folder_dataset_test, transform=transforms.Compose([transforms.Resize((100,100)), transforms.ToTensor() ]) ,should_invert=False) img = Image.open(img) img = img.convert("L") transform=transforms.Compose([transforms.Resize((100,100)), transforms.ToTensor() ]) img = transform(img) # Add a dimension to image to make padding possible. img = img[None,:,:,:] test_dataloader = DataLoader(siamese_dataset,num_workers=3,batch_size=1) dataiter = iter(test_dataloader) net = SiameseNetwork() net.load_state_dict(torch.load("trained_weights.pt")) for i in range(4): _,x1,label2 = next(dataiter) concatenated = torch.cat((img,x1),0) output1,output2 = net(Variable(img),Variable(x1)) euclidean_distance = F.pairwise_distance(output1, output2) imshow(torchvision.utils.make_grid(concatenated),'Dissimilarity: \ {:.2f}'.format(euclidean_distance.data.numpy()[0][0])) if __name__ == "__main__": main()
{"/dataset_validation.py": ["/utils.py", "/dataset_generator.py"], "/testing.py": ["/dataset_generator.py", "/utils.py"], "/training.py": ["/utils.py", "/dataset_generator.py"]}
37,360
raunaqjain/facerecog
refs/heads/master
/dataset_generator.py
from torch.utils.data import Dataset from PIL import Image import PIL.ImageOps import random import numpy as np import torch import torchvision.transforms as transforms class Config(): training_dir = "./data/faces/training/" testing_dir = "./data/faces/testing/" train_batch_size = 64 train_number_epochs = 100 class SiameseNetworkDataset(Dataset): def __init__(self,imageFolderDataset,transform=None,should_invert=True): self.imageFolderDataset = imageFolderDataset self.transform = transform self.should_invert = should_invert def __getitem__(self,index): img0_tuple = random.choice(self.imageFolderDataset.imgs) #we need to make sure approx 50% of images are in the same class should_get_same_class = random.randint(0,1) if should_get_same_class: while True: #keep looping till the same class image is found img1_tuple = random.choice(self.imageFolderDataset.imgs) if img0_tuple[1]==img1_tuple[1]: break else: img1_tuple = random.choice(self.imageFolderDataset.imgs) img0 = Image.open(img0_tuple[0]) img1 = Image.open(img1_tuple[0]) img0 = img0.convert("L") img1 = img1.convert("L") if self.should_invert: img0 = PIL.ImageOps.invert(img0) img1 = PIL.ImageOps.invert(img1) if self.transform is not None: img0 = self.transform(img0) img1 = self.transform(img1) return img0, img1 , torch.from_numpy(np.array([int(img1_tuple[1]!=img0_tuple[1])],dtype=np.float32)) def __len__(self): return len(self.imageFolderDataset.imgs) class Triplet_dataset(Dataset): def __init__(self, imageFolderDataset, transform=None, should_invert=True): self.imageFolderDataset = imageFolderDataset self.transform = transform self.should_invert = should_invert def __getitem__(self, index): anchor_tuple = random.choice(self.imageFolderDataset.imgs) while True: positive_tuple = random.choice(self.imageFolderDataset.imgs) if positive_tuple[1] == anchor_tuple[1]: break while True: negative_tuple = random.choice(self.imageFolderDataset.imgs) if negative_tuple[1] != anchor_tuple[1]: break anchor = Image.open(anchor_tuple[0]) positive = Image.open(positive_tuple[0]) negative = Image.open(negative_tuple[0]) anchor = anchor.convert("L") positive = positive.convert("L") negative = negative.convert("L") if self.should_invert: anchor = PIL.ImageOps.invert(anchor) positive = PIL.ImageOps.invert(positive) negative = PIL.ImageOps.invert(negative) if self.transform is not None: anchor = self.transform(anchor) positive = self.transform(positive) neagtive = self.transform(neagtive) return anchor, positive, negative
{"/dataset_validation.py": ["/utils.py", "/dataset_generator.py"], "/testing.py": ["/dataset_generator.py", "/utils.py"], "/training.py": ["/utils.py", "/dataset_generator.py"]}
37,361
raunaqjain/facerecog
refs/heads/master
/training.py
import torchvision.datasets as dset import torchvision.transforms as transforms from torch.utils.data import DataLoader import numpy as np from torch.autograd import Variable from torch import optim import torch from siamese_network import SiameseNetwork, ContrastiveLoss from utils import imshow, show_plot, save_checkpoint from dataset_generator import SiameseNetworkDataset, Config def main(): # test = Image.open("./data/1.pgm") # test.show() # print (test) print ("Training starts...") folder_dataset = dset.ImageFolder(root=Config.training_dir) siamese_dataset = Contrastive_Dataset(imageFolderDataset=folder_dataset, transform=transforms.Compose([transforms.Resize((100,100)), transforms.ToTensor() ]) ,should_invert=False) train_dataloader = DataLoader(siamese_dataset, shuffle=True, num_workers=8, batch_size=Config.train_batch_size) net = SiameseNetwork() criterion = ContrastiveLoss() optimizer = optim.Adam(net.parameters(),lr = 0.0005 ) counter = [] loss_history = [] iteration_number= 0 for epoch in range(0,Config.train_number_epochs): for i, data in enumerate(train_dataloader,0): img0, img1 , label = data img0, img1 , label = Variable(img0), Variable(img1) , Variable(label) output1,output2 = net(img0,img1) optimizer.zero_grad() loss_contrastive = criterion(output1,output2,label) loss_contrastive.backward() optimizer.step() if i %10 == 0 : print("Epoch number {}\n Current loss {}\n".format(epoch,loss_contrastive.data[0])) iteration_number +=10 counter.append(iteration_number) loss_history.append(loss_contrastive.data[0]) torch.save(net.state_dict(), "trained_weights.pt") # save_checkpoint({ # 'epoch': epoch + 1, # }) show_plot(counter,loss_history) if __name__ == "__main__": main()
{"/dataset_validation.py": ["/utils.py", "/dataset_generator.py"], "/testing.py": ["/dataset_generator.py", "/utils.py"], "/training.py": ["/utils.py", "/dataset_generator.py"]}
37,362
raunaqjain/facerecog
refs/heads/master
/utils.py
import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt import numpy as np import torch def imshow(img,text=None,should_save=False): npimg = img.numpy() plt.axis("off") if text: plt.text(75, 8, text, style='italic',fontweight='bold', bbox={'facecolor':'white', 'alpha':0.8, 'pad':10}) plt.imshow(np.transpose(npimg, (1, 2, 0))) plt.show() def show_plot(iteration,loss): plt.plot(iteration,loss) plt.show() def save_checkpoint(state, is_best=True, filename='./weights/checkpoint.pth.tar'): """Save checkpoint if a new best is achieved""" if is_best: print ("=> Saving a new best") torch.save(state, filename) # save checkpoint else: print ("=> Validation Accuracy did not improve")
{"/dataset_validation.py": ["/utils.py", "/dataset_generator.py"], "/testing.py": ["/dataset_generator.py", "/utils.py"], "/training.py": ["/utils.py", "/dataset_generator.py"]}
37,366
score-p/scorep_cli_score
refs/heads/master
/setup.py
import re import setuptools import subprocess import sys if sys.version_info < (3, 5): sys.exit('Python 3.4 or older is not supported.') def remove_flag3(x): return x[3:] ldflags = subprocess.check_output(["scorep-config", "--ldflags"]).decode('utf-8') cflags = subprocess.check_output(["scorep-config", "--cflags"]).decode('utf-8') ldflags = " " + ldflags cflags = " " + cflags scorep_include_dir = re.findall(" -I[/+-@.\w]*", cflags) scorep_library_dir = re.findall(" -L[/+-@.\w]*", ldflags) scorep_include_dir = list(map(remove_flag3, scorep_include_dir))[0] scorep_library_dir = list(map(remove_flag3, scorep_library_dir))[0] setuptools.setup(name='scorep-cli-score', version='0.1', author='Marcel Achtert', author_email='marcel.achtert@tu-dresden.de', description='A Score-P-score based filter creation tool', url='https://github.com/score-p/scorep-score-gui', packages=['scorep_cli_score'], python_requires='~=3.5', scripts=['scorep_cli_score/scorep-cli-score'], classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', 'License :: OSI Approved :: BSD License 2.0', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ], ext_modules=[ setuptools.Extension('bind', sources=['scorep_cli_score/bind.cpp'], include_dirs=[scorep_include_dir, '{}/cubelib'.format(scorep_include_dir)], library_dirs=[scorep_library_dir], libraries=['z', 'cube4', 'scorep_estimator'], language='c++'), setuptools.Extension('scorep_profile', sources=['scorep_cli_score/scorep_profile.cpp'], include_dirs=[scorep_include_dir, '{}/cubelib'.format(scorep_include_dir)], library_dirs=[scorep_library_dir], libraries=['z', 'cube4', 'scorep_estimator'], extra_compile_args=['-std=c++14'], language='c++'), ])
{"/scorep_cli_score/util.py": ["/scorep_cli_score/model.py"]}
37,367
score-p/scorep_cli_score
refs/heads/master
/scorep_cli_score/util.py
from scorep_cli_score.model import RegionLoad class FilterFile: """Loads filter from file and saves new filter file. """ def __init__(self, name): self.name = name self.content = '' self.file = None self.file_begin = 'SCOREP_REGION_NAMES_BEGIN' self.file_end = 'SCOREP_REGION_NAMES_END' self.include = 'INCLUDE' self.exclude = 'EXCLUDE' self.load_regions = [] self.is_excl = False self.is_mangled = True self.exclude_marker = False self.include_marker = False self.regions = [] self.save_separate = False self.save_exclude_only = True def load(self): """open filter file and save regions rules""" with open(self.name) as self.file: content = [] sep = '#' for line in self.file: if line[0] == sep: continue line = line.strip(' \t\n\r') line = line.split(sep, 1)[0] tmp = line.split(' ') for t in tmp: if t: content.append(t) for param in content: if param == self.file_end: break elif param == self.file_begin: continue elif param == 'INCLUDE': self.is_excl = False self.is_mangled = False elif param == 'EXCLUDE': self.is_excl = True self.is_mangled = False elif param == 'MANGLED': self.is_mangled = True else: region = RegionLoad(self.is_excl) if self.is_mangled: region.mangled_name = param else: region.demangled_name = param self.load_regions.append(region) self.file.closed def save(self): """create filter file with regions rules""" self.file = open(self.name, 'w') self.file.write(self.file_begin) self.file.write('\n') if self.save_separate: exclude_list = [i for i in self.regions if i.exclude] include_list = [i for i in self.regions if not i.exclude] for region in exclude_list: if self.exclude_marker: self.file.write('{}'.format(region.mangled_name).rjust(8 + len(region.mangled_name))) else: self.file.write('EXCLUDE {}'.format(region.mangled_name)) self.exclude_marker = True self.file.write('\n') if not self.save_exclude_only: for region in include_list: if self.include_marker: self.file.write('{}'.format(region.mangled_name).rjust(8 + len(region.mangled_name))) else: self.file.write('INCLUDE {}'.format(region.mangled_name)) self.include_marker = True self.file.write('\n') else: for region in self.regions: if region.filtered or region.exclude: if self.exclude_marker: self.file.write('{}'.format(region.mangled_name).rjust( 8 + len(region.mangled_name))) else: self.file.write('EXCLUDE {}'.format(region.mangled_name)) self.exclude_marker = True self.include_marker = False self.file.write('\n') elif not self.save_exclude_only: if self.include_marker: self.file.write('{}'.format(region.mangled_name).rjust( 8 + len(region.mangled_name))) else: self.file.write('INCLUDE {}'.format(region.mangled_name)) self.include_marker = True self.exclude_marker = False self.file.write('\n') self.file.write(self.file_end) self.file.write('\n') self.file.close() def quicksort(region_list, attr): left = [] center = [] right = [] if len(region_list) <= 1: return region_list else: pivot = getattr(region_list[len(region_list) // 2], attr) for i in region_list: if getattr(i, attr) > pivot: right.append(i) elif getattr(i, attr) < pivot: left.append(i) else: center.append(i) return quicksort(left, attr) + center + quicksort(right, attr)
{"/scorep_cli_score/util.py": ["/scorep_cli_score/model.py"]}
37,368
score-p/scorep_cli_score
refs/heads/master
/scorep_cli_score/model.py
import operator class Region: def __init__(self, type, processes, demangled_name, mangled_name): self.type = type self.processes = processes self.demangled_name = demangled_name self.mangled_name = mangled_name self.visits = 0 self.hits = 0 self.time_excl = 0 self.time_incl = 0 self.filtered = False self.exclude = False def add(self, visits, hits, time_incl, time_excl, process): self.visits += visits self.hits += hits self.time_excl += time_excl self.time_incl += time_incl class RegionLoad: def __init__(self, exclude): self.exclude = exclude self.demangled_name = '' self.mangled_name = '' class FilterBy: def __init__(self): self.attr = '' self.operator = '' self.value = -1 self.active = False self.operators = {'<': operator.lt, '<=': operator.le, '>': operator.gt, '>=': operator.ge, '=': operator.eq, '!=': operator.ne, 'lt': operator.lt, 'le': operator.le, 'gt': operator.gt, 'ge': operator.ge, 'eq': operator.eq, 'ne': operator.ne, } def set(self, operator, attr, value): self.operator = operator self.attr = attr self.value = value self.active = True def get(self): return self.operators[self.operator], self.attr, self.value def reset(self): self.operator = '' self.attr = '' self.value = -1 self.active = False
{"/scorep_cli_score/util.py": ["/scorep_cli_score/model.py"]}
37,369
score-p/scorep_cli_score
refs/heads/master
/scorep_cli_score/__init__.py
name = "scorep_cli_score"
{"/scorep_cli_score/util.py": ["/scorep_cli_score/model.py"]}
37,387
sereneliu/AoC-2019
refs/heads/master
/day2.py
import intcode puzzle_input = open('day2.txt', 'r').read().split(',') # Part 1 def convert_to_int(string_input): return [int(n) for n in string_input] def restore(gravity_assist, noun, verb): gravity_assist[1] = noun gravity_assist[2] = verb return gravity_assist # print intcode(restore(puzzle_input, 12, 2)) # Your puzzle answer was 4930687. # Part 2 def find_inputs(gravity_assist, output): initial_program = gravity_assist test_program = convert_to_int(gravity_assist) for n in range(100): for v in range(100): if intcode.intcode(restore(test_program, n, v), 0) == output: return 100 * n + v else: test_program = convert_to_int(gravity_assist) print find_inputs(puzzle_input, 19690720) # Your puzzle answer was 5335.
{"/test_intcode.py": ["/intcode.py"]}
37,388
sereneliu/AoC-2019
refs/heads/master
/day4.py
puzzle_input = [372304, 847060] def check_not_decreasing(number): str_number = str(number) for i in range(5): if not str_number[i] <= str_number[i + 1]: return False return True def check_adjacent(number, check_larger_group): valid_adjacent = False str_number = str(number) for i in range(5): if not valid_adjacent: if str_number[i] == str_number[i + 1]: valid_adjacent = True if check_larger_group and valid_adjacent: if i != 0: if str_number[i] == str_number[i - 1]: valid_adjacent = False if i < 4: if str_number[i] == str_number[i + 2]: valid_adjacent = False return valid_adjacent def check_valid_pw(number, check_larger_group): return check_not_decreasing(number) and check_adjacent(number, check_larger_group) def find_valid_pws(start, end, check_larger_group): valid_pws = 0 for number in range(start, end): if check_valid_pw(number, check_larger_group) == True: valid_pws += 1 return valid_pws # Part 1 # Key Facts: # It is a six-digit number. # The value is within the range given in your puzzle input. # Two adjacent digits are the same (like 22 in 122345). # Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679). print check_valid_pw(111111, False) # True print check_valid_pw(223450, False) # False print check_valid_pw(123789, False) # False print find_valid_pws(puzzle_input[0], puzzle_input[1], False) # Your puzzle answer was 475. # Part 2 # An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits. print check_valid_pw(112233, True) # True print check_valid_pw(123444, True) # False print check_valid_pw(111122, True) # True print find_valid_pws(puzzle_input[0], puzzle_input[1], True) # Your puzzle answer was 297.
{"/test_intcode.py": ["/intcode.py"]}
37,389
sereneliu/AoC-2019
refs/heads/master
/day12.py
puzzle_input = open('day12.txt', 'r').read().split('\n') def apply_gravity(pos1, pos2, vel1, vel2): if pos1 > pos2: vel1 -= 1 elif pos1 < pos2: vel1 += 1 return vel1 def update_velocity(moon1, moon2): for i in range(3): moon1.vel[i] = apply_gravity(moon1.pos[i], moon2.pos[i], moon1.vel[i], moon2.vel[i]) return moon1, moon2 def update_position(moon): for i in range(3): moon.pos[i] += moon.vel[i] return moon def update_all_velocities(moons): for moon1 in moons: for moon2 in moons: if moon1 != moon2: moon1, moon2 = update_velocity(moon1, moon2) return moons def update_all_positions(moons): for moon in moons: moon = update_position(moon) return moons def take_time_steps(moons, steps): for i in range(steps): update_all_velocities(moons) update_all_positions(moons) return moons class Moon: def __init__(self, x, y, z): self.pos = [x, y, z] self.vel = [0, 0, 0] def create_moon(position): x = int(position[position.index('x=') + 2:position.index('y=') - 2]) y = int(position[position.index('y=') + 2:position.index('z=') - 2]) z = int(position[position.index('z=') + 2:position.index('>')]) return Moon(x, y, z) def create_moons(positions): moon1 = create_moon(positions[0]) moon2 = create_moon(positions[1]) moon3 = create_moon(positions[2]) moon4 = create_moon(positions[3]) return moon1, moon2, moon3, moon4 moons = create_moons(puzzle_input) def calc_energy(x, y, z): return abs(x) + abs(y) + abs(z) def calc_total_energy(pot, kin): return pot * kin def calc_sum(moons): total = 0 for moon in moons: total += calc_total_energy(calc_energy(moon.pos[0], moon.pos[1], moon.pos[2]), calc_energy(moon.vel[0], moon.vel[1], moon.vel[2])) return total print calc_sum(take_time_steps(moons, 1000))
{"/test_intcode.py": ["/intcode.py"]}
37,390
sereneliu/AoC-2019
refs/heads/master
/intcode.py
def intcode(program, i): o = [] p = 0 opcode = program[p] while opcode != 99: if opcode == 1: program[program[p + 3]] = program[program[p + 1]] + program[program[p + 2]] elif opcode == 2: program[program[p + 3]] = program[program[p + 1]] * program[program[p + 2]] elif opcode == 3: program[program[p + 1]] = i elif opcode == 4: o.append(program[program[p + 1]]) p += 4 opcode = program[p] return program[0]
{"/test_intcode.py": ["/intcode.py"]}
37,391
sereneliu/AoC-2019
refs/heads/master
/day1.py
puzzle_input = open('day1.txt', 'r').read().split('\n') # Part 1 def find_fuel_required(mass): return mass//3 - 2 def find_total_fuel(modules): total = 0 for module in modules: total += find_fuel_required(int(module)) return total # print find_total_fuel(puzzle_input) # Answer: 3212842 # Part 2 def find_fuel_for_fuel(fuel): total = 0 while fuel > 0: fuel = find_fuel_required(fuel) if fuel > 0: total += fuel return total def find_total_fuel2(modules): total = 0 for module in modules: total += find_fuel_for_fuel(int(module)) return total print find_total_fuel2(puzzle_input) # Answer: 4816402
{"/test_intcode.py": ["/intcode.py"]}
37,392
sereneliu/AoC-2019
refs/heads/master
/test_intcode.py
import unittest import intcode example_input = [1,9,10,3,2,3,11,0,99,30,40,50] class IntcodeTestCase(unittest.TestCase): def test_intcode1(self): result = intcode.intcode(example_input, 0) self.assertEqual(result, 3500) def test_intcode2(self): result = intcode.intcode([1,0,0,0,99], 0) self.assertEqual(result, 2) def test_intcode3(self): result = intcode.intcode([2,3,0,3,99], 0) self.assertEqual(result, 2) def test_intcode4(self): result = intcode.intcode([2,4,4,5,99,0], 0) self.assertEqual(result, 2) def test_intcode5(self): result = intcode.intcode([1,1,1,4,99,5,6,0,99], 0) self.assertEqual(result, 30) if __name__ == '__main__': unittest.main()
{"/test_intcode.py": ["/intcode.py"]}
37,393
sereneliu/AoC-2019
refs/heads/master
/day3.py
import sys puzzle_input = open('day3.txt', 'r').read().split('\n') # Part 1 example_input = ''' R8,U5,L5,D3 U7,R6,D4,L4 ''' example_input = example_input.strip().splitlines() directions = { 'R': [1, 0], 'U': [0, 1], 'L': [-1, 0], 'D': [0, -1] } def find_segment_pts(path, x, y, steps): segment = {} direction = path[0] distance = int(path[1:]) for i in range(distance): x += directions[direction][0] y += directions[direction][1] steps += 1 if (x, y) not in segment.keys(): segment[(x, y)] = steps else: segment[(x, y)].append(steps) return segment, x, y, steps def store_all_pts(wire): x = 0 y = 0 steps = 0 points = {} wire = wire.split(',') for path in wire: points.update(find_segment_pts(path, x, y, steps)[0]) x = find_segment_pts(path, x, y, steps)[1] y = find_segment_pts(path, x, y, steps)[2] steps = find_segment_pts(path, x, y, steps)[3] return points def find_man_dist(point1, point2): return abs(point2[0] - point1[0]) + abs(point2[1] - point1[1]) # example_wire1 = store_all_pts(example_input[0]) # example_wire2 = store_all_pts(example_input[1]) puzzle_wire1 = store_all_pts(puzzle_input[0]) puzzle_wire2 = store_all_pts(puzzle_input[1]) def find_intersections(wire1, wire2): return set(wire1.keys()).intersection(set(wire2.keys())) # example_intersections = find_intersections(example_wire1, example_wire2) puzzle_intersections = find_intersections(puzzle_wire1, puzzle_wire2) def find_closest_intersection(intersections): man_dist = sys.maxint for intersection in intersections: man_dist = min(man_dist, find_man_dist((0, 0), intersection)) return man_dist # print find_closest_intersection(example_intersections) print find_closest_intersection(puzzle_intersections) # Your puzzle answer was 2427. # Part 2 def find_fewest_steps(intersections): fewest_steps = sys.maxint for intersection in intersections: steps = puzzle_wire1[intersection] + puzzle_wire2[intersection] fewest_steps = min(fewest_steps, steps) return fewest_steps print find_fewest_steps(puzzle_intersections) # Your puzzle answer was 27890.
{"/test_intcode.py": ["/intcode.py"]}
37,398
pet1330/flask-sieve
refs/heads/master
/flask_sieve/exceptions.py
from flask import jsonify class ValidationException(Exception): def __init__(self, errors): self.errors = errors def register_error_handler(app): def validations_error_handler(ex): return jsonify({ 'success': False, 'message': 'Validation error', 'errors': ex.errors }), 400 app.register_error_handler( ValidationException, validations_error_handler )
{"/flask_sieve/__init__.py": ["/flask_sieve/exceptions.py"]}
37,399
pet1330/flask-sieve
refs/heads/master
/flask_sieve/__init__.py
from .requests import JsonRequest, FormRequest from .validator import validate, Validator from .exceptions import ValidationException, register_error_handler class Sieve: def __init__(self, app): register_error_handler(app)
{"/flask_sieve/__init__.py": ["/flask_sieve/exceptions.py"]}
37,476
ettoreleandrotognoli/py-aquaponic
refs/heads/master
/src/iot/views/pid.py
from core.utils.urls import make_url from django import forms from django.shortcuts import get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from iot.models import PID urlpatterns = [] URL = make_url(urlpatterns) class SetValueForm(forms.Form): target = forms.FloatField() @URL('^pid/(?P<pk>\d+)/set/$', name='pid-set-target') def set_value_view(request, **kwargs): pid = get_object_or_404(PID, **kwargs) form = SetValueForm(request.POST) if not form.is_valid(): return redirect('iot:pid-list') pid.target = form.cleaned_data['target'] pid.save() return redirect('iot:pid-list') @URL('^pid/$', name='pid-list') def list_view(request): pid_list = PID.objects.all().select_related( 'input', 'output', ) return render(request, 'pid/list.html', locals())
{"/src/iot/actuators/parport.py": ["/src/iot/actuators/actuator.py"], "/src/iot/api/pid.py": ["/src/iot/api/serializers.py"], "/src/iot/models/control.py": ["/src/iot/models/io.py"], "/src/iot/models/trigger.py": ["/src/iot/models/io.py"], "/src/iot/api/__init__.py": ["/src/iot/api/actuator.py", "/src/iot/api/pid.py", "/src/iot/api/sensor.py"], "/src/iot/apps.py": ["/src/iot/models/__init__.py"], "/src/iot/actuators/mqtt.py": ["/src/iot/actuators/actuator.py"], "/src/iot/models/__init__.py": ["/src/iot/models/io.py", "/src/iot/models/mqtt.py", "/src/iot/models/control.py", "/src/iot/models/trigger.py", "/src/iot/models/geo.py", "/src/iot/models/unit.py"], "/src/iot/api/sensor.py": ["/src/iot/api/serializers.py"], "/src/iot/fusion/sampling.py": ["/src/iot/fusion/__init__.py"], "/src/iot/fusion/filter.py": ["/src/iot/fusion/__init__.py"], "/src/iot/api/actuator.py": ["/src/iot/api/serializers.py"], "/src/iot/actuators/firmata.py": ["/src/iot/actuators/actuator.py"], "/src/iot/fusion/thermistor.py": ["/src/iot/fusion/electronic.py", "/src/iot/fusion/__init__.py"], "/src/iot/views/__init__.py": ["/src/iot/views/actuator.py", "/src/iot/views/dashboard.py", "/src/iot/views/pid.py", "/src/iot/views/sensor.py"], "/src/iot/actuators/__init__.py": ["/src/iot/actuators/actuator.py"], "/src/iot/fusion/ldr.py": ["/src/iot/fusion/__init__.py"]}
37,477
ettoreleandrotognoli/py-aquaponic
refs/heads/master
/src/iot/tests/test_sensor.py
import random from django.test import TestCase from django.contrib.auth import get_user_model from django.test import Client from django.urls import reverse from model_mommy import mommy from iot.models import Sensor, Position, MeasureUnit class TestSensor(TestCase): client = None def setUp(self): self.client = Client() self.client.force_login(get_user_model().objects.get_or_create(username='testuser')[0]) def test_put_single_data(self): max_value = 50 min_value = -50 position = mommy.make(Position) celsius = MeasureUnit.objects.select_related('magnitude').get(name='celsius') sensor = mommy.make( Sensor, position=position, measure_unit=celsius, magnitude=celsius.magnitude ) result = self.client.post( reverse('iot-api:sensor-data', kwargs=dict(pk=sensor.pk)), data={'value': random.uniform(min_value, max_value)} ) self.assertEqual(201, result.status_code)
{"/src/iot/actuators/parport.py": ["/src/iot/actuators/actuator.py"], "/src/iot/api/pid.py": ["/src/iot/api/serializers.py"], "/src/iot/models/control.py": ["/src/iot/models/io.py"], "/src/iot/models/trigger.py": ["/src/iot/models/io.py"], "/src/iot/api/__init__.py": ["/src/iot/api/actuator.py", "/src/iot/api/pid.py", "/src/iot/api/sensor.py"], "/src/iot/apps.py": ["/src/iot/models/__init__.py"], "/src/iot/actuators/mqtt.py": ["/src/iot/actuators/actuator.py"], "/src/iot/models/__init__.py": ["/src/iot/models/io.py", "/src/iot/models/mqtt.py", "/src/iot/models/control.py", "/src/iot/models/trigger.py", "/src/iot/models/geo.py", "/src/iot/models/unit.py"], "/src/iot/api/sensor.py": ["/src/iot/api/serializers.py"], "/src/iot/fusion/sampling.py": ["/src/iot/fusion/__init__.py"], "/src/iot/fusion/filter.py": ["/src/iot/fusion/__init__.py"], "/src/iot/api/actuator.py": ["/src/iot/api/serializers.py"], "/src/iot/actuators/firmata.py": ["/src/iot/actuators/actuator.py"], "/src/iot/fusion/thermistor.py": ["/src/iot/fusion/electronic.py", "/src/iot/fusion/__init__.py"], "/src/iot/views/__init__.py": ["/src/iot/views/actuator.py", "/src/iot/views/dashboard.py", "/src/iot/views/pid.py", "/src/iot/views/sensor.py"], "/src/iot/actuators/__init__.py": ["/src/iot/actuators/actuator.py"], "/src/iot/fusion/ldr.py": ["/src/iot/fusion/__init__.py"]}