Ejemplo n.º 1
0
    def start(self):
        Module.start(self)

        self._agent.setPin(self._cfg.get('pin', None))

        self.setState(False)  # Disabling interface to set the SSP
        self.setSSP(
            False
        )  # Secure Simple Pairing - if enabled will disable pin pairing (not supported) (not secure)
        self.setState(self._cfg.get('enabled', True))
        self.setDeviceClass('0x200420')
        self.setDeviceName(self._cfg.get('name', 'tracker-1'))
        self.setAFH(self._cfg.get('afh', True))
        self.setEncryption(self._cfg.get('encrypt', True))
        self.setVisibility(self._cfg.get('visible', False))
        self.setAuth(self._cfg.get('auth', False))
        self.setFastConnection(self._cfg.get('fast', True))

        manager = dbus.Interface(self._bus.get_object(BUS_NAME, '/org/bluez'),
                                 AGENT_MANAGER_INTERFACE)
        manager.RegisterAgent('/tracker/agent', 'NoInputNoOutput')
        manager.RequestDefaultAgent('/tracker/agent')

        self._listener = self._bus.add_signal_receiver(
            self._devicePropertyChanged,
            bus_name=BUS_NAME,
            signal_name='PropertiesChanged',
            path_keyword='device_path',
            interface_keyword='interface')

        self.restoreLastConnection()
Ejemplo n.º 2
0
    def set_detector_rz_collection(self, list_of_detids):

        # Create detector patches
        self.patches_rz = []
        n_failed = 0
        for detid in list_of_detids:

            module = Module(detid)
            partner_detid = Module(detid).partnerDetId()

            if partner_detid not in self.det_geom.getData().keys():
                # print("{} not found from {} (isLower = {}, isInverted = {})".format(partner_detid, detid, module.isLower(), module.isInverted()))
                n_failed += 1
                continue
            else:
                # print("{}     found from {} (isLower = {}, isInverted = {})".format(partner_detid, detid, module.isLower(), module.isInverted()))
                pass

            six_faces = self.get_six_faces(
                self.det_geom.getData()[detid],
                self.det_geom.getData()[partner_detid])

            for face in six_faces:
                points = [[x[0], math.sqrt(x[1]**2 + x[2]**2)] for x in face]
                polygon = Polygon(np.array(points), True)
                self.patches_rz.append(polygon)
Ejemplo n.º 3
0
    def postStart(self):
        '''Checking the current state of the listening GPIO's and do the configured actions'''
        Module.postStart(self)

        # Init listen GPIO's in poststart
        # We need to be sure that listen isn't triggered until all the modules was started
        for name, item in self._cfg.get('listen', {}).iteritems():
            log.info("Attaching GPIO listener %s to pin %d" %
                     (name, item['pin']))
            self._pin_map[item['pin']] = name
            gpio.setup(item['pin'], gpio.IN)
            while self.isActive():
                # Sometimes event detection is can't be set up - so need retries
                try:
                    gpio.add_event_detect(item['pin'],
                                          gpio.BOTH,
                                          callback=self._listenTrigger)
                except RuntimeError:
                    log.error(
                        'Detected unable to set event detection for GPIO %s, retrying...'
                        % item['pin'])
                    self.waitActive(1.0)
                    continue
                break

        for pin in self._pin_map:
            self._listenTrigger(pin)
Ejemplo n.º 4
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        self._data = {}
        self._data_lock = threading.Lock()
        self._data_send_timer = None
        self._send_interval = None
Ejemplo n.º 5
0
 def stop(self):
     Module.stop(self)
     if self._data_send_timer:
         self._data_send_timer.cancel()
     self._data_send_timer = None
     self._send_interval = None
     self.sendData()
def get_modules(session):
    print("Getting modules...\n")

    modules = []

    resp = session_get('{0}/courses/{1}/modules'.format(CANVAS_URL, COURSE_ID),
                       session)
    tree = html.fromstring(resp.content)
    moduleNodes = tree.xpath(
        "//div[contains(@class, 'context_module') and contains(@class, 'item-group-condensed')]"
    )

    # Last element is a blank module
    moduleNodes.pop()

    for moduleNode in moduleNodes:
        module = Module()
        module.name = moduleNode.attrib['aria-label']

        print("Found Module ", module.name)

        module.items = get_items(moduleNode)
        modules.append(module)

    print("")

    return modules
Ejemplo n.º 7
0
    def start(self):
        Module.start(self)

        # Init socket GPIO's
        for action in self._cfg.get('sockets', []).keys():
            if hasattr(self, action):
                log.error("Unable to redefine existing function by socket %s" %
                          action)
                continue

            socket = self._cfg['sockets'][action]
            log.info("Registering socket action %s for pin %d..." %
                     (action, socket['pin']))
            gpio.setup(socket['pin'],
                       gpio.OUT,
                       initial=socket.get('default', False))

            socket_type = socket.get('type', 'switch')
            if socket_type == 'switch':
                setattr(self,
                        action,
                        lambda self=self, pin=socket['pin'], value=None: self.
                        sendChange(pin, value))
            elif socket_type == 'pulse':
                setattr(self,
                        action,
                        lambda self=self, pin=socket['pin'], duration=socket.
                        get('duration', None): self.sendPulse(pin, duration))
            else:
                log.warn("GPIO type %s unsupported for socket %s" %
                         (socket_type, action))
Ejemplo n.º 8
0
Archivo: Add.py Proyecto: jgoof91/pyblk
 def exec(self, args, **kwargs):
     parse_args = Command.Command.PARSER.parse_args(args)
     module = Module(parse_args.command, parse_args.interval,
                     parse_args.signal, parse_args.align, parse_args.order)
     modules.append(module)
     module.exec(shell)
     epoll.register(module)
     return b'Ok'
Ejemplo n.º 9
0
 def __init__(self):
     Module.__init__(self)
     self.add_method('printout', self.printout)
     self.add_method('assert', self.assertion)
     self.add_method('retract', self.retract)
     self.add_method('bind', self.bind)
     self.add_method('test', self.test)
     self.add_method('strategy', self.strategy)
Ejemplo n.º 10
0
 def __init__(self):
     Module.__init__(self)
     self.add_method('printout', self.printout)
     self.add_method('assert', self.assertion)
     self.add_method('retract', self.retract)
     self.add_method('bind', self.bind)
     self.add_method('test', self.test)
     self.add_method('strategy', self.strategy)
Ejemplo n.º 11
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        self._raw_data = {}
        self._raw_data_lock = threading.Lock()
        self._map_data = {}
        self._map_data_lock = threading.Lock()

        self._thread_control = threading.Thread(target=self._readRawDataThreadWrapper)
Ejemplo n.º 12
0
    def test_progress_module(self):
        module = Module("test_module", 600)
        current_time = datetime.datetime(2014, 1, 1, 0, 0, 0)
        module.calc_deadline(current_time, 10, 0)

        for i in range(60):
            current_time += datetime.timedelta(hours=1)
            module.progress_module(10, current_time)

        self.assertTrue(module.progress >= 500 or module.progress <= 700)
Ejemplo n.º 13
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        self._ignition = None
        self._ignition_lock = threading.Lock()
        self._ignition_off_timer = None

        self._power_outage = None
        self._critical_battery_voltage = None
        self._low_battery_voltage = None
Ejemplo n.º 14
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        self._bus = dbus.SystemBus()
        self._agent = Agent(self._bus, "/tracker/agent")

        self._listener = None
        self._last_device = None
        self._resume_playing = None
        self._connected_devices = {}
Ejemplo n.º 15
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        self._server = Server((self._cfg.get('address', ''), self._cfg.get('port', 9000)))

        self._registerHandlers()

        self._server_proc = Thread(target=self._server.serve)
        self._server_proc.daemon = True
        self._server_proc.start()
Ejemplo n.º 16
0
 def __init__(self):
     Module.__init__(self)
     self.add_method('eq', self.equal)
     self.add_method('neq', self.not_equal)
     self.add_method('<', self.less_than)
     self.add_method('<=', self.less_equal)
     self.add_method('>', self.greater_than)
     self.add_method('>=', self.greater_equal)
     self.add_method('and', self.logical_and)
     self.add_method('or', self.logical_or)
     self.add_method('not', self.logical_not)
Ejemplo n.º 17
0
    def test_calc_deadline(self):
        module = Module("test_module", 600)
        start_time = datetime.datetime(2014, 1, 1, 0, 0, 0)
        deadline = datetime.datetime(2014, 1, 22, 0, 0, 0)

        module.calc_deadline(start_time, 10, 0)
        print module.deadline
        self.assertTrue(module.deadline == deadline)

        module.calc_deadline(start_time, 600, 0)
        self.assertTrue(module.deadline == start_time)
Ejemplo n.º 18
0
 def __init__(self):
     Module.__init__(self)
     self.add_method('eq', self.equal)
     self.add_method('neq', self.not_equal)
     self.add_method('<', self.less_than)
     self.add_method('<=', self.less_equal)
     self.add_method('>', self.greater_than)
     self.add_method('>=', self.greater_equal)
     self.add_method('and', self.logical_and)
     self.add_method('or', self.logical_or)
     self.add_method('not', self.logical_not)
Ejemplo n.º 19
0
    def test_calc_progress(self):
        current_time = datetime.datetime(2014, 1, 1, 0, 0, 0)
        team = Team("test_team", 10)
        module = Module("test_module", 800)
        module.calc_deadline(current_time, 10, 0)
        team.module = module

        while team.module and not team.module.completed:
            current_time += datetime.timedelta(hours=1)
            team.calc_progress(current_time)

        self.assertTrue(team.completed_modules and team.completed_modules[0] == module)
Ejemplo n.º 20
0
    def stop(self):
        Module.stop(self)
        self._bus.remove_signal_receiver(self._listener)

        for addr in self._connected_devices.keys():
            self.stopDev(addr)

        manager = dbus.Interface(self._bus.get_object(BUS_NAME, '/org/bluez'),
                                 AGENT_MANAGER_INTERFACE)
        try:
            manager.UnregisterAgent('/tracker/agent')
        except:
            pass
Ejemplo n.º 21
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        if not hasattr(self, "_command"):
            self._command = None
        if not hasattr(self, "_command_cwd"):
            self._command_cwd = None
        self._process = None
        self._client = None
        self._timer_processcheck = None

        self._pidpath = kwargs.get('pidpath')

        self.start()
Ejemplo n.º 22
0
def LmodModuleList(paths):
    import string
    moduleList = []
    output = pexpect.run(MODULE_COMMAND + ' ' + string.join(paths, ':'))
    import json
    output_js = json.loads(output)
    if "jsonSoftwarePage" in MODULE_COMMAND:
        for elem in output_js:
            for v in elem["versions"]:
                name = v["full"]
                help = "-"
                prereq = "-"
                if v.has_key("help"):
                    help = v["help"]
                if v.has_key("parent"):
                    prereq = string.join(v["parent"], " or ").replace(
                        "default:", "").replace("default",
                                                "").replace(":", " and ")
                newModule = Module(name, help, "-", prereq)
                if newModule.version[0] != ".":
                    moduleList.append(newModule)
    elif "spider-json" in MODULE_COMMAND:
        #        print(str(output_js))
        for module_name in output_js:
            data = output_js[module_name]
            for path in data:
                module_data = data[path]
                #                print(str(module_data))
                if module_data.has_key("fullName"):
                    name = module_data["fullName"]
                help = "-"
                prereq = "-"
                if module_data.has_key("Description"):
                    help = module_data["Description"]
                if module_data.has_key("parentAA"):
                    prereq = string.join(module_data["parentAA"][0], " and ")
                newModule = Module(name, help, "-", prereq)
                if newModule.version[0] != ".":
                    found = False
                    for n, m in enumerate(moduleList):
                        if m.name == newModule.name:
                            newModule = Module(name, help, "-",
                                               m.prereq + " or " + prereq)
                            moduleList[n] = newModule
                            found = True
                            break
                    if not found:
                        moduleList.append(newModule)

    return moduleList
Ejemplo n.º 23
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        if not hasattr(self, "_command"):
            self._command = None
        if not hasattr(self, "_command_cwd"):
            self._command_cwd = None
        self._process = None
        self._client = None
        self._timer_processcheck = None

        self._pidpath = kwargs.get('pidpath')

        self.start()
Ejemplo n.º 24
0
def main():
    ## create patient schedule
    patientList = []
    personA = Person('A', 0)
    patientList.append(personA)
    personB = Person('B', 4)
    patientList.append(personB)
    personC = Person('C', 10)
    patientList.append(personC)

    ## module schedule (from a file)
    moduleList = []
    module1 = Module(0, 2)
    moduleList.append(module1)
    module2 = Module(1, 3)
    moduleList.append(module2)

    moduleCount = len(moduleList)

    ## need a nursing scheduler as nurses could be different than modules.

    ## intialize simulation parameters
    counter = 0
    completed = 0

    ## simulation loop

    while completed < len(patientList):
        print('Time Step: {0}'.format(counter))
        for mod in moduleList:
            for pat in patientList:
                if pat.location == mod.location and pat.serviceTime > 0:
                    mod.serve(pat)
                    break
                if pat.location == mod.location and pat.serviceTime == -1:
                    # This should be a method in the module class.
                    print('Location {0} now serving Patient {1}'.format(
                        mod.location, pat.name))
                    pat.serviceTime = mod.completionTime
                    break

        completed = 0
        # condition to check if all patients have completed the clinic (Can we close?)
        for pat in patientList:
            if pat.location == moduleCount:

                completed += 1
        counter += 1
Ejemplo n.º 25
0
    def set_detector_etaphi_collection(self, list_of_detids):

        # Create detector patches
        self.patches_etaphi = []
        n_failed = 0
        for detid in list_of_detids:

            module = Module(detid)

            bound_points = self.det_geom.getData()[detid]

            points = []
            for bp in bound_points:
                x = bp[1]
                y = bp[2]
                z = bp[
                    0]  # The index is weird because that's how it is saved in det_geom
                phi = math.atan2(y, x)
                print(x, y, phi)
                # print(x, y, z)
                eta = math.copysign(
                    -math.log(
                        math.tan(
                            math.atan(math.sqrt(y**2 + x**2) / abs(z)) / 2.)),
                    z)
                points.append([eta, phi])

            polygon = Polygon(np.array(points), True)
            self.patches_etaphi.append(polygon)
Ejemplo n.º 26
0
def git_init(repo):
  os.mkdir(repo)
  tmp = Module(repo, True)
  os.chdir(tmp.url)
  os.system('git init')
  os.chdir(work_path)
  return tmp
Ejemplo n.º 27
0
  def get_modules(self):
    self.modules = []
    self.bad_modules = []

    # Get possible files that could contain a module
    module_filenames = []
    x = '/' if os.path.sep == '/' else r'\\'
    pattern = re.compile(f'^.{x}modules{x}[^{x}]+$')
    for subdir, _, files in os.walk(os.path.join(os.curdir, 'modules')):
      if pattern.match(subdir):
        if 'main.py' in files:
          module_filenames.append(os.path.join(subdir, 'main.py'))
        else:
          self.bad_modules.append((subdir.split(os.path.sep)[-1], 'No main.py file'))

    # Go through files and try to import a class
    for filename in module_filenames:
      spec = importlib.util.spec_from_file_location(filename[2:-3].replace(os.path.sep, '.'), filename)
      module = importlib.util.module_from_spec(spec)
      spec.loader.exec_module(module)
      if not hasattr(module, 'export'):
        self.bad_modules.append((filename.split(os.path.sep)[-2], 'No exported class in main.py'))
      elif not Module.is_valid(module.export):
        self.bad_modules.append((filename.split(os.path.sep)[-2], 'Exported module is invalid'))
      else:
        self.init_module(module.export)
    
    for module_name, reason in self.bad_modules:
      self.logger.warning(f'Installed module `{module_name}` cannot be loaded: {reason}')
Ejemplo n.º 28
0
    def __init__(self):
        rooms = [["GD923", 60], ["GD924", 60], ["GD926", 60], ["GD929", 60],
                 ["GD933", 60]]
        meeting_times = [["1. Block", "08:00 – 09:50"],
                         ["2. Block", "10:00 – 11:50"],
                         ["3. Block", "13:00 – 14:50"],
                         ["4. Block", "15:00 – 16:50"]]
        dosens = [
            ["HTS", "Humasak Simanjuntak"],
            ["SGS", "Samuel Situmeang"],
            ["JUN", "Junita Amalia"],
            ["MSS", "Mario Simaremare"],
            ["THS", "Tennov Simanjuntak"],
            ["DWS", "Devis Wawan Saputra"],
            ["BLT", "Bonar Lumban Tobing"],
            ["IUS", "Iustisia Simbolon"],
            ["PAT", "Parmonangan Togatorop"],
        ]

        self._rooms = []
        self._meeting_times = []
        self._dosens = []
        self.fill_objects(rooms, meeting_times, dosens)

        module1 = Module("BASDATLAN", "Advanced Database",
                         [self.get_dosen("HTS")])
        module2 = Module("CERTAN", "Artificial Intelligence",
                         [self.get_dosen("SGS")])
        module3 = Module("PROBSTAT", "Probability and Statistics",
                         [self.get_dosen("JUN"),
                          self.get_dosen("THS")])
        module4 = Module("PPW", "Web Application Programming and Testing",
                         [self.get_dosen("MSS")])
        module5 = Module("ALSTRUDAT", "Algorithms and Data Structures", [
            self.get_dosen("THS"),
            self.get_dosen("HTS"),
            self.get_dosen("PAT"),
            self.get_dosen("SGS")
        ])
        module6 = Module("TEKNO", "Technopreneurship", [self.get_dosen("DWS")])
        module7 = Module("ATI", "Religion and Ethics", [self.get_dosen("BLT")])
        module8 = Module("RPL", "Software Engineering",
                         [self.get_dosen("IUS")])
        module9 = Module("MPSI", "Information System Project Management",
                         [self.get_dosen("PAT")])
        self._modules = [module1, module2, module3, module4, module5, module6]

        course1 = Course("11SI", [module1, module3, module4, module7], 59)
        course2 = Course("12SI", [module2, module4, module5, module8], 50)
        course3 = Course("13SI", [module4, module5, module6, module9], 56)
        course4 = Course("14SI", [module5, module3, module1, module9], 48)
        self._courses = [course1, course2, course3, course4]
Ejemplo n.º 29
0
def printPixelMap_v1():

    import os

    dirpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    det_geom = DetectorGeometry(
        "/data2/segmentlinking/phase2_2020_0428.txt".format(dirpath))

    super_bins = {}

    neta = 40.
    nphi = 72.

    isuper_bin = 0
    pt_bounds = [0.9, 2.0, 4.0, 10., 50.]
    # pt_bounds = [0.9, 2.0]
    for ipt in xrange(len(pt_bounds) - 1):
        pt_lo = pt_bounds[ipt]
        pt_hi = pt_bounds[ipt + 1]
        for ieta in xrange(int(neta)):
            eta_lo = -2.6 + (5.2 / neta) * ieta
            eta_hi = -2.6 + (5.2 / neta) * (ieta + 1)
            for iphi in xrange(int(nphi)):
                phi_lo = -math.pi + (2 * math.pi / nphi) * iphi
                phi_hi = -math.pi + (2 * math.pi / nphi) * (iphi + 1)
                super_bins[isuper_bin] = (pt_lo, pt_hi, eta_lo, eta_hi, phi_lo,
                                          phi_hi)
                isuper_bin += 1
    print(len(super_bins))

    maps = {}
    for layer in [1, 2, 3, 4, 5, 6]:
        for subdet in [4, 5]:
            for isuper_bin in super_bins.keys():
                bounds = super_bins[isuper_bin]
                maps[isuper_bin] = []
                for detid in det_geom.getDetIds():
                    if Module(detid).layer() == layer and Module(
                            detid).isLower() == 1 and Module(detid).moduleType(
                            ) == 0 and Module(detid).subdet() == subdet:
                        if det_geom.isConnected(detid, bounds[2], bounds[3],
                                                bounds[4], bounds[5],
                                                bounds[0], bounds[1], -30, 30):
                            maps[isuper_bin].append(detid)
                print(isuper_bin, layer, subdet, bounds[2], bounds[3],
                      bounds[4], bounds[5], maps[isuper_bin])
Ejemplo n.º 30
0
def modules_save():
    user = current_user.id
    name = request.form['name']
    version = request.form['version']
    m = Module(user, name, version)
    m.encrypt = request.form['encrypt']
    m.decrypt = request.form['decrypt']
    m.hack = request.form['hack']
    m.comms = request.form['comms']
    return jsonify(module=dict(
        user=user,
        name=name,
        version=version,
        encrypt=m.encrypt,
        decrypt=m.decrypt,
        hack=m.hack,
        comms=m.comms))
Ejemplo n.º 31
0
 def getModules(self, elements, libraryDict, converter):
     for element in elements:
         elementPackage = element.get("package")
         elementLib = element.get("library")
         libNode = libraryDict.get(elementLib).get(elementPackage)
         modContacts = self.contacts.get(element.get("name"))
         module = Module(libNode, converter, element, modContacts)
         self.elements.append(module)
Ejemplo n.º 32
0
 def get_module_objects(self):
     module_objs = [
         Module(module, self.configs, self.verbosity)
         for module in self.module_path_list
     ]
     if len(module_objs) > 1 and self.verbosity > 1:
         print("[" + str(len(module_objs)) + "]")
     return module_objs
Ejemplo n.º 33
0
 def hangup(fileno):
     if fileno in self.conn_table:
         self.epoll.unregister(fileno)
         self.conn_table[fileno].close()
         self.conn_table.pop(fileno)
     else:
         module = Module.find_modules_by_fileno(self.modules, fileno)
         module.reap()
         self.epoll.unregister(module)
Ejemplo n.º 34
0
    def __init__(self):
        Module.__init__(self)
        self.add_method('+', self.addition)
        self.add_method('-', self.subtraction)
        self.add_method('*', self.multiplication)
        self.add_method('/', self.division)
        self.add_method('%', self.module)
        self.add_method('**', self.power)
        self.add_method('abs', self.abs)
        self.add_method('min', self.minimum)
        self.add_method('max', self.maximum)
        self.add_method('strcat', self.strcat)
        self.add_method('substr', self.substr)
        self.add_method('strlen', self.strlen)
        self.add_method('strindex', self.strindex)
        self.add_method('symcat', self.symcat)
        self.add_method('randint', self.randint)

        random.seed(time.time())
Ejemplo n.º 35
0
    def __init__(self):
        Module.__init__(self)
        self.add_method('+', self.addition)
        self.add_method('-', self.subtraction)
        self.add_method('*', self.multiplication)
        self.add_method('/', self.division)
        self.add_method('%', self.module)
        self.add_method('**', self.power)
        self.add_method('abs', self.abs)
        self.add_method('min', self.minimum)
        self.add_method('max', self.maximum)
        self.add_method('strcat', self.strcat)
        self.add_method('substr', self.substr)
        self.add_method('strlen', self.strlen)
        self.add_method('strindex', self.strindex)
        self.add_method('symcat', self.symcat)
        self.add_method('randint', self.randint)

        random.seed(time.time())
Ejemplo n.º 36
0
    def addModule(self, inputData, register, output):
        """Add a module to the module list

        Parameters:
            input - (DataContainer)  input variables and results from preparatory modules
            register - (DataContainer) registry data of this module
            output - (DataContainer) with output requirements for this module
        """
        module = Module(inputData, register, output)
        self.moduleList.append(module, )
        return
Ejemplo n.º 37
0
    def start(self):
        Module.start(self)
        self._c = serial.Serial(self.getDevice(), self.getRate(), timeout=1.0)

        self.powerOn()

        # Disabling echo
        self.execAT('ATE0')

        # Check the device before running
        if self.checkVersion() != True:
            log.error(
                'Unable to run GSMGPS module due to device version is unsupported: %s'
                % self.checkVersion())
            self.stop()

        if self._cfg.get('net', {}).get('enabled', False):
            self.enableNetwork()

        if self._cfg.get('gps', {}).get('enabled', False):
            self.enableGPS()
Ejemplo n.º 38
0
    def __init__(self, **kwargs):
        Module.__init__(self, **kwargs)

        self.setState(self._cfg.get('enabled', False))
        self.setDeviceClass("0xAA040B")
        self.setDeviceName(self._cfg.get('name', 'OneButton'))
        self.setEncryption(self._cfg.get('encrypt', True))
        self.setVisibility(self._cfg.get('visible', False))

        self._bus = dbus.SystemBus()

        # Required bluez >= 5.40 due to fix in profiles connections
        self._agent = Agent(self._bus, "/onebutton/agent")
        manager = dbus.Interface(self._bus.get_object(BUS_NAME, "/org/bluez"), "org.bluez.AgentManager1")
        manager.RegisterAgent("/onebutton/agent", "NoInputNoOutput")
        manager.RequestDefaultAgent("/onebutton/agent")

        self._btservice = BTService(self._bus, 'OneButton')

        self.registerService('localhost', 9000, 'OneControl')
        self.registerService('localhost', 8881, 'Guitarix RPC')
        self.registerService('localhost', 8000, 'Guitarix WEB')
        self.registerService('localhost', 22, 'SSH')
Ejemplo n.º 39
0
    def __init__(self):
        super().__init__()

        # Get all modules and add client to their variables

        with open("data/config.json", "r") as f:
            self.args = json.loads(f.read())

        # discord.opus.load_opus(self.args["opus"])

        self.htmlsocketserver = htmlsocketserver.Htmlsocketserver(self)
        self.db = pymongo.MongoClient().jaa

        self.modules = [subclass(self) for subclass in Module.__subclasses__()]
Ejemplo n.º 40
0
def modules_get(user, name, version):
    if not (user == current_user.id or current_user.isadmin or (version is not None and version.endswith('p'))):
        return jsonify(error='Not authorised'), 403
    if not Module.exists(user, name, version):
        return jsonify(error='no module of that name'), 404
    m = Module(user, name, version)
    return jsonify(module=dict(
        user=user,
        name=name,
        version=version,
        encrypt=m.encrypt,
        decrypt=m.decrypt,
        hack=m.hack,
        comms=m.comms))
Ejemplo n.º 41
0
 def start_element(self, name, attrs):
     """
     Function called when the start of an XML element is found
     """
     if name == "module":
         self.current_module = Module(attrs['name'])
         self.current_module.add_id(attrs['id'])
     elif name == "dependency":
         self.in_dependency = True
     elif name == "param":
         self.current_param = Parameter()
     elif name == "description":
         self.in_description = True
     elif name == "value":
         self.in_value = True
     elif name == "command":
         self.in_command = True
     elif name == "id":
         self.in_id = True
     elif name == "child":
         self.in_child = True
         self.parent = self.current_module
Ejemplo n.º 42
0
    def test_get_task(self):
        module = Module("test_module", 600)

        task = module.get_task("design")
        self.assertTrue(
            task
            and task.name == "design"
            and task.actual_cost >= int(90 * 0.75)
            and task.actual_cost <= int(90 * 1.25)
            and task.module == module
        )

        task = module.get_task("implementation")
        self.assertTrue(
            task
            and task.name == "implementation"
            and task.actual_cost >= int(90 * 0.75)
            and task.actual_cost <= int(90 * 1.25)
            and task.module == module
        )

        task = module.get_task("unit_test")
        self.assertTrue(
            task
            and task.name == "unit_test"
            and task.actual_cost >= int(60 * 0.75)
            and task.actual_cost <= int(60 * 1.25)
            and task.module == module
        )

        task = module.get_task("integration")
        self.assertTrue(
            task
            and task.name == "integration"
            and task.actual_cost >= int(90 * 0.75)
            and task.actual_cost <= int(90 * 1.25)
            and task.module == module
        )

        task = module.get_task("system_test")
        self.assertTrue(
            task
            and task.name == "system_test"
            and task.actual_cost >= int(90 * 0.75)
            and task.actual_cost <= int(90 * 1.25)
            and task.module == module
        )

        task = module.get_task("deployment")
        self.assertTrue(
            task
            and task.name == "deployment"
            and task.actual_cost >= int(90 * 0.75)
            and task.actual_cost <= int(90 * 1.25)
            and task.module == module
        )

        task = module.get_task("acceptance_test")
        self.assertTrue(
            task
            and task.name == "acceptance_test"
            and task.actual_cost >= int(90 * 0.75)
            and task.actual_cost <= int(90 * 1.25)
            and task.module == module
        )

        task = module.get_task("not_a_task")
        self.assertTrue(not task)
Ejemplo n.º 43
0
    def test_productive_time_on_task(self):
        module = Module("test_module", 600)

        self.assertTrue(module.productive_time_on_task() == 0)
        module.hours_taken += 10
        self.assertTrue(module.productive_time_on_task() == 10)
Ejemplo n.º 44
0
    def test_wall_clock_time(self):
        module = Module("test_module", 600)

        self.assertTrue(module.wall_clock_time() == 0)
        module.total_hours += 10
        self.assertTrue(module.wall_clock_time() == 10)
Ejemplo n.º 45
0
def index():
    current_user.modules = list(Module.getall(current_user))
    return render_template('index.html', user=current_user, page='index', rooms=list(Room.getall()))
Ejemplo n.º 46
0
Archivo: Admin.py Proyecto: sovaa/t1000
 def __init__(self, parent):
     Module.__init__(self, parent, name = 'admin', trigger = None)
     self.config = {}
     execfile('config', {}, self.config)
     return
Ejemplo n.º 47
0
Archivo: Seen.py Proyecto: sovaa/t1000
 def __init__(self, parent, name = 'seen', trigger = '!seen'):
     Module.__init__(self, parent, name, trigger)
     self.seen = {}
     self.lockdb = thread.allocate_lock()
     return
Ejemplo n.º 48
0
 def __init__(self):
     Module.__init__(self)
Ejemplo n.º 49
0
Archivo: APK.py Proyecto: sovaa/t1000
 def __init__(self, parent):
     Module.__init__(self, parent, name = 'apk', trigger = '!apk')
     return
Ejemplo n.º 50
0
 def __init__(self, parent, name = 'megahal', trigger = None):
     Module.__init__(self, parent, name, trigger)
     mh_python.initbrain()
     return
Ejemplo n.º 51
0
	def __init__(self, application):
		Module.__init__(self, application)
		self.token = hashlib.md5("%f%f"%(random.random(), time.time())).hexdigest()
Ejemplo n.º 52
0
 def __init__(self, parent):
     Module.__init__(self, parent, name = 'gaffel', trigger = '!g')
     return
Ejemplo n.º 53
0
def modules_list():
    return jsonify(modules=Module.getall(current_user))
Ejemplo n.º 54
0
 def __init__(self, parent, name = 'httptitle', trigger = None):
     Module.__init__(self, parent, name, trigger)
     return
Ejemplo n.º 55
0
class ModuleXMLParser:
    """
    ModuleXMLParser will parse a list of modules and returns it.
    """
    def __init__(self):
        self.module_list = []
        self.param_list = []

        self.current_module = None
        self.current_param = None
        self.cdata = ""
        self.parent = None

        self.in_description = False
        self.in_command = False
        self.in_value = False
        self.in_id = False
        self.in_child = False
        self.in_dependency = False

    def start_element(self, name, attrs):
        """
        Function called when the start of an XML element is found
        """
        if name == "module":
            self.current_module = Module(attrs['name'])
            self.current_module.add_id(attrs['id'])
        elif name == "dependency":
            self.in_dependency = True
        elif name == "param":
            self.current_param = Parameter()
        elif name == "description":
            self.in_description = True
        elif name == "value":
            self.in_value = True
        elif name == "command":
            self.in_command = True
        elif name == "id":
            self.in_id = True
        elif name == "child":
            self.in_child = True
            self.parent = self.current_module

    def end_element(self, name):
        """
        Function called when the end of an XML element is found
        """
        if name == "description":
            self.in_description = False
            if self.current_param:
                # Parser is inside a parameter, add the description to it
                self.current_param.add_description(self.cdata)
            else:
                self.current_module.add_description(self.cdata)

            self.cdata = ""
        elif name == "dependency":
            self.current_module.dependencies.append(int(self.cdata))
            self.in_dependency = False
            self.cdata = ""
        elif name == "value":
            self.in_value = False
            self.current_param.add_value(self.cdata)
            self.cdata = ""
        elif name == "command":
            self.in_command = False
            self.current_module.add_command(self.cdata)
            self.cdata = ""
        elif name == "id":
            self.in_id = False    
            self.current_param.add_id(self.cdata)
            self.cdata = ""
        elif name == "param":
            self.param_list.append(self.current_param)
            self.current_param = None
        elif name == "module":
            self.module_list.append(self.current_module)
        elif name == "child":
            # TODO: Allow having more than one child
            self.parent.children = self.current_module
            self.current_module = self.parent
            self.in_child = False
            
    def char_data(self, data):
        """
        Function called when some character data within an XML element is found
        """
        data = data.strip()
        if data:
            if self.in_description or self.in_id or self.in_command or self.in_value or self.in_dependency:
                self.cdata = self.cdata + data

    def parse(self, text):
        """
        Sets up expat with the correct custom parser functions and parses text
        """
        parser = expat.ParserCreate()

        parser.StartElementHandler = self.start_element
        parser.EndElementHandler = self.end_element
        parser.CharacterDataHandler = self.char_data
        parser.Parse(text, 1)

        return (self.module_list, self.param_list)
Ejemplo n.º 56
0
 def __init__(self, parent):
     Module.__init__(self, parent, 'weather', '!w')
     return
Ejemplo n.º 57
0
 def __init__(self, parent):
     Module.__init__(self, parent, 'weatherforcast', '!wf')
     return
Ejemplo n.º 58
0
Archivo: F1.py Proyecto: sovaa/t1000
 def __init__(self, parent):
     Module.__init__(self, parent, 'f1', '!f1')
     return