Example #1
0
def run301_04():
    """
    sequence ops
    :return:
    """
    a = [1, 2, 3]
    b = ['a', 'b', 'c']

    print('a=', a)
    print('b=', b)

    print('Constructive:')
    print('concat(a,b): ', concat(a, b))

    print('\nSearching:')
    print('contains(a,1):', contains(a, 1))
    print('contains(b,"d"):', contains(b, 'd'))
    print('countOf(a,1):', countOf(a, 1))
    print('countOf(b,"d"):', countOf(b, 'd'))
    print('indexOf(a,1):', indexOf(a, 1))
    # print('indexOf(a,5):', indexOf(a, 5)) # ValueError

    print('\nAccess Items:')
    print('getitem(b,1):', getitem(b, 1))
    print('getitem(b,slice(1,3)):', getitem(b, slice(1, 3)))
    print('setitem(b,1,"d"):', setitem(b, 1, 'd'))
    print(b)
    print('setitem(a,slice(1,3),[4,5]):', setitem(a, slice(1, 3), [4, 5]))
    print(a)

    print('\nDestructive:')
    print('delitem(b,1)', delitem(b, 1))
    print(b)
    print('delitem(a,slice(1,3))', delitem(b, slice(1, 3)))
    print(a)
Example #2
0
    def test_simple(self):
        # create classes holding simple numeric types, and check
        # various properties.

        init = range(15, 25)

        for fmt in formats:
            alen = len(init)
            int_array = ARRAY(fmt, alen)

            ia = int_array(*init)
            # length of instance ok?
            assert len(ia) == alen

            # slot values ok?
            values = [ia[i] for i in range(len(init))]
            assert values == init

            # change the items
            from operator import setitem
            new_values = range(42, 42 + alen)
            [setitem(ia, n, new_values[n]) for n in range(alen)]
            values = [ia[i] for i in range(len(init))]
            assert values == new_values

            # are the items initialized to 0?
            ia = int_array()
            values = [ia[i] for i in range(len(init))]
            assert values == [0] * len(init)

            # Too many in itializers should be caught
            with pytest.raises(IndexError):
                int_array(*range(alen * 2))

        CharArray = ARRAY(c_char, 3)

        ca = CharArray("a", "b", "c")

        # Should this work? It doesn't:
        # CharArray("abc")
        with pytest.raises(TypeError):
            CharArray("abc")

        assert ca[0] == "a"
        assert ca[1] == "b"
        assert ca[2] == "c"
        assert ca[-3] == "a"
        assert ca[-2] == "b"
        assert ca[-1] == "c"

        assert len(ca) == 3

        # slicing is now supported, but not extended slicing (3-argument)!
        from operator import getslice, delitem
        with pytest.raises(TypeError):
            getslice(ca, 0, 1, -1)

        # cannot delete items
        with pytest.raises(TypeError):
            delitem(ca, 0)
def main():
    a = [1, 2, 3]
    b = ["a", "b", "c"]

    print("a =", a)
    print("b =", b)

    print("\nConstructive:")
    print("  concat(a, b)", operator.concat(a, b))

    print("\nSearching:")
    print("  contains(a, 1)  :", operator.contains(a, 1))
    print("  contains(b, 'd'):", operator.contains(b, "d"))
    print("  countOf(a, 1)   :", operator.countOf(a, 1))
    print("  countOf(b, 'd') :", operator.countOf(b, "d"))
    print("  indexOf(a, 1)   :", operator.indexOf(a, 1))

    print("\nAccess Items:")
    print("  getitem(b, 1)                  :", operator.getitem(b, 1))
    print("  getitem(b, slice(1, 3))        :",
          operator.getitem(b, slice(1, 3)))
    print("  setitem(b, 1, 'd')             :", end=" ")
    operator.setitem(b, 1, "d")
    print(b)
    print("  setitem(a, slice(1, 3), [4,5]):", end=" ")
    operator.setitem(a, slice(1, 3), [4, 5])
    print(a)

    print("\nDestructive:")
    print("  delitem(b, 1)          :", end=" ")
    operator.delitem(b, 1)
    print(b)
    print("  delitem(a, slice(1, 3)):", end=" ")
    operator.delitem(a, slice(1, 3))
    print(a)
Example #4
0
 def remove_index_operation(self, name):
     if name in self._index_operations:
         delitem(self._index_operations, name)
         #delattr(self, name)
     else:
         raise AttributeError(
             "No index operation with the name {}".format(name))
Example #5
0
 def test__delitem__(self):
     from operator import delitem
     del self.stuf['test1']
     self.assertRaises(KeyError, lambda: delitem(self.stuf, 'test2'))
     self.assertRaises(KeyError, lambda: delitem(self.stuf, 'test3'))
     self.assertEqual(len(self.stuf), 2)
     self.assertNotIn('test1', self.stuf)
     self.assertIn('test2', self.stuf)
     self.assertIn('test3', self.stuf)
Example #6
0
 def currMod_End(self, name, attrs):
         log(1, "Fun "+name+"_End", attrs)
         cm="\nvoid test_%s(void)\n{" %self.modName
         cm+=self.elements['lvariable']
         cm+="\n\n  hdr(\"Testing of %s module started\");" %self.modName
         cm+=self.elements['testCase']
         cm+="\n  hdr(\"Testing of %s module compleated\");" %self.modName
         cm+="\n}\n"
         self.elements[name]+=cm
         operator.delitem(self.elements, 'lvariable')
         operator.delitem(self.elements, 'testCase')
    def test_operations(self):
        repl_cfg = {'members': [{}, {}]}
        repl = ReplicaSet(repl_cfg)

        self.assertEqual(len(self.rs), 0)
        operator.setitem(self.rs, 1, repl)
        self.assertEqual(len(self.rs), 1)
        self.assertEqual(operator.getitem(self.rs, 1).repl_id, repl.repl_id)
        operator.delitem(self.rs, 1)
        self.assertEqual(len(self.rs), 0)
        self.assertRaises(KeyError, operator.getitem, self.rs, 1)
Example #8
0
    def test_operations(self):
        repl_cfg = {'members': [{}, {}]}
        repl = ReplicaSet(repl_cfg)

        self.assertEqual(len(self.rs), 0)
        operator.setitem(self.rs, 1, repl)
        self.assertEqual(len(self.rs), 1)
        self.assertEqual(operator.getitem(self.rs, 1).repl_id, repl.repl_id)
        operator.delitem(self.rs, 1)
        self.assertEqual(len(self.rs), 0)
        self.assertRaises(KeyError, operator.getitem, self.rs, 1)
    def test_operations(self):
        config = {'shards': [{}, {}, {}]}
        cluster = ShardedCluster(config)

        self.assertEqual(len(self.sh), 0)
        operator.setitem(self.sh, 1, cluster)
        self.assertEqual(len(self.sh), 1)
        self.assertEqual(operator.getitem(self.sh, 1)['id'], cluster.id)
        operator.delitem(self.sh, 1)
        self.assertEqual(len(self.sh), 0)
        self.assertRaises(KeyError, operator.getitem, self.sh, 1)
        cluster.cleanup()
    def test_operations(self):
        config = {'shards': [{}, {}, {}]}
        cluster = ShardedCluster(config)

        self.assertEqual(len(self.sh), 0)
        operator.setitem(self.sh, 1, cluster)
        self.assertEqual(len(self.sh), 1)
        self.assertEqual(operator.getitem(self.sh, 1)['id'], cluster.id)
        operator.delitem(self.sh, 1)
        self.assertEqual(len(self.sh), 0)
        self.assertRaises(KeyError, operator.getitem, self.sh, 1)
        cluster.cleanup()
    def test_operations(self):
        config = {'members': [{}, {}, {}]}
        shard = Shard(config)

        self.assertEqual(len(self.sh), 0)
        operator.setitem(self.sh, 1, shard)
        self.assertEqual(len(self.sh), 1)
        self.assertEqual(operator.getitem(self.sh, 1)['id'], shard.id)
        operator.delitem(self.sh, 1)
        self.assertEqual(len(self.sh), 0)
        self.assertRaises(KeyError, operator.getitem, self.sh, 1)
        shard.cleanup()
Example #12
0
 def test_delitem(self):
     #operator = self.module
     a = [4, 3, 2, 1]
     self.assertRaises(TypeError, operator.delitem, a)
     self.assertRaises(TypeError, operator.delitem, a, None)
     self.assertTrue(operator.delitem(a, 1) is None)
     self.assertTrue(a == [4, 2, 1])
Example #13
0
 def test_delitem(self):
     #operator = self.module
     a = [4, 3, 2, 1]
     self.assertRaises(TypeError, operator.delitem, a)
     self.assertRaises(TypeError, operator.delitem, a, None)
     self.assertTrue(operator.delitem(a, 1) is None)
     self.assertTrue(a == [4, 2, 1])
Example #14
0
        def patchdict(k, v):
            if k in os.environ:
                self._cleanups.append(lambda old=os.environ[k]: setitem(os.environ, k, old))
            else:
                self._cleanups.append(lambda: delitem(os.environ, k))

            os.environ[k] = v
Example #15
0
 def update(self, __m: Mapping[Any, Any], **kwargs: Any) -> None:
     changes, deletions, = get_diff(self, dict(__m))
     self.diff.changes.update(changes)
     [delitem(self.diff.changes, key) for key in deletions]
     self.diff.deletions.update(deletions)
     [self.diff.deletions.discard(key) for key in changes.keys()]
     super(JSONVC, self).update(__m, **kwargs)
Example #16
0
    def __delitem__(self, key: Any) -> None:

        if isinstance(key, ConstructSymbol):
            del self._dict[key]
            self._disconnect(key)
        else:
            self._consume_multiindex(key[:-1], lambda a: delitem(a, key[-1]))
Example #17
0
        def patchdict(k, v):
            if k in os.environ:
                self._cleanups.append(
                    lambda old=os.environ[k]: setitem(os.environ, k, old))
            else:
                self._cleanups.append(lambda: delitem(os.environ, k))

            os.environ[k] = v
    def test_operations(self):
        server_id = self.servers.create('mongod', {}, autostart=False)
        self.assertTrue(len(self.servers) == 1)
        self.assertTrue(server_id in self.servers)
        server_id2 = 'server-id2'
        server2 = Server(os.path.join(os.environ.get('MONGOBIN', ''), 'mongod'), {})
        server2.start(30)
        server2_pid = server2.info()['procInfo']['pid']
        self.servers[server_id2] = server2
        self.assertTrue(self.servers[server_id2]['procInfo']['pid'] == server2_pid)
        self.assertTrue(server_id2 in self.servers)
        for h_id in self.servers:
            self.assertTrue(h_id in (server_id, server_id2))

        operator.delitem(self.servers, server_id2)
        self.assertFalse(server_id2 in self.servers)
        server2.stop()
        server2.cleanup()
    def test_operations(self):
        host_id = self.hosts.create('mongod', {}, autostart=False)
        self.assertTrue(len(self.hosts) == 1)
        self.assertTrue(host_id in self.hosts)
        host_id2 = 'host-id2'
        host2 = Host(os.path.join(os.environ.get('MONGOBIN', ''), 'mongod'), {})
        host2.start(30)
        host2_pid = host2.info()['procInfo']['pid']
        self.hosts[host_id2] = host2
        self.assertTrue(self.hosts[host_id2]['procInfo']['pid'] == host2_pid)
        self.assertTrue(host_id2 in self.hosts)
        for h_id in self.hosts:
            self.assertTrue(h_id in (host_id, host_id2))

        operator.delitem(self.hosts, host_id2)
        self.assertFalse(host_id2 in self.hosts)
        host2.stop()
        host2.cleanup()
    def test_operations(self):
        server_id = self.servers.create('mongod', {}, autostart=False)
        self.assertTrue(len(self.servers) == 1)
        self.assertTrue(server_id in self.servers)
        server_id2 = 'server-id2'
        server2 = Server(os.path.join(os.environ.get('MONGOBIN', ''), 'mongod'), {})
        server2.start(30)
        server2_pid = server2.info()['procInfo']['pid']
        self.servers[server_id2] = server2
        self.assertTrue(self.servers[server_id2]['procInfo']['pid'] == server2_pid)
        self.assertTrue(server_id2 in self.servers)
        for h_id in self.servers:
            self.assertTrue(h_id in (server_id, server_id2))

        operator.delitem(self.servers, server_id2)
        self.assertFalse(server_id2 in self.servers)
        server2.stop()
        server2.cleanup()
Example #21
0
def operator_sequence_operation():
    """
    we do some sequence operation like following.
    ---CRUD---
    container :: in, append, extend, clear, remove, __new__, __eq__
    sized     :: len, index
    iterable  :: set, get
    """
    a = [1, 2, 3]
    b = list('abc')
    print('a =', a)
    print('b =', b)

    # concatenate
    print('\nConstructive:')
    print('  concat(a, b):', operator.concat(a, b))

    # search
    print('\nSearch:')
    print('  contains(a, 1)  :', operator.contains(a, 1))
    print('  contains(b, "d"):', operator.contains(b, "d"))
    print('  countOf(a, 1)   :', operator.countOf(a, 1))
    print('  countOf(b, "d") :', operator.countOf(b, "d"))
    print('  indexOf(a, 1)   :', operator.indexOf(a, 1))
    # access items
    print('\nAccess:')
    print('  getitem(b, 1)                   :', operator.getitem(b, 1))
    print('  getitem(b, slice(1, 3))         :',
          operator.getitem(b, slice(1, 3)))
    print('  setitem(b, 1, "d")              :', end=' ')
    operator.setitem(b, 1, "d")
    print(b)
    print('  setitem(a, slice(1, 3), [4, 5]) :', end=' ')
    operator.setitem(a, slice(1, 3), [4, 5])
    print(a)
    # remove items
    print('\nDestructive:')
    print('  delitem(b, 1)                   :', end=' ')
    operator.delitem(b, 1)
    print(b)
    print('  delitem(a, slice(1, 3))         :', end=' ')
    operator.delitem(a, slice(1, 3))
    print(a)
Example #22
0
def test_reuse(min_items=2, max_items=1000):
    items = KeypoolDict()

    for i in xrange(0, MAX_ITER):
        rand = random.randint(min_items, max_items)
        keys = [items.setitem(i) for i in xrange(0, rand)]

        # No keys are identical
        assert_unique(keys)

        # Delete all the items
        [delitem(items, key) for key in items.keys()]

        # The old keys are now reused
        keys2 = [items.setitem(i) for i in xrange(0, rand)]

        assert keys == keys2
        assert_unique(keys)

        [delitem(items, key) for key in items.keys()]
Example #23
0
def CreateTree(dataSet, labels):
    classList = [example[-1] for example in dataSet]
    # 如果类别完全相同,这停止划分,退出
    if classList.count(classList[0]) == len(classList):
        return classList[0]
    # 如果只有一个特征,则遍历该特征,返回出现次数最多的
    if len(dataSet[0]) == 1:
        return majorityCnt(classList)
    # 构造根节点
    bestFeat = chooseBestFeatureToSplit(dataSet)
    bestFeatLabel = labels[bestFeat]
    mytree = {bestFeatLabel: {}}
    # 将最佳标签删除
    operator.delitem(labels, bestFeat)
    #operator.del(labels(bestFeat))
    # 最佳标签的取值list
    featValues = [example[bestFeat] for example in dataSet]
    # 去除重复值
    uniqueVals = set(featValues)
    for value in uniqueVals:
        subLabels = labels[:]
        mytree[bestFeatLabel][value] = CreateTree(
            splitDataSet(dataSet, bestFeat, value), subLabels)
    return mytree
Example #24
0
 def codeMod_End(self, name, attrs):
         log(1, "Fun "+name+"_End", attrs)
         if self.elements['func']:
                 cm=self.elements['func']+"\n{\n"+self.elements['lvariable']+self.elements['testCase']+"\n}\n"
         else:
                 cm=self.elements['lvariable']+self.elements['testCase']
         self.elements[name]+=cm
         operator.delitem(self.elements, 'lvariable')
         operator.delitem(self.elements, 'func')
         operator.delitem(self.elements, 'testCase')
Example #25
0
def rpn_calc(source):
    stack = []
    operators = ['+', '-', '/', '*']
    for item in source:
        if item not in operators:
            stack.append(item)
        else:
            if item == '+':
                stack.append(operator.add(stack.pop(), stack.pop()))
            if item == '-':
                stack.append(operator.add(-stack.pop(), stack.pop()))
            if item == '*':
                stack.append(operator.mul(stack.pop(), stack.pop()))
            if item == '/':
                stack.append(operator.delitem(stack.pop(), stack.pop()))
    return stack[0]
Example #26
0
    def io(self, fd, events, ref=True, priority=None):
        # We rely on hard references here and explicit calls to
        # close() on the returned object to correctly manage
        # the watcher lifetimes.

        io_watchers = self._io_watchers
        try:
            io_watcher = io_watchers[fd]
            assert io_watcher._multiplex_watchers, ("IO Watcher %s unclosed but should be dead" % io_watcher)
        except KeyError:
            # Start the watcher with just the events that we're interested in.
            # as multiplexers are added, the real event mask will be updated to keep in sync.
            # If we watch for too much, we get spurious wakeups and busy loops.
            io_watcher = self._watchers.io(self, fd, 0)
            io_watchers[fd] = io_watcher
            io_watcher._no_more_watchers = lambda: delitem(io_watchers, fd)

        return io_watcher.multiplex(events)
Example #27
0
class TestFrozendict:
    @pytest.mark.parametrize('mutator', [
        lambda d: operator.setitem(d, 'key', 'value'),
        lambda d: operator.delitem(d, 'key'),
        frozendict.clear,
        frozendict.popitem,
        lambda d: frozendict.pop(d, 'key', None),
        lambda d: frozendict.setdefault(d, 'key', 'value'),
        lambda d: frozendict.update(d, key='value'),
    ])
    def test_immutability(self, mutator):
        with pytest.raises(TypeError):
            mutator(frozendict())

    def test_copying(self):
        value = frozendict(a=1)
        copied = copy(value)
        assert value == copied
        assert value is not copied
    def _perform_redeem(self, voucher, counter, random_tokens):
        """
        Use the redeemer to redeem the given voucher and random tokens.

        This will not persist the voucher or random tokens but it will persist
        the result.

        :return Deferred[bool]: A ``Deferred`` firing with ``True`` if and
            only if redemption succeeds.
        """
        if not isinstance(voucher.state, model_Pending):
            raise ValueError(
                "Cannot redeem voucher in state {} instead of Pending.".format(
                    voucher.state, ), )

        # Ask the redeemer to do the real task of redemption.
        self._log.info("Redeeming random tokens for a voucher ({voucher}).",
                       voucher=voucher)
        d = bracket(
            lambda: setitem(
                self._active,
                voucher.number,
                model_Redeeming(
                    started=self.store.now(),
                    counter=voucher.state.counter,
                ),
            ),
            lambda: delitem(self._active, voucher.number),
            lambda: self.redeemer.redeemWithCounter(voucher, counter,
                                                    random_tokens),
        )
        d.addCallbacks(
            partial(self._redeem_success, voucher.number, counter),
            partial(self._redeem_failure, voucher.number),
        )
        d.addErrback(partial(self._final_redeem_error, voucher.number))
        return d
Example #29
0
Operation – ob[pos]
'''
import operator

li = [1, 2, 3, 4, 6]

print("The original list is :", end=" ")
for i1 in range(0, len(li)):
    print(li[i1], end=" ")
print("\r")

# using setitem() to assign 3 at 4th position
operator.setitem(li, 3, 90)

print("The Modified list is :", end=" ")
for i in range(0, len(li)):
    print(li[i], end=" ")

print("\r")

# printing modified list after delitem()
operator.delitem(li, 3)
print("The deleted list is :", end=" ")
for i in range(len(li)):
    print(li[i], end=" ")
print("\r")

# using getitem() to access 4th element
print("To get the 3rd position value from list :", end=" ")
print(operator.getitem(li, 3))
#https://www.geeksforgeeks.org/operator-functions-python-set-2/
Example #30
0
import operator
li = [1, 5, 6, 7, 8]
operator.delitem(li, slice(2, 4))
print("modified list :", end="")
for i in range(0, len(li)):
    print(li[i], end="")
Example #31
0
print(my_list[1])

print(operator.getitem(my_list,3)) #it require two elements 

#if sequence is mutable then we can delete or set item
my_list[1] = 100
print(my_list)

del my_list[1]
print(my_list)

#now we use operator for set and delete the item
my_list = [1,2,3,4]
operator.setitem(my_list,1,100)
print(my_list)
operator.delitem(my_list,1)
print(my_list)

print("############################ itemgetter ##############################")
my_list = [1,2,3,4]
f = operator.itemgetter(1) #here we pass index
print(f(my_list))
f = operator.itemgetter(1,3)
print(f(my_list))

print("############################ attrgetter ##############################")
class MyClass:
    def __init__(self):
        self.a = 10
        self.b = 20
        self.c = 30
Example #32
0
def py_delitem(obj, key):
    """ call __delitem__ on obj"""
    operator.delitem(obj, key)
    return (obj,)
Example #33
0
# 0
# 1

c = [1, 'a', None, 10.01, {'key':'value'}]


# 通过下标操作序列
print operator.getitem(c, 4)
print operator.getslice(c, 1, 4)

operator.setitem(c, 2, 9999)
print c
operator.setslice(c, 3,-1, [10,20,30,40,50])
print c

operator.delitem(c, 0)
print c
operator.delslice(c, 2, 7)
print c
# output
# {'key': 'value'}
# ['a', None, 10.01]
# [1, 'a', 9999, 10.01, {'key': 'value'}]
# [1, 'a', 9999, 10, 20, 30, 40, 50, {'key': 'value'}]
# ['a', 9999, 10, 20, 30, 40, 50, {'key': 'value'}]
# ['a', 9999, {'key': 'value'}]


"""
获取对象元素或属性方法:
	1.创建一个回调函数,
Example #34
0
 def clearElements(self):
         _f=lambda x: operator.delitem(self.elements, x)
         list(list(map(_f, ['include', 'define', 'gvariable', 'codeMod', 'currMod'])))
Example #35
0
 def test_modify_tree(self):
     tree = self.repo[TREE_SHA]
     with pytest.raises(TypeError):
         operator.setitem('c', tree['a'])
     with pytest.raises(TypeError):
         operator.delitem('c')
 def test_delitem(self):
     a = [4, 3, 2, 1]
     self.failUnlessRaises(TypeError, operator.delitem, a)
     self.failUnlessRaises(TypeError, operator.delitem, a, None)
     self.failUnless(operator.delitem(a, 1) is None)
     self.assert_(a == [4, 2, 1])
print('#' * 52 + '  We can do the same thing using:')

print(operator.getitem(my_list, 1))

print('#' * 52 +
      '  If the sequence is mutable, we can also set or remove items:')

my_list = [1, 2, 3, 4]
my_list[1] = 100
del my_list[3]
print(my_list)

my_list = [1, 2, 3, 4]
operator.setitem(my_list, 1, 100)

operator.delitem(my_list, 3)
print(my_list)

print(
    '#' * 52 +
    '  We can also do the same thing using the **operator** modules **itemgetter** function.'
)
print('#' * 52 + '  The difference is that this returns a callable:')

f = operator.itemgetter(2)

print(f(my_list))

x = 'python'
print(f(x))
Example #38
0
 def remove_index_operation(self, name):
     if name in self._index_operations:
         delitem(self._index_operations, name)
         delattr(self, name)
     else:
         raise AttributeError("No index operation with the name {}".format(name))
Example #39
0
 def test_modify_tree(self):
     tree = self.repo[TREE_SHA]
     with pytest.raises(TypeError): operator.setitem('c', tree['a'])
     with pytest.raises(TypeError): operator.delitem('c')
Example #40
0
import operator
 def test_delitem(self):
     self.assertEqual(0, len(self.container))
     self.container['key'] = 'value'
     self.assertEqual(1, len(self.container))
     self.assertEqual(None, operator.delitem(self.container, 'key'))
     self.assertEqual(0, len(self.container))
 def test_delitem(self):
     a = [4, 3, 2, 1]
     self.failUnless(operator.delitem(a, 1) is None)
     self.assert_(a == [4, 2, 1])
print("Mul operator:", reduce(operator.mul, [1, 2, 3, 4, 5]))

from operator import is_
print(is_('abc', "def"))

print('\n*** Attribute getters and setters ***')
l = [1, 2, 3, 4]
g = operator.getitem(l, 1)
print(g)

l[1] = 10
del l[3]
print(l)
l = [1, 2, 3, 4]
g = operator.setitem(l, 1, 10)
g = operator.delitem(l, 3)
print(l)

print('\n*** Item getter, think like a partial function ***')
f = operator.itemgetter(2)
print("\tf is a callable: ", type(f))
print("\tGet item(from list)  ", f(l))
s = "Python"
print("\tGet item(from string)", f(s))
f = operator.itemgetter(-1, -2, 0)
print("\tGet item(from string)", f(s))
l = [1, 2, 3, 4, 5]
print("\tGet items(from list)  ", f(l))

print('\n*** Attribute getter ***')
Example #44
0
 def testDeleteNonExistingItem(self):
     storage = self.storage
     # This used to raise a KeyError, but sometimes the underlying storage
     # can get inconsistent, so it is nicer to accept it.
     # See https://github.com/plone/plone.scale/issues/15
     delitem(storage, 'foo')
Example #45
0
    def resource_factory(self, name, schema, resource_cls=None):
        """
        Registers a new resource with a given schema. The schema must not have any unresolved references
        (such as `{"$ref": "#"}` for self-references, or otherwise). A subclass of :class:`Resource`
        may be provided to add specific functionality to the resulting :class:`Resource`.

        :param str name:
        :param dict schema:
        :param Resource resource_cls: a subclass of :class:`Resource` or None
        :return: The new :class:`Resource`.
        """
        cls = type(str(upper_camel_case(name)), (resource_cls or Resource, collections.MutableMapping), {
            '__doc__': schema.get('description', '')
        })

        cls._schema = schema
        cls._client = self
        cls._links = links = {}

        for link_schema in schema['links']:
            link = Link(self,
                        rel=link_schema['rel'],
                        href=link_schema['href'],
                        method=link_schema['method'],
                        schema=link_schema.get('schema', None),
                        target_schema=link_schema.get('targetSchema', None))

            # Set Resource._self, etc. for the special methods as they are managed by the Resource class
            if link.rel in ('self', 'instances', 'create', 'update', 'destroy'):
                setattr(cls, '_{}'.format(link.rel), link)
            links[link.rel] = link

            if link.rel != 'update':  # 'update' is a special case because of MutableMapping.update()
                setattr(cls, snake_case(link.rel), link)

        # TODO routes (instance & non-instance)

        for property_name, property_schema in schema.get('properties', {}).items():
            # skip $uri and $id as these are already implemented in Resource and overriding them causes unnecessary
            # fetches.
            if property_name.startswith('$'):
                continue

            if property_schema.get('readOnly', False):
                # TODO better error message. Raises AttributeError("can't set attribute")
                setattr(cls,
                        property_name,
                        property(fget=partial((lambda name, obj: getitem(obj, name)), property_name),
                                 doc=property_schema.get('description', None)))
            else:
                setattr(cls,
                        property_name,
                        property(fget=partial((lambda name, obj: getitem(obj, name)), property_name),
                                 fset=partial((lambda name, obj, value: setitem(obj, name, value)), property_name),
                                 fdel=partial((lambda name, obj: delitem(obj, name)), property_name),
                                 doc=property_schema.get('description', None)))

        root = None
        if 'instances' in links:
            root = cls._instances.href
        elif 'self' in links:
            root = cls._self.href[:cls._self.href.rfind('/')]
        else:
            root = self._root_path + '/' + name.replace('_', '-')

        self._resources[root] = cls
        return cls
Example #46
0
File: t505.py Project: Afey/skulpt
print operator.contains(l, 2)
print operator.contains(l, 30)
print operator.contains(s, "ll")
print operator.contains(s, "z")
print operator.contains(t, "a")
print operator.contains(t, 2)
print operator.contains(d, 3)
print operator.contains(d, 0)

print operator.countOf(l, 9)
print operator.countOf(l, 30)
print operator.countOf(s, "l")
print operator.countOf(t, "a")

operator.delitem(l, 9)
print l

operator.delitem(l, 0)
print l

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9]
s = "hello world"
t = ("a", "b", "c")
d = {1:1, 2:2, 3:3, 4:4, 5:5}

print operator.getitem(l, 2)
print operator.getitem(s, 0)
print operator.getitem(t, 1)
print operator.getitem(d, 4)
Example #47
0
 def __delitem__(self, key):
     return operator.delitem(self._dict, key)
Example #48
0
 def add_consumer(self, consumer):
     self.consumers[consumer.tag] = consumer
     # so the consumer gets garbage collected when it is cancelled
     consumer.cancelled_future.add_done_callback(lambda fut: delitem(self.consumers, fut.result().tag))
Example #49
0
 def test_delitem(self):
     a = [4, 3, 2, 1]
     self.failUnlessRaises(TypeError, operator.delitem, a)
     self.failUnlessRaises(TypeError, operator.delitem, a, None)
     self.failUnless(operator.delitem(a, 1) is None)
     self.assert_(a == [4, 2, 1])
Example #50
0
 def test_errors(self):
     self.assertRaises(TypeError, lambda: self.g1a['attempting'])
     self.assertRaises(IndexError, lambda: self.g1b[1])
     self.assertRaises(TypeError, lambda: operator.delitem(self.g1c, 0) )
Example #51
0
import operator
li = [1, 2, 3, 4, 5]
for i in range(0, len(li)):
    print(li[i], end=" ")
print("\r")
print("after set iteam")
operator.setitem(li, 3, 2)
###obj,postion,value
for i in range(0, len(li)):
    print(li[i], end=" ")
print("\r")
print("after delete")
operator.delitem(li, 2)
for i in range(0, len(li)):
    print(li[i], end=" ")
print("\r")
print("get value")
print(operator.getitem(li, 1))
Example #52
0
 def __delitem__(self, *args):
     return operator.delitem(self.value, *args)
Example #53
0
class TestWebElementWrapper:
    """Generic tests for WebElementWrapper.

    Note: For some methods, there's a dedicated test class with more involved
    tests.
    """
    @pytest.fixture
    def elem(self):
        return get_webelem()

    def test_nullelem(self):
        """Test __init__ with a null element."""
        with pytest.raises(webelem.IsNullError):
            get_webelem(null=True)

    def test_double_wrap(self, elem):
        """Test wrapping a WebElementWrapper."""
        with pytest.raises(TypeError) as excinfo:
            webelem.WebElementWrapper(elem)
        assert str(excinfo.value) == "Trying to wrap a wrapper!"

    @pytest.mark.parametrize(
        'code',
        [
            str,
            lambda e: e[None],
            lambda e: operator.setitem(e, None, None),
            lambda e: operator.delitem(e, None),
            lambda e: None in e,
            len,
            lambda e: e.is_visible(None),
            lambda e: e.rect_on_view(),
            lambda e: e.is_writable(),
            lambda e: e.is_content_editable(),
            lambda e: e.is_editable(),
            lambda e: e.is_text_input(),
            lambda e: e.debug_text(),
            list,  # __iter__
        ])
    def test_vanished(self, elem, code):
        """Make sure methods check if the element is vanished."""
        elem._elem.isNull.return_value = True
        with pytest.raises(webelem.IsNullError):
            code(elem)

    def test_str(self, elem):
        assert str(elem) == 'text'

    @pytest.mark.parametrize('is_null, expected', [
        (False, "<qutebrowser.browser.webelem.WebElementWrapper "
         "html='<fakeelem/>'>"),
        (True, '<qutebrowser.browser.webelem.WebElementWrapper html=None>'),
    ])
    def test_repr(self, elem, is_null, expected):
        elem._elem.isNull.return_value = is_null
        assert repr(elem) == expected

    def test_getitem(self):
        elem = get_webelem(attributes={'foo': 'bar'})
        assert elem['foo'] == 'bar'

    def test_getitem_keyerror(self, elem):
        with pytest.raises(KeyError):
            elem['foo']  # pylint: disable=pointless-statement

    def test_setitem(self, elem):
        elem['foo'] = 'bar'
        assert elem._elem.attribute('foo') == 'bar'

    def test_delitem(self):
        elem = get_webelem(attributes={'foo': 'bar'})
        del elem['foo']
        assert not elem._elem.hasAttribute('foo')

    def test_setitem_keyerror(self, elem):
        with pytest.raises(KeyError):
            del elem['foo']

    def test_contains(self):
        elem = get_webelem(attributes={'foo': 'bar'})
        assert 'foo' in elem
        assert 'bar' not in elem

    @pytest.mark.parametrize('attributes, expected', [
        ({
            'one': '1',
            'two': '2'
        }, {'one', 'two'}),
        ({}, set()),
    ])
    def test_iter(self, attributes, expected):
        elem = get_webelem(attributes=attributes)
        assert set(elem) == expected

    @pytest.mark.parametrize('attributes, length', [
        ({
            'one': '1',
            'two': '2'
        }, 2),
        ({}, 0),
    ])
    def test_len(self, attributes, length):
        elem = get_webelem(attributes=attributes)
        assert len(elem) == length

    @pytest.mark.parametrize('attributes, writable', [
        ([], True),
        (['disabled'], False),
        (['readonly'], False),
        (['disabled', 'readonly'], False),
    ])
    def test_is_writable(self, attributes, writable):
        elem = get_webelem(attributes=attributes)
        assert elem.is_writable() == writable

    @pytest.mark.parametrize('attributes, expected', [
        ({}, False),
        ({
            'contenteditable': 'false'
        }, False),
        ({
            'contenteditable': 'inherit'
        }, False),
        ({
            'contenteditable': 'true'
        }, True),
    ])
    def test_is_content_editable(self, attributes, expected):
        elem = get_webelem(attributes=attributes)
        assert elem.is_content_editable() == expected

    @pytest.mark.parametrize('tagname, attributes, expected', [
        ('input', {}, True),
        ('textarea', {}, True),
        ('select', {}, False),
        ('foo', {
            'role': 'combobox'
        }, True),
        ('foo', {
            'role': 'textbox'
        }, True),
        ('foo', {
            'role': 'bar'
        }, False),
        ('input', {
            'role': 'bar'
        }, True),
    ])
    def test_is_text_input(self, tagname, attributes, expected):
        elem = get_webelem(tagname=tagname, attributes=attributes)
        assert elem.is_text_input() == expected

    @pytest.mark.parametrize('xml, expected', [
        ('<fakeelem/>', '<fakeelem/>'),
        ('<foo>\n<bar/>\n</foo>', '<foo><bar/></foo>'),
        ('<foo>{}</foo>'.format('x' * 500), '<foo>{}…'.format('x' * 494)),
    ],
                             ids=['fakeelem', 'newlines', 'long'])
    def test_debug_text(self, elem, xml, expected):
        elem._elem.toOuterXml.return_value = xml
        assert elem.debug_text() == expected
Example #54
0
 def testDeleteNonExistingItem(self):
     storage = self.storage
     # This used to raise a KeyError, but sometimes the underlying storage
     # can get inconsistent, so it is nicer to accept it.
     # See https://github.com/plone/plone.scale/issues/15
     delitem(storage, 'foo')
Example #55
0
class TestWebKitElement:
    """Generic tests for WebKitElement.

    Note: For some methods, there's a dedicated test class with more involved
    tests.
    """
    @pytest.fixture
    def elem(self):
        return get_webelem()

    def test_nullelem(self):
        """Test __init__ with a null element."""
        with pytest.raises(webkitelem.IsNullError):
            get_webelem(null=True)

    def test_double_wrap(self, elem):
        """Test wrapping a WebKitElement."""
        with pytest.raises(TypeError, match="Trying to wrap a wrapper!"):
            webkitelem.WebKitElement(elem, tab=None)

    @pytest.mark.parametrize('code', [
        pytest.param(str, id='str'),
        pytest.param(lambda e: e[None], id='getitem'),
        pytest.param(lambda e: operator.setitem(e, None, None), id='setitem'),
        pytest.param(lambda e: operator.delitem(e, None), id='delitem'),
        pytest.param(lambda e: '' in e, id='contains'),
        pytest.param(list, id='iter'),
        pytest.param(len, id='len'),
        pytest.param(lambda e: e.has_frame(), id='has_frame'),
        pytest.param(lambda e: e.geometry(), id='geometry'),
        pytest.param(lambda e: e.value(), id='value'),
        pytest.param(lambda e: e.set_value('foo'), id='set_value'),
        pytest.param(lambda e: e.insert_text('foo'), id='insert_text'),
        pytest.param(lambda e: e.is_writable(), id='is_writable'),
        pytest.param(lambda e: e.is_content_editable(),
                     id='is_content_editable'),
        pytest.param(lambda e: e.is_editable(), id='is_editable'),
        pytest.param(lambda e: e.is_text_input(), id='is_text_input'),
        pytest.param(lambda e: e.remove_blank_target(),
                     id='remove_blank_target'),
        pytest.param(lambda e: e.outer_xml(), id='outer_xml'),
        pytest.param(lambda e: e.is_content_editable_prop(),
                     id='is_content_editable_prop'),
        pytest.param(lambda e: e.tag_name(), id='tag_name'),
        pytest.param(lambda e: e.rect_on_view(), id='rect_on_view'),
        pytest.param(lambda e: e._is_visible(None), id='is_visible'),
    ])
    def test_vanished(self, elem, code):
        """Make sure methods check if the element is vanished."""
        elem._elem.isNull.return_value = True
        elem._elem.tagName.return_value = 'span'
        with pytest.raises(webkitelem.IsNullError):
            code(elem)

    def test_str(self, elem):
        assert str(elem) == 'text'

    wke_qualname = 'qutebrowser.browser.webkit.webkitelem.WebKitElement'

    @pytest.mark.parametrize('is_null, xml, expected', [
        (False, '<fakeelem/>', "<{} html='<fakeelem/>'>".format(wke_qualname)),
        (False, '<foo>\n<bar/>\n</foo>',
         "<{} html='<foo><bar/></foo>'>".format(wke_qualname)),
        (False, '<foo>{}</foo>'.format('x' * 500),
         "<{} html='<foo>{}…'>".format(wke_qualname, 'x' * 494)),
        (True, None, '<{} html=None>'.format(wke_qualname)),
    ])
    def test_repr(self, elem, is_null, xml, expected):
        elem._elem.isNull.return_value = is_null
        elem._elem.toOuterXml.return_value = xml
        assert repr(elem) == expected

    def test_getitem(self):
        elem = get_webelem(attributes={'foo': 'bar'})
        assert elem['foo'] == 'bar'

    def test_getitem_keyerror(self, elem):
        with pytest.raises(KeyError):
            elem['foo']

    def test_setitem(self, elem):
        elem['foo'] = 'bar'
        assert elem._elem.attribute('foo') == 'bar'

    def test_delitem(self):
        elem = get_webelem(attributes={'foo': 'bar'})
        del elem['foo']
        assert not elem._elem.hasAttribute('foo')

    def test_setitem_keyerror(self, elem):
        with pytest.raises(KeyError):
            del elem['foo']

    def test_contains(self):
        elem = get_webelem(attributes={'foo': 'bar'})
        assert 'foo' in elem
        assert 'bar' not in elem

    def test_not_eq(self):
        one = get_webelem()
        two = get_webelem()
        assert one != two

    def test_eq(self):
        one = get_webelem()
        two = webkitelem.WebKitElement(one._elem, tab=None)
        assert one == two

    def test_eq_other_type(self):
        assert get_webelem() != object()

    @pytest.mark.parametrize('attributes, expected', [
        ({
            'one': '1',
            'two': '2'
        }, {'one', 'two'}),
        ({}, set()),
    ])
    def test_iter(self, attributes, expected):
        elem = get_webelem(attributes=attributes)
        assert set(elem) == expected

    @pytest.mark.parametrize('attributes, length', [
        ({
            'one': '1',
            'two': '2'
        }, 2),
        ({}, 0),
    ])
    def test_len(self, attributes, length):
        elem = get_webelem(attributes=attributes)
        assert len(elem) == length

    @pytest.mark.parametrize('attributes, writable', [
        ([], True),
        (['disabled'], False),
        (['readonly'], False),
        (['disabled', 'readonly'], False),
    ])
    def test_is_writable(self, attributes, writable):
        elem = get_webelem(attributes=attributes)
        assert elem.is_writable() == writable

    @pytest.mark.parametrize('attributes, expected', [
        ({}, False),
        ({
            'contenteditable': 'false'
        }, False),
        ({
            'contenteditable': 'inherit'
        }, False),
        ({
            'contenteditable': 'true'
        }, True),
    ])
    def test_is_content_editable(self, attributes, expected):
        elem = get_webelem(attributes=attributes)
        assert elem.is_content_editable() == expected

    @pytest.mark.parametrize('tagname, attributes, expected', [
        ('input', {}, True),
        ('textarea', {}, True),
        ('select', {}, False),
        ('foo', {
            'role': 'combobox'
        }, True),
        ('foo', {
            'role': 'textbox'
        }, True),
        ('foo', {
            'role': 'bar'
        }, False),
        ('input', {
            'role': 'bar'
        }, True),
    ])
    def test_is_text_input(self, tagname, attributes, expected):
        elem = get_webelem(tagname=tagname, attributes=attributes)
        assert elem.is_text_input() == expected

    @pytest.mark.parametrize('attribute, code', [
        ('geometry', lambda e: e.geometry()),
        ('toOuterXml', lambda e: e.outer_xml()),
    ])
    def test_simple_getters(self, elem, attribute, code):
        sentinel = object()
        mock = getattr(elem._elem, attribute)
        mock.return_value = sentinel
        assert code(elem) is sentinel

    @pytest.mark.parametrize('frame, expected', [(object(), True),
                                                 (None, False)])
    def test_has_frame(self, elem, frame, expected):
        elem._elem.webFrame.return_value = frame
        assert elem.has_frame() == expected

    def test_tag_name(self, elem):
        elem._elem.tagName.return_value = 'SPAN'
        assert elem.tag_name() == 'span'

    def test_value(self, elem):
        elem._elem.evaluateJavaScript.return_value = 'js'
        assert elem.value() == 'js'

    @pytest.mark.parametrize('editable, value, uses_js, arg', [
        ('false', 'foo', True, 'this.value="foo"'),
        ('false', "foo'bar", True, r'this.value="foo\'bar"'),
        ('true', 'foo', False, 'foo'),
    ])
    def test_set_value(self, editable, value, uses_js, arg):
        elem = get_webelem(attributes={'contenteditable': editable})
        elem.set_value(value)
        attr = 'evaluateJavaScript' if uses_js else 'setPlainText'
        called_mock = getattr(elem._elem, attr)
        called_mock.assert_called_with(arg)
Example #56
0
#包含 同 in
print operator.sequenceIncludes([1,2,3],1)
print operator.sequenceIncludes("123","1")

#计数,计算某个值在序列中出现的次数
print operator.countOf([1,2,1,3,1],1)
#set序列可以去重
print operator.countOf(set([1,2,1,3,1]),1)

#变量的值 同__index__()
a = 12
print operator.index(a)

#删除字典中的某对数值 同del a[b]
a = {0:"zero",1:"one",2:"two"}
operator.delitem(a,0)
print a

#删除序列中的某片数值 同del a[b:c]
a = [1,2,3,4,5]
operator.delslice(a,0,1)
print a

#取得字典的值 同 a[b]
a = {0:"zero",1:"one",2:"two"}
print operator.getitem(a,0)

#取得序列的片段 同 a[b:c]
a = [1,2,3,4,5]
print operator.getslice(a,0,2)
Example #57
0
print(" is_", op.is_("abc","abc"))
print(" is not ", "abc" is not "abcd")
print(" is_", op.is_not("abc","abcd"))

print(" in ", "a" in "abc")
print(" __contains__", "abc".__contains__('a'))
print(" contains", op.contains("abc",'a'))

print(" in ", "a" not in "abc")
print(" __contains__", not("abc".__contains__('a')))
print(" contains", op.not_(op.contains("abc",'a')))


print(" __getslice__ :", [0,1,2,3].__getslice__(0,2))
print("  getslice    :", op.getslice([0,1,2,3],0,2))
l=[0,1,2,3]
print(" __setslice__ :", l.__setslice__(0,2,[99,99]),l)
print(" __delslice__ :", l.__delslice__(0,2),l)
l=[0,1,2,3]
print("  setslice    :", op.setslice(l,0,2,[99,99]),l)
print("  delslice    :", op.delslice(l,0,2),l)

print(" __getitem__  : ", [0,1,2,3].__getitem__(slice(0,2)))
print(" getitem      : ", op.getitem([0,1,2,3],slice(0,2)))
l=[0,1,2,3]
print(" __setitem__ :", l.__setitem__(slice(0,2),[99,99]),l)
print(" __delitem__ :", l.__delitem__(slice(0,2)),l)
l=[0,1,2,3]
print("  setitem    :", op.setitem(l,slice(0,2),[99,99]),l)
print("  delitem    :", op.delitem(l,slice(0,2)),l)
Example #58
0
def delitem(a, b):
    return operator.delitem(a, b)