<commit_before># -*- coding: utf-8 -*-
# vim:set et tabstop=4 shiftwidth=4 nu nowrap fileencoding=utf-8:

import sys
from os import path
from twisted.python import log
from twisted.internet import reactor, task
from zope.interface import implements

sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..', '..')))
import devicehive
import devicehive.poll
import devicehive.ws
import devicehive.auto
import devicehive.interfaces

class LogicHandler(object):
    """
    Abstract implementation of IProtoHandler. Handles only one device.
    """

    implements(devicehive.interfaces.IProtoHandler)

    def __init__(self):
        self.factory = None
        self.dev1_connected = False
        self.dev2_connected = False

    def test_factory(self):
        return IProtoFactory.implementedBy(self.factory.__class__)

    def on_apimeta(self, websocket_server, server_time):
        log.msg('API Info. WebSocket server: {0}; server time: {1}.'.format(websocket_server, server_time))

    def on_closing_connection(self):
        pass

    def on_connection_failed(self, reason):
        pass

    def on_command(self, deviceguid, command, finished):
        raise NotImplementedError('COMMAND IS NOT IMPLEMENTED')

    def on_connected(self):
        log.msg('Connected to devicehive.')
        for info in self.DEVICES :
            self.connect_device(info)

    def on_failure(self, device_id, reason):
        """
        @type device_id: C{str}
        @param device_id: device guid
        """
        log.err('Unhandled error. Device: {0}. Reason: {1}.'.format(device_id, reason))

    def connect_device(self, info):
        def on_subscribe(result) :
            if info.name == 'PyExample1' :
                self.dev1_connected = True
            elif info.name == 'PythonExample2' :
                self.dev2_connected = True
            self.factory.subscribe(info.id, info.key)
        def on_failed(reason) :
            log.err('Failed to save device {0}. Reason: {1}.'.format(info, reason))
        self.factory.device_save(info).addCallbacks(on_subscribe, on_failed)

    def on_command(self, device_id, command, finished):
        if command.command == 'test_cmd' :
            finished.callback("Good news everyone! I'm still technically alive.")
        else :
            finished.errback(NotImplementedError())

    def notify1(self, name, **kwargs):
        if self.dev1_connected :
            dev = self.DEVICES[0]
            self.factory.notify(name, kwargs, dev.id, dev.key)

    def notify2(self, name, **kwargs):
        if self.dev2_connected :
            dev = self.DEVICES[1]
            self.factory.notify(name, kwargs,  dev.id, dev.key)

    def generate_devices():
        """
        Method returns a list of object each of which has to implement C{devicehive.interfaces.IDeviceInfo} interface.
        """
        net = devicehive.Network(key = 'network11', name = 'network11', descr = 'network11')
        dec = devicehive.DeviceClass(name = 'Example Device Class', version = 'Example Device Class 1.1')
        eqp = [devicehive.Equipment(name = 'Example Equipment', code = 'EXEQCO', type = 'ExampleType11'), ]
        di1 = devicehive.DeviceInfo(id = '22345678-9012-3456-7890-123456789012',
                                   key = 'net11dev1',
                                   name = 'PyExample1',
                                   status = 'Online',
                                   network = net,
                                   device_class = dec,
                                   equipment = eqp)
        di2 = devicehive.DeviceInfo(id = '13456789-0123-4567-8901-234567890123',
                                   key = 'net11dev2',
                                   name = 'PythonExample2',
                                   status = 'Online',
                                   network = net,
                                   device_class = dec,
                                   equipment = eqp)
        return (di1, di2)

    DEVICES = generate_devices()

i = 0
def looping_call(hnd):
    global i
    print ('Sending looping notification {0}.'.format(i))
    hnd.notify1('looping_notification_dev1', count = i, one_more_parameter = 'parameter_value')
    hnd.notify2('looping_notification_dev2', count = i, one_more_parameter = 'parameter_value')
    i += 1

def create_factory(use_ws, handler) :
    if use_ws is None :
        return devicehive.auto.AutoFactory(handler)
    elif use_ws :
        return devicehive.ws.WebSocketFactory(handler)
    else :
        return devicehive.poll.PollFactory(handler)

def main():
    log.startLogging(sys.stdout)
    handler = LogicHandler()
    factory = create_factory(None, handler)
    reactor.connectDeviceHive('http://ecloud.dataart.com/ecapi8/', factory)
    #
    lc = task.LoopingCall(looping_call, handler)
    lc.start(10)
    #
    reactor.run()

if __name__ == '__main__' :
    main()

<commit_msg>test app has been changed<commit_after># -*- coding: utf-8 -*-
# vim:set et tabstop=4 shiftwidth=4 nu nowrap fileencoding=utf-8:

import sys
from os import path
from twisted.python import log
from twisted.internet import reactor, task
from zope.interface import implements

sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..', '..')))
import devicehive
import devicehive.poll
import devicehive.ws
import devicehive.auto
import devicehive.interfaces

class LogicHandler(object):
    """
    Abstract implementation of IProtoHandler. Handles only one device.
    """

    implements(devicehive.interfaces.IProtoHandler)

    def __init__(self):
        self.factory = None
        self.dev1_connected = False
        self.dev2_connected = False

    def test_factory(self):
        return IProtoFactory.implementedBy(self.factory.__class__)

    def on_apimeta(self, websocket_server, server_time):
        log.msg('API Info. WebSocket server: {0}; server time: {1}.'.format(websocket_server, server_time))

    def on_closing_connection(self):
        pass

    def on_connection_failed(self, reason):
        pass

    def on_connected(self):
        log.msg('Connected to devicehive.')
        for info in self.DEVICES :
            self.connect_device(info)

    def on_failure(self, device_id, reason):
        """
        @type device_id: C{str}
        @param device_id: device guid
        """
        log.err('Unhandled error. Device: {0}. Reason: {1}.'.format(device_id, reason))

    def connect_device(self, info):
        def on_subscribe(result) :
            if info.name == 'PyExample1' :
                self.dev1_connected = True
            elif info.name == 'PythonExample2' :
                self.dev2_connected = True
            self.factory.subscribe(info.id, info.key)
        def on_failed(reason) :
            log.err('Failed to save device {0}. Reason: {1}.'.format(info, reason))
        self.factory.device_save(info).addCallbacks(on_subscribe, on_failed)

    def on_command(self, device_id, command, finished):
        if command.command == 'test_cmd' :
            finished.callback("Good news everyone! I'm still technically alive.")
        else :
            finished.errback(NotImplementedError())

    def notify1(self, name, **kwargs):
        if self.dev1_connected :
            dev = self.DEVICES[0]
            self.factory.notify(name, kwargs, dev.id, dev.key)

    def notify2(self, name, **kwargs):
        if self.dev2_connected :
            dev = self.DEVICES[1]
            self.factory.notify(name, kwargs,  dev.id, dev.key)

    def generate_devices():
        """
        Method returns a list of object each of which has to implement C{devicehive.interfaces.IDeviceInfo} interface.
        """
        net = devicehive.Network(key = 'network11', name = 'network11', descr = 'network11')
        dec = devicehive.DeviceClass(name = 'Example Device Class', version = 'Example Device Class 1.1')
        eqp = [devicehive.Equipment(name = 'Example Equipment', code = 'EXEQCO', type = 'ExampleType11'), ]
        di1 = devicehive.DeviceInfo(id = '22345678-9012-3456-7890-123456789012',
                                   key = 'net11dev1',
                                   name = 'PyExample1',
                                   status = 'Online',
                                   network = net,
                                   device_class = dec,
                                   equipment = eqp)
        di2 = devicehive.DeviceInfo(id = '13456789-0123-4567-8901-234567890123',
                                   key = 'net11dev2',
                                   name = 'PythonExample2',
                                   status = 'Online',
                                   network = net,
                                   device_class = dec,
                                   equipment = eqp)
        return (di1, di2)

    DEVICES = generate_devices()

i = 0
def looping_call(hnd):
    global i
    print ('Sending looping notification {0}.'.format(i))
    hnd.notify1('looping_notification_dev1', count = i, one_more_parameter = 'parameter_value')
    hnd.notify2('looping_notification_dev2', count = i, one_more_parameter = 'parameter_value')
    i += 1

def create_factory(use_ws, handler) :
    if use_ws is None :
        return devicehive.auto.AutoFactory(handler)
    elif use_ws :
        return devicehive.ws.WebSocketFactory(handler)
    else :
        return devicehive.poll.PollFactory(handler)

def main():
    log.startLogging(sys.stdout)
    handler = LogicHandler()
    factory = create_factory(None, handler)
    reactor.connectDeviceHive('http://ecloud.dataart.com/ecapi8/', factory)
    #
    lc = task.LoopingCall(looping_call, handler)
    lc.start(10)
    #
    reactor.run()

if __name__ == '__main__' :
    main()

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import os
#print('Process(%s) start...' % os.getpid())
#pid = os.fork()
#if pid == 0:
#    print('i am a child process (%s) and my parent is %s' % (os.getpid(),os.getppid()))
#else:
#    print('i (%s) just created a child process(%s)' % (os.getpid,pid))
#windows系统当中没有os.fork的调用，所以会报错
from multiprocessing import Process
import os

def run_proc(name):
    print('run child process %s (%s)...' % (name,os.getpid()))

#if __name__ =='__main__':
#    print('Parent process1 %s' % os.getpid())
#    p = Process(target=run_proc,args=('test',))
#    print('child process will start.')
#    p.start()
#    p.join()
#    print('child process end')
#注意，这里的父进程，就是文件执行本身的进程
#通过Process创建子进程实质上就是用Process建立一个实例，其中target参数代表子进程调用的对象，args代表给调用对象传入的参数
#对子进程实例进行p.start()操作，代表开始子进程，join方法代表阻塞当前进程，先调用子进程，执行完毕之后再执行后面的内容
#如果没有join方法，则会向下执行，在执行子进程调用的对象
#而if后面的print内容，则是if执行完毕之后会执行的内容
print('##############################')
#第二个Process实例，python文档当中的
#def info(title):
#    print(title)
#    print('module name:', __name__)
#    print('parent process:', os.getppid())
#    print('process id:', os.getpid())
#
#def f(name):
#    info('function f')
#    print('hello', name)
#
#if __name__ == '__main__':
#    info('main line')
#    p = Process(target=f, args=('bob',))
#    p.start()
#    p.join()
#这里在if后面就是按先后顺序执行，但将进程实例化成p之后，由于由join方法的存在，先执行子进程
from multiprocessing import Pool
import os,time,random

#for i in range(5):
#    print(i)
#def long_time_task(name):
#    print('run task %s (%s)' % (name,os.getpid()))
#    start = time.time()
#    time.sleep(1)
#    end = time.time()
#    print('task %s runs %0.2f seconds.' % (name,(end-start)))
#
#if __name__ == '__main__':
#    print('parent process %s' % os.getpid())
#    p = Pool(4)
#    for i in range(5):
#        p.apply_async(long_time_task,args=(i,))
#    print('waiting for all subprocess done...')
#    p.close()
#    p.join()
#    print('all subprocess done.')

#注意多进程之间的执行一定是并行的，虽然是并行的执行，但是由于long_time_task中的sleep函数存在，执行时间仍然是有区别的
#而且通过p.join方法，可知在子进程执行的时候，父进程是阻塞的，待子进程全部执行完毕，父进程才会执行完毕，所以all subprocess done是最后执行的
#由于在if当中定义了Pool(4)，所以进程池只能同时并行4个进程，由于time.sleep的存在，4个并行进程的start时间按循环的先后顺序来
#但是子进程的结束时间要看随机的sleep函数何时完毕，所以最终每个子进程执行完毕打印task runs的顺序并不一样，因为执行时间不同
#需要注意的是，由于进程池只有4个进程，而for循环当中有0-4一共5个循环过程，所以当执行完0123四个进程中最快结束的那个后（最快是由sleep方法随机决定的）
#才会执行第5个进程，即for循环当中的4号循环，同时按照执行完成的先后顺序打印执行结果
#p.apply_async是非阻塞版本的多进程执行，所以在执行子进程的时候，子进程是并行执行的，并不会等待某个子进程结束后再执行另一个，执行允许只和for执行顺序有关
#而p.close则是关闭进程池，必须，p.join代表主进程阻塞，等待子进程执行完毕之后，再执行join方法之后的主进程内容

import subprocess
#print('$ nslookup www.python.org')
#r = subprocess.call(['nslookup','www.python.org'])
#print(r)
#
#print('$ nslookup')
#p = subprocess.Popen(['nslookup'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
#output,err=p.communicate(b'set q=mx\npython.org\nexit\n')
#print(output.decode('utf-8'))
#print('exit code: ',p.returncode)
#这两个子进程的例子，用于在更复杂的子进程当中，其中call方法是popen方法的简化版本，可以快速调用系统命令，传入参数是一个list
#popen方法更加基础，可以传入一个list为命令，通过stdin,stdout,stderr获取对应的输入和输出数据
#pipe则是linux当中标准的进程通讯方式，在subprocess.Popen当中，接收stdin管道输入的数据，输出stdout和stderr当中输出的数据，需要培训communicate
#communicate接收一个参数，通过管道输入给stdin，并且返回两个参数，通过管道接收自Popen方法，即输出和报错
#所以在Popen方法之后，通过stdout管道输出到communicate方法，再通过communicate方法返回到output值，打印即结果

#例题：通过多进程ping www.baidu.com一共100次，并返回结果，看单进程耗时，和多进程耗时
#单进程耗时

def baidu_ping():
    p = subprocess.call(['ping','www.baidu.com','-c','4'])
    print(p)
    print('subprocess pid is: ', os.getpid(),os.getppid())
if __name__ == '__main__':
    s = Process(target=baidu_ping)
    s.start()
    s.join()
    print('ping pid is',os.getpid())
<commit_msg>20170312<commit_after># -*- coding: utf-8 -*-
import os
#print('Process(%s) start...' % os.getpid())
#pid = os.fork()
#if pid == 0:
#    print('i am a child process (%s) and my parent is %s' % (os.getpid(),os.getppid()))
#else:
#    print('i (%s) just created a child process(%s)' % (os.getpid,pid))
#windows系统当中没有os.fork的调用，所以会报错
from multiprocessing import Process
import os

def run_proc(name):
    print('run child process %s (%s)...' % (name,os.getpid()))

#if __name__ =='__main__':
#    print('Parent process1 %s' % os.getpid())
#    p = Process(target=run_proc,args=('test',))
#    print('child process will start.')
#    p.start()
#    p.join()
#    print('child process end')
#注意，这里的父进程，就是文件执行本身的进程
#通过Process创建子进程实质上就是用Process建立一个实例，其中target参数代表子进程调用的对象，args代表给调用对象传入的参数
#对子进程实例进行p.start()操作，代表开始子进程，join方法代表阻塞当前进程，先调用子进程，执行完毕之后再执行后面的内容
#如果没有join方法，则会向下执行，在执行子进程调用的对象
#而if后面的print内容，则是if执行完毕之后会执行的内容
print('##############################')
#第二个Process实例，python文档当中的
#def info(title):
#    print(title)
#    print('module name:', __name__)
#    print('parent process:', os.getppid())
#    print('process id:', os.getpid())
#
#def f(name):
#    info('function f')
#    print('hello', name)
#
#if __name__ == '__main__':
#    info('main line')
#    p = Process(target=f, args=('bob',))
#    p.start()
#    p.join()
#这里在if后面就是按先后顺序执行，但将进程实例化成p之后，由于由join方法的存在，先执行子进程
from multiprocessing import Pool
import os,time,random

#for i in range(5):
#    print(i)
#def long_time_task(name):
#    print('run task %s (%s)' % (name,os.getpid()))
#    start = time.time()
#    time.sleep(1)
#    end = time.time()
#    print('task %s runs %0.2f seconds.' % (name,(end-start)))
#
#if __name__ == '__main__':
#    print('parent process %s' % os.getpid())
#    p = Pool(4)
#    for i in range(5):
#        p.apply_async(long_time_task,args=(i,))
#    print('waiting for all subprocess done...')
#    p.close()
#    p.join()
#    print('all subprocess done.')

#注意多进程之间的执行一定是并行的，虽然是并行的执行，但是由于long_time_task中的sleep函数存在，执行时间仍然是有区别的
#而且通过p.join方法，可知在子进程执行的时候，父进程是阻塞的，待子进程全部执行完毕，父进程才会执行完毕，所以all subprocess done是最后执行的
#由于在if当中定义了Pool(4)，所以进程池只能同时并行4个进程，由于time.sleep的存在，4个并行进程的start时间按循环的先后顺序来
#但是子进程的结束时间要看随机的sleep函数何时完毕，所以最终每个子进程执行完毕打印task runs的顺序并不一样，因为执行时间不同
#需要注意的是，由于进程池只有4个进程，而for循环当中有0-4一共5个循环过程，所以当执行完0123四个进程中最快结束的那个后（最快是由sleep方法随机决定的）
#才会执行第5个进程，即for循环当中的4号循环，同时按照执行完成的先后顺序打印执行结果
#p.apply_async是非阻塞版本的多进程执行，所以在执行子进程的时候，子进程是并行执行的，并不会等待某个子进程结束后再执行另一个，执行允许只和for执行顺序有关
#而p.close则是关闭进程池，必须，p.join代表主进程阻塞，等待子进程执行完毕之后，再执行join方法之后的主进程内容

import subprocess
#print('$ nslookup www.python.org')
#r = subprocess.call(['nslookup','www.python.org'])
#print(r)
#
#print('$ nslookup')
#p = subprocess.Popen(['nslookup'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
#output,err=p.communicate(b'set q=mx\npython.org\nexit\n')
#print(output.decode('utf-8'))
#print('exit code: ',p.returncode)
#这两个子进程的例子，用于在更复杂的子进程当中，其中call方法是popen方法的简化版本，可以快速调用系统命令，传入参数是一个list
#popen方法更加基础，可以传入一个list为命令，通过stdin,stdout,stderr获取对应的输入和输出数据
#pipe则是linux当中标准的进程通讯方式，在subprocess.Popen当中，接收stdin管道输入的数据，输出stdout和stderr当中输出的数据，需要培训communicate
#communicate接收一个参数，通过管道输入给stdin，并且返回两个参数，通过管道接收自Popen方法，即输出和报错
#所以在Popen方法之后，通过stdout管道输出到communicate方法，再通过communicate方法返回到output值，打印即结果

#例题：通过多进程ping www.baidu.com一共100次，并返回结果，看单进程耗时，和多进程耗时
#单进程耗时

#def baidu_ping():
#    p = subprocess.call(['ping','www.baidu.com','-c','12'])
#    print(p)
#    print('subprocess pid is: ', os.getpid(),os.getppid())
#if __name__ == '__main__':
#    s = Process(target=baidu_ping)
#    s_time = time.time()
#    s.start()
#    s.join()
#    e_time = time.time()
#    print('use time %0.2f ' % (e_time-s_time))
#

#进程间通讯
from multiprocessing import Process,Queue
import os,time,random
<|endoftext|>


<commit_before>#-*- coding: utf-8 -*-
import json
import enum
from ryu.app.simple_switch_13 import SimpleSwitch13
from ryu.controller  import ofp_event, event
from ryu.controller.handler import set_ev_cls,MAIN_DISPATCHER,CONFIG_DISPATCHER
from ryu.ofproto.ofproto_v1_3 import *
from ryu.ofproto.ofproto_v1_3_parser import OFPMatch
from ryu.ofproto.ofproto_parser import *
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet, ipv4,arp
from ryu.controller import dpset
from qsys import Qsys
class SystemActionModei(enum.Enum):
   # あとでモード実装するはず？
    learn = 0
    quarantine = 1

class QsysTest(SimpleSwitch13):
    __DEBUG_MODE__ = False#T:on,F:off
	#動作モード
    #ACTION_MODE = SystemActionMode.quarantine

    def __init__(self, *args, **kwargs):
        super(QsysTest, self).__init__(*args, **kwargs)
        self.mac_to_port = {}#{[dpid][addr] = in_port}

    #コントローラにSWが接続される
    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        self.logger.info("Simple_Switch13_features")
        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)
    #Packet_inのハンドラが呼ばれる
    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        #パケットから送信元のIP・MAC・宛先のIP・MAC・dataを取得
        allowTransportFlag = False
        msg = ev.msg
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        #送信元MACと送信元SWのポートの対応関係を記録
        self.mac_to_port.setdefault(dpid, {})
        pkt = packet.Packet(msg.data)
        if self.__DEBUG_MODE__:
            self.logger.info("packet-in {}".format(pkt))
        _eth = pkt.get_protocol(ethernet.ethernet)
        if not _eth:
            self.logger.info("Not Ether type")
            return
        #スイッチのポート
        in_port = msg.match['in_port']
        #[swのid][MACAddr]のテーブルにSwitch input portを登録
        self.mac_to_port[dpid][_eth.src] = in_port
#        pkt_head = packet.packet_base.PacketBase(msg.data)
#       pkt_head.get_packet_type()
        _ipv4 = pkt.get_protocol(ipv4.ipv4)
        if not _ipv4:
            _arp = pkt.get_protocol(arp.arp)

        pkt_dict = {
            'src':_eth.src,
            'dst':_eth.dst,
            'data':msg.data,
            }
        #pkt_json = json.dumps(pkt_dict, sort_keys=True)

        if not self.send_qsys(pkt_dict):#通信許可T/Fを返す
            logger.info('Drop:{}'.format(pkt_dict))
            return
        #Transport to dst
        #print('Transport:{}⇢{}'.format(packet.ipv4_src))
        if self.__DEBUG_MODE__:
            self.logger.info('json:{}'.format(json.dumps(ev.msg.to_jsondict(), ensure_ascii=True,
                                  indent=3, sort_keys=True)))
        #該当するSWの中にMacAddrがあるか？
        if _eth.dst in self.mac_to_port[dpid]:
            #Switch output portをテーブルから指定
            out_port = self.mac_to_port[dpid][_eth.dst]
        else:
            #フラッディング
            out_port = ofproto.OFPP_FLOOD
        actions = [parser.OFPActionOutput(out_port)]
        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port,
            actions=actions, data=msg.data)
        datapath.send_msg(out)

    def send_qsys(self, pkt_dict):
        self.logger.info("Qsys_in{}".format(pkt_dict))
        res = Qsys(pkt_dict)
        if res == True:
            return True
        else:
            return False
<commit_msg>no message<commit_after>#-*- coding: utf-8 -*-
import json
import enum
from ryu.app.simple_switch_13 import SimpleSwitch13
from ryu.controller  import ofp_event, event
from ryu.controller.handler import set_ev_cls,MAIN_DISPATCHER,CONFIG_DISPATCHER
from ryu.ofproto.ofproto_v1_3 import *
from ryu.ofproto.ofproto_v1_3_parser import OFPMatch
from ryu.ofproto.ofproto_parser import *
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet, ipv4,arp
from ryu.controller import dpset
from qsys import Qsys
class SystemActionModei(enum.Enum):
   # あとでモード実装するはず？
    learn = 0
    quarantine = 1

class QsysTest(SimpleSwitch13):
    __DEBUG_MODE__ = False#T:on,F:off
	#動作モード
    #ACTION_MODE = SystemActionMode.quarantine

    def __init__(self, *args, **kwargs):
        super(QsysTest, self).__init__(*args, **kwargs)
        self.mac_to_port = {}#{[dpid][addr] = in_port}

    #コントローラにSWが接続される
    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        self.logger.info("Simple_Switch13_features")
        # install table-miss flow entry
        #
        # We specify NO BUFFER to max_len of the output action due to
        # OVS bug. At this moment, if we specify a lesser number, e.g.,
        # 128, OVS will send Packet-In with invalid buffer_id and
        # truncated packet data. In that case, we cannot output packets
        # correctly.  The bug has been fixed in OVS v2.1.0.
        match = parser.OFPMatch()
        actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
                                          ofproto.OFPCML_NO_BUFFER)]
        self.add_flow(datapath, 0, match, actions)
    #Packet_inのハンドラが呼ばれる
    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def _packet_in_handler(self, ev):
        #パケットから送信元のIP・MAC・宛先のIP・MAC・dataを取得
        allowTransportFlag = False
        msg = ev.msg
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        #送信元MACと送信元SWのポートの対応関係を記録
        self.mac_to_port.setdefault(dpid, {})
        pkt = packet.Packet(msg.data)
        if self.__DEBUG_MODE__:
            self.logger.info("packet-in {}".format(pkt))
        _eth = pkt.get_protocol(ethernet.ethernet)
        if not _eth:
            self.logger.info("Not Ether type")
            return
        #スイッチのポート
        in_port = msg.match['in_port']
        #[swのid][MACAddr]のテーブルにSwitch input portを登録
        self.mac_to_port[dpid][_eth.src] = in_port
#        pkt_head = packet.packet_base.PacketBase(msg.data)
#       pkt_head.get_packet_type()
        _ipv4 = pkt.get_protocol(ipv4.ipv4)
        if not _ipv4:
            _arp = pkt.get_protocol(arp.arp)

        pkt_dict = {
            'src':_eth.src,
            'dst':_eth.dst,
            'data':msg.data,
            }
        #pkt_json = json.dumps(pkt_dict, sort_keys=True)

        if not self.send_qsys(pkt_dict):#通信許可T/Fを返す
            self.logger.info('Drop:{}'.format(pkt_dict))
            return
        #Transport to dst
        #print('Transport:{}⇢{}'.format(packet.ipv4_src))
        if self.__DEBUG_MODE__:
            self.logger.info('json:{}'.format(json.dumps(ev.msg.to_jsondict(), ensure_ascii=True,
                                  indent=3, sort_keys=True)))
        #該当するSWの中にMacAddrがあるか？
        if _eth.dst in self.mac_to_port[dpid]:
            #Switch output portをテーブルから指定
            out_port = self.mac_to_port[dpid][_eth.dst]
        else:
            #フラッディング
            out_port = ofproto.OFPP_FLOOD
        actions = [parser.OFPActionOutput(out_port)]
        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath, buffer_id=msg.buffer_id, in_port=in_port,
            actions=actions, data=msg.data)
        datapath.send_msg(out)

    def send_qsys(self, pkt_dict):
        self.logger.info("Qsys_in{}".format(pkt_dict))
        res = Qsys(pkt_dict)
        if res == True:
            return True
        else:
            return False
<|endoftext|>


<commit_before>#!/usr/bin/env python
from os.path import dirname, realpath, join
import IPython
from gap.utils.setup import fix_sys_path, build_stubs

app_path = join(realpath(dirname(dirname(__file__))), 'src')
fix_sys_path(app_path)
build_stubs()

IPython.embed()
<commit_msg>project ipython now uses googles testbed stubs<commit_after>#!/usr/bin/env python
import sys
from os.path import dirname, realpath, join
import IPython
from gap.utils.setup import fix_sys_path, setup_testbed, setup_stubs

app_path = join(realpath(dirname(dirname(__file__))), 'src')
fix_sys_path(app_path)
TESTBED = setup_testbed()

# preimport common google apis
from google.appengine.api.urlfetch import fetch
from google.appengine.ext import db, ndb
from google.appengine.api import memcache

IPython.embed()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from telegram.ext import (
    Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
    ConversationHandler)

with open('../conf', 'r') as conf:
    TOKEN = conf.read()

# STATES
WAIT_FOR_TASK, WRITING_TASK = 1, 2

def start(bot, update):
    bot.sendMessage(update.message.chat_id, text=u'Принимаю описание задачи')
    return WRITING_TASK

def cancel(bot, update):
    bot.sendMessage(update.message.chat_id,
                    text='Canceled')
    return ConversationHandler.END

def _help(bot, update):
    bot.sendMessage(update.message.chat_id, text=u'Справка')
    return WAIT_FOR_TASK

def error(bot, update, error):
    pass

def foo(bot, update):
    return WAIT_FOR_TASK

# def gender(bot, update):
#     user = update.message.from_user
#     logger.info("Gender of %s: %s" % (user.first_name, update.message.text))
#     bot.sendMessage(update.message.chat_id,
#                     text='I see! Please send me a photo of yourself, '
#                          'so I know what you look like, or send /skip if you don\'t want to.')
#
#     return PHOTO

def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater(TOKEN)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start),
                      CommandHandler('help', _help)],

        states={
            WRITING_TASK: [RegexHandler('^(Boy|Girl|Other)$', foo)],

            WAIT_FOR_TASK: [MessageHandler([Filters.text], start),
                    CommandHandler('cancel', cancel)],

            # LOCATION: [MessageHandler([Filters.location], location),
            #            CommandHandler('skip', skip_location)],
            #
            # BIO: [MessageHandler([Filters.text], bio)]
        },

        fallbacks=[CommandHandler('cancel', cancel)]
    )

    dp.add_handler(conv_handler)

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()<commit_msg>some work<commit_after># -*- coding: utf-8 -*-
from telegram.ext import (
    Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
    ConversationHandler)

with open('../conf', 'r') as conf:
    TOKEN = conf.read()

TEXT = u''

# STATES
DO_SOMETHING= 1

def start(bot, update):
    bot.sendMessage(update.message.chat_id, 'started')
    return DO_SOMETHING

def stop(bot, update):
    bot.sendMessage(update.message.chat_id, 'Ended')
    return ConversationHandler.END

def cancel(bot, update):
    bot.sendMessage(update.message.chat_id, text='Canceled')
    return ConversationHandler.END

def do_something(bot, update):
    bot.sendMessage(update.message.chat_id, update.message.text)
    bot.sendMessage(update.message.chat_id, 'do something')
    return DO_SOMETHING

def main():
    # Create the EventHandler and pass it your bot's token.
    updater = Updater(TOKEN)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # Add conversation handler with the states GENDER, PHOTO, LOCATION and BIO
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        allow_reentry=True,

        states={
            DO_SOMETHING: [MessageHandler([Filters.text], do_something),
                           CommandHandler('stop', stop)],
        },

        fallbacks=[CommandHandler('cancel', cancel)]
    )

    dp.add_handler(conv_handler)

    # log all errors
    # dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from socket import setdefaulttimeout
from json import loads as load_json
from datetime import datetime
from twitter import Twitter, TwitterStream, OAuth, OAuth2
from pypump import PyPump
from gazouilleur import config
from gazouilleur.lib.log import *
from gazouilleur.lib.utils import *

class Microblog():

    def __init__(self, site, conf, bearer_token=None, get_token=False, streaming=False):
        self.site = site.lower()
        self.conf = conf[site.upper()]
        # Identi.ca service only supported for commands "ping" and "microblog"
        if self.site == "identica":
            self.domain = "identi.ca"
            self.api_version = "api"
            # Old Status.net Identi.ca connection:
            #self.auth = UserPassAuth(self.conf['USER'], self.conf['PASS'])
            #self.conn = Twitter(domain=self.domain, api_version=self.api_version, auth=self.auth)
            # New Pump.io Identi.ca connection:
            self.user = "%s@%s" % (self.conf['USER'].lower(), self.domain)
            from gazouilleur.identica_auth_config import identica_auth
            self.conf.update(identica_auth[self.conf['USER'].lower()])
            self.conn = PyPump(self.user, key=self.conf['key'], secret=self.conf['secret'], token=self.conf['token'], token_secret=self.conf['token_secret'])
        elif self.site == "twitter":
            if 'USER' in self.conf:
                self.user = self.conf['USER']
            self.domain = "api.twitter.com"
            if get_token:
                self.api_version = None
                self.format = ""
                self.auth = OAuth2(self.conf['KEY'], self.conf['SECRET'])
            else:
                self.api_version = config.TWITTER_API_VERSION
                self.format = "json"
                if bearer_token:
                    self.auth = OAuth2(bearer_token=bearer_token)
                else:
                    self.auth = OAuth(self.conf['OAUTH_TOKEN'], self.conf['OAUTH_SECRET'], self.conf['KEY'], self.conf['SECRET'])
            args = {"api_version": self.api_version, "auth": self.auth, "secure": True}
            if streaming:
                self.domain = "stream.twitter.com"
                conn = TwitterStream
                args["block"] = False
            else:
                conn = Twitter
                args['format'] = self.format
            args['domain'] = self.domain
            self.conn = conn(**args)

    def get_oauth2_token(self):
        res = self.conn.oauth2.token(grant_type="client_credentials")
        obj = load_json(res)
        if "token_type" not in obj or obj["token_type"] != "bearer" or "access_token" not in obj:
            raise Exception("Wrong token type given by twitter, weird : %s" % res)
        return obj["access_token"]

    def _send_query(self, function, args={}, tryout=0, previous_exception=None, return_result=False, channel=None):
        if tryout > 2:
            return previous_exception
        try:
            if not return_result:
                args['trim_user'] = 'true'
            args['source'] = config.BOTNAME
            setdefaulttimeout(35)
            res = function(**args)
            if return_result:
                return res
            elif config.DEBUG:
                loggvar("%s %s" % (res['text'].encode('utf-8'), args), action=self.site)
            if self.site == 'twitter' and channel and 'id_str' in res:
                save_lasttweet_id(channel, res['id_str'])
            return "[%s] Huge success!" % self.site
        except Exception as e:
            exc_str = str(e).lower()
            pos = exc_str.find('status 4') + 7
            if pos != 6:
                code = int(exc_str[pos:pos+3])
                if code == 404:
                    err = "[%s] ERROR: Not Found: %s." % (self.site, code)
                elif code == 501:
                    err = "[%s] WARNING: Not responding: %s." % (self.site, code)
                else:
                    err = "[%s] WARNING: Forbidden: %s. Check your commands (already done? forbidden?) or take a breather and wait a bit, you may have overpassed Twitter's API 15min limits." % (self.site, code)
                return err
            exception = "[%s] %s" % (self.site, sending_error(e))
            if config.DEBUG and exception != previous_exception:
                try:
                    loggerr("%s: http://%s/%s.%s %s" % (exception, self.domain, e.uri, e.format, args), action=self.site)
                except:
                    print exception, e, args
            return self._send_query(function, args, tryout+1, exception, return_result)

    def ping(self):
        setdefaulttimeout(35)
        try:
            if self.site == "identica":
                return "%s@%s" % (self.conn.Person(self.user).username, self.domain) == self.user
            creds = self.conn.account.verify_credentials(include_entities='false', skip_status='true')
            dms = ("FORBID_POST" not in self.conf or str(self.conf["FORBID_POST"]).lower() != "true") or isinstance(check_twitter_results(self.get_dms()), list)
            if config.DEBUG and not (creds and dms):
                raise Exception("%s\n%s" % (creds, dms))
            return creds is not None and dms
        except Exception as e:
            if config.DEBUG:
                loggerr("Ping failed: %s" % e, action=self.site)
            return False

    def microblog(self, text="", tweet_id=None, channel=None):
        if text.startswith("%scount" % config.COMMAND_CHARACTER):
            text = text.replace("%scount" % config.COMMAND_CHARACTER, "").strip()
        if self.site == "identica":
            try:
                note = self.conn.Note(text)
                note.to = (self.conn.Public, self.conn.Followers, self.conn.Following)
                note.send()
                return "[identica] Huge success!"
            except Exception as e:
                if "[Errno 111] Connection refused" in str(e):
                    err_msg = "https://identi.ca seems down"
                else:
                    err_msg = sending_error(e)
                exception = "[identica] %s" % err_msg
                if config.DEBUG:
                    loggerr("%s %s" % (exception, e), action=self.site)
                return exception
        text = text.replace('~', '~')
        args = {'status': text}
        if tweet_id:
            args['in_reply_to_status_id'] = tweet_id
        return self._send_query(self.conn.statuses.update, args, channel=channel)

    def delete(self, tweet_id):
        return self._send_query(self.conn.statuses.destroy, {'id': tweet_id})

    def retweet(self, tweet_id, channel=None):
        return self._send_query(self.conn.statuses.retweet, {'id': tweet_id}, channel=channel)

    def show_status(self, tweet_id):
        return self._send_query(self.conn.statuses.show, {'id': tweet_id}, return_result=True)

    def get_mytweets(self, **kwargs):
        return self._send_query(self.conn.statuses.user_timeline, {'screen_name': self.user, 'count': 15, 'include_rts': 'true'}, return_result=True)

    def get_mentions(self, **kwargs):
        return self._send_query(self.conn.statuses.mentions_timeline, {'count': 200, 'include_entities': 'false'}, return_result=True)

    def get_retweets(self, retweets_processed={}, bearer_token=None, **kwargs):
        tweets = self._send_query(self.conn.statuses.retweets_of_me, {'count': 50, 'trim_user': 'true', 'include_entities': 'false', 'include_user_entities': 'false'}, return_result=True)
        done = 0
        retweets = []
        check_twitter_results(tweets)
        if bearer_token:
            helper = Microblog("twitter", {"TWITTER": self.conf}, bearer_token=bearer_token)
            limitfactor = 4
        else:
            helper = self
            limitfactor = 1
        for tweet in tweets:
            if tweet['id_str'] not in retweets_processed or tweet['retweet_count'] > retweets_processed[tweet['id_str']]:
                new_rts = helper.get_retweets_by_id(tweet['id'])
                if "Forbidden: " in new_rts:
                    break
                retweets += new_rts
                done += 1
            retweets_processed[tweet['id_str']] = tweet['retweet_count']
            if done >= limitfactor*config.TWITTER_API_LIMIT:
                break
        return retweets, retweets_processed

    def get_retweets_by_id(self, tweet_id, **kwargs):
        return self._send_query(self.conn.statuses.retweets, {'id': tweet_id, 'count': 100}, return_result=True)

    def directmsg(self, user, text):
        text = text.replace('~', '~')
        return self._send_query(self.conn.direct_messages.new, {'user': user, 'text': text})

    def get_dms(self, **kwargs):
        return self._send_query(self.conn.direct_messages, return_result=True)

    def get_stats(self, db=None, **kwargs):
        timestamp = timestamp_hour(datetime.today())
        db.authenticate(config.MONGODB['USER'], config.MONGODB['PSWD'])
        last = db['stats'].find_one({'user': self.user.lower()}, sort=[('timestamp', pymongo.DESCENDING)])
        if last and timestamp == last['timestamp']:
            res = None
        elif self.api_version == 1:
            res = self._send_query(self.conn.account.totals, return_result=True)
        else:
            res = self._send_query(self.conn.users.show, {'screen_name': self.user}, return_result=True)
        check_twitter_results(res)
        return res, last, timestamp

    def search(self, query, count=50, max_id=None):
        args = {'q': query, 'count': count, 'include_entities': 'false', 'result_type': 'recent'}
        if max_id:
            args['max_id'] = max_id
        return self._send_query(self.conn.search.tweets, args, return_result=True)

    def search_stream(self, follow=[], track=[]):
        if not "stream" in self.domain or not len(follow) + len(track):
            return None
        args = {'filter_level': 'none'}
        if track:
            args['track'] = ",".join(track)
        if follow:
            args['follow']= ",".join(follow)
        if config.DEBUG:
            loggvar(args, action="stream")
        return self.conn.statuses.filter(**args)

    def search_users(self, list_users, cache_users={}):
        good = {}
        todo = []
        for name in list_users:
            name = name.lower().lstrip('@')
            if name in cache_users:
                good[name] = cache_users[name]
            else:
                todo.append(name)
        users = self._send_query(self.conn.users.lookup, {'screen_name': ','.join(todo), 'include_entities': 'false'}, return_result=True)
        if "Forbidden" in users or "404" in users:
            return good, cache_users
        for u in users:
            name = u['screen_name'].lower()
            if name in list_users:
                good[name] = u['id_str']
        cache_users.update(good)
        return good, cache_users

    re_twitter_account = re.compile('(^|\W)@([A-Za-z0-9_]{1,15})')
    def test_microblog_users(self, text, cache_users={}):
        match = self.re_twitter_account.findall(text)
        if not len(match):
            return True, cache_users, "No user quoted"
        check = []
        for _, m in match:
            user = m.lower().lstrip('@')
            if user not in cache_users:
                check.append(user)
        good, cache_users = self.search_users(check, cache_users)
        for user in check:
            if user not in good.keys():
                return False, cache_users, "Sorry but @%s doesn't seem like a real account. Please correct your tweet of force by adding --force" % user
        return True, cache_users, "All users quoted passed"

def check_twitter_results(data):
    text = data
    if not isinstance(text, str):
        try:
            text = text[0]
        except:
            pass
    if text and isinstance(text, str) and ("WARNING" in text or "RROR" in text):
        raise(Exception(text))
    return data

def grab_extra_meta(source, result):
    for meta in ["in_reply_to_status_id_str", "in_reply_to_screen_name", "lang", "geo", "coordinates", "source"]:
        if meta in source:
            result[meta] = source [meta]
    for meta in ['name', 'friends_count', 'followers_count', 'statuses_count', 'listed_count']:
        key = "user_%s" % meta.replace('_count', '')
        if key in source:
            result[key] = source[key]
        elif 'user' in source and meta in source['user']:
            result[key] = source['user'][meta]
    return result

<commit_msg>fix missing rts<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from socket import setdefaulttimeout
from json import loads as load_json
from datetime import datetime
from twitter import Twitter, TwitterStream, OAuth, OAuth2
from pypump import PyPump
from gazouilleur import config
from gazouilleur.lib.log import *
from gazouilleur.lib.utils import *

class Microblog():

    def __init__(self, site, conf, bearer_token=None, get_token=False, streaming=False):
        self.site = site.lower()
        self.conf = conf[site.upper()]
        # Identi.ca service only supported for commands "ping" and "microblog"
        if self.site == "identica":
            self.domain = "identi.ca"
            self.api_version = "api"
            # Old Status.net Identi.ca connection:
            #self.auth = UserPassAuth(self.conf['USER'], self.conf['PASS'])
            #self.conn = Twitter(domain=self.domain, api_version=self.api_version, auth=self.auth)
            # New Pump.io Identi.ca connection:
            self.user = "%s@%s" % (self.conf['USER'].lower(), self.domain)
            from gazouilleur.identica_auth_config import identica_auth
            self.conf.update(identica_auth[self.conf['USER'].lower()])
            self.conn = PyPump(self.user, key=self.conf['key'], secret=self.conf['secret'], token=self.conf['token'], token_secret=self.conf['token_secret'])
        elif self.site == "twitter":
            if 'USER' in self.conf:
                self.user = self.conf['USER']
            self.domain = "api.twitter.com"
            if get_token:
                self.api_version = None
                self.format = ""
                self.auth = OAuth2(self.conf['KEY'], self.conf['SECRET'])
            else:
                self.api_version = config.TWITTER_API_VERSION
                self.format = "json"
                if bearer_token:
                    self.auth = OAuth2(bearer_token=bearer_token)
                else:
                    self.auth = OAuth(self.conf['OAUTH_TOKEN'], self.conf['OAUTH_SECRET'], self.conf['KEY'], self.conf['SECRET'])
            args = {"api_version": self.api_version, "auth": self.auth, "secure": True}
            if streaming:
                self.domain = "stream.twitter.com"
                conn = TwitterStream
                args["block"] = False
            else:
                conn = Twitter
                args['format'] = self.format
            args['domain'] = self.domain
            self.conn = conn(**args)

    def get_oauth2_token(self):
        res = self.conn.oauth2.token(grant_type="client_credentials")
        obj = load_json(res)
        if "token_type" not in obj or obj["token_type"] != "bearer" or "access_token" not in obj:
            raise Exception("Wrong token type given by twitter, weird : %s" % res)
        return obj["access_token"]

    def _send_query(self, function, args={}, tryout=0, previous_exception=None, return_result=False, channel=None):
        if tryout > 2:
            return previous_exception
        try:
            if not return_result:
                args['trim_user'] = 'true'
            args['source'] = config.BOTNAME
            setdefaulttimeout(35)
            res = function(**args)
            if return_result:
                return res
            elif config.DEBUG:
                loggvar("%s %s" % (res['text'].encode('utf-8'), args), action=self.site)
            if self.site == 'twitter' and channel and 'id_str' in res:
                save_lasttweet_id(channel, res['id_str'])
            return "[%s] Huge success!" % self.site
        except Exception as e:
            exc_str = str(e).lower()
            pos = exc_str.find('status 4') + 7
            if pos != 6:
                code = int(exc_str[pos:pos+3])
                if code == 404:
                    err = "[%s] ERROR: Not Found: %s." % (self.site, code)
                elif code == 501:
                    err = "[%s] WARNING: Not responding: %s." % (self.site, code)
                else:
                    err = "[%s] WARNING: Forbidden: %s. Check your commands (already done? forbidden?) or take a breather and wait a bit, you may have overpassed Twitter's API 15min limits." % (self.site, code)
                return err
            exception = "[%s] %s" % (self.site, sending_error(e))
            if config.DEBUG and exception != previous_exception:
                try:
                    loggerr("%s: http://%s/%s.%s %s" % (exception, self.domain, e.uri, e.format, args), action=self.site)
                except:
                    print exception, e, args
            return self._send_query(function, args, tryout+1, exception, return_result)

    def ping(self):
        setdefaulttimeout(35)
        try:
            if self.site == "identica":
                return "%s@%s" % (self.conn.Person(self.user).username, self.domain) == self.user
            creds = self.conn.account.verify_credentials(include_entities='false', skip_status='true')
            dms = ("FORBID_POST" not in self.conf or str(self.conf["FORBID_POST"]).lower() != "true") or isinstance(check_twitter_results(self.get_dms()), list)
            if config.DEBUG and not (creds and dms):
                raise Exception("%s\n%s" % (creds, dms))
            return creds is not None and dms
        except Exception as e:
            if config.DEBUG:
                loggerr("Ping failed: %s" % e, action=self.site)
            return False

    def microblog(self, text="", tweet_id=None, channel=None):
        if text.startswith("%scount" % config.COMMAND_CHARACTER):
            text = text.replace("%scount" % config.COMMAND_CHARACTER, "").strip()
        if self.site == "identica":
            try:
                note = self.conn.Note(text)
                note.to = (self.conn.Public, self.conn.Followers, self.conn.Following)
                note.send()
                return "[identica] Huge success!"
            except Exception as e:
                if "[Errno 111] Connection refused" in str(e):
                    err_msg = "https://identi.ca seems down"
                else:
                    err_msg = sending_error(e)
                exception = "[identica] %s" % err_msg
                if config.DEBUG:
                    loggerr("%s %s" % (exception, e), action=self.site)
                return exception
        text = text.replace('~', '~')
        args = {'status': text}
        if tweet_id:
            args['in_reply_to_status_id'] = tweet_id
        return self._send_query(self.conn.statuses.update, args, channel=channel)

    def delete(self, tweet_id):
        return self._send_query(self.conn.statuses.destroy, {'id': tweet_id})

    def retweet(self, tweet_id, channel=None):
        return self._send_query(self.conn.statuses.retweet, {'id': tweet_id}, channel=channel)

    def show_status(self, tweet_id):
        return self._send_query(self.conn.statuses.show, {'id': tweet_id}, return_result=True)

    def get_mytweets(self, **kwargs):
        return self._send_query(self.conn.statuses.user_timeline, {'screen_name': self.user, 'count': 15, 'include_rts': 1}, return_result=True)

    def get_mentions(self, **kwargs):
        return self._send_query(self.conn.statuses.mentions_timeline, {'count': 200, 'include_entities': 'false', 'include_rts': 1}, return_result=True)

    def get_retweets(self, retweets_processed={}, bearer_token=None, **kwargs):
        tweets = self._send_query(self.conn.statuses.retweets_of_me, {'count': 50, 'trim_user': 'true', 'include_entities': 'false', 'include_user_entities': 'false'}, return_result=True)
        done = 0
        retweets = []
        check_twitter_results(tweets)
        if bearer_token:
            helper = Microblog("twitter", {"TWITTER": self.conf}, bearer_token=bearer_token)
            limitfactor = 4
        else:
            helper = self
            limitfactor = 1
        for tweet in tweets:
            if tweet['id_str'] not in retweets_processed or tweet['retweet_count'] > retweets_processed[tweet['id_str']]:
                new_rts = helper.get_retweets_by_id(tweet['id'])
                if "Forbidden: " in new_rts:
                    break
                retweets += new_rts
                done += 1
            retweets_processed[tweet['id_str']] = tweet['retweet_count']
            if done >= limitfactor*config.TWITTER_API_LIMIT:
                break
        return retweets, retweets_processed

    def get_retweets_by_id(self, tweet_id, **kwargs):
        return self._send_query(self.conn.statuses.retweets, {'id': tweet_id, 'count': 100}, return_result=True)

    def directmsg(self, user, text):
        text = text.replace('~', '~')
        return self._send_query(self.conn.direct_messages.new, {'user': user, 'text': text})

    def get_dms(self, **kwargs):
        return self._send_query(self.conn.direct_messages, return_result=True)

    def get_stats(self, db=None, **kwargs):
        timestamp = timestamp_hour(datetime.today())
        db.authenticate(config.MONGODB['USER'], config.MONGODB['PSWD'])
        last = db['stats'].find_one({'user': self.user.lower()}, sort=[('timestamp', pymongo.DESCENDING)])
        if last and timestamp == last['timestamp']:
            res = None
        elif self.api_version == 1:
            res = self._send_query(self.conn.account.totals, return_result=True)
        else:
            res = self._send_query(self.conn.users.show, {'screen_name': self.user}, return_result=True)
        check_twitter_results(res)
        return res, last, timestamp

    def search(self, query, count=50, max_id=None):
        args = {'q': query, 'count': count, 'include_entities': 'false', 'result_type': 'recent'}
        if max_id:
            args['max_id'] = max_id
        return self._send_query(self.conn.search.tweets, args, return_result=True)

    def search_stream(self, follow=[], track=[]):
        if not "stream" in self.domain or not len(follow) + len(track):
            return None
        args = {'filter_level': 'none'}
        if track:
            args['track'] = ",".join(track)
        if follow:
            args['follow']= ",".join(follow)
        if config.DEBUG:
            loggvar(args, action="stream")
        return self.conn.statuses.filter(**args)

    def search_users(self, list_users, cache_users={}):
        good = {}
        todo = []
        for name in list_users:
            name = name.lower().lstrip('@')
            if name in cache_users:
                good[name] = cache_users[name]
            else:
                todo.append(name)
        users = self._send_query(self.conn.users.lookup, {'screen_name': ','.join(todo), 'include_entities': 'false'}, return_result=True)
        if "Forbidden" in users or "404" in users:
            return good, cache_users
        for u in users:
            name = u['screen_name'].lower()
            if name in list_users:
                good[name] = u['id_str']
        cache_users.update(good)
        return good, cache_users

    re_twitter_account = re.compile('(^|\W)@([A-Za-z0-9_]{1,15})')
    def test_microblog_users(self, text, cache_users={}):
        match = self.re_twitter_account.findall(text)
        if not len(match):
            return True, cache_users, "No user quoted"
        check = []
        for _, m in match:
            user = m.lower().lstrip('@')
            if user not in cache_users:
                check.append(user)
        good, cache_users = self.search_users(check, cache_users)
        for user in check:
            if user not in good.keys():
                return False, cache_users, "Sorry but @%s doesn't seem like a real account. Please correct your tweet of force by adding --force" % user
        return True, cache_users, "All users quoted passed"

def check_twitter_results(data):
    text = data
    if not isinstance(text, str):
        try:
            text = text[0]
        except:
            pass
    if text and isinstance(text, str) and ("WARNING" in text or "RROR" in text):
        raise(Exception(text))
    return data

def grab_extra_meta(source, result):
    for meta in ["in_reply_to_status_id_str", "in_reply_to_screen_name", "lang", "geo", "coordinates", "source"]:
        if meta in source:
            result[meta] = source [meta]
    for meta in ['name', 'friends_count', 'followers_count', 'statuses_count', 'listed_count']:
        key = "user_%s" % meta.replace('_count', '')
        if key in source:
            result[key] = source[key]
        elif 'user' in source and meta in source['user']:
            result[key] = source['user'][meta]
    return result

<|endoftext|>


<commit_before>from collections import OrderedDict

from sympy import Eq

from devito.ir.support import Interval, DataSpace, IterationSpace, Stencil
from devito.symbolics import dimension_sort, indexify

__all__ = ['LoweredEq']

class EqMixin(object):

    """
    A mixin providing operations common to all :mod:`ir` equation types.
    """

    @property
    def is_Scalar(self):
        return self.lhs.is_Symbol

    @property
    def is_Tensor(self):
        return self.lhs.is_Indexed

class LoweredEq(Eq, EqMixin):

    """
    LoweredEq(expr, subs=None)

    A SymPy equation with associated iteration and data spaces.

    All :class:`Function` objects within ``expr`` get indexified and thus turned
    into objects of type :class:`types.Indexed`.

    The data space is an object of type :class:`DataSpace`. It represents the
    data points accessed by the equation along each :class:`Dimension`. The
    :class:`Dimension`s are extracted directly from the equation.

    The iteration space is an object of type :class:`IterationSpace`. It
    represents the iteration points along each :class:`Dimension` that the
    equation may traverse with the guarantee that no out-of-bounds accesses
    will be performed.
    """

    def __new__(cls, *args, **kwargs):
        # Parse input
        if len(args) == 1:
            input_expr = args[0]
            assert type(input_expr) != LoweredEq
            assert isinstance(input_expr, Eq)
        elif len(args) == 2:
            # Reconstructing from existing Eq. E.g., we end up here after xreplace
            expr = super(Eq, cls).__new__(cls, *args, evaluate=False)
            stamp = kwargs.get('stamp')
            assert isinstance(stamp, Eq)
            expr.is_Increment = stamp.is_Increment
            expr.dspace = stamp.dspace
            expr.ispace = stamp.ispace
            return expr
        else:
            raise ValueError("Cannot construct Eq from args=%s "
                             "and kwargs=%s" % (str(args), str(kwargs)))

        # Indexification
        expr = indexify(input_expr)

        # Apply caller-provided substitution
        subs = kwargs.get('subs')
        if subs is not None:
            expr = expr.xreplace(subs)

        expr = super(LoweredEq, cls).__new__(cls, expr.lhs, expr.rhs, evaluate=False)
        expr.is_Increment = getattr(input_expr, 'is_Increment', False)

        # Get the accessed data points
        stencil = Stencil(expr)

        # Well-defined dimension ordering
        ordering = dimension_sort(expr, key=lambda i: not i.is_Time)

        # Split actual Intervals (the data spaces) from the "derived" iterators,
        # to build an IterationSpace
        iterators = OrderedDict()
        for i in ordering:
            if i.is_Derived:
                iterators.setdefault(i.parent, []).append(stencil.entry(i))
            else:
                iterators.setdefault(i, [])
        intervals = []
        for k, v in iterators.items():
            offs = set.union(set(stencil.get(k)), *[i.ofs for i in v])
            intervals.append(Interval(k, min(offs), max(offs)))

        # Data space and Iteration space
        expr.dspace = DataSpace(intervals)
        expr.ispace = IterationSpace([i.negate() for i in intervals], iterators)

        return expr

    def xreplace(self, rules):
        return Eq(self.lhs.xreplace(rules), self.rhs.xreplace(rules), stamp=self)
<commit_msg>regions: Use the region information in LoweredEq<commit_after>from collections import OrderedDict

from sympy import Eq

from devito.dimension import SubDimension
from devito.ir.support import Interval, DataSpace, IterationSpace, Stencil
from devito.region import DOMAIN, INTERIOR
from devito.symbolics import dimension_sort, indexify

__all__ = ['LoweredEq']

class EqMixin(object):

    """
    A mixin providing operations common to all :mod:`ir` equation types.
    """

    @property
    def is_Scalar(self):
        return self.lhs.is_Symbol

    @property
    def is_Tensor(self):
        return self.lhs.is_Indexed

class LoweredEq(Eq, EqMixin):

    """
    LoweredEq(expr, subs=None)

    A SymPy equation with associated iteration and data spaces.

    All :class:`Function` objects within ``expr`` get indexified and thus turned
    into objects of type :class:`types.Indexed`.

    The data space is an object of type :class:`DataSpace`. It represents the
    data points accessed by the equation along each :class:`Dimension`. The
    :class:`Dimension`s are extracted directly from the equation.

    The iteration space is an object of type :class:`IterationSpace`. It
    represents the iteration points along each :class:`Dimension` that the
    equation may traverse with the guarantee that no out-of-bounds accesses
    will be performed.
    """

    def __new__(cls, *args, **kwargs):
        # Parse input
        if len(args) == 1:
            input_expr = args[0]
            assert type(input_expr) != LoweredEq
            assert isinstance(input_expr, Eq)
        elif len(args) == 2:
            # Reconstructing from existing Eq. E.g., we end up here after xreplace
            expr = super(Eq, cls).__new__(cls, *args, evaluate=False)
            stamp = kwargs.get('stamp')
            assert isinstance(stamp, Eq)
            expr.is_Increment = stamp.is_Increment
            expr.dspace = stamp.dspace
            expr.ispace = stamp.ispace
            return expr
        else:
            raise ValueError("Cannot construct Eq from args=%s "
                             "and kwargs=%s" % (str(args), str(kwargs)))

        # Indexification
        expr = indexify(input_expr)

        # Apply caller-provided substitution
        subs = kwargs.get('subs')
        if subs is not None:
            expr = expr.xreplace(subs)

        # Well-defined dimension ordering
        ordering = dimension_sort(expr, key=lambda i: not i.is_Time)

        # Introduce space sub-dimensions if need to
        region = getattr(input_expr, '_region', DOMAIN)
        if region == INTERIOR:
            mapper = {i: SubDimension("%si" % i, i, 1, -1)
                      for i in ordering if i.is_Space}
            expr = expr.xreplace(mapper)
            ordering = [mapper.get(i, i) for i in ordering]

        # Get the accessed data points
        stencil = Stencil(expr)

        # Split actual Intervals (the data spaces) from the "derived" iterators,
        # to build an IterationSpace
        iterators = OrderedDict()
        for i in ordering:
            if i.is_Stepping:
                iterators.setdefault(i.parent, []).append(stencil.entry(i))
            else:
                iterators.setdefault(i, [])
        intervals = []
        for k, v in iterators.items():
            offs = set.union(set(stencil.get(k)), *[i.ofs for i in v])
            intervals.append(Interval(k, min(offs), max(offs)))

        # Finally create the LoweredEq with all metadata attached
        expr = super(LoweredEq, cls).__new__(cls, expr.lhs, expr.rhs, evaluate=False)
        expr.is_Increment = getattr(input_expr, 'is_Increment', False)
        expr.dspace = DataSpace(intervals)
        expr.ispace = IterationSpace([i.negate() for i in intervals], iterators)

        return expr

    def xreplace(self, rules):
        return Eq(self.lhs.xreplace(rules), self.rhs.xreplace(rules), stamp=self)
<|endoftext|>


<commit_before>#!/usr/bin/env python

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import os
import ctypes
import pyglet.window
from pyglet.window.event import *

from pyglet.GL.VERSION_1_1 import *
from pyglet.GLU.VERSION_1_1 import *
from pyglet import clock
from pyglet.model import obj

factory = pyglet.window.WindowFactory()
factory.config._attributes['doublebuffer'] = 1
w1 = factory.create(width=200, height=200)

class ExitHandler(object):
    running = True
    def on_close(self):
        self.running = False
    def on_keypress(self, symbol, modifiers):
        if symbol == pyglet.window.key.K_ESCAPE:
            self.running = False
        return EVENT_UNHANDLED
exit_handler = ExitHandler()
w1.push_handlers(exit_handler)

c = clock.Clock()

fourfv = ctypes.c_float * 4
c_float_p = ctypes.POINTER(ctypes.c_float)
glLightfv(GL_LIGHT0, GL_POSITION,
    ctypes.cast(fourfv(100, 200, 100, 0), c_float_p))
glLightfv(GL_LIGHT0, GL_AMBIENT,
    ctypes.cast(fourfv(0.2, 0.2, 0.2, 1.0), c_float_p))
glLightfv(GL_LIGHT0, GL_DIFFUSE,
    ctypes.cast(fourfv(0.5, 0.5, 0.5, 1.0), c_float_p))
glEnable(GL_LIGHT0)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)

glPolygonMode(GL_FRONT, GL_FILL)
glDepthFunc(GL_LESS)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., 1., 1., 100.)

glMatrixMode(GL_MODELVIEW)
glClearColor(0, 0, 0, 0)

bunny = obj.OBJ(os.path.join(os.path.split(__file__)[0], 'rabbit.obj'))

r = 0
while exit_handler.running:
    c.set_fps(60)
    w1.dispatch_events()

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    gluLookAt(0, 5, 5, 0, 1, -1, 0, 1, 0)

    r += 1
    if r > 360: r = 0
    glRotatef(r, 0, 1, 0)
    glCallList(bunny.gl_list)

    w1.flip()

<commit_msg>Allocate depth buffer.<commit_after>#!/usr/bin/env python

'''
'''

__docformat__ = 'restructuredtext'
__version__ = '$Id$'

import os
import ctypes
import pyglet.window
from pyglet.window.event import *

from pyglet.GL.VERSION_1_1 import *
from pyglet.GLU.VERSION_1_1 import *
from pyglet import clock
from pyglet.model import obj

factory = pyglet.window.WindowFactory()
factory.config._attributes['doublebuffer'] = 1
factory.config._attributes['depth_size'] = 24
w1 = factory.create(width=200, height=200)

class ExitHandler(object):
    running = True
    def on_close(self):
        self.running = False
    def on_keypress(self, symbol, modifiers):
        if symbol == pyglet.window.key.K_ESCAPE:
            self.running = False
        return EVENT_UNHANDLED
exit_handler = ExitHandler()
w1.push_handlers(exit_handler)

c = clock.Clock()

fourfv = ctypes.c_float * 4
c_float_p = ctypes.POINTER(ctypes.c_float)
glLightfv(GL_LIGHT0, GL_POSITION,
    ctypes.cast(fourfv(100, 200, 100, 0), c_float_p))
glLightfv(GL_LIGHT0, GL_AMBIENT,
    ctypes.cast(fourfv(0.2, 0.2, 0.2, 1.0), c_float_p))
glLightfv(GL_LIGHT0, GL_DIFFUSE,
    ctypes.cast(fourfv(0.5, 0.5, 0.5, 1.0), c_float_p))
glEnable(GL_LIGHT0)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_DEPTH_TEST)
glShadeModel(GL_SMOOTH)

glPolygonMode(GL_FRONT, GL_FILL)
glDepthFunc(GL_LESS)
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(60., 1., 1., 100.)

glMatrixMode(GL_MODELVIEW)
glClearColor(0, 0, 0, 0)

bunny = obj.OBJ(os.path.join(os.path.split(__file__)[0], 'rabbit.obj'))

r = 0
while exit_handler.running:
    c.set_fps(60)
    w1.dispatch_events()

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glLoadIdentity()
    gluLookAt(0, 5, 5, 0, 1, -1, 0, 1, 0)

    r += 1
    if r > 360: r = 0
    glRotatef(r, 0, 1, 0)
    glCallList(bunny.gl_list)

    w1.flip()

<|endoftext|>


<commit_before>import asyncio
import discord
from   datetime    import datetime
from   discord.ext import commands
from   shutil      import copyfile
import time
import json
import os
import re
from   Cogs        import DisplayName
from   Cogs        import Nullify

class Welcome:

    def __init__(self, bot, settings):
        self.bot = bot
        self.settings = settings
        self.regexUserName = re.compile(r"\[\[[user]+\]\]", re.IGNORECASE)
        self.regexUserPing = re.compile(r"\[\[[atuser]+\]\]", re.IGNORECASE)
        self.regexServer   = re.compile(r"\[\[[server]+\]\]", re.IGNORECASE)

    async def onjoin(self, member, server):
        # Welcome
        welcomeChannel = self.settings.getServerStat(server, "WelcomeChannel")
        if welcomeChannel:
            for channel in server.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            await self._welcome(member, server, welcomeChannel)
        else:
            await self._welcome(member, server)

    async def onleave(self, member, server):
        # Goodbye
        if not server in self.bot.guilds:
            # We're not on this server - and can't say anything there
            return
        welcomeChannel = self.settings.getServerStat(server, "WelcomeChannel")
        if welcomeChannel:
            for channel in server.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            await self._goodbye(member, server, welcomeChannel)
        else:
            await self._goodbye(member, server)

    @commands.command(pass_context=True)
    async def setwelcome(self, ctx, *, message = None):
        """Sets the welcome message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if message == None:
            self.settings.setServerStat(ctx.message.guild, "Welcome", None)
            await ctx.channel.send('Welcome message removed!')
            return

        self.settings.setServerStat(ctx.message.guild, "Welcome", message)
        await ctx.channel.send('Welcome message updated!\n\nHere\'s a preview:')
        await self._welcome(ctx.message.author, ctx.message.guild, ctx.message.channel)

    @commands.command(pass_context=True)
    async def testwelcome(self, ctx, *, member = None):
        """Prints the current welcome message (bot-admin only)."""

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True

        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if member == None:
            member = ctx.message.author
        if type(member) is str:
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'I couldn\'t find *{}*...'.format(memberName)
                # Check for suppress
                if suppress:
                    msg = Nullify.clean(msg)
                await ctx.channel.send(msg)
                return
        # Here we have found a member, and stuff.
        # Let's make sure we have a message
        message = self.settings.getServerStat(ctx.message.guild, "Welcome")
        if message == None:
            await ctx.channel.send('Welcome message not setup.  You can do so with the `{}setwelcome [message]` command.'.format(ctx.prefix))
            return
        await self._welcome(member, ctx.message.guild, ctx.message.channel)
        # Print the welcome channel
        welcomeChannel = self.settings.getServerStat(ctx.message.guild, "WelcomeChannel")
        if welcomeChannel:
            for channel in ctx.message.guild.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            msg = 'The current welcome channel is **{}**.'.format(welcomeChannel.name)
        else:
            msg = 'The current welcome channel is the server\'s default channel (**{}**).'.format(ctx.message.guild.default_channel.name)
        await ctx.channel.send(msg)

    @commands.command(pass_context=True)
    async def setgoodbye(self, ctx, *, message = None):
        """Sets the goodbye message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if message == None:
            self.settings.setServerStat(ctx.message.guild, "Goodbye", None)
            await ctx.channel.send('Goodbye message removed!')
            return

        self.settings.setServerStat(ctx.message.guild, "Goodbye", message)
        await ctx.channel.send('Goodbye message updated!\n\nHere\'s a preview:')
        await self._goodbye(ctx.message.author, ctx.message.guild, ctx.message.channel)

    @commands.command(pass_context=True)
    async def testgoodbye(self, ctx, *, member = None):
        """Prints the current goodbye message (bot-admin only)."""

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True

        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if member == None:
            member = ctx.message.author
        if type(member) is str:
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'I couldn\'t find *{}*...'.format(memberName)
                # Check for suppress
                if suppress:
                    msg = Nullify.clean(msg)
                await ctx.channel.send(msg)
                return
        # Here we have found a member, and stuff.
        # Let's make sure we have a message
        message = self.settings.getServerStat(ctx.message.guild, "Goodbye")
        if message == None:
            await ctx.channel.send('Goodbye message not setup.  You can do so with the `{}setgoodbye [message]` command.'.format(ctx.prefix))
            return
        await self._goodbye(member, ctx.message.guild, ctx.message.channel)

        # Print the goodbye channel
        welcomeChannel = self.settings.getServerStat(ctx.message.guild, "WelcomeChannel")
        if welcomeChannel:
            for channel in ctx.message.guild.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            msg = 'The current goodbye channel is **{}**.'.format(welcomeChannel.name)
        else:
            msg = 'The current goodbye channel is the server\'s default channel (**{}**).'.format(ctx.message.guild.default_channel.name)
        await ctx.channel.send(msg)

    async def _welcome(self, member, server, channel = None):
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(server, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False
        message = self.settings.getServerStat(server, "Welcome")
        if message == None:
            return
        # Let's regex and replace [[user]] [[atuser]] and [[server]]
        message = re.sub(self.regexUserName, "{}".format(DisplayName.name(member)), message)
        message = re.sub(self.regexUserPing, "{}".format(member.mention), message)
        message = re.sub(self.regexServer,   "{}".format(server.name), message)

        if suppress:
            message = Nullify.clean(message)

        if channel:
            await channel.send(message)
        else:
            await server.default_channel.send(message)

    async def _goodbye(self, member, server, channel = None):
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(server, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False
        message = self.settings.getServerStat(server, "Goodbye")
        if message == None:
            return
        # Let's regex and replace [[user]] [[atuser]] and [[server]]
        message = re.sub(self.regexUserName, "{}".format(DisplayName.name(member)), message)
        message = re.sub(self.regexUserPing, "{}".format(member.mention), message)
        message = re.sub(self.regexServer,   "{}".format(server.name), message)

        if suppress:
            message = Nullify.clean(message)
        if channel:
            await channel.send(message)
        else:
            await server.default_channel.send(message)

    @commands.command(pass_context=True)
    async def setwelcomechannel(self, ctx, *, channel : discord.TextChannel = None):
        """Sets the channel for the welcome and goodbye messages (bot-admin only)."""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True

        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if channel == None:
            self.settings.setServerStat(ctx.message.guild, "WelcomeChannel", "")
            msg = 'Welcome and goodbye messages will be displayed in the default channel (**{}**).'.format(ctx.message.guild.default_channel.name)
            await ctx.channel.send(msg)
            return

        if type(channel) is str:
            try:
                role = discord.utils.get(message.guild.channels, name=role)
            except:
                print("That channel does not exist")
                return

        # If we made it this far - then we can add it
        self.settings.setServerStat(ctx.message.guild, "WelcomeChannel", channel.id)

        msg = 'Welcome and goodbye messages will be displayed in **{}**.'.format(channel.name)
        await ctx.channel.send(msg)

    @setwelcomechannel.error
    async def setwelcomechannel_error(self, ctx, error):
        # do stuff
        msg = 'setwelcomechannel Error: {}'.format(ctx)
        await error.channel.send(msg)
<commit_msg>Update Welcome.py<commit_after>import asyncio
import discord
from   datetime    import datetime
from   discord.ext import commands
from   shutil      import copyfile
import time
import json
import os
import re
from   Cogs        import DisplayName
from   Cogs        import Nullify

class Welcome:

    def __init__(self, bot, settings):
        self.bot = bot
        self.settings = settings
        self.regexUserName = re.compile(r"\[\[[user]+\]\]", re.IGNORECASE)
        self.regexUserPing = re.compile(r"\[\[[atuser]+\]\]", re.IGNORECASE)
        self.regexServer   = re.compile(r"\[\[[server]+\]\]", re.IGNORECASE)

    async def onjoin(self, member, server):
        # Welcome
        welcomeChannel = self.settings.getServerStat(server, "WelcomeChannel")
        if welcomeChannel:
            for channel in server.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            await self._welcome(member, server, welcomeChannel)
        else:
            await self._welcome(member, server)

    async def onleave(self, member, server):
        # Goodbye
        if not server in self.bot.guilds:
            # We're not on this server - and can't say anything there
            return
        welcomeChannel = self.settings.getServerStat(server, "WelcomeChannel")
        if welcomeChannel:
            for channel in server.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            await self._goodbye(member, server, welcomeChannel)
        else:
            await self._goodbye(member, server)

    async def _getDefault(self, server):
        # Returns the default channel for the server
        targetChan = server.default_channel
        targetChanID = self.settings.getServerStat(server, "DefaultChannel")
        if len(targetChanID):
            # We *should* have a channel
            tChan = self.bot.get_channel(int(targetChanID))
            if tChan:
                # We *do* have one
                targetChan = tChan
        return targetChan

    @commands.command(pass_context=True)
    async def setwelcome(self, ctx, *, message = None):
        """Sets the welcome message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if message == None:
            self.settings.setServerStat(ctx.message.guild, "Welcome", None)
            await ctx.channel.send('Welcome message removed!')
            return

        self.settings.setServerStat(ctx.message.guild, "Welcome", message)
        await ctx.channel.send('Welcome message updated!\n\nHere\'s a preview:')
        await self._welcome(ctx.message.author, ctx.message.guild, ctx.message.channel)

    @commands.command(pass_context=True)
    async def testwelcome(self, ctx, *, member = None):
        """Prints the current welcome message (bot-admin only)."""

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True

        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if member == None:
            member = ctx.message.author
        if type(member) is str:
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'I couldn\'t find *{}*...'.format(memberName)
                # Check for suppress
                if suppress:
                    msg = Nullify.clean(msg)
                await ctx.channel.send(msg)
                return
        # Here we have found a member, and stuff.
        # Let's make sure we have a message
        message = self.settings.getServerStat(ctx.message.guild, "Welcome")
        if message == None:
            await ctx.channel.send('Welcome message not setup.  You can do so with the `{}setwelcome [message]` command.'.format(ctx.prefix))
            return
        await self._welcome(member, ctx.message.guild, ctx.message.channel)
        # Print the welcome channel
        welcomeChannel = self.settings.getServerStat(ctx.message.guild, "WelcomeChannel")
        if welcomeChannel:
            for channel in ctx.message.guild.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            msg = 'The current welcome channel is **{}**.'.format(welcomeChannel.name)
        else:
            msg = 'The current welcome channel is the server\'s default channel (**{}**).'.format(self._getDefault(ctx.guild).name)
        await ctx.channel.send(msg)

    @commands.command(pass_context=True)
    async def setgoodbye(self, ctx, *, message = None):
        """Sets the goodbye message for your server (bot-admin only). [[user]] = user name, [[atuser]] = user mention, [[server]] = server name"""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True
        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if message == None:
            self.settings.setServerStat(ctx.message.guild, "Goodbye", None)
            await ctx.channel.send('Goodbye message removed!')
            return

        self.settings.setServerStat(ctx.message.guild, "Goodbye", message)
        await ctx.channel.send('Goodbye message updated!\n\nHere\'s a preview:')
        await self._goodbye(ctx.message.author, ctx.message.guild, ctx.message.channel)

    @commands.command(pass_context=True)
    async def testgoodbye(self, ctx, *, member = None):
        """Prints the current goodbye message (bot-admin only)."""

        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True

        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if member == None:
            member = ctx.message.author
        if type(member) is str:
            memberName = member
            member = DisplayName.memberForName(memberName, ctx.message.guild)
            if not member:
                msg = 'I couldn\'t find *{}*...'.format(memberName)
                # Check for suppress
                if suppress:
                    msg = Nullify.clean(msg)
                await ctx.channel.send(msg)
                return
        # Here we have found a member, and stuff.
        # Let's make sure we have a message
        message = self.settings.getServerStat(ctx.message.guild, "Goodbye")
        if message == None:
            await ctx.channel.send('Goodbye message not setup.  You can do so with the `{}setgoodbye [message]` command.'.format(ctx.prefix))
            return
        await self._goodbye(member, ctx.message.guild, ctx.message.channel)

        # Print the goodbye channel
        welcomeChannel = self.settings.getServerStat(ctx.message.guild, "WelcomeChannel")
        if welcomeChannel:
            for channel in ctx.message.guild.channels:
                if str(channel.id) == str(welcomeChannel):
                    welcomeChannel = channel
                    break
        if welcomeChannel:
            msg = 'The current goodbye channel is **{}**.'.format(welcomeChannel.name)
        else:
            msg = 'The current goodbye channel is the server\'s default channel (**{}**).'.format(self._getDefault(ctx.guild).name)
        await ctx.channel.send(msg)

    async def _welcome(self, member, server, channel = None):
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(server, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False
        message = self.settings.getServerStat(server, "Welcome")
        if message == None:
            return
        # Let's regex and replace [[user]] [[atuser]] and [[server]]
        message = re.sub(self.regexUserName, "{}".format(DisplayName.name(member)), message)
        message = re.sub(self.regexUserPing, "{}".format(member.mention), message)
        message = re.sub(self.regexServer,   "{}".format(server.name), message)

        if suppress:
            message = Nullify.clean(message)

        if channel:
            await channel.send(message)
        else:
            await self._getDefault(ctx.guild).send(message)

    async def _goodbye(self, member, server, channel = None):
        # Check if we're suppressing @here and @everyone mentions
        if self.settings.getServerStat(server, "SuppressMentions").lower() == "yes":
            suppress = True
        else:
            suppress = False
        message = self.settings.getServerStat(server, "Goodbye")
        if message == None:
            return
        # Let's regex and replace [[user]] [[atuser]] and [[server]]
        message = re.sub(self.regexUserName, "{}".format(DisplayName.name(member)), message)
        message = re.sub(self.regexUserPing, "{}".format(member.mention), message)
        message = re.sub(self.regexServer,   "{}".format(server.name), message)

        if suppress:
            message = Nullify.clean(message)
        if channel:
            await channel.send(message)
        else:
            await self._getDefault(ctx.guild).send(message)

    @commands.command(pass_context=True)
    async def setwelcomechannel(self, ctx, *, channel : discord.TextChannel = None):
        """Sets the channel for the welcome and goodbye messages (bot-admin only)."""

        isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator
        if not isAdmin:
            checkAdmin = self.settings.getServerStat(ctx.message.guild, "AdminArray")
            for role in ctx.message.author.roles:
                for aRole in checkAdmin:
                    # Get the role that corresponds to the id
                    if str(aRole['ID']) == str(role.id):
                        isAdmin = True

        # Only allow admins to change server stats
        if not isAdmin:
            await ctx.channel.send('You do not have sufficient privileges to access this command.')
            return

        if channel == None:
            self.settings.setServerStat(ctx.message.guild, "WelcomeChannel", "")
            msg = 'Welcome and goodbye messages will be displayed in the default channel (**{}**).'.format(self._getDefault(ctx.guild).name)
            await ctx.channel.send(msg)
            return

        if type(channel) is str:
            try:
                role = discord.utils.get(message.guild.channels, name=role)
            except:
                print("That channel does not exist")
                return

        # If we made it this far - then we can add it
        self.settings.setServerStat(ctx.message.guild, "WelcomeChannel", channel.id)

        msg = 'Welcome and goodbye messages will be displayed in **{}**.'.format(channel.name)
        await ctx.channel.send(msg)

    @setwelcomechannel.error
    async def setwelcomechannel_error(self, ctx, error):
        # do stuff
        msg = 'setwelcomechannel Error: {}'.format(ctx)
        await error.channel.send(msg)
<|endoftext|>