Ejemplo n.º 1
0
def end_subscription(message):
    uid = str(message.from_user.id)
    cid = str(message.chat.id)

    if message.chat.type == 'private':
        if uid in loadjson("userlist"):
            deljson(uid, "userlist")
            bot.send_message(
                uid,
                'You have been removed from the subscription list',
                parse_mode="Markdown")
        else:
            bot.send_message(
                uid,
                'You can\'t unsubscribe without subscribing first dummy!',
                parse_mode="Markdown")
    elif message.chat.type == 'group' or message.chat.type == 'supergroup':
        if cid in loadjson("grouplist"):
            bot.reply_to(message,
                         'Oh no more updates? Okay...',
                         parse_mode="Markdown")
            gid = str(message.chat.id)
            deljson(gid, "grouplist")
        else:
            bot.send_message(cid, 'Not subscibed yet', parse_mode="Markdown")
    else:
        pass
Ejemplo n.º 2
0
def start_subscription(message):
    uid = str(message.from_user.id)
    cid = str(message.chat.id)

    if message.chat.type == 'private':
        if uid not in loadjson("userlist"):
            addUser(uid, message.from_user.first_name, "userlist")
            bot.send_message(uid, 'egine eisgwrh', parse_mode="Markdown")
        else:
            bot.send_message(uid, 'halloooooo', parse_mode="Markdown")
    elif message.chat.type == 'group' or message.chat.type == 'supergroup':
        if cid not in loadjson("grouplist"):
            bot.reply_to(
                message,
                'Hello fans, this awesome group is now added and I will keep you guys up to date',
                parse_mode="Markdown")
            gid = str(message.chat.id)
            gname = message.chat.title
            addUser(gid, gname, "grouplist")
        else:
            bot.send_message(
                cid,
                'Hello again fans, your group has already been registered',
                parse_mode="Markdown")
    else:
        pass
Ejemplo n.º 3
0
    def create_generator(self, path, debug):
        ############################
        ##   paths
        ###########################
        train_csv = f'{path}full_train.csv'
        vfeats_txt = f'{path}vfeats.txt'
        hfeats_txt = f'{path}hfeats.txt'
        htoi_json = f'{path}htoi.json'
        vtoi_json = f'{path}vtoi.json'

        ############################
        ##   Load data
        ############################
        print('-' * 15, "Loading data", '-' * 15)
        print("loading traning matrix at: ", train_csv)
        M = pd.read_csv(train_csv)

        if debug:
            print("Making debug dataset.....")
            pos = M.loc[M['edge'] > 0].sample(frac=1)
            negs = M.loc[M['edge'] == 0].sample(frac=1)
            M = pd.concat([pos, negs[:len(pos)]],
                          ignore_index=True).sample(frac=1)

        print("loading features at: ", vfeats_txt, hfeats_txt)
        vfeats = np.loadtxt(vfeats_txt)
        hfeats = np.loadtxt(hfeats_txt)

        print("loading indices at: ", vtoi_json, htoi_json)
        htoi = loadjson(htoi_json)
        vtoi = loadjson(vtoi_json)
        print('-' * 15, "Finished loading data", '-' * 15)
        print()

        ############################
        ##   Prepare data (dataloader)
        ############################
        print('-' * 15, "Creating Generator", '-' * 15)

        data_config = {
            'interactions': M,
            'htoi': htoi,
            'vtoi': vtoi,
            'pct_test': .10,
            'device': self.device
        }

        self.vfeats = vfeats
        self.hfeats = hfeats
        self.n_v = len(vtoi)
        self.n_h = len(htoi)
        self.latent_dim = vfeats.shape[1]
        self.gen = ProteinInteractionGenerator(data_config)

        print('-' * 15, "Generator done", '-' * 15)
        print()
Ejemplo n.º 4
0
def notify_users_and_groups(message):
    # Notify subscribed users
    for user_id in loadjson("userlist"):
        try:
            bot.send_message(user_id, message, parse_mode="Markdown")
        except telebot.apihelper.ApiException as ex:
            USER_BLOCK_ERROR = "Forbidden: bot was blocked by the user"
            if (USER_BLOCK_ERROR in str(ex)):
                print(
                    "{date}: The user {user_id} has blocked the bot. The user will be removed."
                    .format(date=datetime.now(), user_id=user_id),
                    file=log)
                deljson(user_id, "userlist")
            else:
                telebot.logger.error(ex)
                print(
                    "{}: Message could not be sent to group - Telebot API Error"
                    .format(datetime.now()),
                    file=log)
        except Exception as ex:
            telebot.logger.error(ex)
            print("{}: Message could not be sent to users".format(
                datetime.now()),
                  file=log)

    # Notify subscribed groups
    for gid in loadjson("grouplist").keys():
        try:
            bot.send_message(gid, message, parse_mode="Markdown")
        except telebot.apihelper.ApiException as ex:
            GROUP_BLOCK_ERROR = "Forbidden: bot was kicked from the group chat"
            if (GROUP_BLOCK_ERROR in str(ex)):
                print(
                    "{date}: The group {gid} has kicked the bot. The group will be removed."
                    .format(date=datetime.now(), gid=gid),
                    file=log)
                deljson(gid, "grouplist")
            else:
                telebot.logger.error(ex)
                print(
                    "{}: Message could not be sent to group - Telebot API Error"
                    .format(datetime.now()),
                    file=log)
        except Exception as ex:
            telebot.logger.error(ex)
            print("{}: Message could not be sent to groups".format(
                datetime.now()),
                  file=log)
Ejemplo n.º 5
0
	def __init__(self, *args):
		ffmpeg.InitLib()				
		self.svcplugin = None	
		self.conf = None
		self.conf = utils.loadjson('plugin.txt')
		self.wndconsole = PlayConsoleWindow(self)		
		self.wndquery = PlayQueryWindow(self)
Ejemplo n.º 6
0
def load_fit(name, sim):
    sim = deepcopy(sim)
    model = sim.model
    model.params.fromdict(utils.loadjson(fname_fit(name)))
    sim.init_model(model)
    sim.init_params()
    return sim
Ejemplo n.º 7
0
    def __init__(self):

        self.appData = utils.loadjson("./data/app.json")
        self.appID = self.appData["appid"]
        self.appSecret = self.appData["appsecret"]

        self.redirURL = "http://localhost:7777/"
        self.server = httpserver.HTTPServer(("localhost", 7777), httpServHandler)
Ejemplo n.º 8
0
    def __init__(self):

        self.appData = utils.loadjson('./data/app.json')
        self.appID = self.appData['appid']
        self.appSecret = self.appData['appsecret']

        self.redirURL = 'http://localhost:7777/'
        self.server = httpserver.HTTPServer(('localhost', 7777),
                                            httpServHandler)
Ejemplo n.º 9
0
def notify_users_and_groups(message):
    # Notify subscribed users
    for user_id in loadjson("userlist"):
        try:
            bot.send_message(user_id, message, parse_mode="Markdown")
        except:
            print("{}: Message could not be sent to users".format(
                datetime.now()),
                  file=log)

    # Notify subscribed groups
    for gid in loadjson("grouplist").keys():
        try:
            bot.send_message(gid, message, parse_mode="Markdown")
        except:
            print("{}: Message could not be sent to groups".format(
                datetime.now()),
                  file=log)
Ejemplo n.º 10
0
def end_subscription(message):
    uid = str(message.from_user.id)
    cid = str(message.chat.id)

    if message.chat.type == 'private':
        if uid in loadjson("userlist"):
            deljson(uid, "userlist")
            bot.send_message(uid, 'You have been removed from the subscription list', parse_mode="Markdown")
        else:
            bot.send_message(uid, 'You can\'t unsubscribe without subscribing first dummy!', parse_mode="Markdown")
    elif message.chat.type == 'group' or message.chat.type == 'supergroup':
        if cid in loadjson("grouplist"):
            bot.reply_to(message, 'Oh, no more updates? Okay...', parse_mode="Markdown")
            gid = str(message.chat.id)
            deljson(gid, "grouplist")
        else:
            bot.send_message(cid, 'Not subscibed yet', parse_mode="Markdown")
    else:
        pass
Ejemplo n.º 11
0
	def __init__(self, argv):
		QApplication.__init__(self,argv)

		ffmpeg.InitLib()
		self.db = None
		self.svcplugin = None	
		self.conf = None
		self.conf = utils.loadjson('plugin.txt')

		self.main()
Ejemplo n.º 12
0
	def init(self,confile):
		self.conf = utils.loadjson(confile)
		if not self.conf:
			print 'NetworkServer::loadconfig failed!'
			return False
		logfile = self.conf.get('log')
		if not logfile:
			logfile = self.name
		self.log = loggin.Logger(self.name).addHandler(loggin.stdout()).\
			addHandler(loggin.FileHandler(logfile,subfix='_%Y%m%d.txt'))
		
		return True
Ejemplo n.º 13
0
	def main(self,argv):
		conf = utils.loadjson('node.txt')
		if not conf:
			print 'read configuration file failed!'
			return False
		

		self.conf = conf
		self.id = conf['id']

		zones = self.conf['zones']
		for z in zones:
			if z['enable']:
				zone = stoZone.stoZone(self,z['id'],z['path'],z['tempdir'],z['lowater'])
				if zone.load():
					self.zones.append(zone)

		#测试从zone目录的wmv,trp生成记录到数据库,完成即可退出
		if conf['rebuildimages_fromlocal'] == True:
			for z in self.zones:
				imgidx.rebuildImages_fromlocal(z,self)
			return



#		if not self.initDB(conf['db']):
#			print 'Init Database failed!'
#			return False
		#--End Zone configuration
		self.svcfile = NodeFileServer('filesvc',self.conf['filesvc'],self)
		self.addService(self.svcfile)
		self.svcfile.start()

		self.svcmedia = NodeMediaServer('mediasvc',self.conf['mediasvc'],self)
		self.addService(self.svcmedia)
		self.svcmedia.start()

		self.initZones()

		#1.启动索引后台工作线程 
		thread = threading.Thread(target=self.threadBackService)
		thread.start()
		#2.索引服务线程

		if self.conf.get('image_convert',False):
			for n in range(self.conf.get('idxthread',1)):
				thread = threading.Thread(target=self.threadIndexService)
				thread.start()
		
		print '\nNodeServer starting...'
		utils.waitForShutdown()
Ejemplo n.º 14
0
def start_subscription(message):
    uid = str(message.from_user.id)
    cid = str(message.chat.id)

    if message.chat.type == 'private':
        if uid not in loadjson("userlist"):
            addUser(uid, message.from_user.first_name, "userlist")
            bot.send_message(uid, 'You will now receive updates!', parse_mode="Markdown")
        else:
            bot.send_message(uid, 'halloooooo', parse_mode="Markdown")
    elif message.chat.type == 'group' or message.chat.type == 'supergroup':
        if cid not in loadjson("grouplist"):
            bot.reply_to(
                message,
                'Hello fans, this awesome group is now added and I will keep you guys up to date',
                parse_mode="Markdown")
            gid = str(message.chat.id)
            gname = message.chat.title
            addUser(gid, gname, "grouplist")
        else:
            bot.send_message(cid, 'Hello again fans, your group has already been registered', parse_mode="Markdown")
    else:
        pass
Ejemplo n.º 15
0
def syncDir(dir):
	conf = utils.loadjson('sync.txt')
	if not conf:
		print 'read config failed!'
		return
	#调度一个空闲的nodeserver

	node =None
	if not os.path.exists(dir):
		print 'dir:%s is not reachable!'%dir

	#计算视频总消耗容量 m

	#递归处理每一个mov,并将对应的trp和dat上传到服务器
	for root,dirs,files in os.walk(dir):
		for file in files:
			file = file.lower()
			b,ext = os.path.splitext(file)

			if ext.lower() not in ('.mov',):
				continue

#			trp = os.path.join(root,b+'.trp')
#			if not os.path.exists(trp):
#				continue

			mov = os.path.join(root,file)
			mov = os.path.normpath(mov)
			needspace = os.path.getsize(mov)
			print 'show:',needspace,mov
			#申请一个nodeserver
			server = conf['ctrlserver']

			node = applyNodeServer(needspace,server)
			if not node:
				print 'no NodeSpace available!'
				return False
#			print node
			sync = ImageSyncronizer()
			rc =   sync.send(node,mov)
			print rc
			if not rc:
				return False
Ejemplo n.º 16
0
	def main(self,argv):
		conf = utils.loadjson('ctrl.txt')
		if not conf:
			print 'read configuration file failed!'
			return False
		if not self.initDB(conf['db']):
			print 'Init Database failed!'
			return False
		self.conf = conf

		#--End Zone configuration
		self.svcmgr = ManagementService('management',
										self.conf['service_mgr'],self )
		self.addService(self.svcmgr)
		self.svcmgr.start()
		
		#1.启动索引后台工作线程 
		thread = threading.Thread(target=self.threadBackService)
		print 'ctrlserver starting...'
		#self.test()
		utils.waitForShutdown()
Ejemplo n.º 17
0
	def main(self):
		'''
			启动插件服务,接收作业软件的交互命令
		'''

		imgbase.AppInstance.instance().app = self

		#显示登录界面
		import form_userlogin
		f = form_userlogin.UserLogin()
		r = f.exec_()
#		print r
		if r == 0:
#			self.wndquery.close()
#			self.quit()
			QtGui.qApp.quit()
			sys.exit()
			return
#		self.wndquery.show()

		self.wndconsole = PlayConsoleWindow(self)
		self.wndquery = PlayQueryWindow(self)
		self.wndconsole.showWindow(False)

		self.server = NetworkServer('test-server')
		
		addr = self.conf.get('pluginserver',('localhost',12006))
		
		self.svcplugin = PluginService(self,'pluginserver',addr )
		self.server.addService(self.svcplugin)
		enable = self.conf.get('xproxy.debug',False)
		self.svcplugin.start(enableproxy=enable) #插件服务

		

		taglist = utils.loadjson('taglist.txt')
		imgbase.AppInstance.instance().tagkeys = taglist

		self.init_hotkeys()
		form_taglist.FormTagListAdd.instance()
Ejemplo n.º 18
0
# -*- coding:utf-8 -*-
Ejemplo n.º 19
0
import flask
from flask import jsonify, render_template, redirect, url_for, request

import pymongo

from utils import loadjson

app = flask.Flask(__name__)

db_client = pymongo.MongoClient(loadjson("cred.json")["db_url"])
db = db_client["database0"]
p1_t = db["p1_t"]
p2_t = db["p2_t"]

@app.before_first_request
def startup_func():
    print(" * Startup function Called")
    p2_t.delete_many({})
    p2_t.insert_one({"_id": 0, "main light": 0})
    if p1_t.find_one(filter={"_id": 0}) is None: p1_t.insert({"_id":0, "message": ""})
    print(" * Startup function Finished")

@app.route('/', methods=['GET'])
def home():
    return render_template("home.html")

@app.route('/p1', methods=['GET'])
@app.route('/p1/home', methods=['GET'])
def p1_home():
    return render_template('p1.html')
Ejemplo n.º 20
0
def post_is_fresh(post, filename):
    return post.title not in loadjson(filename)
Ejemplo n.º 21
0
# -*- coding:utf-8 -*-
Ejemplo n.º 22
0
print("loading traning matrix at: ", train_csv)
M = pd.read_csv(train_csv)

if DEBUG:
    print("Making debug dataset.....")
    pos = M.loc[M['edge'] > 0].sample(frac=1)
    negs = M.loc[M['edge'] == 0].sample(frac=1)
    M = pd.concat([pos, negs[:len(pos)]], ignore_index=True).sample(frac=1)

print("loading features at: ", vfeats_txt, hfeats_txt)
vfeats = np.loadtxt(vfeats_txt)
hfeats = np.loadtxt(hfeats_txt)

print("loading indices at: ", vtoi_json, htoi_json)
htoi = loadjson(htoi_json)
vtoi = loadjson(vtoi_json)
print('-' * 15, "Finished loading data", '-' * 15)
print()

############################
##   Prepare data (dataloader)
############################
print('-' * 15, "Creating data loaders", '-' * 15)

data_config = {
    'interactions': M,
    'htoi': htoi,
    'vtoi': vtoi,
    'pct_test': .10,
    'device': device
Ejemplo n.º 23
0
            cyborgmatt_content = cyborgmatt_feed["items"][0]["summary"]
            cyborgmatt_content = cyborgmatt_content[1:100]
        else:
            cyborgmatt_content = None
    except:
        cyborgmatt_content = None
        print("%s Unexpected error. ECODE:1003" % str(datetime.now()),
              file=log)

    if blog_content is not None:
        #try:
        #    print (blog_feed["items"][0]["title"] + " |time: %s" %str(datetime.now()))
        #except:
        #    print ("%s MANASU. ECODE:9001"%str(datetime.now()), file=log)
        for blogpost in blog_feed.entries:
            if blogpost.title not in loadjson("previousblogposts"):
                for uid in loadjson("userlist"):
                    try:
                        bot.send_message(
                            uid,
                            '[New blog post!]({url}) \n\n *{title}* ```\n\n{content}...\n\n```'
                            .format(url=blogpost.link,
                                    title=blogpost.title,
                                    content=blog_content),
                            parse_mode="Markdown")
                    except:
                        print("%s Unexpected error. ECODE:0001" %
                              str(datetime.now()),
                              file=log)
                for gid in loadjson("grouplist").keys():
                    try:
Ejemplo n.º 24
0
 def __init__(self, name):
     self.name = name
     self.config = loadjson(os.path.join('plugins', name, 'config.json'))
     self.areas = self.config.keys()
Ejemplo n.º 25
0
        # print(previoustime)
        currenttime = os.path.getmtime(file)
        # print(currenttime)
        #print(previoustime < currenttime)
        if previoustime > currenttime:
            print("Error!")
            sys.exit()
        previoustime = os.path.getmtime(file)
    except:
        previoustime = os.path.getmtime(file)

# отсортировать - не нужно
# сделать дифф
    try:
        previousjson
        currentjson = utils.loadjson(file, quiet=True)
        currentcustomtime = ntpath.getmtime(file)
        #print(currentcustomtime)
        #print(currentjson["group1"]["lastnum"] > previousjson["group1"]["lastnum"])
        if currentjson["group1"]["lastnum"] > previousjson["group1"]["lastnum"]:
            utils.plog(
                logfile,
                "напечатано " + str(currentjson["group1"]["lastnum"] -
                                    previousjson["group1"]["lastnum"]) +
                " бирок для первой группы", currentcustomtime)
        if currentjson["group2"]["lastnum"] > previousjson["group2"]["lastnum"]:
            utils.plog(
                logfile,
                "напечатано " + str(currentjson["group2"]["lastnum"] -
                                    previousjson["group2"]["lastnum"]) +
                " бирок для второй группы", currentcustomtime)