prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def <|fim_middle|>():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_text
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def <|fim_middle|>():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_bytes
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def <|fim_middle|>():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_string
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def <|fim_middle|>():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_dict
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def <|fim_middle|>():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_dict_None
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def <|fim_middle|>():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_list
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def <|fim_middle|>():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_list_None
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def <|fim_middle|>():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_set
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def <|fim_middle|>():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_set_None
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def <|fim_middle|>():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_tuple
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def <|fim_middle|>():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_tuple_None
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def <|fim_middle|>():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_None
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def <|fim_middle|>():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_unsafe_text
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def <|fim_middle|>():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_unsafe_bytes
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def <|fim_middle|>():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_wrap_var_no_ref
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def <|fim_middle|>():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def test_AnsibleUnsafeBytes():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_AnsibleUnsafeText
|
<|file_name|>test_unsafe_proxy.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from ansible.module_utils.six import PY3
from ansible.utils.unsafe_proxy import AnsibleUnsafe, AnsibleUnsafeBytes, AnsibleUnsafeText, wrap_var
def test_wrap_var_text():
assert isinstance(wrap_var(u'foo'), AnsibleUnsafeText)
def test_wrap_var_bytes():
assert isinstance(wrap_var(b'foo'), AnsibleUnsafeBytes)
def test_wrap_var_string():
if PY3:
assert isinstance(wrap_var('foo'), AnsibleUnsafeText)
else:
assert isinstance(wrap_var('foo'), AnsibleUnsafeBytes)
def test_wrap_var_dict():
assert isinstance(wrap_var(dict(foo='bar')), dict)
assert not isinstance(wrap_var(dict(foo='bar')), AnsibleUnsafe)
assert isinstance(wrap_var(dict(foo=u'bar'))['foo'], AnsibleUnsafeText)
def test_wrap_var_dict_None():
assert wrap_var(dict(foo=None))['foo'] is None
assert not isinstance(wrap_var(dict(foo=None))['foo'], AnsibleUnsafe)
def test_wrap_var_list():
assert isinstance(wrap_var(['foo']), list)
assert not isinstance(wrap_var(['foo']), AnsibleUnsafe)
assert isinstance(wrap_var([u'foo'])[0], AnsibleUnsafeText)
def test_wrap_var_list_None():
assert wrap_var([None])[0] is None
assert not isinstance(wrap_var([None])[0], AnsibleUnsafe)
def test_wrap_var_set():
assert isinstance(wrap_var(set(['foo'])), set)
assert not isinstance(wrap_var(set(['foo'])), AnsibleUnsafe)
for item in wrap_var(set([u'foo'])):
assert isinstance(item, AnsibleUnsafeText)
def test_wrap_var_set_None():
for item in wrap_var(set([None])):
assert item is None
assert not isinstance(item, AnsibleUnsafe)
def test_wrap_var_tuple():
assert isinstance(wrap_var(('foo',)), tuple)
assert not isinstance(wrap_var(('foo',)), AnsibleUnsafe)
assert isinstance(wrap_var(('foo',))[0], AnsibleUnsafe)
def test_wrap_var_tuple_None():
assert wrap_var((None,))[0] is None
assert not isinstance(wrap_var((None,))[0], AnsibleUnsafe)
def test_wrap_var_None():
assert wrap_var(None) is None
assert not isinstance(wrap_var(None), AnsibleUnsafe)
def test_wrap_var_unsafe_text():
assert isinstance(wrap_var(AnsibleUnsafeText(u'foo')), AnsibleUnsafeText)
def test_wrap_var_unsafe_bytes():
assert isinstance(wrap_var(AnsibleUnsafeBytes(b'foo')), AnsibleUnsafeBytes)
def test_wrap_var_no_ref():
thing = {
'foo': {
'bar': 'baz'
},
'bar': ['baz', 'qux'],
'baz': ('qux',),
'none': None,
'text': 'text',
}
wrapped_thing = wrap_var(thing)
thing is not wrapped_thing
thing['foo'] is not wrapped_thing['foo']
thing['bar'][0] is not wrapped_thing['bar'][0]
thing['baz'][0] is not wrapped_thing['baz'][0]
thing['none'] is not wrapped_thing['none']
thing['text'] is not wrapped_thing['text']
def test_AnsibleUnsafeText():
assert isinstance(AnsibleUnsafeText(u'foo'), AnsibleUnsafe)
def <|fim_middle|>():
assert isinstance(AnsibleUnsafeBytes(b'foo'), AnsibleUnsafe)
<|fim▁end|>
|
test_AnsibleUnsafeBytes
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear<|fim▁hole|> WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()<|fim▁end|>
| |
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
<|fim_middle|>
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
<|fim_middle|>
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
<|fim_middle|>
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
<|fim_middle|>
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
<|fim_middle|>
<|fim▁end|>
|
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def <|fim_middle|>(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
step_impl
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def <|fim_middle|>(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
step_impl
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def <|fim_middle|>(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
step_impl
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def <|fim_middle|>(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def step_impl(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
step_impl
|
<|file_name|>share.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64
import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
history = context.browser.find_element_by_id("HistoryPopup")
entries = history.find_elements_by_xpath('.//li[not(@data-clone-template)]')
assert len(entries) > 0, "There are no entries in the history"
item = entries[0]
item.find_elements_by_xpath('.//*[@data-share-item]')[0].click()
@then('the json to share is shown with url "{url}" and contains the following headers')
def step_impl(context, url):
# Wait for modal to appear
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ShareRequestForm')))
output = context.browser.execute_script("return restman.ui.editors.get('#ShareRequestEditor').getValue();")
snippet = json.loads(output)
assert url == snippet["url"], "URL: \"{}\" not in output.\nOutput: {}".format(value, output)
for row in context.table:
assert row['key'] in snippet['headers'], "Header {} is not in output".format(row['key'])
assert row['value'] == snippet['headers'][row['key']], "Header value is not correct. Expected: {}; Actual: {}".format(value, snippet['headers'][name])
@step('I click on import request')
def step_impl(context):
context.execute_steps(u'''
given I open History dialog
''')
# Click on import
context.browser.find_element_by_id('ImportHistory').click()
WebDriverWait(context.browser, 10).until(
expected_conditions.visibility_of_element_located(
(By.ID, 'ImportRequestForm')))
@step('I write a shared request for "{url}"')
def step_impl(context, url):
req = json.dumps({
"method": "POST",
"url": url,
"headers": {
"Content-Type": "application/json",
"X-Test-Header": "shared_request"
},
"body": {
"type": "form",
"content": {
"SomeKey": "SomeValue11233",
"SomeOtherKey": "SomeOtherValue019",
}
}
})
context.browser.execute_script("return restman.ui.editors.setValue('#ImportRequestEditor', atob('{}'));".format(base64.b64encode(req)))
@step('I click on load import request')
def <|fim_middle|>(context):
# Import request
context.browser.find_element_by_xpath("//*[@id='ImportRequestForm']//input[@value='Import']").click()
<|fim▁end|>
|
step_impl
|
<|file_name|>publicationfolder.py<|end_file_name|><|fim▁begin|># encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'''Folder containing publications.'''
class PublicationIngestor(Ingestor):
u'''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def getContainedObjectInterface(self):
return IPublication
class View(IngestableFolderView):
u'''View for an publication folder'''<|fim▁hole|><|fim▁end|>
|
grok.context(IPublicationFolder)
|
<|file_name|>publicationfolder.py<|end_file_name|><|fim▁begin|># encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'<|fim_middle|>
class PublicationIngestor(Ingestor):
u'''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def getContainedObjectInterface(self):
return IPublication
class View(IngestableFolderView):
u'''View for an publication folder'''
grok.context(IPublicationFolder)
<|fim▁end|>
|
''Folder containing publications.'''
|
<|file_name|>publicationfolder.py<|end_file_name|><|fim▁begin|># encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'''Folder containing publications.'''
class PublicationIngestor(Ingestor):
u'<|fim_middle|>
class View(IngestableFolderView):
u'''View for an publication folder'''
grok.context(IPublicationFolder)
<|fim▁end|>
|
''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def getContainedObjectInterface(self):
return IPublication
|
<|file_name|>publicationfolder.py<|end_file_name|><|fim▁begin|># encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'''Folder containing publications.'''
class PublicationIngestor(Ingestor):
u'''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def getContainedObjectInterface(self):
re<|fim_middle|>
class View(IngestableFolderView):
u'''View for an publication folder'''
grok.context(IPublicationFolder)
<|fim▁end|>
|
turn IPublication
|
<|file_name|>publicationfolder.py<|end_file_name|><|fim▁begin|># encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'''Folder containing publications.'''
class PublicationIngestor(Ingestor):
u'''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def getContainedObjectInterface(self):
return IPublication
class View(IngestableFolderView):
u'<|fim_middle|>
<|fim▁end|>
|
''View for an publication folder'''
grok.context(IPublicationFolder)
|
<|file_name|>publicationfolder.py<|end_file_name|><|fim▁begin|># encoding: utf-8
u'''MCL — Publication Folder'''
from ._base import IIngestableFolder, Ingestor, IngestableFolderView
from .interfaces import IPublication
from five import grok
class IPublicationFolder(IIngestableFolder):
u'''Folder containing publications.'''
class PublicationIngestor(Ingestor):
u'''RDF ingestor for publication.'''
grok.context(IPublicationFolder)
def ge<|fim_middle|>elf):
return IPublication
class View(IngestableFolderView):
u'''View for an publication folder'''
grok.context(IPublicationFolder)
<|fim▁end|>
|
tContainedObjectInterface(s
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
<|fim▁hole|> config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()<|fim▁end|>
|
@ndb.transactional
def increase_shards(name, num_shards):
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
<|fim_middle|>
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
<|fim_middle|>
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
<|fim_middle|>
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
count = ndb.IntegerProperty(default=0)
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
<|fim_middle|>
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
<|fim_middle|>
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
<|fim_middle|>
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
<|fim_middle|>
<|fim▁end|>
|
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
<|fim_middle|>
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
<|fim_middle|>
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
<|fim_middle|>
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
<|fim_middle|>
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
return get_count(name)
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
<|fim_middle|>
<|fim▁end|>
|
config.num_shards = num_shards
config.put()
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def <|fim_middle|>(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
all_keys
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def <|fim_middle|>(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
get_count
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def <|fim_middle|>(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
increment
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def <|fim_middle|>(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def increase_shards(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
_increment
|
<|file_name|>shardcounter_sync.py<|end_file_name|><|fim▁begin|>import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
shard_key_strings = [SHARD_KEY_TEMPLATE.format(name, index) for index in range(config.num_shards)]
return [ndb.Key(GeneralCounterShard, shard_key_string) for shard_key_string in shard_key_strings]
class GeneralCounterShard(ndb.Model):
count = ndb.IntegerProperty(default=0)
def get_count(name):
total = memcache.get(name)
if total is None:
total = 0
parent_key = ndb.Key('ShardCounterParent', name)
shard_query = GeneralCounterShard.query(ancestor=parent_key)
shard_counters = shard_query.fetch(limit=None)
for counter in shard_counters:
if counter is not None:
total += counter.count
memcache.add(name, total, 7200) # 2 hours to expire
return total
def increment(name):
config = GeneralCounterShardConfig.get_or_insert(name)
return _increment(name, config.num_shards)
@ndb.transactional
def _increment(name, num_shards):
index = random.randint(0, num_shards - 1)
shard_key_string = SHARD_KEY_TEMPLATE.format(name, index)
parent_key = ndb.Key('ShardCounterParent', name)
counter = GeneralCounterShard.get_by_id(shard_key_string, parent = parent_key)
if counter is None:
counter = GeneralCounterShard(parent = parent_key, id=shard_key_string)
counter.count += 1
counter.put()
rval = memcache.incr(name) # Memcache increment does nothing if the name is not a key in memcache
if rval is None:
return get_count(name)
return rval
@ndb.transactional
def <|fim_middle|>(name, num_shards):
config = GeneralCounterShardConfig.get_or_insert(name)
if config.num_shards < num_shards:
config.num_shards = num_shards
config.put()
<|fim▁end|>
|
increase_shards
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):<|fim▁hole|> res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')<|fim▁end|>
| |
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
<|fim_middle|>
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
<|fim_middle|>
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
<|fim_middle|>
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
<|fim_middle|>
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
j = 2 * i
while j <= n:
d[j].add(i)
j += i
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
<|fim_middle|>
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
return n - 1
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
<|fim_middle|>
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
print(c)
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
<|fim_middle|>
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
res.append((i, tot, Fraction(i, tot)))
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def <|fim_middle|>(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
reverse_erathos
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def <|fim_middle|>(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def compute_solution(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
totient
|
<|file_name|>problem.py<|end_file_name|><|fim▁begin|>from math import sqrt
from collections import defaultdict, Counter
from fractions import Fraction
def reverse_erathos(n):
d = defaultdict(set)
for i in range(2, n + 1):
if i not in d:
j = 2 * i
while j <= n:
d[j].add(i)
j += i
return d
def totient(n, prime_decs):
if n not in prime_decs:
return n - 1
res = n
for prime in prime_decs[n]:
res *= 1 - Fraction(1, prime)
return int(res)
def <|fim_middle|>(n):
c = 1
prime_decs = reverse_erathos(n)
res = []
for i in range(2, n + 1):
if c % 50000 == 0:
print(c)
tot = totient(i, prime_decs)
if Counter(str(i)) == Counter(str(tot)):
res.append((i, tot, Fraction(i, tot)))
c += 1
return min(res, key = lambda x: x[2])
print(compute_solution(10000000), sep='\n')
<|fim▁end|>
|
compute_solution
|
<|file_name|>__main__.py<|end_file_name|><|fim▁begin|># coding=utf-8<|fim▁hole|>
tp.Main().parse_and_run()<|fim▁end|>
|
''' tagsPlorer package entry point (C) 2021-2021 Arne Bachmann https://github.com/ArneBachmann/tagsplorer '''
from tagsplorer import tp
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()<|fim▁hole|> prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
asid = tokens[0].split("_")[0]
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
<|fim_middle|>
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
<|fim_middle|>
<|fim▁end|>
|
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
<|fim_middle|>
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
uniprot_to_index_to_core[prot][index] = core
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
<|fim_middle|>
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
uniprot_to_index_to_core[prot] = {index: core}
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
<|fim_middle|>
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
rough_a_length = 0
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
<|fim_middle|>
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def <|fim_middle|>(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
build_uniprot_to_index_to_core
|
<|file_name|>uniprot_core.py<|end_file_name|><|fim▁begin|># reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):
uniprot_to_index_to_core[prot][index] = core
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def <|fim_middle|>(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
prot = tokens[1]
sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4])
eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
c2_count = score_differences(uniprot_to_index_to_core, prot, end, eend)
prot_len = int(line.split("\t")[7].strip())
canonical_absolute = score_differences(uniprot_to_index_to_core, prot, 1, prot_len)
print >> write_to, tokens[0] + "\t" + prot + "\t" + repr(c1_count) + "\t" + repr(a_count) + "\t" + repr(
c2_count) + "\t" + repr(canonical_absolute)
write_to.close()<|fim▁end|>
|
get_sable_scores
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3<|fim▁hole|>from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];<|fim▁end|>
|
from pyamf import remoting
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
<|fim_middle|>
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
<|fim▁end|>
|
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
<|fim_middle|>
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
<|fim▁end|>
|
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def play(const, playerID, videoPlayer, publisherID, playerKey):
<|fim_middle|>
<|fim▁end|>
|
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
<|fim_middle|>
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
<|fim▁end|>
|
streamUrl = item['defaultURL']
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def <|fim_middle|>(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
<|fim▁end|>
|
build_amf_request
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def <|fim_middle|>(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def play(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
<|fim▁end|>
|
get_clip_info
|
<|file_name|>brightcovePlayer.py<|end_file_name|><|fim▁begin|>import httplib
from pyamf import AMF0, AMF3
from pyamf import remoting
from pyamf.remoting.client import RemotingService
height = 1080
def build_amf_request(const, playerID, videoPlayer, publisherID):
env = remoting.Envelope(amfVersion=3)
env.bodies.append(
(
"/1",
remoting.Request(
target="com.brightcove.player.runtime.PlayerMediaFacade.findMediaById",
body=[const, playerID, videoPlayer, publisherID],
envelope=env
)
)
)
return env
def get_clip_info(const, playerID, videoPlayer, publisherID, playerKey):
conn = httplib.HTTPConnection("c.brightcove.com")
envelope = build_amf_request(const, playerID, videoPlayer, publisherID)
conn.request("POST", "/services/messagebroker/amf?playerKey=" + playerKey, str(remoting.encode(envelope).read()), {'content-type': 'application/x-amf'})
response = conn.getresponse().read()
response = remoting.decode(response).bodies[0][1].body
return response
def <|fim_middle|>(const, playerID, videoPlayer, publisherID, playerKey):
rtmpdata = get_clip_info(const, playerID, videoPlayer, publisherID, playerKey)
streamName = ""
streamUrl = rtmpdata['FLVFullLengthURL'];
for item in sorted(rtmpdata['renditions'], key=lambda item:item['frameHeight'], reverse=False):
streamHeight = item['frameHeight']
if streamHeight <= height:
streamUrl = item['defaultURL']
streamName = streamName + rtmpdata['displayName']
return [streamName, streamUrl];
<|fim▁end|>
|
play
|
<|file_name|>action_registry_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#<|fim▁hole|># you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for methods in the action registry."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import action_registry
from core.tests import test_utils
class ActionRegistryUnitTests(test_utils.GenericTestBase):
"""Test for the action registry."""
def test_action_registry(self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3)<|fim▁end|>
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
<|file_name|>action_registry_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for methods in the action registry."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import action_registry
from core.tests import test_utils
class ActionRegistryUnitTests(test_utils.GenericTestBase):
<|fim_middle|>
<|fim▁end|>
|
"""Test for the action registry."""
def test_action_registry(self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3)
|
<|file_name|>action_registry_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for methods in the action registry."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import action_registry
from core.tests import test_utils
class ActionRegistryUnitTests(test_utils.GenericTestBase):
"""Test for the action registry."""
def test_action_registry(self):
<|fim_middle|>
<|fim▁end|>
|
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3)
|
<|file_name|>action_registry_test.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for methods in the action registry."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.domain import action_registry
from core.tests import test_utils
class ActionRegistryUnitTests(test_utils.GenericTestBase):
"""Test for the action registry."""
def <|fim_middle|>(self):
"""Do some sanity checks on the action registry."""
self.assertEqual(
len(action_registry.Registry.get_all_actions()), 3)
<|fim▁end|>
|
test_action_registry
|
<|file_name|>set_volume_option.py<|end_file_name|><|fim▁begin|>import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
<|fim▁hole|> option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))<|fim▁end|>
|
def start(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
|
<|file_name|>set_volume_option.py<|end_file_name|><|fim▁begin|>import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
<|fim_middle|>
<|fim▁end|>
|
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
def start(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))
|
<|file_name|>set_volume_option.py<|end_file_name|><|fim▁begin|>import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
<|fim_middle|>
def start(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))
<|fim▁end|>
|
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
|
<|file_name|>set_volume_option.py<|end_file_name|><|fim▁begin|>import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
def start(self):
<|fim_middle|>
<|fim▁end|>
|
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))
|
<|file_name|>set_volume_option.py<|end_file_name|><|fim▁begin|>import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def <|fim_middle|>(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
def start(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))
<|fim▁end|>
|
__init__
|
<|file_name|>set_volume_option.py<|end_file_name|><|fim▁begin|>import json
import etcd
from tendrl.gluster_bridge.atoms.volume.set import Set
class SetVolumeOption(object):
def __init__(self, api_job):
super(SetVolumeOption, self).__init__()
self.api_job = api_job
self.atom = SetVolumeOption
def <|fim_middle|>(self):
attributes = json.loads(self.api_job['attributes'].decode('utf-8'))
vol_name = attributes['volname']
option = attributes['option_name']
option_value = attributes['option_value']
self.atom().start(vol_name, option, option_value)
self.api_job['status'] = "finished"
etcd.Client().write(self.api_job['request_id'],
json.dumps(self.api_job))
<|fim▁end|>
|
start
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='easy 249')<|fim▁hole|>
def stock(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])<|fim▁end|>
|
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
<|fim_middle|>
def stock(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
<|fim▁end|>
|
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
def stock(stock_prices):
<|fim_middle|>
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
<|fim▁end|>
|
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
def stock(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
<|fim_middle|>
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
<|fim▁end|>
|
max_profit = profit
max_buy = buy_day
max_sell = sell_day
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
def stock(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|>
|
args = parse_args()
stock([float(price) for price in args.stock_prices])
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def <|fim_middle|>():
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
def stock(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
<|fim▁end|>
|
parse_args
|
<|file_name|>easy-249.py<|end_file_name|><|fim▁begin|>#! /usr/bin/env python3
'''
given a list of stock price ticks for the day, can you tell me what
trades I should make to maximize my gain within the constraints of the
market? Remember - buy low, sell high, and you can't sell before you
buy.
Sample Input
19.35 19.30 18.88 18.93 18.95 19.03 19.00 18.97 18.97 18.98
'''
import argparse
def parse_args():
parser = argparse.ArgumentParser(description='easy 249')
parser.add_argument('stock_prices', action='store', nargs='+',
help='prices of a given stock')
return parser.parse_args()
def <|fim_middle|>(stock_prices):
buy_day = 0
max_profit = 0
max_buy = 0
max_sell = 0
for buy_day in range(len(stock_prices) - 2):
# maybe do a max(here)
for sell_day in range(buy_day + 2, len(stock_prices)):
profit = stock_prices[sell_day] - stock_prices[buy_day]
if profit > max_profit:
max_profit = profit
max_buy = buy_day
max_sell = sell_day
print("max profit: %.2f from buy on day %d at %.2f sell on day %d at %.2f" %
(max_profit, max_buy, stock_prices[max_buy], max_sell, stock_prices[max_sell]))
if __name__ == '__main__':
args = parse_args()
stock([float(price) for price in args.stock_prices])
<|fim▁end|>
|
stock
|
<|file_name|>discount.py<|end_file_name|><|fim▁begin|># Possible discounts:
# - Node (administer inline with nodes)
# - Bulk amounts on nodes
# - User
# - Group of users
# - Order (this is more-or-less a voucher)
# - Shipping costs
# Possible amounts:
# - Percentage
# - Fixed amount<|fim▁hole|># Flag indicating if a discount can be combined with other discounts.
# Boolean "offer" to include in list of offers. Default to true if discount is at node level.
# Save all applied discounts when ordering in a ManyToMany relationship with Order.<|fim▁end|>
| |
<|file_name|>sdb_dump_patch.py<|end_file_name|><|fim▁begin|>import sys
import logging
import hexdump
import vstruct
import vivisect
import envi
import envi.archs.i386 as x86
import envi.archs.amd64 as x64
import sdb
from sdb import SDB_TAGS
from sdb_dump_common import SdbIndex
from sdb_dump_common import item_get_child
from sdb_dump_common import item_get_children
logging.basicConfig(level=logging.DEBUG)
g_logger = logging.getLogger("sdb_dump_patch")
g_logger.setLevel(logging.DEBUG)
ARCH_32 = "32"
ARCH_64 = "64"
def disassemble(buf, base=0, arch=ARCH_32):
if arch == ARCH_32:
d = x86.i386Disasm()
elif arch == ARCH_64:
d = x64.Amd64Disasm()
else:
raise RuntimeError('unknown arch: ' + str(arch))
offset = 0
while True:
if offset >= len(buf):
break
o = d.disasm(buf, offset, base)
yield "0x%x: %s" % (base + offset, str(o))
offset += o.size
class GreedyVArray(vstruct.VArray):
def __init__(self, C):
vstruct.VArray.__init__(self)
self._C = C
def vsParse(self, bytez, offset=0, fast=False):
soffset = offset
while offset < len(bytez):
c = self._C()
try:
offset = c.vsParse(bytez, offset=offset, fast=False)
except:
break
self.vsAddElement(c)
return offset
def vsParseFd(self, fd):
raise NotImplementedError()
def dump_patch(bits, arch=ARCH_32):
ps = GreedyVArray(sdb.PATCHBITS)
ps.vsParse(bits.value.value)
for i, _ in ps:
p = ps[int(i)]
print(" opcode: %s" % str(p["opcode"]))
print(" module name: %s" % p.module_name)
print(" rva: 0x%08x" % p.rva)
print(" unk: 0x%08x" % p.unknown)
print(" payload:")
print(hexdump.hexdump(str(p.pattern), result="return"))
print(" disassembly:")
for l in disassemble(str(p.pattern), p.rva, arch=arch):
print(" " + l)
print("")
def _main(sdb_path, patch_name):
from sdb import SDB
with open(sdb_path, "rb") as f:
buf = f.read()
g_logger.debug("loading database")
s = SDB()
s.vsParse(bytearray(buf))
g_logger.debug("done loading database")
index = SdbIndex()
g_logger.debug("indexing strings")
index.index_sdb(s)
g_logger.debug("done indexing strings")
try:
library = item_get_child(s.database_root, SDB_TAGS.TAG_LIBRARY)
except KeyError:
pass
else:
for shim_ref in item_get_children(library, SDB_TAGS.TAG_SHIM_REF):
patch = item_get_child(shim_ref, SDB_TAGS.TAG_PATCH)<|fim▁hole|> name_ref = item_get_child(patch, SDB_TAGS.TAG_NAME)
name = index.get_string(name_ref.value.reference)
if name != patch_name:
continue
bits = item_get_child(patch, SDB_TAGS.TAG_PATCH_BITS)
dump_patch(bits, arch=ARCH_32)
try:
patch = item_get_child(s.database_root, SDB_TAGS.TAG_PATCH)
except KeyError:
pass
else:
name_ref = item_get_child(patch, SDB_TAGS.TAG_NAME)
name = index.get_string(name_ref.value.reference)
if name == patch_name:
bits = item_get_child(patch, SDB_TAGS.TAG_PATCH_BITS)
dump_patch(bits, arch=ARCH_32)
def main():
import sys
return sys.exit(_main(*sys.argv[1:]))
if __name__ == "__main__":
main()<|fim▁end|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.