Example #1
0
  def start(self):
    game = self.session.query(Games).order_by(Games.game_id.desc()).first()
    if  not game is None and game.result == 0:
      self.player.setHand(list(game.player_hand))
      self.dealer.setHand(list(game.dealer_hand))
      self.game.setDeck(list(game.deck))

    start(self.game,self.player,self.dealer)
    r1 = self.player.getResult(self.game) 
    r2 = self.dealer.getResult(self.game)

    if ( r1 == "" and r2 == ""):
      message = ""
      result = 0
    else:
      message = ' use start() to start a new game'
      result = 1

    if game is None or game.result == 1:
      add(self.session,self.player.hand,self.dealer.hand,self.game.deck,result)
    else:
      update(game,self.player.hand,self.dealer.hand,self.game.deck,result)

    self.session.commit()

    return "Player's hand: ", self.player.hand, "Dealer's hand: ", self.dealer.hand,'  ',r1+r2,message
Example #2
0
def read_test():
    with open("spider_testphp.vulnweb.com.json") as f:
        datas = f.readlines()
    for data in datas:
        item = json.loads(data)
        url = item["url"]
        method = item["method"]
        headers = item["headers"]
        data = item["data"]

        try:
            if method.lower() == 'post':
                req = requests.post(url, data=data, headers=headers)
                http_model = HTTPMETHOD.POST
            else:
                req = requests.get(url, headers=headers)
                http_model = HTTPMETHOD.GET
        except Exception as e:
            logger.error("request method:{} url:{} faild,{}".format(method, url, e))
            continue

        fake_req = FakeReq(req.url, {}, http_model, data)
        fake_resp = FakeResp(req.status_code, req.content, req.headers)
        task_push_from_name('loader', fake_req, fake_resp)
    logger.info("爬虫结束,开始漏洞扫描")
    start()
Example #3
0
def start():
    for resname, default_amount in sliver_vs.DEFAULT_ALLOCATION.iteritems():
        DEFAULT_ALLOCATION[resname]=default_amount

    accounts.register_class(sliver_vs.Sliver_VS)
    accounts.register_class(controller.Controller)
    database.start()
    api_calls.deliver_ticket = deliver_ticket
    api.start()
Example #4
0
def vulscan(target):
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                      "Chrome/74.0.3945.0 Safari/537.36",
        "Spider-Name": "Baidu.Inc"
    }
    if target == "":
        return
    elif "://" not in target:
        target = "http://" + target
    try:
        req = requests.get(target, headers=headers, timeout=60)
        target = req.url
    except:
        return
    netloc = urlparse(target).netloc
    logger.info("开始爬虫:{}".format(target))
    cmd = [Excvpath, "-c", Chromepath, "--fuzz-path", "--robots-path", "-t", "20", "--custom-headers",
           json.dumps(headers), "--max-crawled-count", "10086", "-i", "-o", "json",
           target]
    rsp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = rsp.communicate()
    try:
        result = json.loads(output.decode().split("--[Mission Complete]--")[1])
    except IndexError:
        return
    if result:
        all_req_list = result["req_list"]
        logger.info("获得数据:{}".format(len(all_req_list)))
        for item in all_req_list:
            with open("spider_{}.json".format(netloc), "a+") as f:
                f.write(json.dumps(item) + '\n')
            url = item["url"]
            method = item["method"]
            headers = item["headers"]
            data = item["data"]

            try:
                if method.lower() == 'post':
                    req = requests.post(url, data=data, headers=headers)
                    http_model = HTTPMETHOD.POST
                else:
                    req = requests.get(url, headers=headers)
                    http_model = HTTPMETHOD.GET
            except Exception as e:
                logger.error("request method:{} url:{} faild,{}".format(method, url, e))
                continue

            fake_req = FakeReq(req.url, {}, http_model, data)
            fake_resp = FakeResp(req.status_code, req.content, req.headers)
            task_push_from_name('loader', fake_req, fake_resp)
            logger.info("加入扫描目标:{}".format(req.url))

    logger.info("爬虫结束,开始漏洞扫描")
    start()
    logger.info("漏洞扫描结束")
    logger.info("发现漏洞:{}".format(KB.output.count()))
Example #5
0
def start():
    # No default allocation values for LXC yet, think if its necessary given
    # that they are also default allocation values in this module
    if implementation == 'vs':
        for resname, default_amount in sliver_vs.DEFAULT_ALLOCATION.iteritems():
            DEFAULT_ALLOCATION[resname]=default_amount

    account.register_class(sliver_class_to_register)
    account.register_class(controller.Controller)
    database.start()
    api_calls.deliver_ticket = deliver_ticket
    api.start()
Example #6
0
    def start(self):
        start(self.game, self.player, self.dealer)
        r1 = self.player.getResult(self.game)
        r2 = self.dealer.getResult(self.game)

        if (r1 == "" and r2 == ""):
            message = ""
            result = 0
        else:
            message = ' use start() to start a new game'
            result = 1

        return "Player's hand: ", self.player.hand, "Dealer's hand: ", self.dealer.hand, '  ', r1 + r2, message
Example #7
0
def main():
    parser = argparse.ArgumentParser(description='SiteGeist: Analysing twitter sentiment in a geofenced area.')

    parser.add_argument('-g', '--geofence', nargs='+', type=float)
    parser.add_argument('-t', '--twitter-api-keys', nargs=4, type=str)

    args = parser.parse_args()

    locations = args.geofence
    keys = args.twitter_api_keys

    validate_lat_long(locations[0], locations[1])
    validate_lat_long(locations[2], locations[3])

    ta = analyser.TweetAnalyser(locations[0], locations[1], locations[2], locations[3],
                                consumer_key=keys[0], consumer_secret=keys[1], access_token_key=keys[2],
                                access_token_secret=keys[3])

    # start web front end
    api.start(Database.instance, ta)
Example #8
0
def main():
    global game_timer

    if not os.path.exists('config'):
        shutil.copyfile('config.default.xml', 'config')

    conf_tree = Et.parse('config')
    conf_root = conf_tree.getroot()
    conf_settings = conf_root.find('settings')
    conf_timer = int(conf_settings.find('timer').text)

    if api.generate_tokens(conf_root):
        conf_tree.write('config')

    if not os.path.exists('openToW.sqlite'):
        queries.setup(conf_root)

    reset()
    api.start(conf_settings.find('ip').text, conf_settings.find('port').text)
    game_timer = RepeatedTimer(conf_timer, reset)
    menu_loop()
Example #9
0
def load(repo_file, tag_file, target_file):

    # Verify that tag file content matches our own tag
    tag = get_tag()
    with open(tag_file) as f:
        tag_from_file = f.read().strip()
        # Use no tag if the provided file is empty
        if not tag_from_file:
            tag = ''
        if tag != tag_from_file:
            raise Exception("ERROR: Tag file content '{}' differs from the Loader's tag '{}'."
                            " Please check sanity of the sail script.".format(tag_from_file, tag))

    with open(repo_file) as f:
        repo = f.read().strip()
    with open(target_file) as f:
        target = f.read().strip()

    modify_yaml(repo, tag)
    call_crane('run', target)
    start(repo, target, repo_file, tag_file, target_file, tag)
Example #10
0
def load(repo_file, tag_file, target_file):

    # Verify that tag file content matches our own tag
    tag = get_tag()
    with open(tag_file) as f:
        tag_from_file = f.read().strip()
        # Use no tag if the provided file is empty
        if not tag_from_file:
            tag = ''
        if tag != tag_from_file:
            raise Exception(
                "ERROR: Tag file content '{}' differs from the Loader's tag '{}'."
                " Please check sanity of the sail script.".format(
                    tag_from_file, tag))

    with open(repo_file) as f:
        repo = f.read().strip()
    with open(target_file) as f:
        target = f.read().strip()

    modify_yaml(repo, tag)
    call_crane('run', target)
    start(repo, target, repo_file, tag_file, target_file, tag)
Example #11
0
def start():
    try:
        config = load_config()
        if config is None or 'account' not in config:
            return {'code': 1, 'msg': '未绑定银行卡'}

        res = api.start(serial_no, config['account']['alias'])
        if res is None or res['code'] != 0:
            return {'code': 1, 'msg': '获取银行卡信息失败'}

        convert(data=res['data'])
        print(res['data'])
        bot_factory = BotFactory()
        bot_util.cast_transfer = bot_factory.cast_transfer
        bot_util.cast_transaction_history = bot_factory.cast_transaction_history
        bot_util.cast_post_sms = bot_factory.cast_post_sms
        bot_util.cast_stop = bot_factory.cast_stop
        bot_util.do_works = bot_factory.do_works
        bot_util.do_verify_code = bot_factory.do_verify_code
        bot_util.do_works()
    except ConnectionRefusedError:
        res = {'code': 1, 'msg': '启动失败,ConnectionRefusedError!'}
        logger.info('/start rsp: %s', res)
    return {'code': 0, 'msg': '启动成功'}
Example #12
0
from api import start
start()
Example #13
0
    #         logger.error('[%s] %s' % (chat_id, repr(e)))
    update.message.reply_text('Test takings scheduled')


def alarm(bot, job):
    chat_id = job.context[0]
    message = job.context[1]
    logger.info('[%s] Checking alarm.' % chat_id)

    bot.sendMessage(chat_id, message)


# updater
updater = Updater(API_KEY)

# REST API

api.start(context=updater)

# scheduler
scheduler = Scheduler()

updater.dispatcher.add_handler(MessageHandler(Filters.text, answer))
# updater.dispatcher.add_handler(get_start_conversation_handler())
updater.dispatcher.add_handler(CommandHandler('id', id))
# updater.dispatcher.add_handler(CommandHandler('debug_info', info))
updater.dispatcher.add_handler(
    CommandHandler('test', test, pass_job_queue=True))

updater.start_polling()
updater.idle()
Example #14
0
################################# Import Libraries ################################
import os.path
import sys

from loadConf import loadAPIConf
import api
#######################################################################################

configAPI = loadAPIConf()

serverAPI = {
    'port': configAPI['serverAPI']['port'],
    'local': configAPI['serverAPI']['local']
}

api = api.API(serverAPI['port'], serverAPI['local'])
api.start()
Example #15
0
def handle_dialog(res, req):
    user_id = req['session']['user_id']
    if req['session']['new']:
        res['response']['text'] = 'Привет! Назови своё имя!'
        sessionStorage[user_id] = {
            'first_name': None,
            'game_started': False,
            'game_id': None,
            'point': 0
        }
        return

    if sessionStorage[user_id]['first_name'] is None:
        first_name = get_first_name(req)
        if first_name is None:
            res['response']['text'] = 'Не расслышала имя. Повтори, пожалуйста!'
        else:
            sessionStorage[user_id]['first_name'] = first_name
            res['response'][
                'text'] = f'Приятно познакомиться, {first_name.title()}. Хочешь поиграть в карты?'
            res['response']['buttons'] = [{
                'title': 'Да',
                'hide': True
            }, {
                'title': 'Нет',
                'hide': True
            }, {
                'title': 'Правила',
                'hide': True
            }]

    else:
        if not sessionStorage[user_id]['game_started']:
            if 'да' in req['request']['nlu']['tokens']:
                game_id = start()
                sessionStorage[user_id]['game_id'] = game_id
                sessionStorage[user_id]['game_started'] = True
                # res['response']['text'] = game_id
                play_game(res, req)

            elif 'нет' in req['request']['nlu']['tokens']:
                res['response']['text'] = 'Хорошо, приходите ещё!'
                sessionStorage[user_id]['game_started'] = False
                sessionStorage[user_id]['game_id'] = None
                sessionStorage[user_id]['point'] = 0
                res['end_session'] = True

            elif 'правила' in req['request']['nlu']['tokens']:
                res['response'][
                    'text'] = 'Вам произвольно выбирается карта из колоды. Количество очков равно номиналу карты. Король, дама, валет оцениваются как 10 очков, а туз как 11. Карты берутся, пока количество набранных очков не равно 21 или более. Если вы набрали ровно 21 очко - вы выиграли, больше - проиграли. Будем играть?'
                res['response']['buttons'] = [{
                    'title': 'Да',
                    'hide': True
                }, {
                    'title': 'Нет',
                    'hide': True
                }, {
                    'title': 'Правила',
                    'hide': True
                }]
            else:
                res['response']['text'] = 'Так ты хочешь сыграть?'
                res['response']['buttons'] = [{
                    'title': 'Да',
                    'hide': True
                }, {
                    'title': 'Нет',
                    'hide': True
                }, {
                    'title': 'Правила',
                    'hide': True
                }]
        else:
            if 'да' in req['request']['nlu']['tokens']:
                play_game(res, req)

            elif 'нет' in req['request']['nlu']['tokens']:
                res['response']['text'] = 'Хорошо, приходите ещё!'
                sessionStorage[user_id]['game_started'] = False
                sessionStorage[user_id]['game_id'] = None
                sessionStorage[user_id]['point'] = 0
                res['end_session'] = True

            elif 'правила' in req['request']['nlu']['tokens']:
                res['response'][
                    'text'] = 'Вам произвольно выбирается карта из колоды. Количество очков равно номиналу карты. Король, дама, валет оцениваются как 10 очков, а туз - 11. Карты берутся, пока количество набранных очков не равно 21 или более. Если вы набрали ровно 21 очко - вы выиграли, больше - проиграли. Продолжим?'
                res['response']['buttons'] = [{
                    'title': 'Да',
                    'hide': True
                }, {
                    'title': 'Нет',
                    'hide': True
                }, {
                    'title': 'Правила',
                    'hide': True
                }]
            else:
                res['response'][
                    'text'] = 'Кажется, я не поняла, что вы хотели сказать. Повторите, пожалуйста.'
                res['response']['buttons'] = [{
                    'title': 'Да',
                    'hide': True
                }, {
                    'title': 'Нет',
                    'hide': True
                }, {
                    'title': 'Правила',
                    'hide': True
                }]
Example #16
0
def checkConnection():
    api = start()
    iqoption = api.getApi()
    if not check_connect_v3():
        check_connect_v2()
Example #17
0
from utils import Utils
from datetime import datetime, date, timedelta
from dateutil import tz, rrule
import threading
from iqoptionapi.expiration import get_expiration_time
import asyncio
from config import startConfig
import iqoptionapi.global_value as global_value
import concurrent.futures

logging, handler = Utils.setup_logger('copylogger', 'atividades.log', 'w')
loggingHistory, handlerHistory = Utils.setup_logger('historylogger',
                                                    'resultados.log.config',
                                                    'a')

api = start()
iqoption = api.getApi()
check, reason = iqoption.connect()

config = startConfig().getConfig()


def logActivities(isHeader, msg):
    if isHeader:
        logging.info(
            '<blockquote class="blockquote-custom-header">{}</blockquote>'.
            format(str(msg).upper()))
    else:
        logging.info(
            '<blockquote class="blockquote-custom-body">{}</blockquote>'.
            format(msg))
Example #18
0
                value = get_current_aggreement(fid, attribute)
                if value != agreement['value']:
                    if f_uri is not None:
                        agreement['uri'] = f_uri
                    publish(dict(agreement, **position_dict))
                    set_current_aggreement(fid, attribute, agreement['value'])
                    annotation.delete_temporal(fid)
            try:
                if agreed_color and agreed_cover and agreed_wattage:
                    pollution = calculate_pollution(agreed_color, agreed_wattage, agreed_cover)
                    current_pollution = get_current_aggreement(fid, 'pollution')
                    if current_pollution is None or current_pollution != pollution:
                        set_current_aggreement(fid, 'pollution', pollution)
                        data = {'id': fid, 'attribute': 'pollution', 'value': str(pollution)}
                        if f_uri is not None:
                            data['uri'] = f_uri
                        publish(dict(data, **position_dict))
            except Exception as e:
                print e.message

        sleep(3)


monitor = Thread(target=check_annotations)
monitor.daemon = True
monitor.start()

start()

monitor.join()
log('starting...')

#wraps the system clock
from clock import Clock 
clock = Clock(log)
 
#data storage / retrieval layer
from datastore_sqlite import DatastoreSqlite
datastore = DatastoreSqlite(log)

#for debugging seperately from the raspberry pi
if DEBUG:
    from device_stub import DeviceStub
    device = DeviceStub(log)
else:
    from device_rpi import DeviceRpi
    device = DeviceRpi(log)    

#put it all together
from orchestrator import Orchestrator
orchestrator = Orchestrator(log, clock, device, datastore)

from interval_worker import IntervalWorker
worker = IntervalWorker(log, orchestrator.update, 15)
worker.start()

#start up the flask api
import api 
api.start(log, orchestrator)