示例#1
0
from opensimplex import OpenSimplex
import random
import pygame
from config import Settings
import sys

Settings = Settings()

pygame.init()
pygame.font.init()
clock = pygame.time.Clock()
czcionka = pygame.font.Font("Czcionki/Montserrat-ExtraBold.otf", 10)
czcionkaBIG = pygame.font.Font("Czcionki/Montserrat-ExtraBold.otf", 40)
obraz = pygame.display.set_mode([1000, 1000])

rozmiarpiksela = 5


def redraw_game(r, g, b):
    pygame.Surface.fill(obraz, [r, g, b])


def off():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit(0)
    pygame.display.flip()
    if pygame.key.get_pressed()[pygame.K_ESCAPE]:
        return False
    else:
        return True
示例#2
0
import requests
import orm
from pymessenger import Bot
from config import Settings
from quick_replies import quick_replies

PAGE_ACCESS_TOKEN = Settings().PAGE_ACCESS_TOKEN
bot = Bot(PAGE_ACCESS_TOKEN)
ngrok = "https://36fd-27-240-176-17.ngrok.io"


async def research_phone(sender_id, headers, params, **kwargs):
    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'SEARCH_PHONE').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()
    print(user.fb_id, state.name, '----------- is me research phone')

    await quick_replies(sender_id, headers, params, state)
    db.close()


async def none_search(sender_id, headers, params, **kwargs):
    data = {
        "recipient": {
            "id": sender_id
        },
        "messaging_type": "RESPONSE",
示例#3
0
from pydantic import parse_file_as
from .models import NATSettings
from config import Settings

env = Settings()
config_file_path = "{0}/nat.json".format(env.config_directory)


def read_config():
    settings = parse_file_as(NATSettings, config_file_path)
    return settings


def save_config(config: NATSettings):
    with open(config_file_path, "w") as f:
        f.write(config.json())

    settings = parse_file_as(NATSettings, config_file_path)
    return settings


def apply_config():
    pass


def read_log():
    pass


def start_service():
    pass
def configure_main(config_results_queue, cgw, cgw_peer):
    logger = logging.getLogger(__name__)
    settings = Settings()
    temp_l = cgw.DmvpnCidr.split('/')
    temp_l[1] = str(int(temp_l[1]) + 1)
    dynamic_peers = '/'.join(temp_l)

    keyfile = settings.regions[cgw.Region]['key']
    result = check_responsive(cgw)
    if result == 'fail':
        result = {'fail': cgw}
        clean_up(cgw)
        config_results_queue.put(result)
    else:
        try:
            with open('templates/cgw_hub_base.j2', 'r') as t:
                template_data = t.readlines()
            configuration = list()
            conf_vars_dict = dict()
            conf_vars_dict['cgw'] = cgw.__dict__
            conf_vars_dict['cgw_peer'] = cgw_peer.__dict__
            conf_vars_dict['settings'] = dict()
            conf_vars_dict['settings'][
                'dmvpn_password'] = settings.dmvpn_password
            conf_vars_dict['settings']['dynamic_peers'] = dynamic_peers

            for line in template_data:
                line = line.rstrip('\n')
                t = Template(line)
                new_line = t.render(conf_vars_dict)
                configuration.append(new_line)

            c = paramiko.SSHClient()
            c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            c.connect(cgw.PublicIp,
                      username='******',
                      key_filename=f'keys/{keyfile}.pem',
                      timeout=15.0)
            ssh = c.invoke_shell()
            ssh.send('config t\n')
            prompt(ssh)

            for line in configuration:
                ssh.send(line + '\n')
                prompt(ssh)

            ssh.send('end\n')
            prompt(ssh)
            ssh.send('event manager run 10interface\n')
            prompt(ssh)
            ssh.send('wr mem\n')
            prompt(ssh)
            ssh.close()
            logger.info(
                'Successfully configured csr %s for cluster_add cluster %s',
                cgw.CustomerGatewayId, cgw.cluster_value)

            if settings.regions[cgw.Region]['smart_licensing'] == 'True':
                sl_helper = LicenseHelper(cgw)
                result, license_throughput = sl_helper.register()
                if not result:
                    cgw.eligible = 'False'
                    cgw.registration_failed = True
                    logger.warning(
                        'Smart Licensing Registration failed for router %s',
                        cgw.PublicIp)
                else:
                    cgw.eligible = settings.regions[
                        cgw.Region]['eligible_default']
                    cgw.registration_failed = False
                    # Make the available_bandwidth TAG the lesser of the Smart Licensing and instance max performance
                    if license_throughput < cgw.available_bandwidth:
                        cgw.available_bandwidth = license_throughput
                        cgw.update_available_bandwidth_tag()
            else:
                cgw.eligible = settings.regions[cgw.Region]['eligible_default']
                cgw.registration_failed = False
            cgw.update_eligible_tag()

            result = {'success': cgw}
            config_results_queue.put(result)
        except Exception as e:
            logger.error("Exception occurred", exc_info=True)
            clean_up(cgw)
            result = {'fail': cgw}
            config_results_queue.put(result)
示例#5
0
from config import Settings
import mbot_functions
from datetime import datetime
from controlmtable import ControlMTable
from job import Job

# Monitoring Bot for Tx jobs

if __name__ == '__main__':
    try:
        c = Settings()
        print('Start @ ', datetime.now().strftime(c.date_format))

        # Extract from DataMiner and save into File and  Table
        df_list = []
        if mbot_functions.extract_and_load(c):
            # Load all Input Flat files into a List of Dataframes
            df_list = mbot_functions.read_input_files(c)
            df_list[2].loc[df_list[2].FROM_TIME.isnull(),
                           'FROM_TIME'] = ' '  # todo remove hard coded values
            df_list[1]['STATE'] = df_list[1]['STATE'].fillna(' ')
            print(
                f'{len(df_list)} Input files read successfully - FuncName: read_input_files()\n'
            )

        print(datetime.now().strftime(c.date_format))

        # Create table objects
        active_tables_df = df_list[0].loc[df_list[0].Active == 'Y']
        tabs = mbot_functions.create_objects(active_tables_df, ControlMTable)
        print(f'Total table objects created - {ControlMTable.total_tables}')
示例#6
0
from threading import Thread, Event
from collections import deque

from config import Settings
from pid import PID
from knob import Knob

import logging

logger = logging.getLogger(__name__)

config = Settings()
pid = PID(
    Kp=config.get_setting("Kp"),
    Ki=config.get_setting("Ki"),
    Kd=config.get_setting("Kd"),
    sample_time=config.get_setting("sample_time"),
    output_limits=(0, config.get_setting("output_limit")),
    is_enabled=False,
    proportional_on_measurement=True,
)
knob = Knob()

DEADBAND_THRESHOLD = 2.5


class Control(object):
    """Wrapper for PID module, manage control data structures for `main.py`"""
    def __init__(self):

        logger.info("Initialising control script...")
def build_main(results_queue, cgw):
    logger = logging.getLogger(__name__)
    settings = Settings()
    try:
        ec2 = boto3.resource('ec2', region_name=cgw.Region)

        client = boto3.client('ec2', region_name=cgw.Region)

        response = client.allocate_address(Domain='vpc')
        cgw.eip_AllocationId = response['AllocationId']
        cgw.PublicIp = response['PublicIp']

        vpc = ec2.create_vpc(CidrBlock=cgw.vpc_cidr)
        time.sleep(5)
        cgw.VpcId = vpc.id
        vpc.wait_until_available()
        vpc.create_tags(Tags=[{
            "Key": "Name",
            "Value": "transit_vpc"
        }, {
            "Key": settings.tvpc_program_key,
            "Value": cgw.cluster_value
        }])

        ig = ec2.create_internet_gateway()
        vpc.attach_internet_gateway(InternetGatewayId=ig.id)

        # create a route table and route to igw
        route_table = vpc.create_route_table()
        route_table.create_route(DestinationCidrBlock='0.0.0.0/0',
                                 GatewayId=ig.id)

        subnet_1 = ec2.create_subnet(AvailabilityZone=cgw.AvailabilityZone,
                                     CidrBlock=cgw.vpc_cidr,
                                     VpcId=vpc.id)
        route_table.associate_with_subnet(SubnetId=subnet_1.id)

        sec_group = ec2.create_security_group(GroupName='tvpc security group',
                                              Description='tvpc ipsec',
                                              VpcId=vpc.id)

        sec_group.authorize_ingress(
            IpPermissions=[{
                'FromPort': 4500,
                'IpProtocol': 'udp',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 4500
            }, {
                'FromPort': 0,
                'IpProtocol': '50',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 0
            }, {
                'FromPort': 500,
                'IpProtocol': 'udp',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 500
            }, {
                'FromPort': 22,
                'IpProtocol': 'tcp',
                'IpRanges': [{
                    'CidrIp': '0.0.0.0/0'
                }],
                'ToPort': 22
            }])

        instance_1 = ec2.create_instances(ImageId=cgw.AmiId,
                                          InstanceType=cgw.InstanceType,
                                          MaxCount=1,
                                          MinCount=1,
                                          KeyName=cgw.KeyName,
                                          NetworkInterfaces=[{
                                              'SubnetId':
                                              subnet_1.id,
                                              'DeviceIndex':
                                              0,
                                              'AssociatePublicIpAddress':
                                              True,
                                              'Groups': [sec_group.group_id]
                                          }],
                                          TagSpecifications=[{
                                              'ResourceType':
                                              'instance',
                                              'Tags': [{
                                                  'Key':
                                                  settings.tvpc_program_key,
                                                  'Value':
                                                  cgw.cluster_value
                                              }]
                                          }])
        instance_1[0].wait_until_running()

        cgw.InstanceId = instance_1[0].id

        response = client.associate_address(
            AllocationId=cgw.eip_AllocationId,
            InstanceId=instance_1[0].id,
        )
        cgw.eip_AssociationId = response['AssociationId']

        ec2.create_tags(Resources=[
            instance_1[0].id, ig.id, route_table.id, subnet_1.id, sec_group.id,
            cgw.eip_AllocationId
        ],
                        Tags=[
                            {
                                'Key': 'Name',
                                'Value': cgw.PublicIp
                            },
                            {
                                'Key': settings.tvpc_program_key,
                                'Value': cgw.cluster_value
                            },
                            {
                                'Key': 'tvpc_hub',
                                'Value': str(cgw.hub)
                            },
                            {
                                'Key': 'tvpc_region_extension',
                                'Value': str(cgw.region_extension)
                            },
                            {
                                'Key': 'tvpc_eligible',
                                'Value': 'False'
                            },
                            {
                                'Key': 'tvpc_asn',
                                'Value': str(cgw.asn)
                            },
                            {
                                'Key': 'tvpc_available_bandwidth',
                                'Value': str(cgw.available_bandwidth)
                            },
                            {
                                'Key': 'tvpc_vpc_cidr',
                                'Value': cgw.vpc_cidr
                            },
                            {
                                'Key': 'tvpc_DmvpnAddress',
                                'Value': cgw.DmvpnAddress
                            },
                        ])
        response = client.create_customer_gateway(BgpAsn=cgw.asn,
                                                  PublicIp=cgw.PublicIp,
                                                  Type='ipsec.1')
        cgw.CustomerGatewayId = response['CustomerGateway'][
            'CustomerGatewayId']
        ec2.create_tags(Resources=[
            cgw.CustomerGatewayId,
        ],
                        Tags=[
                            {
                                'Key': 'Name',
                                'Value': cgw.PublicIp
                            },
                            {
                                'Key': settings.tvpc_program_key,
                                'Value': cgw.cluster_value
                            },
                            {
                                'Key': 'InstanceId',
                                'Value': cgw.InstanceId
                            },
                        ])
        logger.info('Successfully built a cluster vpc %s for cluster %s',
                    cgw.VpcId, cgw.cluster_value)
        result = {'success': cgw}
        results_queue.put(result)
    except Exception as e:
        logger.error("Exception occurred", exc_info=True)
        clean_up(cgw)
        result = {'fail': cgw}
        results_queue.put(result)
示例#8
0
from telethon.sessions import StringSession

import re2 as re
import asyncio

from systemd.daemon import notify, Notification

from psutil import Process
from os import getpid

from config import Settings
from sessions import Session
from opts import Options

options = Options()
settings = Settings(options.configname)
session = Session(settings.sessionfile)
client = TelegramClient(StringSession(session.string), settings.api_id,
                        settings.api_hash)
client.start()
string = StringSession.save(client.session)
if string != session.string:
    session.save(string)

is_systemd = Process(getpid()).ppid() == 1

pattern = re.compile(settings.pattern, re.IGNORECASE)

admins = [settings.admins[admin]['id'] for admin in settings.admins]

示例#9
0
import socket
from config import Settings

settings = Settings('settings.ini')
udp_client_enabled = settings.getParser().getboolean('default',
                                                     'udp_client_enabled')
udp_host = settings.getParser().get('default', 'udp_host')
udp_port = settings.getParser().getint('default', 'udp_port')

host_and_port = (udp_host, udp_port)
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


def send(command):
    if udp_client_enabled:
        client.sendto(bytes(command, 'utf8'), host_and_port)
    print(f'Sending UDP message to {host_and_port}: {command}')
示例#10
0
import orm
import sqlalchemy
from pymessenger import Bot
from config import Settings
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig

conf = ConnectionConfig(MAIL_USERNAME=Settings().MAIL_USERNAME,
                        MAIL_PASSWORD=Settings().MAIL_PASSWORD,
                        MAIL_FROM=Settings().MAIL_FROM,
                        MAIL_PORT=Settings().MAIL_PORT,
                        MAIL_SERVER=Settings().MAIL_SERVER,
                        MAIL_TLS=Settings().MAIL_TLS,
                        MAIL_SSL=Settings().MAIL_SSL,
                        USE_CREDENTIALS=Settings().USE_CREDENTIALS)
PAGE_ACCESS_TOKEN = Settings().PAGE_ACCESS_TOKEN

bot = Bot(PAGE_ACCESS_TOKEN)


async def feedback(sender_id, headers, params, **kwargs):
    text = "您的意見是UB醬前進的動力,請問有什麼建議給UB醬的嗎?可以在對話框直接留言唷~"
    bot.send_text_message(sender_id, text)

    db = orm.SessionLocal()
    user = db.query(orm.User).filter(orm.User.fb_id == sender_id).one_or_none()
    state = db.query(
        orm.State).filter(orm.State.name == 'SEND_FEEDBACK').one_or_none()
    user.state_id = state.id
    db.add(user)
    db.commit()
def capture_setting():
    # intialising the key information
    counter = 1
    marker = 1
    distance = 0
    predicted_character_list = []
    predicted_color_list = []
    end = time.time()
    start = time.time()
    config = Settings()
    save = Saving(config.name_of_folder, config.exist_ok)

    if config.capture == "pc":
        if config.testing == "video":
            cap = cv2.VideoCapture(config.media)
        else:
            cap = cv2.VideoCapture(0)
            cap.set(cv2.CAP_PROP_FRAME_WIDTH, 960)  # 800 default
            cap.set(3, 960)  # 800 default
            cap.set(4, 540)  # 800 default
            cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 540)
            cap.set(cv2.CAP_PROP_FPS, 60)

            time.sleep(2)  # allows the camera to start-up
        print('Camera on')
        while True:
            if counter == 1:
                if config.pause:
                    distance = input("Are you Ready?")
            if counter == 1 or end - start < 10:
                end = time.time()
                ret, frame = cap.read()
                if config.Step_camera:
                    cv2.imshow('frame', frame)
                    k = cv2.waitKey(5) & 0xFF
                    if k == 27:
                        break

                color, roi, frame, success = detection(frame, config)

                if success:
                    counter = counter + 1

                    # time that the target has been last seen
                    start = time.time()

                    predicted_character, contour_image, chosen_image = character_recognition.character(color)
                    predicted_color, processed_image = colour_recognition.colour(color)

                    predicted_character_list.append(predicted_character)
                    predicted_color_list.append(predicted_color)

                    if config.save_results:
                        name_of_results = ["color", "roi", "frame","contour_image","processed_image", "chosen_image"]
                        image_results = [color, roi, frame, contour_image, processed_image, chosen_image]
                        for value, data in enumerate(name_of_results):
                            image_name = f"{marker}_{data}_{counter}.jpg"
                            image = image_results[value]
                            if image is not None:
                                save.save_the_image(image_name, image)

                if counter == 8:
                    print("Starting Recognition Thread")
                    common_character = Counter(predicted_character_list).most_common(1)[0][0]
                    common_color = Counter(predicted_color_list).most_common(1)[0][0]
                    solution(counter, marker, common_character, common_color, save.save_dir)
                    predicted_character_list = []
                    predicted_color_list = []

            else:
                print("Starting Recognition Thread")
                common_character = Counter(predicted_character_list).most_common(1)[0][0]
                common_color = Counter(predicted_color_list).most_common(1)[0][0]
                solution(counter, marker, common_character, common_color, save.save_dir)
                predicted_character_list = []
                predicted_color_list = []

    elif config.capture == "pi":
        from picamera.array import PiRGBArray
        from picamera import PiCamera

        camera = PiCamera()
        camera.resolution = (1280, 720)
        camera.brightness = 50  # 50 is default
        camera.framerate = 90
        camera.awb_mode = 'auto'
        camera.shutter_speed = camera.exposure_speed
        cap = PiRGBArray(camera, size=(1280, 720))

        for image in camera.capture_continuous(cap, format="bgr", use_video_port=True):
            #  to start the progress of capture and don't stop unless the counter increases and has surpass 5 seconds
            if counter == 1 or end - start < 10:
                frame = image.array
                end = time.time()

                color, roi, frame, success = detection(frame, config)
                
                if success:
                    counter = counter + 1

                    # time that the target has been last seen
                    start = time.time()

                    predicted_character, contour_image, chosen_image = character_recognition.character(color)
                    predicted_color, processed_image = colour_recognition.colour(color)

                    predicted_character_list.append(predicted_character)
                    predicted_color_list.append(predicted_color)

                    if config.save_results:
                        name_of_results = ["color", "roi", "frame","contour_image","processed_image", "chosen_image"]
                        image_results = [color, roi, frame, contour_image, processed_image, chosen_image]
                        for value, data in enumerate(name_of_results):
                            image_name = f"{marker}_{data}_{counter}.jpg"
                            image = image_results[value]
                            if image is not None:
                                save.save_the_image(image_name, image)

                if counter == 8:
                    print("Starting Recognition Thread")
                    common_character = Counter(predicted_character_list).most_common(1)[0][0]
                    common_color = Counter(predicted_color_list).most_common(1)[0][0]
                    marker, counter = solution(counter, marker, common_character, common_color, save.save_dir)
                    predicted_character_list = []
                    predicted_color_list = []

            else:
                print("Starting Recognition Thread")
                common_character = Counter(predicted_character_list).most_common(1)[0][0]
                common_color = Counter(predicted_color_list).most_common(1)[0][0]
                marker, counter = solution(counter, marker, common_character, common_color, save.save_dir)
                predicted_character_list = []
                predicted_color_list = []
            cap.truncate(0)
                
    elif config.capture == "image":
        cap = [] # to store the names of the images
        data_dir = Path(config.media)

        # the following code interite over the extension that exist within a folder and place them into a single list
        image_count = list(itertools.chain.from_iterable(data_dir.glob(pattern) for pattern in ('*.jpg', '*.png')))
        # image_count = len(list(data_dir.glob('*.jpg')))
        for name in image_count:
                # head, tail = ntpath.split(name)
                filename = Path(name)  # .stem removes the extension and .name grabs the filename with extension
                cap.append(filename)
                test_image = cv2.imread(str(filename))
                marker = Path(name).stem # grabs the name with the extension

                color, roi, frame, success = detection(test_image, config)

                if success:
                    predicted_character, contour_image, chosen_image = character_recognition.character(color)
                    predicted_color, processed_image = colour_recognition.colour(color)

                    _, _ = solution(counter, marker, predicted_character, predicted_color, save.save_dir)

                    if config.save_results:
                        name_of_results = ["color", "roi", "frame","contour_image","processed_image", "chosen_image", color, roi, frame, contour_image, processed_image, chosen_image]
                        for value in range(5):
                            image_name = f"{marker}_{name_of_results[value]}.jpg"
                            image = name_of_results[value + 6]
                            if image is not None:
                                save.save_the_image(image_name, image)

                    print("Detected and saved a target")
        print(f"there is a total image count of {len(image_count)} and frames appended {len(cap)}")
def get_settings():
    return Settings()