Ejemplo n.º 1
0
    def set_sales(self):
        if self._sales_open:
            # TODO - add some post calculations
            # close the sales
            self.sales_button.setText('Open Sales')
            self._sales_open = False

            # clear all the controls
            self.clear_product_controls(True)

            logger('Sales closed. Running total: %s' %
                   str(self._running_total))
        else:
            # get the sales session
            self._sales_session = open_sales(self.db_session)

            # set the sales to open
            self.sales_button.setText('Close Sales')
            self._sales_open = True

            # load the categories and subcategories
            self.load_categories()
            self.load_subcategories()

            # log the opening
            logger('Sales opened.')
Ejemplo n.º 2
0
    def insert_matchinfo(self, lotteryid):
        from data import jc_data
        if lotteryid in [20, 21, 22, 23, 25, 26, 2521]:
            lotterytype = 'jczq'
        else:
            lotterytype = 'jclq'
        match_url, cart, tag_info = jc_data(lotteryid)
        match_url = match_url.format(**locals())
        html = get(match_url).content
        tag = tag_info.get('tag')
        league_info = tag_info.get('leagueinfo')
        li = self.jc_bs4_for_list(html, tag, league_info)
        self.mem.setmem("bs4_page_info_{}".format(lotteryid), li)
        league_no1, numb1, data_type1, tmp_win1, ins1 = li[0]
        league_no2, numb2, data_type2, tmp_win2, ins2 = li[1]
        win1 = self.win_str(lotteryid, data_type1, tmp_win1, ins1)
        win2 = self.win_str(lotteryid, data_type2, tmp_win2, ins2)
        cart = cart.format(**locals()).replace('(', '{').replace(')', '}')

        bet_info = {
            "cart": quote(cart),
            "tag": lotterytype,
            "lotteryid": lotteryid if lotteryid != 2521 else 25,
            "bonus": 'NTY0MA=='
        }

        self.mem.setmem("bet_{}".format(lotteryid), bet_info)
        logger(lotteryid, "{}投注串写入缓存成功".format(lotteryid))
        return bet_info
Ejemplo n.º 3
0
	def jc_bs4_for_list(self,html,tag,league_info):
		'''
		@html实例,从页面获取的html内容
		@tag:从data文件jc_data中根据不同彩种获取不同标签
		@league_info:比赛名称,如<周五002>
		注:有些彩种的win信息拼接需要拿到ins信息,有些彩种没有ins信息,所以用‘-’代替占位
		'''
		try:
			soup = BeautifulSoup(html, 'lxml')
			tr = soup.find_all("td", class_=tag)
			li = []
			for i in tr:
				sp = BeautifulSoup(str(i), 'lxml')
				s = sp.find_all('a')
				for j in s:
					if j.get(league_info)  and int(j.get('numb')) > 10000:
						if j.string:
							#此处无ins信息,使用-占位
							tmp =(j.get(league_info), j.get('numb'),j.get('data-odd-type'),j.string,'-')
						else:
							win = sp.find('a').find('span').string
							ins = sp.find('a').find('ins').string
							tmp = (j.get(league_info), j.get('numb'),j.get('data-odd-type'),win,ins)
						li.append(tmp)
			tmp_dict ={}
			for i in li:
				_,x,_,_,_ = i
				tmp_dict[int(x)] = i
			# 去除重复数据,拿取前2个足够
			li= [x[1] for x in sorted(tmp_dict.items(),key = lambda s :s[0])[:2]]
		except Exception ,e:
			logger('bs4',e)
Ejemplo n.º 4
0
    def strip_overlay(self, username):
        # only log if not cancelling
        if username != '<cancel>':
            logger('Validated user %s' % username)

        # remove the layout
        self.base_layout.removeWidget(self.overlay_widget)
        sip.delete(self.overlay_widget)
Ejemplo n.º 5
0
 def number_issue(self):
     lotteryid_list = [51, 52, 53, 54, 200, 201, 202]
     for lotteryid in lotteryid_list:
         issue = get_num_issue(lotteryid)
         key = "issue_{}".format(lotteryid)
         self.mem.setmem(key, issue)
         logger(lotteryid, "{}在售期号写入缓存成功".format(lotteryid))
     return
Ejemplo n.º 6
0
 def wrapper_function(*args, **kwargs):
     print('\n')
     logger('{}'.format(self.__name__))
     session = args[0].session
     print('{} Request Headers {}'.format('#'*20, '#'*20))
     for header_name, header_value in session.headers.items():
         print(f'[{header_name} : {header_value}]')
     print('#'*57)
     return self(*args, **kwargs)
Ejemplo n.º 7
0
 def process_transaction(self, transaction, sender_pubk):
     verified_check = self.verify_transaction(transaction, sender_pubk)
     double_spending_check = self.is_double_spending(transaction)
     if not verified_check:
         logger('|TRANSACTION REJECTED\t-\tInvalid Transaction|')
         return
     if double_spending_check:
         logger('|TRANSACTION REJECTED\t-\tDouble Spending Detected|\n|From User \t\t\t\t'+str(sender_pubk.__hash__())+'|')
         return
     transaction_previous_hash = self.retrieve_transaction_previous_hash(transaction)
     transaction.add_prev_transaction(transaction_previous_hash)
     self.add_transaction_to_block(transaction)
Ejemplo n.º 8
0
def resetAT():
    error = None
    try:
        data = exeReq("UPDATE users SET accesstoken = '' WHERE login='******'login'] + "'")
    except Exception as e:
        logger('resetAT', 'DB connection/request error!')
        return render_template('login.html', error=error)

    session['accesstoken'] = ''
    logger('resetAT', 'Your access token was resetted properly')
    return redirect(url_for('login_api.logout'))
Ejemplo n.º 9
0
def userlogin(login, password):

    if not login or not password:
        logger('login', 'Thanks to provide login and password')
        return 'ko'

    try:
        sql = "SELECT u.email, u.landline, u.mobile, u.accesstoken,"
        sql += "  (SELECT ids.id FROM ids, mapping WHERE ids.sid = mapping.roomid AND ids.type = 'roomid' AND u.uid = mapping.uid), "
        sql += "  (SELECT ids.id FROM ids, mapping WHERE ids.sid = mapping.teamid AND ids.type = 'teamid' AND u.uid = mapping.uid) "
        sql += "FROM users u, mapping m "
        sql += "WHERE u.login = '******' AND pw_hash=PASSWORD('" + password + "') AND u.uid = m.uid"
        data = exeReq(sql)
    except Exception as e:
        logger('login', 'DB connection/login request error!')
        return 'ko'

    if data is None:
        logger('login', 'Wrong email or password!')
        return 'ko'
    else:
        session['logged_in'] = True
        session['login'] = login
        session['email'] = data[0][0]
        session['mobile'] = data[0][2]
        session['accesstoken'] = ""
        session['roomid'] = data[0][4]
        session['teamid'] = data[0][5]

        if data[0][3]:  # if accesstoken set so finalize the login
            session['accesstoken'] = "Bearer " + data[0][3]
            logger(
                'login', 'You were logged (login:'******',email:' +
                session['email'] + ').')
            return 'ok'
        else:  # no accesstoken so Cisco registration request
            logger(
                'login',
                'You were logged but without access token, redirect on AT request page ongoing (login:'******',email:' + session['email'] + ').')
            return 'accesstoken'

    return 'ko'
Ejemplo n.º 10
0
 def pc_touzhu(self, lotteryid):
     import urllib
     #获取投注form表单,pc_bet_data传递的参数详情见data文件中的bet_info
     if lotteryid > 10000:
         forms_data = pc_bet_data(lotteryid)
         print lotteryid
         print forms_data
         bet_url = readconfig('num_bet_url')
         print bet_url
     else:
         forms_data = eval(
             self.mem.getmem("bet_{lotteryid}".format(**locals())).replace(
                 ' ', ''))
         if lotteryid == 2521:
             forms_data['lotterytype'] = 'exy'
         if lotteryid in num_for_lotteryid('jclq'):
             bet_url = readconfig('jclq_bet_url')
         elif lotteryid in num_for_lotteryid('jczq'):
             bet_url = readconfig('jczq_bet_url')
     #发送投注请求
     print bet_url
     print forms_data
     s = self.session.post(url=bet_url, data=forms_data).content
     if eval(s).get('url'):
         # 获取返回值中的url参数
         url = eval(s).get('url')
     else:
         logger('投注失败', "投注结果:{}".format(s))
         return
     # 拼接url
     url = self.base_url + urllib.unquote(url)[1:]
     # 获取url中的参数信息,以字典形式返回
     data_info = url2Dict(url)
     #记录投注结果
     logger(
         lotteryid, "{}投注成功,orderid:{}".format(data_info.get('lotteryname'),
                                               data_info.get('orderid')))
     # 请求上一个请求返回的url,跳转支付页面
     html = self.session.get(url).content
     #返回支付页面html及sid,userid等data信息
     return html, data_info
Ejemplo n.º 11
0
def userlogin(login, password):
    if not login or not password:
        logger('login', 'Thanks to provide login and password')
        return 'ko'

    try:
        sql = "SELECT email, webhook, mobile, accesstoken "
        sql += "FROM users "
        sql += "WHERE login = '******' AND pw_hash = PASSWORD('" + password + "');"
        print sql
        data = exeReq(sql)
    except Exception as e:
        logger('login', 'DB connection/login request error!')
        return 'ko'

    if data is None:
        logger('login', 'Wrong email or password!')
        return 'ko'
    else:
        session['logged_in'] = True
        session['login'] = login
        session['email'] = data[0][0]
        session['webhook'] = data[0][1]
        session['mobile'] = data[0][2]
        session['accesstoken'] = ""

        if data[0][3]:  # if accesstoken set so finalize the login
            session['accesstoken'] = "Bearer " + data[0][3]
            logger(
                'login', 'You were logged (login:'******',email:' +
                session['email'] + ').')
            return 'ok'
        else:  # no accesstoken so Cisco registration request
            logger(
                'login',
                'You were logged but without access token, redirect on AT request page ongoing (login:'******',email:' + session['email'] + ').')
            return 'accesstoken'

    return 'ko'
Ejemplo n.º 12
0
    def create_transaction(self, receiver, scrooge):
        list_coins = self.balance(scrooge)
        if(receiver.public_key == self.public_key):
            logger('*'*20 + '\nTransaction [Aborted]\nSelf Transfer is not Allowed\nFrom:\t' + str(self.id.__hash__()) + '\nTo:\t' + str(receiver.id.__hash__())+'\n'+'*'*20)
            return
        if len(list_coins) == 0:
            logger('|TRANSACTION REJECTED\t-\tInsuficient Balance|')
            return

        transfer_coin_index = random.randint(0, len(list_coins) - 1)
        transfer_coin = list_coins[transfer_coin_index]
        transaction = Transaction(self.public_key, [transfer_coin], receiver.public_key)
        if self.__sign( transaction):
            logger('*'*22 + '\nTransaction [Created]\nFrom:\t' + str(self.id.__hash__()) + '\nTo:\t' + str(receiver.id.__hash__())+'\n'+'*'*22)
            scrooge.process_transaction(transaction, self.public_key)
Ejemplo n.º 13
0
def open_sales(session):
    # get the current date so we can filter
    today = datetime.date.today()

    # create a query to see what the sessions are, get any with a date >= than today
    q = session.query(SaleSession).filter(
        SaleSession.time_opened >= today).all()

    if len(q) >= 1:
        logger('Found session(s) %s. Using latest.' % str(q))
        sale_session = q[-1]
    else:
        logger('No sessions found. Opening new session.')

        # create a new session and commit it
        sale_session = SaleSession(time_opened=datetime.datetime.now())
        session.add(sale_session)
        session.commit()

        logger('Opened new session: %s' % str(sale_session))

    # return the sale session object
    return sale_session
Ejemplo n.º 14
0
 def validate(self):
     logger('Validating user %s' % self.username_box.currentText())
     self.emit(SIGNAL('user_validated'), self.username_box.currentText())
Ejemplo n.º 15
0
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
import MySQLdb
from MySQLdb.cursors import DictCursor
import redis
import base_conf
import tools
from DBUtils.PooledDB import PooledDB

module_logger = tools.logger("./logs/sql.query")

class DbConfReader(object):
    '''
        name : table_name
        colums : 必须是完整的列名
        key : 索引项
        auto_key : 自增key
    '''
    def __init__(self, conf):
        self.conf = base_conf.base_conf_t([conf])
        self.gen_sql()

    def gen_sql(self):
        self.table_name = self.conf.name
        self.colums = [x.strip() for x in self.conf.colums.split(",")]
        try:
            self.auto_key = self.conf.auto_increment
        except:
            self.auto_key = None
        self.insert_colums = [col for col in self.colums if col != self.auto_key]
Ejemplo n.º 16
0
 def on_space_press(_):
     logger("Wrap up! Check your `./output/log.txt` file for logs.")
     scrooge.sign_last_block()
     # logger('\nLast block successfully signed:\t'+scrooge.current_building_block.signature)
     _exit(0)
Ejemplo n.º 17
0
 def add_transaction(self, coins):
     for coin in coins:
         self.coins.append(coin)
         coin.change_ownership(self.id)
     logger('User:\t\t' + str(self.id.__hash__()) + '\nReceived:\t' + str(len(coins))+' coin(s)\n')
Ejemplo n.º 18
0
Archivo: parse.py Proyecto: brrr2/lykos
# The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from oyoyo.ircevents import generated_events, protocol_events,\
                            all_events, numeric_events

from tools import logger # external dependency

log = logger(None, None, None)

# avoiding regex
def parse_raw_irc_command(element):
    """
    This function parses a raw irc command and returns a tuple
    of (prefix, command, args).
    The following is a psuedo BNF of the input text:

    <message>  ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
    <prefix>   ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
    <command>  ::= <letter> { <letter> } | <number> <number> <number>
    <SPACE>    ::= ' ' { ' ' }
    <params>   ::= <SPACE> [ ':' <trailing> | <middle> <params> ]

    <middle>   ::= <Any *non-empty* sequence of octets not including SPACE
Ejemplo n.º 19
0
Archivo: api.py Proyecto: wind9/api
import requests
import threading
import random
import time
import tools
import traceback
import json
from threading import Thread
from config import global_config as config

log = tools.logger('bn')
agentId = config.get('bn', 'agentId')
businessId = config.get('bn', 'businessId')
tradePwd = config.get('bn', 'tradePwd')
charge_url = config.get('bn', 'charge_url')
appKey = config.get('bn', 'appKey')
thread_num = int(config.get('bn', 'thread_num'))
sleep_time = int(config.get('bn', 'sleep_time'))
redis = tools.get_redis('bn')


def charge(phone, face):
    resp = ''
    param = {
        "agentId":
        agentId,
        "businessId":
        businessId,
        "reqStreamId":
        "fd{}{}".format(str(round(time.time() * 1000)),
                        random.randint(100, 1000)),
Ejemplo n.º 20
0
# The bot commands implemented in here are present no matter which module is loaded

import botconfig
from tools import decorators
import tools.moduleloader as ld
import traceback
from settings import common as var
from base64 import b64encode
from oyoyo.parse import parse_nick
import imp
from tools import logger

log = logger("errors.log")
alog = logger(None)

def on_privmsg(cli, rawnick, chan, msg, notice = False):
    currmod = ld.MODULES[ld.CURRENT_MODULE]
    
    if botconfig.IGNORE_HIDDEN_COMMANDS and (chan.startswith("@#") or chan.startswith("+#")):
        return
    
    if (notice and ((chan != botconfig.NICK and not botconfig.ALLOW_NOTICE_COMMANDS) or
                    (chan == botconfig.NICK and not botconfig.ALLOW_PRIVATE_NOTICE_COMMANDS))):
        return  # not allowed in settings

    if chan == botconfig.NICK:
        chan = parse_nick(rawnick)[0]

    if currmod and "" in currmod.COMMANDS.keys():
        for fn in currmod.COMMANDS[""]:
            try:
Ejemplo n.º 21
0
from threading import Thread
from taskManager import TaskManager, Task
from Globals import TOKEN

message_queue = Queue()
write_queue = Queue()


def handler_write():
    while True:
        item = write_queue.get()
        UsersProject.insert(item.__dict__).execute()
        write_queue.task_done()


log = logger("echoBot", "echoBot.log")


def func1(data):
    ll = []
    for project in data:
        ll.append(project)
    return ll


def func2(data):
    [write_queue.put(obj) for obj in data]


def hole(data):
    pass
Ejemplo n.º 22
0
def logout():
    session.pop('logged_in', None)
    session.clear()
    logger('logout', 'You were logged out')
    return render_template('login.html')
Ejemplo n.º 23
0
    def setup_ui(self):
        # set the product box up
        self.product_box = QGroupBox()
        product_box_layout = QGridLayout(self.product_box)

        # category box which will hold the categories
        self.cat_box = QGroupBox()
        self.cat_box.setMaximumWidth(200)

        # add to the various layouts
        cat_layout = QVBoxLayout(self.cat_box)
        product_box_layout.addWidget(self.cat_box, 0, 0)
        self.base_layout.addWidget(self.product_box, 0, 0)

        # add this so it doesn't sit up the top
        cat_layout.addStretch()
        cat_layout.addWidget(QPushButton('Deals'))

        # The subcategory box
        self.subcat_box = QGroupBox()
        subcat_layout = QGridLayout(self.subcat_box)

        # add to the product box layout
        product_box_layout.addWidget(self.subcat_box, 0, 1)

        # add the scan box and holder
        scan_group_box = QGroupBox()
        scan_layout = QHBoxLayout(scan_group_box)
        self.base_layout.addWidget(scan_group_box, 1, 0)
        self.scan_box = QLineEdit()
        self.scan_box.setPlaceholderText('scan here')
        scan_layout.addStretch()
        scan_layout.addWidget(QLabel('Sale Scan:'))
        scan_layout.addWidget(self.scan_box)

        # TODO - Put sales button in proper place
        self.sales_button = QPushButton('Open Sales')
        self.sales_button.clicked.connect(self.set_sales)
        scan_layout.addWidget(self.sales_button)

        # add the utilities box for search and menu etc
        self.utilities_box = QGroupBox()
        utilities_layout = QGridLayout(self.utilities_box)
        utilities_menu = QGroupBox()
        utilities_menu.setMaximumWidth(200)
        utilities_menu_layout = QVBoxLayout(utilities_menu)
        utilities_layout.addWidget(utilities_menu, 0, 0)

        # load the utilities controls
        utilities_buttons = ['Search', 'Books', 'Notifications', 'Messages']
        for b in utilities_buttons:
            utilities_menu_layout.addWidget(QPushButton(b))

        self.base_layout.addWidget(self.utilities_box, 2, 0)

        # the utilities content area
        self.utilities_content = QGroupBox()
        utilities_content_layout = QGridLayout(self.utilities_content)
        utilities_layout.addWidget(self.utilities_content, 0, 1)

        # add the status bar to the application window
        self.setStatusBar(QStatusBar())

        # add the sales group
        sales_box = QGroupBox()
        sales_box_layout = QVBoxLayout(sales_box)
        self.base_layout.addWidget(sales_box, 0, 1, 3, 1)
        sales_box.setMinimumWidth(400)
        sales_box.setMaximumWidth(400)

        # sale scroll for holding current sale items
        self.sale_scroll = QScrollArea()
        scroll_layout = QVBoxLayout(self.sale_scroll)
        self.sale_scroll.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.sale_scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        sales_box_layout.addWidget(self.sale_scroll)
        scroll_layout.addWidget(SaleButton('Test Sale (C1,SC1,Q1,$1.00)'))

        # price group box
        price_box = QGroupBox()
        price_box_layout = QGridLayout(price_box)
        sales_box_layout.addWidget(price_box)

        # actual controls for changing the values
        self.price_box = QLineEdit()
        self.price_box.setPlaceholderText('price')
        self.quantity_box = QLineEdit()
        self.quantity_box.setPlaceholderText('quantity')

        # add them to the layout
        price_box_layout.addWidget(self.price_box, 0, 0)
        price_box_layout.addWidget(self.quantity_box, 1, 0)
        price_box_layout.addWidget(QPushButton('Apply'), 2, 0)

        # the overlay for logging in and stuff
        self.overlay_widget = QGroupBox()
        overlay_layout = QGridLayout(self.overlay_widget)
        self.overlay_widget.setStyleSheet(
            'QGroupBox{background-color: rgba(0,0,0,40%)}')
        login_form = LoginForm(self.db_session)
        overlay_layout.addWidget(login_form)
        self.base_layout.addWidget(self.overlay_widget, 0, 0, 3, 3)

        QObject.connect(login_form, SIGNAL('user_validated'),
                        self.strip_overlay)
        # ---------------------------------------------------------------------------
        # ---------------------------------------------------------------------------
        # get the style sheet and apply it
        try:
            style = ''
            style_file = open('./style.css')
            for line in style_file:
                style += line
            self.setStyleSheet(style)
        except IOError as e:
            logger('Could not apply styles: %s' % str(e.args))
Ejemplo n.º 24
0
# Copyright (c) 2011, Jimmy Cao
# All rights reserved.

# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

# Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from oyoyo.parse import parse_nick
import fnmatch
import botconfig
import settings.wolfgame as var
from tools import logger

adminlog = logger(None)


def generate(fdict, permissions=True, **kwargs):
    """Generates a decorator generator.  Always use this"""
    def cmd(*s,
            raw_nick=False,
            admin_only=False,
            owner_only=False,
            chan=True,
            pm=False,
            game=False,
            join=False,
            none=False,
            playing=False,
            roles=(),
Ejemplo n.º 25
0
# All rights reserved.

# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

# Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


from oyoyo.parse import parse_nick
import fnmatch
import botconfig
import settings.wolfgame as var
from tools import logger

adminlog = logger(None)

def generate(fdict, permissions=True, **kwargs):
    """Generates a decorator generator.  Always use this"""
    def cmd(*s, raw_nick=False, admin_only=False, owner_only=False, chan=True, pm=False,
                game=False, join=False, none=False, playing=False, roles=(), hookid=-1):
        def dec(f):
            def innerf(*args):
                largs = list(args)
                rawnick = largs[1]
                if not permissions:
                    return f(*largs)
                if len(largs) > 1 and largs[1]:
                    nick, _, _, cloak = parse_nick(largs[1])

                    if cloak is None:
Ejemplo n.º 26
0
import tools


tools.logger('predictor.log')


data4work = tools.extractor('predictor.log')

true_slice_list = tools.true_slicer(data4work)

true_chunks = tools.true_chunker(data4work)
false_chunks = tools.false_chunker(data4work)

for true_slice in true_slice_list:
    for chunk in true_slice.copy():
        if chunk in false_chunks:
            true_slice.remove(chunk)
            true_chunks.remove(chunk)


print(tools.find_intersection(true_slice_list))
Ejemplo n.º 27
0
 def add_transaction(self, transaction):
     self.transactions.append(transaction)
     logger('=' * 64 + '\n(UNDER CONSTRUCTION) \n' + self.__str__() +
            '=' * 64 + '\n')
     return len(self.transactions) != 10
Ejemplo n.º 28
0
import os
import botconfig
from tools import logger

MODULES = {}

for modfile in os.listdir("modules"):
    if modfile == "common.py":
        continue  # no need to load this one
    if modfile.startswith("__"):
        continue
    if not modfile.endswith(".py"):
        continue  # not a module
    if not os.path.isfile("modules/"+modfile):
        continue  # not a file
        
    modfile = modfile[:-3]
    
    logger(None)("Loading module "+modfile)
    
    MODULES[modfile] = getattr(__import__("modules."+modfile), modfile)
    
if botconfig.DEFAULT_MODULE in MODULES.keys():
    CURRENT_MODULE = botconfig.DEFAULT_MODULE.lower()
else:
    CURRENT_MODULE = "wolfgame"
Ejemplo n.º 29
0
# The above copyright notice and this permission notice shall be included in
#  all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from oyoyo.ircevents import generated_events, protocol_events,\
                            all_events, numeric_events

from tools import logger  # external dependency

log = logger(None, None, None)


# avoiding regex
def parse_raw_irc_command(element):
    """
    This function parses a raw irc command and returns a tuple
    of (prefix, command, args).
    The following is a psuedo BNF of the input text:

    <message>  ::= [':' <prefix> <SPACE> ] <command> <params> <crlf>
    <prefix>   ::= <servername> | <nick> [ '!' <user> ] [ '@' <host> ]
    <command>  ::= <letter> { <letter> } | <number> <number> <number>
    <SPACE>    ::= ' ' { ' ' }
    <params>   ::= <SPACE> [ ':' <trailing> | <middle> <params> ]
Ejemplo n.º 30
0
# The bot commands implemented in here are present no matter which module is loaded

import botconfig
from tools import decorators
import tools.moduleloader as ld
import traceback
from settings import common as var
from base64 import b64encode
from oyoyo.parse import parse_nick
import imp
from tools import logger

log = logger("errors.log")
alog = logger(None)


def on_privmsg(cli, rawnick, chan, msg, notice=False):
    currmod = ld.MODULES[ld.CURRENT_MODULE]

    if botconfig.IGNORE_HIDDEN_COMMANDS and (chan.startswith("@#")
                                             or chan.startswith("+#")):
        return

    if (notice and
        ((chan != botconfig.NICK and not botconfig.ALLOW_NOTICE_COMMANDS) or
         (chan == botconfig.NICK
          and not botconfig.ALLOW_PRIVATE_NOTICE_COMMANDS))):
        return  # not allowed in settings

    if chan == botconfig.NICK:
        chan = parse_nick(rawnick)[0]
Ejemplo n.º 31
0
 def log_users(self):
     logger('='*64+'\nUsers Report:\n'+'='*64)
     string_users = ''
     for user in self.users:
         string_users += user.to_string(self)
     logger(string_users+'\n'+'='*64)
Ejemplo n.º 32
0
import pickle, time, os
from threading import Thread, Lock
from tools import log as logger, hash_, divide_message
from Globals import PATH
log = logger("task manager", "task_manager.log")


class Memento:
    def __init__(self, state):
        self._state = state

    def get_state(self):
        return self._state


class Task:
    def __init__(self, *args):
        self.func = args[0]
        self.func2 = args[1]
        self.sent = []

    def __call__(self, *args, **kwargs):
        data = args[0]
        projects = self.func(data)
        temp = []
        for project in projects:
            hs = project.hash()
            if hs not in self.sent:

                temp.append(project)
                self.sent.append(hs)
Ejemplo n.º 33
0
def main():
    cli = IRCClient(
        {
            "privmsg":
            modules.common.on_privmsg,
            "notice":
            lambda a, b, c, d: modules.common.on_privmsg(a, b, c, d, True),
            "":
            modules.common.__unhandled__
        },
        host=botconfig.HOST,
        port=botconfig.PORT,
        authname=botconfig.USERNAME,
        password=botconfig.PASS,
        nickname=botconfig.NICK,
        ident=botconfig.IDENT,
        real_name=botconfig.REALNAME,
        sasl_auth=botconfig.SASL_AUTHENTICATION,
        use_ssl=botconfig.USE_SSL,
        connect_cb=modules.common.connect_callback,
        stream_handler=tools.stream,
    )
    cli.mainLoop()


if __name__ == "__main__":
    try:
        main()
    except Exception:
        tools.logger("errors.log")(traceback.format_exc())
Ejemplo n.º 34
0
Archivo: api.py Proyecto: wind9/api
import requests
import threading
import random
import time
import tools
import traceback
import json
from threading import Thread
from config import global_config as config

log = tools.logger('fl')
agentId = config.get('fl', 'agentId')
businessId = config.get('fl', 'businessId')
tradePwd = config.get('fl', 'tradePwd')
charge_url = config.get('fl', 'charge_url')
appKey = config.get('fl', 'appKey')
thread_num = int(config.get('fl', 'thread_num'))
sleep_time = int(config.get('fl', 'sleep_time'))
redis = tools.get_redis('fl')


def charge(phone, face):
    resp = ''
    param = {
        "agentId":
        agentId,
        "businessId":
        businessId,
        "reqStreamId":
        "fd{}{}".format(str(round(time.time() * 1000)),
                        random.randint(100, 1000)),
Ejemplo n.º 35
0
import os
import botconfig
from tools import logger

MODULES = {}

for modfile in os.listdir("modules"):
    if modfile == "common.py":
        continue  # no need to load this one
    if modfile.startswith("__"):
        continue
    if not modfile.endswith(".py"):
        continue  # not a module
    if not os.path.isfile("modules/" + modfile):
        continue  # not a file

    modfile = modfile[:-3]

    logger(None)("Loading module " + modfile)

    MODULES[modfile] = getattr(__import__("modules." + modfile), modfile)

if botconfig.DEFAULT_MODULE in MODULES.keys():
    CURRENT_MODULE = botconfig.DEFAULT_MODULE.lower()
else:
    CURRENT_MODULE = "wolfgame"
Ejemplo n.º 36
0
import traceback
import modules.common
import tools


def main():
    cli = IRCClient(
                      {"privmsg": modules.common.on_privmsg,
                       "notice": lambda a, b, c, d: modules.common.on_privmsg(a, b, c, d, True),
                       "": modules.common.__unhandled__},
                     host=botconfig.HOST,
                     port=botconfig.PORT,
                     authname=botconfig.USERNAME,
                     password=botconfig.PASS,
                     nickname=botconfig.NICK,
                     ident=botconfig.IDENT,
                     real_name=botconfig.REALNAME,
                     sasl_auth=botconfig.SASL_AUTHENTICATION,
                     use_ssl=botconfig.USE_SSL,
                     connect_cb=modules.common.connect_callback,
                     stream_handler=tools.stream,
    )
    cli.mainLoop()


if __name__ == "__main__":
    try:
        main()
    except Exception:
        tools.logger("errors.log")(traceback.format_exc())