prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
<|fim_middle|>
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token()) |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
<|fim_middle|>
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200) |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
<|fim_middle|>
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | modified_token = '1' + token[1:] |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def <|fim_middle|>(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | get |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def <|fim_middle|>(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | post |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def <|fim_middle|>(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | put |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def <|fim_middle|>(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | delete |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def <|fim_middle|>(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | setUp |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def <|fim_middle|>(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_get_secret_key |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def <|fim_middle|>(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_tokens_are_equal |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def <|fim_middle|>(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_make_token_includes_time |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def <|fim_middle|>(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_make_token_requires_login |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def <|fim_middle|>(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_make_token_includes_path |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def <|fim_middle|>(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_token_is_valid |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def <|fim_middle|>(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def test_mutators_require_csrf_token(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_get_has_csrf_token |
<|file_name|>csrf_test.py<|end_file_name|><|fim▁begin|>"""Tests for the CSRF helper."""
import unittest
import mock
import webapp2
import webtest
from ctc.helpers import csrf
from ctc.testing import testutil
MOCKED_TIME = 123
# Tests don't need docstrings, so pylint: disable=C0111
# Tests can test protected members, so pylint: disable=W0212
class CsrfTests(testutil.CtcTestCase):
# Helpers
class TestHandler(csrf.CsrfHandler):
"""A handler for testing whether or not requests are CSRF protected."""
def get(self):
self.response.write('CSRF Token:%s' % self.csrf_token)
def post(self):
pass
def put(self):
pass
def delete(self):
pass
def setUp(self):
super(CsrfTests, self).setUp()
# The CSRF library uses the time, so we mock it out.
self.time_mock = mock.Mock()
csrf.time = self.time_mock
self.time_mock.time = mock.Mock(return_value=MOCKED_TIME)
# The handler tests need a WSGIApplication.
app = webapp2.WSGIApplication([('/', self.TestHandler)])
self.testapp = webtest.TestApp(app)
def test_get_secret_key(self):
first_key = csrf._get_secret_key()
self.assertEqual(len(first_key), 32)
second_key = csrf._get_secret_key()
self.assertEqual(first_key, second_key)
def test_tokens_are_equal(self):
# It should fail if the tokens aren't equal length.
self.assertFalse(csrf._tokens_are_equal('a', 'ab'))
# It should fail if the tokens are different.
self.assertFalse(csrf._tokens_are_equal('abcde', 'abcdf'))
# It should succeed if the tokens are the same.
self.assertTrue(csrf._tokens_are_equal('abcde', 'abcde'))
# Make Token
def test_make_token_includes_time(self):
self.login()
# It should get the current time.
token1 = csrf.make_token()
self.assertEqual(token1.split()[-1], str(MOCKED_TIME))
# It should use the provided time.
token2 = csrf.make_token(token_time='456')
self.assertEqual(token2.split()[-1], '456')
# Different time should cause the digest to be different.
self.assertNotEqual(token1.split()[0], token2.split()[0])
token3 = csrf.make_token(token_time='456')
self.assertEqual(token2, token3)
def test_make_token_requires_login(self):
token1 = csrf.make_token()
self.assertIsNone(token1)
self.login()
token2 = csrf.make_token()
self.assertIsNotNone(token2)
def test_make_token_includes_path(self):
self.login()
# It should get the current path.
self.testbed.setup_env(PATH_INFO='/action/1', overwrite=True)
token1 = csrf.make_token(token_time='123')
self.testbed.setup_env(PATH_INFO='/action/23', overwrite=True)
token2 = csrf.make_token(token_time='123')
token3 = csrf.make_token(token_time='123')
self.assertNotEqual(token1, token2)
self.assertEqual(token2, token3)
# It should let the client pass in a path.
token4 = csrf.make_token(path='/action/4', token_time='123')
token5 = csrf.make_token(path='/action/56', token_time='123')
token6 = csrf.make_token(path='/action/56', token_time='123')
self.assertNotEqual(token4, token5)
self.assertEqual(token5, token6)
# Token Is Valid
def test_token_is_valid(self):
self.login()
# Token is required.
self.assertFalse(csrf.token_is_valid(None))
# Token needs to have a timestamp on it.
self.assertFalse(csrf.token_is_valid('hello'))
# The timestamp needs to be within the current date range.
self.time_mock.time = mock.Mock(return_value=9999999999999)
self.assertFalse(csrf.token_is_valid('hello 123'))
# The user needs to be logged in.
token = csrf.make_token()
self.logout()
self.assertFalse(csrf.token_is_valid(token))
self.login()
# Modifying the token should break everything.
modified_token = '0' + token[1:]
if token == modified_token:
modified_token = '1' + token[1:]
self.assertFalse(csrf.token_is_valid(modified_token))
# The original token that we got should work.
self.assertTrue(csrf.token_is_valid(token))
def test_get_has_csrf_token(self):
self.login()
response = self.testapp.get('/', status=200).body
self.assertIn('CSRF Token:', response)
self.assertEqual(response.split(':')[-1], csrf.make_token())
def <|fim_middle|>(self):
self.login()
self.testapp.put('/', status=403)
self.testapp.post('/', status=403)
self.testapp.delete('/', status=403)
csrf_param = 'csrf_token=' + csrf.make_token(path='/')
self.testapp.put('/', params=csrf_param, status=200)
self.testapp.post('/', params=csrf_param, status=200)
# Though the spec allows DELETE to have a body, it tends to be ignored
# by servers (http://stackoverflow.com/questions/299628), and webapp2
# ignores it as well, so we have to put the params in the URL.
self.testapp.delete('/?' + csrf_param, status=200)
if __name__ == '__main__':
unittest.main()
<|fim▁end|> | test_mutators_require_csrf_token |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionmaker,
)
from zope.sqlalchemy import ZopeTransactionExtension
import tornado.web<|fim▁hole|>
import logging
logging.getLogger().setLevel(logging.DEBUG)
app = tornado.web.Application([
(r'/', IndexHandler),
(r'/sensors', SensorsHandler)
])
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()<|fim▁end|> | from handlers.index import IndexHandler
from handlers.sensors import SensorsHandler |
<|file_name|>circular_tree.py<|end_file_name|><|fim▁begin|>import networkx as nx
import matplotlib.pyplot as plt
try:
import pygraphviz
from networkx.drawing.nx_agraph import graphviz_layout
except ImportError:
try:
import pydot
from networkx.drawing.nx_pydot import graphviz_layout
except ImportError:
raise ImportError("This example needs Graphviz and either "
"PyGraphviz or pydot")
<|fim▁hole|>plt.figure(figsize=(8, 8))
nx.draw(G, pos, node_size=20, alpha=0.5, node_color="blue", with_labels=False)
plt.axis('equal')
plt.savefig('circular_tree.png')
plt.show()<|fim▁end|> | G = nx.balanced_tree(3, 5)
pos = graphviz_layout(G, prog='twopi', args='') |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
<|fim▁hole|>import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()<|fim▁end|> | # example setselection.py
|
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
<|fim_middle|>
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show() |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
<|fim_middle|>
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
<|fim_middle|>
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | self.have_selection = False
widget.set_active(False)
return True |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
<|fim_middle|>
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
<|fim_middle|>
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show() |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
<|fim_middle|>
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | gtk.main()
return 0 |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
<|fim_middle|>
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False) |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
<|fim_middle|>
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | widget.set_active(False) |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
<|fim_middle|>
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
<|fim_middle|>
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | self.have_selection = False |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | SetSelectionExample()
main() |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def <|fim_middle|>(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | selection_toggled |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def <|fim_middle|>(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | selection_clear |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def <|fim_middle|>(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | selection_handle |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def <|fim_middle|>(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | __init__ |
<|file_name|>065-setselection.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example setselection.py
import pygtk
pygtk.require('2.0')
import gtk
import time
class SetSelectionExample:
# Callback when the user toggles the selection
def selection_toggled(self, widget, window):
if widget.get_active():
self.have_selection = window.selection_owner_set("PRIMARY")
# if claiming the selection failed, we return the button to
# the out state
if not self.have_selection:
widget.set_active(False)
else:
if self.have_selection:
# Not possible to release the selection in PyGTK
# just mark that we don't have it
self.have_selection = False
return
# Called when another application claims the selection
def selection_clear(self, widget, event):
self.have_selection = False
widget.set_active(False)
return True
# Supplies the current time as the selection.
def selection_handle(self, widget, selection_data, info, time_stamp):
current_time = time.time()
timestr = time.asctime(time.localtime(current_time))
# When we return a single string, it should not be null terminated.
# That will be done for us
selection_data.set_text(timestr, len(timestr))
return
def __init__(self):
self.have_selection = False
# Create the toplevel window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Set Selection")
window.set_border_width(10)
window.connect("destroy", lambda w: gtk.main_quit())
self.window = window
# Create an eventbox to hold the button since it no longer has
# a GdkWindow
eventbox = gtk.EventBox()
eventbox.show()
window.add(eventbox)
# Create a toggle button to act as the selection
selection_button = gtk.ToggleButton("Claim Selection")
eventbox.add(selection_button)
selection_button.connect("toggled", self.selection_toggled, eventbox)
eventbox.connect_object("selection_clear_event", self.selection_clear,
selection_button)
eventbox.selection_add_target("PRIMARY", "STRING", 1)
eventbox.selection_add_target("PRIMARY", "COMPOUND_TEXT", 1)
eventbox.connect("selection_get", self.selection_handle)
selection_button.show()
window.show()
def <|fim_middle|>():
gtk.main()
return 0
if __name__ == "__main__":
SetSelectionExample()
main()
<|fim▁end|> | main |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None<|fim▁end|> | from abc import ABC
import configargparse
from sklearn.externals import joblib |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
<|fim_middle|>
<|fim▁end|> | """
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
<|fim_middle|>
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names) |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
<|fim_middle|>
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | """
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file) |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
<|fim_middle|>
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | """
Method fetches pipeline from server/cloud
"""
# TODO
pass |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
<|fim_middle|>
<|fim▁end|> | """
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
<|fim_middle|>
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | self.feature_names = self.load_pipeline(args.feature_names) |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def <|fim_middle|>(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | __init__ |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def <|fim_middle|>(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | load_pipeline |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def <|fim_middle|>(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def predict(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | fetch_pipeline_from_server |
<|file_name|>scikitbase.py<|end_file_name|><|fim▁begin|>from abc import ABC
import configargparse
from sklearn.externals import joblib
from termcolor import colored
class ScikitBase(ABC):
"""
Base class for AI strategies
"""
arg_parser = configargparse.get_argument_parser()
arg_parser.add('-p', '--pipeline', help='trained model/pipeline (*.pkl file)', required=True)
arg_parser.add('-f', '--feature_names', help='List of features list pipeline (*.pkl file)')
pipeline = None
def __init__(self):
args = self.arg_parser.parse_known_args()[0]
super(ScikitBase, self).__init__()
self.pipeline = self.load_pipeline(args.pipeline)
if args.feature_names:
self.feature_names = self.load_pipeline(args.feature_names)
@staticmethod
def load_pipeline(pipeline_file):
"""
Loads scikit model/pipeline
"""
print(colored('Loading pipeline: ' + pipeline_file, 'green'))
return joblib.load(pipeline_file)
def fetch_pipeline_from_server(self):
"""
Method fetches pipeline from server/cloud
"""
# TODO
pass
def <|fim_middle|>(self, df):
"""
Returns predictions based on the model/pipeline
"""
try:
return self.pipeline.predict(df)
except (ValueError, TypeError):
print(colored('Got ValueError while using scikit model.. ', 'red'))
return None
<|fim▁end|> | predict |
<|file_name|>calculate_pi_old.py<|end_file_name|><|fim▁begin|>import tensorflow as tf
import matplotlib.pyplot as plt
import math
x_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='x_node')
y_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='y_node')
times = 5000
hits = 0
pis = []
<|fim▁hole|> x = session.run(x_node)
y = session.run(y_node)
if x*x + y*y < 1:
hits += 1
pass
pi = 4 * float(hits) / i
print(pi)
pis.append(pi)
pass
pass
plt.plot(pis)
plt.plot([0, times], [math.pi, math.pi])
plt.show()<|fim▁end|> | with tf.Session() as session:
for i in range(1, times): |
<|file_name|>calculate_pi_old.py<|end_file_name|><|fim▁begin|>import tensorflow as tf
import matplotlib.pyplot as plt
import math
x_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='x_node')
y_node = tf.random_uniform([1], minval=-1, maxval=1, dtype=tf.float32,
name='y_node')
times = 5000
hits = 0
pis = []
with tf.Session() as session:
for i in range(1, times):
x = session.run(x_node)
y = session.run(y_node)
if x*x + y*y < 1:
<|fim_middle|>
pi = 4 * float(hits) / i
print(pi)
pis.append(pi)
pass
pass
plt.plot(pis)
plt.plot([0, times], [math.pi, math.pi])
plt.show()
<|fim▁end|> | hits += 1
pass |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.<|fim▁hole|># THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()<|fim▁end|> | # |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | unittest.main() |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def <|fim_middle|>( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | test |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def <|fim_middle|>( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | testImageWithANegativeDataWindow |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def <|fim_middle|>( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | testHashVariesPerTileAndChannel |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
<|fim_middle|>
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
) |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
<|fim_middle|>
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i ) |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
<|fim_middle|>
def testHashVariesPerTileAndChannel( self ) :
n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
)
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i ) |
<|file_name|>ObjectToImageTest.py<|end_file_name|><|fim▁begin|>##########################################################################
#
# Copyright (c) 2013-2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
import os
import unittest
import IECore
import Gaffer
import GafferImage
import GafferImageTest
class ObjectToImageTest( GafferImageTest.ImageTestCase ) :
fileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checker.exr" )
negFileName = os.path.expandvars( "$GAFFER_ROOT/python/GafferImageTest/images/checkerWithNegativeDataWindow.200x150.exr" )
def test( self ) :
i = IECore.Reader.create( self.fileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testImageWithANegativeDataWindow( self ) :
i = IECore.Reader.create( self.negFileName ).read()
n = GafferImage.ObjectToImage()
n["object"].setValue( i )
self.assertEqual( n["out"].image(), i )
def testHashVariesPerTileAndChannel( self ) :
<|fim_middle|>
if __name__ == "__main__":
unittest.main()
<|fim▁end|> | n = GafferImage.ObjectToImage()
n["object"].setValue( IECore.Reader.create( self.fileName ).read() )
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "G", IECore.V2i( 0 ) )
)
self.assertNotEqual(
n["out"].channelDataHash( "R", IECore.V2i( 0 ) ),
n["out"].channelDataHash( "R", IECore.V2i( GafferImage.ImagePlug.tileSize() ) )
) |
<|file_name|>production.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Production Configurations
- Use Redis for cache
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
SECRET_KEY = env('DJANGO_SECRET_KEY')
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# SECURITY CONFIGURATION
# ------------------------------------------------------------------------------
# See https://docs.djangoproject.com/en/1.9/ref/middleware/#module-django.middleware.security
# and https://docs.djangoproject.com/ja/1.9/howto/deployment/checklist/#run-manage-py-check-deploy
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True)
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['example.com'])
# END SITE CONFIGURATION
INSTALLED_APPS += ('gunicorn', )
# STORAGE CONFIGURATION
# ------------------------------------------------------------------------------
# Uploaded Media Files
# ------------------------
# See: http://django-storages.readthedocs.io/en/latest/index.html
INSTALLED_APPS += (
'storages',
)
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
# TODO See: https://github.com/jschneier/django-storages/issues/47
# Revert the following and use str after the above-mentioned bug is fixed in
# either django-storage-redux or boto
AWS_HEADERS = {
'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % (
AWS_EXPIRY, AWS_EXPIRY))
}
# URL that handles the media served from MEDIA_ROOT, used for managing
# stored files.<|fim▁hole|># See:http://stackoverflow.com/questions/10390244/
from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media')
DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage'
#MEDIA_URL = 'https://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME
# Static Assets
# ------------------------
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See:
# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader',
['django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader', ]),
]
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# Use the Heroku-style specification
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
DATABASES['default'] = env.db('DATABASE_URL')
# CACHING
# ------------------------------------------------------------------------------
REDIS_LOCATION = '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0)
# Heroku URL does not pass the DB number, so we parse it in
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': REDIS_LOCATION,
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'IGNORE_EXCEPTIONS': True, # mimics memcache behavior.
# http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
}
}
}
# Custom Admin URL, use {% url 'admin:index' %}
ADMIN_URL = env('DJANGO_ADMIN_URL')
# Your production stuff: Below this line define 3rd party library settings
# ------------------------------------------------------------------------------
# EMAIL
# ------------------------------------------------------------------------------
# for now, send emails to console, even in production
EMAIL_BACKEND = env('DJANGO_EMAIL_BACKEND', default='django.core.mail.backends.console.EmailBackend')<|fim▁end|> | |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|>"""
Django settings for keyman project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$-2ijwgs8-3i*r#j@1ian5xrp+17)fz)%cdjjhwa#4x&%lk7v@'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'keys',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'keyman.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'keyman.wsgi.application'
<|fim▁hole|># Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'<|fim▁end|> | |
<|file_name|>partition_health.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .entity_health import EntityHealth
class PartitionHealth(EntityHealth):
"""Information about the health of a Service Fabric partition.
:param aggregated_health_state: Possible values include: 'Invalid', 'Ok',
'Warning', 'Error', 'Unknown'
:type aggregated_health_state: str or :class:`enum
<azure.servicefabric.models.enum>`
:param health_events: The list of health events reported on the entity.
:type health_events: list of :class:`HealthEvent
<azure.servicefabric.models.HealthEvent>`
:param unhealthy_evaluations:
:type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper
<azure.servicefabric.models.HealthEvaluationWrapper>`
:param health_statistics:
:type health_statistics: :class:`HealthStatistics
<azure.servicefabric.models.HealthStatistics>`
:param partition_id:
:type partition_id: str
:param replica_health_states: The list of replica health states associated
with the partition.
:type replica_health_states: list of :class:`ReplicaHealthState
<azure.servicefabric.models.ReplicaHealthState>`
"""
_attribute_map = {
'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'},
'health_events': {'key': 'HealthEvents', 'type': '[HealthEvent]'},
'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'},
'health_statistics': {'key': 'HealthStatistics', 'type': 'HealthStatistics'},<|fim▁hole|>
def __init__(self, aggregated_health_state=None, health_events=None, unhealthy_evaluations=None, health_statistics=None, partition_id=None, replica_health_states=None):
super(PartitionHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations, health_statistics=health_statistics)
self.partition_id = partition_id
self.replica_health_states = replica_health_states<|fim▁end|> | 'partition_id': {'key': 'PartitionId', 'type': 'str'},
'replica_health_states': {'key': 'ReplicaHealthStates', 'type': '[ReplicaHealthState]'},
} |
<|file_name|>partition_health.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .entity_health import EntityHealth
class PartitionHealth(EntityHealth):
<|fim_middle|>
<|fim▁end|> | """Information about the health of a Service Fabric partition.
:param aggregated_health_state: Possible values include: 'Invalid', 'Ok',
'Warning', 'Error', 'Unknown'
:type aggregated_health_state: str or :class:`enum
<azure.servicefabric.models.enum>`
:param health_events: The list of health events reported on the entity.
:type health_events: list of :class:`HealthEvent
<azure.servicefabric.models.HealthEvent>`
:param unhealthy_evaluations:
:type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper
<azure.servicefabric.models.HealthEvaluationWrapper>`
:param health_statistics:
:type health_statistics: :class:`HealthStatistics
<azure.servicefabric.models.HealthStatistics>`
:param partition_id:
:type partition_id: str
:param replica_health_states: The list of replica health states associated
with the partition.
:type replica_health_states: list of :class:`ReplicaHealthState
<azure.servicefabric.models.ReplicaHealthState>`
"""
_attribute_map = {
'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'},
'health_events': {'key': 'HealthEvents', 'type': '[HealthEvent]'},
'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'},
'health_statistics': {'key': 'HealthStatistics', 'type': 'HealthStatistics'},
'partition_id': {'key': 'PartitionId', 'type': 'str'},
'replica_health_states': {'key': 'ReplicaHealthStates', 'type': '[ReplicaHealthState]'},
}
def __init__(self, aggregated_health_state=None, health_events=None, unhealthy_evaluations=None, health_statistics=None, partition_id=None, replica_health_states=None):
super(PartitionHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations, health_statistics=health_statistics)
self.partition_id = partition_id
self.replica_health_states = replica_health_states |
<|file_name|>partition_health.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .entity_health import EntityHealth
class PartitionHealth(EntityHealth):
"""Information about the health of a Service Fabric partition.
:param aggregated_health_state: Possible values include: 'Invalid', 'Ok',
'Warning', 'Error', 'Unknown'
:type aggregated_health_state: str or :class:`enum
<azure.servicefabric.models.enum>`
:param health_events: The list of health events reported on the entity.
:type health_events: list of :class:`HealthEvent
<azure.servicefabric.models.HealthEvent>`
:param unhealthy_evaluations:
:type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper
<azure.servicefabric.models.HealthEvaluationWrapper>`
:param health_statistics:
:type health_statistics: :class:`HealthStatistics
<azure.servicefabric.models.HealthStatistics>`
:param partition_id:
:type partition_id: str
:param replica_health_states: The list of replica health states associated
with the partition.
:type replica_health_states: list of :class:`ReplicaHealthState
<azure.servicefabric.models.ReplicaHealthState>`
"""
_attribute_map = {
'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'},
'health_events': {'key': 'HealthEvents', 'type': '[HealthEvent]'},
'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'},
'health_statistics': {'key': 'HealthStatistics', 'type': 'HealthStatistics'},
'partition_id': {'key': 'PartitionId', 'type': 'str'},
'replica_health_states': {'key': 'ReplicaHealthStates', 'type': '[ReplicaHealthState]'},
}
def __init__(self, aggregated_health_state=None, health_events=None, unhealthy_evaluations=None, health_statistics=None, partition_id=None, replica_health_states=None):
<|fim_middle|>
<|fim▁end|> | super(PartitionHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations, health_statistics=health_statistics)
self.partition_id = partition_id
self.replica_health_states = replica_health_states |
<|file_name|>partition_health.py<|end_file_name|><|fim▁begin|># coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .entity_health import EntityHealth
class PartitionHealth(EntityHealth):
"""Information about the health of a Service Fabric partition.
:param aggregated_health_state: Possible values include: 'Invalid', 'Ok',
'Warning', 'Error', 'Unknown'
:type aggregated_health_state: str or :class:`enum
<azure.servicefabric.models.enum>`
:param health_events: The list of health events reported on the entity.
:type health_events: list of :class:`HealthEvent
<azure.servicefabric.models.HealthEvent>`
:param unhealthy_evaluations:
:type unhealthy_evaluations: list of :class:`HealthEvaluationWrapper
<azure.servicefabric.models.HealthEvaluationWrapper>`
:param health_statistics:
:type health_statistics: :class:`HealthStatistics
<azure.servicefabric.models.HealthStatistics>`
:param partition_id:
:type partition_id: str
:param replica_health_states: The list of replica health states associated
with the partition.
:type replica_health_states: list of :class:`ReplicaHealthState
<azure.servicefabric.models.ReplicaHealthState>`
"""
_attribute_map = {
'aggregated_health_state': {'key': 'AggregatedHealthState', 'type': 'str'},
'health_events': {'key': 'HealthEvents', 'type': '[HealthEvent]'},
'unhealthy_evaluations': {'key': 'UnhealthyEvaluations', 'type': '[HealthEvaluationWrapper]'},
'health_statistics': {'key': 'HealthStatistics', 'type': 'HealthStatistics'},
'partition_id': {'key': 'PartitionId', 'type': 'str'},
'replica_health_states': {'key': 'ReplicaHealthStates', 'type': '[ReplicaHealthState]'},
}
def <|fim_middle|>(self, aggregated_health_state=None, health_events=None, unhealthy_evaluations=None, health_statistics=None, partition_id=None, replica_health_states=None):
super(PartitionHealth, self).__init__(aggregated_health_state=aggregated_health_state, health_events=health_events, unhealthy_evaluations=unhealthy_evaluations, health_statistics=health_statistics)
self.partition_id = partition_id
self.replica_health_states = replica_health_states
<|fim▁end|> | __init__ |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)<|fim▁hole|>
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")<|fim▁end|> |
super(EnkfNode, self).__init__(c_pointer, config_node, True) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
<|fim_middle|>
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
<|fim_middle|>
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
<|fim_middle|>
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | return EnkfNode.cNamespace().value_ptr(self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
<|fim_middle|>
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | """ @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
<|fim_middle|>
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | """ @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
<|fim_middle|>
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | """ @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
<|fim_middle|>
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | """
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
<|fim_middle|>
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | return EnkfNode.cNamespace().get_name(self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
<|fim_middle|>
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step)) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
<|fim_middle|>
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
<|fim_middle|>
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | EnkfNode.cNamespace().free(self) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
<|fim_middle|>
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | c_pointer = EnkfNode.cNamespace().alloc_private(config_node) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
<|fim_middle|>
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | c_pointer = EnkfNode.cNamespace().alloc(config_node) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
<|fim_middle|>
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step)) |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def <|fim_middle|>(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | __init__ |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def <|fim_middle|>(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | valuePointer |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def <|fim_middle|>(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | asGenData |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def <|fim_middle|>(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | asGenKw |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def <|fim_middle|>(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | asCustomKW |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def <|fim_middle|>(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | tryLoad |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def <|fim_middle|>(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | name |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def <|fim_middle|>(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | load |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def <|fim_middle|>(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def free(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | save |
<|file_name|>enkf_node.py<|end_file_name|><|fim▁begin|># Copyright (C) 2012 Statoil ASA, Norway.
#
# The file 'enkf_node.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.
#
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
# for more details.
from ert.cwrap import BaseCClass, CWrapper
from ert.enkf import ENKF_LIB, EnkfFs, NodeId
from ert.enkf.data import EnkfConfigNode, GenKw, GenData, CustomKW
from ert.enkf.enums import ErtImplType
class EnkfNode(BaseCClass):
def __init__(self, config_node, private=False):
assert isinstance(config_node, EnkfConfigNode)
if private:
c_pointer = EnkfNode.cNamespace().alloc_private(config_node)
else:
c_pointer = EnkfNode.cNamespace().alloc(config_node)
super(EnkfNode, self).__init__(c_pointer, config_node, True)
def valuePointer(self):
return EnkfNode.cNamespace().value_ptr(self)
def asGenData(self):
""" @rtype: GenData """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_DATA
return GenData.createCReference(self.valuePointer(), self)
def asGenKw(self):
""" @rtype: GenKw """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.GEN_KW
return GenKw.createCReference(self.valuePointer(), self)
def asCustomKW(self):
""" @rtype: CustomKW """
impl_type = EnkfNode.cNamespace().get_impl_type(self)
assert impl_type == ErtImplType.CUSTOM_KW
return CustomKW.createCReference(self.valuePointer(), self)
def tryLoad(self, fs, node_id):
"""
@type fs: EnkfFS
@type node_id: NodeId
@rtype: bool
"""
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
return EnkfNode.cNamespace().try_load(self, fs, node_id)
def name(self):
return EnkfNode.cNamespace().get_name(self)
def load(self, fs, node_id):
if not self.tryLoad(fs, node_id):
raise Exception("Could not load node: %s iens: %d report: %d" % (self.name(), node_id.iens, node_id.report_step))
def save(self, fs, node_id):
assert isinstance(fs, EnkfFs)
assert isinstance(node_id, NodeId)
EnkfNode.cNamespace().store(self, fs, True, node_id)
def <|fim_middle|>(self):
EnkfNode.cNamespace().free(self)
cwrapper = CWrapper(ENKF_LIB)
cwrapper.registerObjectType("enkf_node", EnkfNode)
EnkfNode.cNamespace().free = cwrapper.prototype("void enkf_node_free(enkf_node)")
EnkfNode.cNamespace().alloc = cwrapper.prototype("c_void_p enkf_node_alloc(enkf_node)")
EnkfNode.cNamespace().alloc_private = cwrapper.prototype("c_void_p enkf_node_alloc_private_container(enkf_node)")
EnkfNode.cNamespace().get_name = cwrapper.prototype("char* enkf_node_get_key(enkf_node)")
EnkfNode.cNamespace().value_ptr = cwrapper.prototype("c_void_p enkf_node_value_ptr(enkf_node)")
EnkfNode.cNamespace().try_load = cwrapper.prototype("bool enkf_node_try_load(enkf_node, enkf_fs, node_id)")
EnkfNode.cNamespace().get_impl_type = cwrapper.prototype("ert_impl_type_enum enkf_node_get_impl_type(enkf_node)")
EnkfNode.cNamespace().store = cwrapper.prototype("void enkf_node_store(enkf_node, enkf_fs, bool, node_id)")
<|fim▁end|> | free |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):<|fim▁hole|>class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val<|fim▁end|> | # self.val = x
# self.next = None
|
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
<|fim_middle|>
<|fim▁end|> | _largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
<|fim_middle|>
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx) |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
<|fim_middle|>
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
<|fim_middle|>
<|fim▁end|> | def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
<|fim_middle|>
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | p = start
while delta:
p = p.next
delta -= 1
return p.val |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
<|fim_middle|>
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx) |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
<|fim_middle|>
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | return _get(nextpos, self.head) |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
<|fim_middle|>
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | val = _get(nextpos, self.head) |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
<|fim_middle|>
else:
val = _get(nextpos - self.m2_idx, self.m2)
return val
<|fim▁end|> | val = _get(nextpos - self.m1_idx, self.m1) |
<|file_name|>382-linked-list-random-node.py<|end_file_name|><|fim▁begin|>import random
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
_largesize = 300
def __init__(self, head):
self.head = head
self.lsize = 0
while head.next:
head = head.next
self.lsize += 1
self.m1_idx = None
self.m2_idx = None
if self.lsize > self._largesize:
self.m1_idx = self.lsize / 3 # start from 1/3
self.m1 = self._getN(self.m1_idx)
self.m2_idx = self.m1_idx * 2 # start from 2/3
self.m2 = self._getN(self.m2_idx)
def _getN(self, n):
n -= 1
p = self.head
while n:
p = p.next
n -= 1
return p
def getRandom(self):
def _get(delta, start):
p = start
while delta:
p = p.next
delta -= 1
return p.val
nextpos = random.randint(0, self.lsize)
if not self.m1_idx:
return _get(nextpos, self.head)
if nextpos < self.m1_idx:
val = _get(nextpos, self.head)
elif nextpos < self.m2_idx:
val = _get(nextpos - self.m1_idx, self.m1)
else:
<|fim_middle|>
return val
<|fim▁end|> | val = _get(nextpos - self.m2_idx, self.m2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.