Пример #1
0
def parse_to_dict(lines):
    # Initialize a first group to store key value pairs listed before the first group.
    groups = ODict()
    stats = ODict()
    name = '_root'
    groups[name] = ODict()
    stats[name] = [0,0]
    num_comment = 1
    for line in lines:
        line = line.strip()
        # Skip empty lines
        if line == "":
            continue
        # Identify a header line
        if line[0] == '[':
            if line[-1] != ']':
                raise ValueError('Found a line starting wih "[" but not ending in "]"!')
            name = line.lstrip('[').rstrip(']')
            groups[name] = ODict()
            stats[name] = [0, 0]
        # Append normal lines to the last group
        else:
            if line[0] in ["#",";"]:
                groups[name]["__comment_" + "{}".format(num_comment)] = line
                num_comment += 1
            else:
                parts = line.split()
                groups[name][parts[0]] = parts[1:]
                stats[name] += [0]*(len(parts) - len(stats[name]))
                for n,p in enumerate(parts):
                    stats[name][n] = max(stats[name][n], len(p))


    return (groups, stats)
Пример #2
0
def testValidateDataValidSigsConflictingData():
    consense = consensing.CompositeConsense()

    response1 = builder.DideryResponseBuilder(
        builder.CompositeHistoryBuilder().withRotations()).withPort(8000)
    response2 = builder.DideryResponseBuilder(
        builder.CompositeHistoryBuilder().withRotations().withRotations())
    response3 = builder.DideryResponseBuilder(
        builder.CompositeHistoryBuilder().withRotations()).withPort(8081)

    data = {
        'http://localhost:8000/event/': response1.build(),
        'http://localhost:8080/event/': response2.build(),
        'http://localhost:8081/event/': response3.build()
    }

    consense.validateData(data)

    exp_data = response1.historyBuilder.build()
    sha = sha256(str(ODict(exp_data)).encode()).hexdigest()
    bad_exp_data = response2.historyBuilder.build()
    bad_sha = sha256(str(ODict(bad_exp_data)).encode()).hexdigest()

    assert sha in consense.valid_data
    assert consense.valid_data[sha]['0'] == exp_data['0'].data
    assert consense.valid_data[sha]['1'] == exp_data['1'].data
    assert sha in consense.valid_match_counts
    assert consense.valid_match_counts[sha] == 2

    assert bad_sha in consense.valid_data
    assert consense.valid_data[bad_sha]['0'] == bad_exp_data['0'].data
    assert consense.valid_data[bad_sha]['1'] == bad_exp_data['1'].data
    assert consense.valid_data[bad_sha]['2'] == bad_exp_data['2'].data
    assert bad_sha in consense.valid_match_counts
    assert consense.valid_match_counts[bad_sha] == 1
Пример #3
0
def test_loadAllKeys():
    """
    Test loading all key files from directory
    """
    print("Testing loadAllKeys")

    keepDirPath = keeping.setupTestKeep()
    assert keepDirPath.startswith("/tmp/bluepea")
    assert keepDirPath.endswith("test/bluepea/keep")
    assert os.path.exists(keepDirPath)
    assert keepDirPath == keeping.gKeepDirPath

    prefix = "server"
    keyFilePath = os.path.join(keepDirPath, "key.{}.json".format(prefix))
    assert keyFilePath.endswith("/bluepea/keep/key.{}.json".format(prefix))

    # random seed used to generate private signing key
    #seed = libnacl.randombytes(libnacl.crypto_sign_SEEDBYTES)
    seed = (
        b'PTi\x15\xd5\xd3`\xf1u\x15}^r\x9bfH\x02l\xc6\x1b\x1d\x1c\x0b9\xd7{\xc0_'
        b'\xf2K\x93`')

    # creates signing/verification key pair
    verkey, sigkey = libnacl.crypto_sign_seed_keypair(seed)

    assert seed == sigkey[:32]
    assert verkey == (
        b'B\xdd\xbb}8V\xa0\xd6lk\xcf\x15\xad9\x1e\xa7\xa1\xfe\xe0p<\xb6\xbex'
        b'\xb0s\x8d\xd6\xf5\xa5\xe8Q')
    assert sigkey == (
        b'PTi\x15\xd5\xd3`\xf1u\x15}^r\x9bfH\x02l\xc6\x1b\x1d\x1c\x0b9\xd7{\xc0_'
        b'\xf2K\x93`B\xdd\xbb}8V\xa0\xd6lk\xcf\x15\xad9\x1e\xa7\xa1\xfe\xe0p<\xb6\xbex'
        b'\xb0s\x8d\xd6\xf5\xa5\xe8Q')

    keys = ODict(seed=binascii.hexlify(seed).decode('utf-8'),
                 sigkey=binascii.hexlify(sigkey).decode('utf-8'),
                 verkey=binascii.hexlify(verkey).decode('utf-8'))

    assert keys == ODict([
        ('seed',
         '50546915d5d360f175157d5e729b6648026cc61b1d1c0b39d77bc05ff24b9360'),
        ('sigkey',
         ('50546915d5d360f175157d5e729b6648026cc61b1d1c0b39d77bc05ff24b93604'
          '2ddbb7d3856a0d66c6bcf15ad391ea7a1fee0703cb6be78b0738dd6f5a5e851')),
        ('verkey',
         '42ddbb7d3856a0d66c6bcf15ad391ea7a1fee0703cb6be78b0738dd6f5a5e851')
    ])

    keeping.dumpKeys(keys, keyFilePath)
    assert os.path.exists(keyFilePath)
    mode = stat.filemode(os.stat(keyFilePath).st_mode)
    assert mode == "-rw-------"

    roles = keeping.loadAllKeyRoles(keepDirPath)
    assert prefix in roles
    assert roles[prefix] == keys  # round trip

    cleanupTmpBaseDir(keepDirPath)
    assert not os.path.exists(keepDirPath)
    print("Done Test")
Пример #4
0
def test_Stimulus___eq__():
    # Two Stimulus objects created from the same source data are considered
    # equal:
    for source in [3, [], np.ones(3), [3, 4, 5], np.ones((3, 6))]:
        npt.assert_equal(Stimulus(source) == Stimulus(source), True)
    stim = Stimulus(np.ones((2, 3)), compress=True)
    # Compressed vs uncompressed:
    npt.assert_equal(stim == Stimulus(np.ones((2, 3)), compress=False), False)
    npt.assert_equal(stim != Stimulus(np.ones((2, 3)), compress=False), True)
    # Different electrode names:
    npt.assert_equal(stim == Stimulus(stim, electrodes=[0, 'A2']), False)
    # Different time points:
    npt.assert_equal(stim == Stimulus(stim, time=[0, 3], compress=True), False)
    # Different data shape:
    npt.assert_equal(stim == Stimulus(np.ones((2, 4))), False)
    npt.assert_equal(stim == Stimulus(np.ones(2)), False)
    # Different data points:
    npt.assert_equal(stim == Stimulus(np.ones((2, 3)) * 1.1, compress=True),
                     False)
    # Different shape
    npt.assert_equal(stim == Stimulus(np.ones((2, 5))), False)
    # Different type:
    npt.assert_equal(stim == ODict(), False)
    npt.assert_equal(stim != ODict(), True)
    # Time vs no time:
    npt.assert_equal(Stimulus(2) == stim, False)
    # Annoying but possible:
    npt.assert_equal(Stimulus([]), Stimulus(()))
Пример #5
0
def cast_parameters(xml_block, default_parameters):
    """
    Cast parameters of an xml block with the default parameters
    """
    result = ODict(default_parameters)
    for name, value in xml_block.parameters.items():
        if name not in default_parameters:
            msg = "Action '{}' has no parameters called '{}'"
            msg = msg.format(xml_block.block_id, name)
            raise ActionCreationError(msg)
        try:
            if isinstance(default_parameters[name], bool) and \
               isinstance(value, basestring):
                if value.lower() in ["true", "1"]:
                    cast_value = True
                elif value.lower() in ["false", "0"]:
                    cast_value = False
                else:
                    raise Exception()
            else:
                cast_value = type(default_parameters[name])(value)
        except:
            msg = "Error while casting parameters '{}' of action '{}'"
            msg = msg.format(name, xml_block.block_id)
            raise ActionCreationError(msg)
        result[name] = cast_value
    # Save values
    xml_block.parameters = ODict(result)
    # Cast Enum to string
    for name, value in result.items():
        if isinstance(value, BaseEnum):
            result[name] = unicode(value)
    return result
Пример #6
0
 def __init__(self, source, *args, **kwargs): 
     LOGGER.debug("WebData Loading: {}".format(self.__class__.__name__)) 
     parent = self.WebDOM(self.setup(source))   
     if bool(parent): LOGGER.debug("WebData Loaded: {}".format(self.__class__.__name__))
     else: LOGGER.debug("WebData Missing: {}".format(self.__class__.__name__))    
     if bool(parent): children = ODict([(key, WebDOMChild(parent.DOM)) for key, WebDOMChild in self.WebDOMChildren.items()])
     else: children = ODict([(key, None) for key, WebDOMchild in self.WebDOMChildren.items()])            
     super().__init__(parent, children)         
Пример #7
0
    def _internal(self, source):
        # Error check
        data = np.asarray(source['data'])
        if data.ndim == 0:
            # Convert scalar to 1-dim array:
            data = np.array([data])
        if source['axes'] is None:
            # Automatic axis labels and values: 'axis0', 'axis1', etc.
            axes = ODict([('axis%d' % d, np.arange(data.shape[d]))
                          for d in np.arange(data.ndim)])
        else:
            # Build an ordered dictionary from the provided axis labels/values
            # and make sure it lines up with the dimensions of the NumPy array:
            try:
                axes = ODict(source['axes'])
            except TypeError:
                raise TypeError("'axes' must be either an ordered dictionary "
                                "or a list of tuples (label, values).")
            if len(axes) != data.ndim:
                raise ValueError("Number of axis labels (%d) does not match "
                                 "number of dimensions in the NumPy array "
                                 " (%d)." % (len(axes), data.ndim))
            if len(np.unique(list(axes.keys()))) < data.ndim:
                raise ValueError("All axis labels must be unique.")
            for i, (key, values) in enumerate(axes.items()):
                if values is None:
                    # Fill in omitted axis:
                    axes[key] = np.arange(data.shape[i])
                    continue
                if len(values) != data.shape[i]:
                    err_str = ("Number of values for axis '%s' (%d) does not "
                               "match data.shape[%d] "
                               "(%d)" % (key, len(values), i, data.shape[i]))
                    raise ValueError(err_str)

        # Create a property for each of the following:
        pprint_params = ['data', 'dtype', 'shape', 'metadata']
        for param in pprint_params:
            setattr(self.__class__, param,
                    property(fget=self._fget_prop(param)))

        # Also add axis labels as properties:
        for axis, values in axes.items():
            setattr(self.__class__, axis, property(fget=self._fget_axes(axis)))
        pprint_params += list(axes.keys())

        # Internal data structure is a dictionary that stores the actual data
        # container as an N-dim array alongside axis labels and metadata.
        # Setting all elements at once enforces consistency; e.g. between shape
        # and axes:
        self.__internal = {
            'data': data,
            'dtype': data.dtype,
            'shape': data.shape,
            'axes': axes,
            'metadata': source['metadata'],
            'pprint_params': pprint_params
        }
Пример #8
0
    def __init__(self, urdf, options={}) :
        if opt_key_prune not in options:
            options[opt_key_prune] = False
        if opt_key_toframes not in options:
            options[opt_key_toframes] = True
        if opt_key_lumpi not in options :
            options[opt_key_lumpi] = True

        self.robotName = urdf.robotName
        self.links  = ODict()
        self.joints = ODict()
        self.frames = ODict()

        for urdfname in urdf.links.keys() :
            name = self.toValidID( urdfname )
            link = Converter.Link( name )
            self.links[name] = link

        for jname in urdf.joints.keys() :
            urdfjoint = urdf.joints[jname]
            name = self.toValidID( jname )
            joint= Converter.Joint( name )
            joint.type = urdfjoint.type

            joint.predecessor = self.links[ self.toValidID(urdfjoint.parent) ]
            joint.successor   = self.links[ self.toValidID(urdfjoint.child)  ]
            self.convertJointFrame(joint, urdfjoint)

            joint.successor.parent = joint.predecessor
            joint.successor.parentJ= joint
            joint.predecessor.children.append( (joint.successor, joint) )
            self.joints[name] = joint

        orphans = [l for l in self.links.values() if l.parent==None]
        if len(orphans)==0 :
            logger.fatal("Could not find any root link (i.e. a link without parent).")
            logger.fatal("Check for kinematic loops.")
            raise RuntimeError("no root link found")
        if len(orphans) > 1 :
            logger.warning("Found {0} links without parent, only one expected".format(len(orphans)))
            logger.warning("Any robot model must have exactly one root element.")
            logger.warning("This might lead to unexpected results.")
        self.root = orphans[0]

        self.leafs = [l for l in self.links.values() if len(l.children)==0]

        # Conversion of the inertia must happen after the joint frame conversion,
        # which determines the required coordinate transforms
        for urdfname in urdf.links.keys() :
            name = self.toValidID( urdfname )
            self.convertInertialData(self.links[name], urdf.links[urdfname].inertia)

        if options[opt_key_prune] :
            # Let's first explicitly check for the nasty case where the root is
            # a dummy link, connected via a fixed joint to the first link
            self._collapseDummyRoots()
            self._pruneFixedJoints(options)
Пример #9
0
    def extract(self, format_hint=None):
        funs = ODict(self._XMAPPING)

        fmt, text = self.content_str()

        if fmt and not format_hint:
            format_hint = fmt

        if format_hint:
            assert format_hint in funs.keys()

        if format_hint:
            try:
                f = funs.pop(format_hint)
                return format_hint, self.do_parse(f, text)
            except Exception as e:
                pass

        for fname, f in funs.items():
            try:
                return fname, self.do_parse(f, text)
            except Exception as e:
                pass

        raise Exception('Unspported format')
Пример #10
0
def testValidateDataMajorityPasses():
    consense = consensing.CompositeConsense()

    response1 = builder.DideryResponseBuilder(
        builder.CompositeHistoryBuilder().withRotations()).withPort(8000)
    response2 = builder.DideryResponseBuilder(builder.CompositeHistoryBuilder(
    ).withRotations().withInvalidRotationSigAt(1))
    response3 = builder.DideryResponseBuilder(
        builder.CompositeHistoryBuilder().withRotations()).withPort(8081)

    data = {
        'http://localhost:8000/event/': response1.build(),
        'http://localhost:8080/event/': response2.build(),
        'http://localhost:8081/event/': response3.build()
    }

    consense.validateData(data)

    exp_data = response1.historyBuilder.build()
    sha = sha256(str(ODict(exp_data)).encode()).hexdigest()

    assert sha in consense.valid_data
    assert consense.valid_data[sha]['0'] == exp_data['0'].data
    assert consense.valid_data[sha]['1'] == exp_data['1'].data
    assert sha in consense.valid_match_counts
    assert consense.valid_match_counts == {sha: 2}
Пример #11
0
def loadAllKeyRoles(dirpath, prefix="key", role=""):
    """
    Load and Return the keys dict indexed by role for all key data files with
    prefix in  directory at dirpath  both .json and .msgpack file extensions
    are supported

    If role is not empty then loads last keyfile that matches both prefix and role

    key files names of form:
    prefix.role.json
    prefix.role.msgpack

    (when prefix is the default "key" )
    key.server.json
    key.server.msgpack

    key fields in keyfiles should be in:
    ('seed', 'sigkey', 'verkey', 'prikey', 'pubkey')

    values are bytes of binary key value

    """
    roles = ODict()
    for filename in os.listdir(dirpath):  # filenames without directory
        filepath = os.path.join(dirpath, filename)  # need full path for isfile
        if not os.path.isfile(filepath):
            continue
        root, ext = os.path.splitext(filename)
        if ext not in ['.json', '.msgpack']:
            continue
        pre, sep, rol = root.partition('.')
        if not rol or pre != prefix or (role and rol != role):
            continue
        roles[rol] = loadKeys(filepath)
    return roles
Пример #12
0
class CallRecording(Module):
    description = "Call Recordings"
    item_name = "Call Recording"
    repr_format = "{description}"
    dest_regex = "ext-callrecording,([0-9]+)"

    pk_field = "callrecording_id"
    db_table = "callrecording"

    render_template = "list.tpl"

    config_param = staticmethod(
        lambda s: {
            "display": "callrecording",
            "type": "setup",
            "extdisplay": s["callrecording_id"]
        })

    fields = ODict([
        ("callrecording_id", IntField()),
        ("description", StringField("description")),
        ("callrecording_mode",
         EnumField(
             "call recording mode", {
                 "": "Allow",
                 "delayed": "Record on Answer",
                 "force": "Record Immediately",
                 "never": "Never"
             })),
        ("dest", DestinationField("destination")),
    ])
Пример #13
0
    def validateData(self, history_events):
        """
            Checks for request errors and counts valid signatures

            :param history_events: dict of history rotation events returned by the didery server
        """
        for url, response in history_events.items():
            status = response.status
            data = response.response

            if status == 0:
                self.addTimeOut(url)  # Request timed out
                continue
            elif status != 200:
                self.addError(url, data, status)  # Error with request
                continue

            valid = True if len(data) > 0 else False

            for index, event in data.items():
                if not event.valid:
                    valid = False

            if valid:
                sha = sha256(str(ODict(data)).encode()).hexdigest()
                self.addSuccess(url, sha, self._dataToDict(data), status)  # Signature validated
            else:
                self.addFailure(url, data, status)  # Signature validation failed
Пример #14
0
def getRecsTree(srcDir):
    depths, dataFolders = getDataFolders(srcDir)
    recsTree = ODict()
    for depth, dataFoldersAtDepth in zip(depths, dataFolders):
        recs = []
        if not depth in recsTree.keys():
            recsTree[depth] = {}
        for folder in dataFoldersAtDepth:
            try:
                recs.append(Recording(folder))
            except RuntimeError as err:  # Could not create instance
                print(
                    "Warning: could not create recording for folder {}, skipping; {}"
                    .format(folder, err))
        numberedRecs = setRecNbs(recs)
        if numberedRecs:  # Skip if nothing of type 'rec'
            try:
                angle = list(numberedRecs.keys())[0]
                numberedRecsDict = list(numberedRecs.values())[0]
            except IndexError:
                print("Depth: {}".format(depth))
                print("\tRecordings: {}".format(numberedRecs))
                raise
            recsTree[depth][angle] = numberedRecsDict
    return recsTree
def calc_using_eval_module(
    y_clean: ndarray, y_est: ndarray, T_ys: Sequence[int] = (0, )) -> ODict:
    """ calculate metric using EvalModule. y can be a batch.

    :param y_clean:
    :param y_est:
    :param T_ys:
    :return:
    """

    if y_clean.ndim == 1:
        y_clean = y_clean[np.newaxis, ...]
        y_est = y_est[np.newaxis, ...]
    if T_ys == (0, ):
        T_ys = (y_clean.shape[1], ) * y_clean.shape[0]

    keys = None
    sum_result = None
    for T, item_clean, item_est in zip(T_ys, y_clean, y_est):
        # noinspection PyArgumentList,PyTypeChecker
        temp: ODict = EvalModule(item_clean[:T], item_est[:T], hp.fs)
        result = np.array(list(temp.values()))
        if not keys:
            keys = temp.keys()
            sum_result = result
        else:
            sum_result += result

    return ODict(zip(keys, sum_result.tolist()))
Пример #16
0
def test_exists():
    """

    """
    print("Testing exits in DB Env")

    dbEnv = dbing.setupTestDbEnv()

    data = ODict()
    data["name"] = "John Smith"
    data["city"] = "Alta"
    datab = json.dumps(data, indent=2).encode("utf-8")

    dbCore = dbing.gDbEnv.open_db(
        b'core')  # open named sub db named 'core' within env
    with dbing.gDbEnv.begin(db=dbCore,
                            write=True) as txn:  # txn is a Transaction object
        txn.put(b'person0', datab)  # keys and values are bytes
        d0b = txn.get(b'person0')
        assert d0b == datab

    result = dbing.exists(key="person0")
    assert result is True
    result = dbing.exists(key="person1")
    assert result is False

    cleanupTmpBaseDir(dbEnv.path())
    print("Done Test")
Пример #17
0
class Queue(Module):
    description = "Queues"
    item_name = "Queue"
    repr_format = "{extension}: {descr}"
    dest_regex = "ext-queues,([0-9]+)"
    db_table = "queues_config"
    render_template = "list.tpl"
    pk_field = "extension"

    config_param = staticmethod(lambda s: {
        "display": "queues",
        "extdisplay": s["extension"]
    })

    fields = ODict([
        ("extension", IntField("queue number")),
        ("descr", StringField("queue name")),
        ("password", StringField("queue password")),
        ("togglehint", BooleanField("generate device hints", (0, 1))),
        ("callconfirm", BooleanField("call confirm", (0, 1))),
        ("callconfirm_id",
         ForeignKeyField("call confirm announce", "Recording",
                         {0: "Default"})),
        ("grppre", StringField("CID name prefix")),
        ("queuewait", BooleanField("wait time prefix", (0, 1))),
        ("alertinfo", StringField("alertinfo")),
        ("members", ListField(
            "\n", "static agents").xpath('//textarea[@id="members"]//text()')),
        ("dynmembers", ListField(
            "\n",
            "dynamic members").xpath('//textarea[@id="dynmembers"]//text()')),
        ("dest", DestinationField("fail over destination")),
    ])
Пример #18
0
 def default(self, obj):
     if isinstance(obj, PlotData):
         return ODict([("__type__", "PlotData"), ("title", obj.title),
                       ("plot_type", obj.plot_type), ("xlabel", obj.xlabel),
                       ("ylabel", obj.ylabel), ("subplots", obj.subplots)])
     else:
         return json.JSONEncoder.default(self, obj)
Пример #19
0
    def on_post(self, req, rep, userId):
        """
        Handles POST requests
        """
        try:
            raw_json = req.stream.read()
        except Exception:
            raise falcon.HTTPError(falcon.HTTP_748, 'Read Error',
                                   'Could not read the request body.')

        try:
            data = json.loads(raw_json, 'utf-8')
        except ValueError:
            raise falcon.HTTPError(
                falcon.HTTP_753, 'Malformed JSON',
                'Could not decode the request body. The '
                'JSON was incorrect.')

        #console.terse("Received JSON Data: \n{}\n".format(data))

        result = ODict(userId=userId, data=data)

        #rep.status = falcon.HTTP_201
        #rep.location = '/example/%s' % (userId)  # location header redirect

        rep.status = falcon.HTTP_200  # This is the default status
        rep.body = json.dumps(result)
Пример #20
0
class DirectoryEntry(Module):
    description = "Directory Entries"
    item_name = "Directory Entry"
    repr_format = "{name}"
    db_table = "directory_entries"
    pk_field = "id"

    render_template = None

    fields = ODict([("id", IntField()), ("e_id", IntField()),
                    ("name", StringField()), ("audio", StringField()),
                    ("type", StringField()), ("foreign_id", IntField()),
                    ("dial", StringField())])

    def __repr__(self):
        #for k, v in self.fields.iteritems():
        #print self["audio"].value
        if self["type"].value == "user":
            self["dial"].value = str(self["foreign_id"])
            self["name"].value = self._pbx["Extension"].get(
                self["foreign_id"].value)["name"].value

        audio = {
            "tts": "Text-to-speech",
            "spell": "Spell name",
            "vm": "Voicemail Greeting",
            None: "Voicemail Greeting"
        }.get(self["audio"].value, "")

        if len(audio) == 0:
            audio = int(self["audio"].value)
            audio = "Recording: %s" % self._pbx["Recording"].get(audio)

        return "%s (%s): %s" % (self["name"], audio, self["dial"])
Пример #21
0
 def __init__(self, source, *args, **kwargs): 
     LOGGER.debug("WebDatas Loading: {}".format(self.__class__.__name__)) 
     parents = [self.WebDOM(dom) for dom in self.setup(source)] 
     if bool(parents): LOGGER.debug("WebDatas Loaded: {}".format(self.__class__.__name__))
     else: LOGGER.debug("WebDatas Missing: {}".format(self.__class__.__name__))    
     childrens = [ODict([(key, WebDOMChild(parent.DOM)) for key, WebDOMChild in self.WebDOMChildren.items()]) for parent in parents]
     self.__collection = [(parent, children) for parent, children in zip(parents, childrens)]         
Пример #22
0
class Recording(Module):
    description = "Recordings"
    item_name = "Recording"
    repr_format = "{displayname}"
    render_template = "list.tpl"
    db_table = "recordings"
    pk_field = "id"

    config_param = staticmethod(lambda s: {
        "display": "recordings",
        "action": "edit",
        "usersnum": "",
        "id": s["id"]
    })

    fields = ODict([
        ("id", IntField()),
        ("displayname", StringField("name")),
        ("filename", StringField("file path")),
        ("fcode", BooleanField("link to feature code", (0, 1))),
        ("fcode_pass", IntField("feature code password")),
    ])

    def __len__(self):
        return Module.__len__(self)
Пример #23
0
def xmlEntry(entry, path):
    dEntry = ODict({
        'Password': '',
        'Title': '',
        'UserName': '',
        'URL': '',
        'Notes': ''
    })
    sEntry = ''

    for string in entry.findall('String'):
        key = string.find('Key').text
        val = string.find('Value').text

        if key in dEntry:
            dEntry[key] = val

    path += "/{}".format(dEntry['Title'])
    del dEntry['Title']

    print(path)
    print("=" * len(path))

    for key, val in dEntry.items():
        if (val is not None):
            if (key.lower() == 'password'):
                sEntry += "{}\n".format(val)
            elif (key.lower() == 'username'):
                sEntry += "user: {}\n\n".format(val)
            elif ():
                sEntry += "{}\n".format(val)
            else:
                sEntry += "{}: {}\n".format(key.lower(), val)
    print(sEntry)
    passAddEntry(sEntry, path)
Пример #24
0
class RingGroup(Module):
    description = "Ring Groups"
    item_name = "Ring Group"
    repr_format = "{description} ({grpnum})"
    dest_regex = "ext-group,([0-9]+)"

    db_table = "ringgroups"
    pk_field = "grpnum"
    render_template = "list.tpl"
    config_param = staticmethod(lambda s: {
        "display": "ringgroups",
        "extdisplay": "GRP-%s" % s["grpnum"]
    })

    fields = ODict([
        ("grpnum", IntField("group number")),
        ("description", StringField("group description")),
        ("strategy", StringField("ring strategy")),
        ("grptime", IntField("ring time")),
        ("grplist", ListField("-", "extension list")),
        ("annmsg_id", ForeignKeyField("announcement", "Recording",
                                      {0: "None"})),
        ("ringing", StringField("play music on hold")),
        ("grppre", StringField("CID name prefix")),
        ("alertinfo", StringField("alert info")),
        ("cfignore", BooleanField("ignore CF settings", ("", "CHECKED"))),
        ("cwignore", BooleanField("skip busy agent", ("", "CHECKED"))),
        ("cpickup", BooleanField("enable call pickup", ("", "CHECKED"))),
        ("needsconf", BooleanField("confirm calls", ("", "CHECKED"))),
        ("remotealert_id",
         ForeignKeyField("remote announce", "Recording", {0: "Default"})),
        ("toolate_id",
         ForeignKeyField("too-late announce", "Recording", {0: "Default"})),
        ("postdest", DestinationField("destination if no answer")),
    ])
Пример #25
0
class Announcement(Module):
    description = "Announcements"
    item_name = "Announcement"
    repr_format = "{description}"
    dest_regex = "app-announcement-([0-9]+)"

    db_table = "announcement"
    pk_field = "announcement_id"
    render_template = "list.tpl"
    config_param = staticmethod(
        lambda s: {
            "display": "announcement",
            "type": "setup",
            "extdisplay": s["announcement_id"]
        })

    fields = ODict([
        ("announcement_id", IntField()),
        ("description", StringField("description")),
        ("recording_id", ForeignKeyField("recording", "Recording",
                                         {0: "None"})),
        ("allow_skip", BooleanField("allow skip", (0, 1))),
        ("return_ivr", BooleanField("return to IVR", (0, 1))),
        ("noanswer", BooleanField("don't answer channel", (0, 1))),
        ("repeat_msg", StringField("repeat")),
        ("post_dest", DestinationField("destination after playback")),
    ])
Пример #26
0
def delegator():
    """
    example generator that yields empty bytes before returning data
    """
    for i in range(10):
        yield bytes()
        time.sleep(0.1)
    return ODict(name="John Smith", country="United States")
Пример #27
0
 def __init__(self, namestr):
     self.name    = namestr
     self.parent  = None
     self.parentJ = None
     self.children= list()
     self.inertia = dict()
     self.frames  = ODict()
     self.rcg_R_urdf = np.identity(3)
Пример #28
0
    def __call__(self, clean: ndarray, noisy: ndarray, fs: int) -> ODict:
        import matlab
        clean = matlab.double(clean.tolist())
        noisy = matlab.double(noisy.tolist())
        fs = matlab.double([fs])
        results = self.eng.se_eval(clean, noisy, fs, nargout=3, stdout=self.strio)

        return ODict([(m, r) for m, r in zip(Evaluation.metrics, results)])
Пример #29
0
    def __init__(self, obj, defaultflags=None):
        """
        :param obj, (int, dict):
            either the decimal form of the bitwise array, or
            a dictionary (complete or otherwise) of the form
            {flag : bool, flag : bool, ...}
        :param defaultflags, dict:
            a dictionary representing the default for
            one or more flags.  Only applicable
            when a dictionary is passed to obj.  It's
            ignored when obj is an integer.
        """

        # calculate an msb-like number, which is actually
        # the msb * 2 to get one more digit than
        # the number of flags

        self.msb = 2 ** (len(BitFlag.flags) + 1)

        # if an integer was passed...
        # convert it to a boolean array
        if isinstance(obj, int):
            self.val = obj % self.msb
            tmp = self.val + self.msb

            self.bools = []
            while tmp != 0:
                self.bools.append(tmp % 2 == 1)
                tmp >>= 1
            self.bools = self.bools[:-1]

            for i, key in enumerate(BitFlag.flags):
                setattr(self, key, self.bools[i])

        # a dict of the form {flags : bool, } was passed...
        # convert it to the boolean array just the same.
        elif isinstance(obj, (dict, list)):
            if isinstance(obj, list):
                obj = dict(zip(obj, [True] * len(obj)))
            # if there are defaultflags, use them, otherwise assume all flags
            # are unset
            if defaultflags:
                defaults = defaultflags
            else:
                defaults = zip(BitFlag.flags, [False] * len(BitFlag.flags))
                defaults = ODict(defaults)

            self.bools = []
            self.val = 0
            for i, key in enumerate(BitFlag.flags):
                if key in obj:
                    val = obj[key]
                else:
                    val = defaults[key]
                setattr(self, key, val)
                self.bools.append(val)
                if val:
                    self.val += 2 ** i
Пример #30
0
class IVR(Module):
    description = "IVRs"
    item_name = "IVR"
    repr_format = "{name}"
    dest_regex = "ivr-([0-9]+)"

    db_table = "ivr_details"
    pk_field = "id"
    render_template = "list.tpl"
    config_param = staticmethod(lambda s: {
        "display": "ivr",
        "action": "edit",
        "id": s["id"]
    })

    fields = ODict([
        ("id", IntField()),
        ("name", StringField("IVR name")),
        ("description", StringField("IVR description")),
        ("announcement",
         ForeignKeyField("announcement", "Recording", {0: "None"})),
        ("directdial",
         ForeignKeyField("direct dial", "Directory", {
             "": "Disabled",
             "ext-local": "Extensions"
         })),
        ("timeout_time", IntField("timeout")),
        ("invalid_loops", IntField("invalid loops")),
        ("invalid_retry_recording",
         ForeignKeyField("invalid retry recording", "Recording", {
             "": "None",
             "default": "Default"
         })),
        ("invalid_append_announce",
         BooleanField("append announcement on invalid", (0, 1))),
        ("invalid_recording",
         ForeignKeyField("invalid recording", "Recording", {
             "": "None",
             "default": "Default"
         })),
        ("invalid_destination", DestinationField("invalid destination")),
        ("timeout_loops", IntField("timeout retries")),
        ("timeout_retry_recording",
         ForeignKeyField("timeout retry recording", "Recording", {
             "": "None",
             "default": "Default"
         })),
        ("timeout_append_announce",
         BooleanField("append announcement on timeout", (0, 1))),
        ("timeout_recording",
         ForeignKeyField("timeout recording", "Recording", {
             "": "None",
             "default": "Default"
         })),
        ("timeout_destination", DestinationField("timeout destination")),
        ("retvm", BooleanField("return to IVR after VM", ("", "on"))),
        ("entries", ManyToManyField("IVR entries", "IVREntry", "ivr_id")),
    ])