code
stringlengths 3
1.05M
| repo_name
stringlengths 5
104
| path
stringlengths 4
251
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.05M
|
|---|---|---|---|---|---|
# coding=utf-8
from __future__ import unicode_literals, division
import sys
import logging
from subprocess import Popen, PIPE
import shutil
import os
import re
from os.path import join as pjoin
from PIL import Image
from django.utils.six import StringIO
from django.core import management
from django.core.files.storage import default_storage
from django.template.loader import render_to_string
from django.test.client import Client
from django.test import TestCase
from django.test.utils import override_settings
from sorl.thumbnail import default, get_thumbnail, delete
from sorl.thumbnail.conf import settings
from sorl.thumbnail.engines.pil_engine import Engine as PILEngine
from sorl.thumbnail.helpers import get_module_class, ThumbnailError
from sorl.thumbnail.images import ImageFile
from sorl.thumbnail.log import ThumbnailLogHandler
from sorl.thumbnail.parsers import parse_crop, parse_geometry
from sorl.thumbnail.templatetags.thumbnail import margin
from sorl.thumbnail.base import ThumbnailBackend
from .models import Item
from .storage import MockLoggingHandler
from .compat import unittest
from .utils import same_open_fd_count, override_custom_settings
skip = unittest.skip
skipIf = unittest.skipIf
handler = ThumbnailLogHandler()
handler.setLevel(logging.ERROR)
logging.getLogger('sorl.thumbnail').addHandler(handler)
class BaseStorageTestCase(unittest.TestCase):
im = None
def setUp(self):
os.makedirs(settings.MEDIA_ROOT)
fn = pjoin(settings.MEDIA_ROOT, self.name)
Image.new('L', (100, 100)).save(fn)
self.im = ImageFile(self.name)
logger = logging.getLogger('slog')
logger.setLevel(logging.DEBUG)
handler = MockLoggingHandler(level=logging.DEBUG)
logger.addHandler(handler)
self.log = handler.messages['debug']
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
class StorageTestCase(BaseStorageTestCase):
name = 'org.jpg'
def test_a_new(self):
get_thumbnail(self.im, '50x50')
actions = [
'open: org.jpg', # open the original for thumbnailing
# save the file
'save: test/cache/ca/1a/ca1afb02b7250c125d8830c0e8a492ad.jpg',
# check for filename
'get_available_name: test/cache/ca/1a/ca1afb02b7250c125d8830c0e8a492ad.jpg',
# called by get_available_name
'exists: test/cache/ca/1a/ca1afb02b7250c125d8830c0e8a492ad.jpg',
]
self.assertEqual(self.log, actions)
def test_b_cached(self):
get_thumbnail(self.im, '50x50')
self.assertEqual(self.log, []) # now this should all be in cache
def test_c_safe_methods(self):
im = default.kvstore.get(self.im)
im.url, im.x, im.y
self.assertEqual(self.log, [])
class AlternativeResolutionsTest(BaseStorageTestCase):
name = 'retina.jpg'
def setUp(self):
settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS = [1.5, 2]
super(AlternativeResolutionsTest, self).setUp()
def tearDown(self):
super(AlternativeResolutionsTest, self).tearDown()
settings.THUMBNAIL_ALTERNATIVE_RESOLUTIONS = []
def test_retina(self):
get_thumbnail(self.im, '50x50')
actions = [
# save regular resolution, same as in StorageTestCase
'open: retina.jpg',
'save: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
'get_available_name: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
'exists: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19.jpg',
# save the 1.5x resolution version
'save: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@1.5x.jpg',
'get_available_name: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@1.5x.jpg',
'exists: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@1.5x.jpg',
# save the 2x resolution version
'save: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@2x.jpg',
'get_available_name: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@2x.jpg',
'exists: test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@2x.jpg'
]
self.assertEqual(self.log, actions)
with open(pjoin(settings.MEDIA_ROOT, 'test/cache/19/10/1910dc350bbe9ee55fd9d8d3d5e38e19@1.5x.jpg')) as fp:
engine = PILEngine()
self.assertEqual(engine.get_image_size(engine.get_image(ImageFile(file_=fp))), (75, 75))
class UrlStorageTestCase(unittest.TestCase):
def test_encode_utf8_filenames(self):
storage = get_module_class('sorl.thumbnail.images.UrlStorage')()
self.assertEqual(
storage.normalize_url('El jovencito emponzoñado de whisky, qué figura exhibe'),
'El%20jovencito%20emponzoado%20de%20whisky%2C%20qu%20figura%20exhibe'
)
class ParsersTestCase(unittest.TestCase):
def test_alias_crop(self):
crop = parse_crop('center', (500, 500), (400, 400))
self.assertEqual(crop, (50, 50))
crop = parse_crop('right', (500, 500), (400, 400))
self.assertEqual(crop, (100, 50))
def test_percent_crop(self):
crop = parse_crop('50% 0%', (500, 500), (400, 400))
self.assertEqual(crop, (50, 0))
crop = parse_crop('10% 80%', (500, 500), (400, 400))
self.assertEqual(crop, (10, 80))
def test_px_crop(self):
crop = parse_crop('200px 33px', (500, 500), (400, 400))
self.assertEqual(crop, (100, 33))
def test_bad_crop(self):
self.assertRaises(ThumbnailError, parse_crop, '-200px', (500, 500), (400, 400))
def test_geometry(self):
g = parse_geometry('222x30')
self.assertEqual(g, (222, 30))
g = parse_geometry('222')
self.assertEqual(g, (222, None))
g = parse_geometry('x999')
self.assertEqual(g, (None, 999))
class SimpleTestCaseBase(unittest.TestCase):
backend = None
engine = None
kvstore = None
def setUp(self):
self.backend = get_module_class(settings.THUMBNAIL_BACKEND)()
self.engine = get_module_class(settings.THUMBNAIL_ENGINE)()
self.kvstore = get_module_class(settings.THUMBNAIL_KVSTORE)()
if not os.path.exists(settings.MEDIA_ROOT):
os.makedirs(settings.MEDIA_ROOT)
dims = [
(500, 500),
(100, 100),
(200, 100),
]
for dim in dims:
name = '%sx%s.jpg' % dim
fn = pjoin(settings.MEDIA_ROOT, name)
im = Image.new('L', dim)
im.save(fn)
Item.objects.get_or_create(image=name)
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
class SimpleTestCase(SimpleTestCaseBase):
def test_simple(self):
item = Item.objects.get(image='500x500.jpg')
t = self.backend.get_thumbnail(item.image, '400x300', crop='center')
self.assertEqual(t.x, 400)
self.assertEqual(t.y, 300)
t = self.backend.get_thumbnail(item.image, '1200x900', crop='13% 89%')
self.assertEqual(t.x, 1200)
self.assertEqual(t.y, 900)
def test_upscale(self):
item = Item.objects.get(image='100x100.jpg')
t = self.backend.get_thumbnail(item.image, '400x300', upscale=False)
self.assertEqual(t.x, 100)
self.assertEqual(t.y, 100)
t = self.backend.get_thumbnail(item.image, '400x300', upscale=True)
self.assertEqual(t.x, 300)
self.assertEqual(t.y, 300)
def test_upscale_and_crop(self):
item = Item.objects.get(image='200x100.jpg')
t = self.backend.get_thumbnail(item.image, '400x300', crop='center', upscale=False)
self.assertEqual(t.x, 200)
self.assertEqual(t.y, 100)
t = self.backend.get_thumbnail(item.image, '400x300', crop='center', upscale=True)
self.assertEqual(t.x, 400)
self.assertEqual(t.y, 300)
def test_kvstore(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.kvstore.delete_thumbnails(im)
th1 = self.backend.get_thumbnail(im, '50')
th2 = self.backend.get_thumbnail(im, 'x50')
th3 = self.backend.get_thumbnail(im, '20x20')
self.assertEqual(
set([th1.key, th2.key, th3.key]),
set(self.kvstore._get(im.key, identity='thumbnails'))
)
self.kvstore.delete_thumbnails(im)
self.assertEqual(
None,
self.kvstore._get(im.key, identity='thumbnails')
)
def test_is_portrait(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
th = self.backend.get_thumbnail(im, '50x200', crop='center')
self.assertEqual(th.is_portrait(), True)
th = self.backend.get_thumbnail(im, '500x2', crop='center')
self.assertEqual(th.is_portrait(), False)
def test_margin(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.assertEqual(margin(im, '1000x1000'), '250px 250px 250px 250px')
self.assertEqual(margin(im, '800x1000'), '250px 150px 250px 150px')
self.assertEqual(margin(im, '500x500'), '0px 0px 0px 0px')
self.assertEqual(margin(im, '500x501'), '0px 0px 1px 0px')
self.assertEqual(margin(im, '503x500'), '0px 2px 0px 1px')
self.assertEqual(margin(im, '300x300'), '-100px -100px -100px -100px')
def test_kvstore_get_and_set(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.kvstore.delete(im)
self.assertEqual(self.kvstore.get(im), None)
self.kvstore.set(im)
self.assertEqual(im.size, [500, 500])
def test_cleanup1(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.kvstore.delete_thumbnails(im)
th = self.backend.get_thumbnail(im, '3x3')
self.assertEqual(th.exists(), True)
th.delete()
self.assertEqual(th.exists(), False)
self.assertEqual(self.kvstore.get(th).x, 3)
self.assertEqual(self.kvstore.get(th).y, 3)
self.kvstore.cleanup()
self.assertEqual(self.kvstore.get(th), None)
self.kvstore.delete(im)
def test_cleanup2(self):
self.kvstore.clear()
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
th3 = self.backend.get_thumbnail(im, '27x27')
th4 = self.backend.get_thumbnail(im, '81x81')
def keys_test(x, y, z):
self.assertEqual(x, len(list(self.kvstore._find_keys(identity='image'))))
self.assertEqual(y, len(list(self.kvstore._find_keys(identity='thumbnails'))))
self.assertEqual(z, len(self.kvstore._get(im.key, identity='thumbnails') or []))
keys_test(3, 1, 2)
th3.delete()
keys_test(3, 1, 2)
self.kvstore.cleanup()
keys_test(2, 1, 1)
th4.delete()
keys_test(2, 1, 1)
self.kvstore.cleanup()
keys_test(1, 0, 0)
self.kvstore.clear()
keys_test(0, 0, 0)
def test_storage_serialize(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.assertEqual(im.serialize_storage(), 'thumbnail_tests.storage.TestStorage')
self.assertEqual(
ImageFile('http://www.image.jpg').serialize_storage(),
'sorl.thumbnail.images.UrlStorage',
)
self.assertEqual(
ImageFile('http://www.image.jpg', default.storage).serialize_storage(),
'thumbnail_tests.storage.TestStorage',
)
self.assertEqual(
ImageFile('getit', default_storage).serialize_storage(),
'thumbnail_tests.storage.TestStorage',
)
@skipIf(sys.platform == 'darwin', 'quality is saved a different way on os x')
def test_quality(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
th = self.backend.get_thumbnail(im, '100x100', quality=50)
p1 = Popen(['identify', '-verbose', th.storage.path(th.name)], stdout=PIPE)
p2 = Popen(['grep', '-c', 'Quality: 50'], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0].strip()
self.assertEqual(output.decode('utf-8'), '1')
def test_image_file_deserialize(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
default.kvstore.set(im)
self.assertEqual(
default.kvstore.get(im).serialize_storage(),
'thumbnail_tests.storage.TestStorage',
)
im = ImageFile('http://dummyimage.com/300x300/')
default.kvstore.set(im)
self.assertEqual(
default.kvstore.get(im).serialize_storage(),
'sorl.thumbnail.images.UrlStorage',
)
def test_abspath(self):
item = Item.objects.get(image='500x500.jpg')
image = ImageFile(item.image.path)
val = render_to_string('thumbnail20.html', {
'image': image,
}).strip()
im = self.backend.get_thumbnail(image, '32x32', crop='center')
self.assertEqual('<img src="%s">' % im.url, val)
def test_new_tag_style(self):
item = Item.objects.get(image='500x500.jpg')
image = ImageFile(item.image.path)
val = render_to_string('thumbnail20a.html', {
'image': image,
}).strip()
im = self.backend.get_thumbnail(image, '32x32', crop='center')
self.assertEqual('<img src="%s">' % im.url, val)
def test_html_filter(self):
text = '<img alt="A image!" src="http://dummyimage.com/800x800" />'
val = render_to_string('htmlfilter.html', {
'text': text,
}).strip()
self.assertEqual('<img alt="A image!" src="/media/test/cache/2e/35/2e3517d8aa949728b1ee8b26c5a7bbc4.jpg" />',
val)
def test_markdown_filter(self):
text = ''
val = render_to_string('markdownfilter.html', {
'text': text,
}).strip()
self.assertEqual('', val)
class TemplateTestCaseA(SimpleTestCaseBase):
def test_model(self):
item = Item.objects.get(image='500x500.jpg')
val = render_to_string('thumbnail1.html', {
'item': item,
}).strip()
self.assertEqual(val, '<img style="margin:0px 0px 0px 0px" width="200" height="100">')
val = render_to_string('thumbnail2.html', {
'item': item,
}).strip()
self.assertEqual(val, '<img style="margin:0px 50px 0px 50px" width="100" height="100">')
def test_nested(self):
item = Item.objects.get(image='500x500.jpg')
val = render_to_string('thumbnail6.html', {
'item': item,
}).strip()
self.assertEqual(val, (
'<a href="/media/test/cache/ba/d7/bad785264867676a926566150f90f87c.jpg">'
'<img src="/media/test/cache/c6/7a/c67a64c3145f8834cd6770f6f80198c9.jpg" width="400" height="400">'
'</a>')
)
def test_serialization_options(self):
item = Item.objects.get(image='500x500.jpg')
for j in range(0, 20):
# we could be lucky...
val0 = render_to_string('thumbnail7.html', {
'item': item,
}).strip()
val1 = render_to_string('thumbnail7a.html', {
'item': item,
}).strip()
self.assertEqual(val0, val1)
def test_options(self):
item = Item.objects.get(image='500x500.jpg')
options = {
'crop': "center",
'upscale': True,
'quality': 77,
}
val0 = render_to_string('thumbnail8.html', {
'item': item,
'options': options,
}).strip()
val1 = render_to_string('thumbnail8a.html', {
'item': item,
}).strip()
self.assertEqual(val0, val1)
def test_progressive(self):
im = Item.objects.get(image='500x500.jpg').image
th = self.backend.get_thumbnail(im, '100x100', progressive=True)
path = pjoin(settings.MEDIA_ROOT, th.name)
p = Popen(['identify', '-verbose', path], stdout=PIPE)
p.wait()
m = re.search('Interlace: JPEG', str(p.stdout.read()))
self.assertEqual(bool(m), True)
def test_nonprogressive(self):
im = Item.objects.get(image='500x500.jpg').image
th = self.backend.get_thumbnail(im, '100x100', progressive=False)
path = pjoin(settings.MEDIA_ROOT, th.name)
p = Popen(['identify', '-verbose', path], stdout=PIPE)
p.wait()
m = re.search('Interlace: None', str(p.stdout.read()))
self.assertEqual(bool(m), True)
def test_orientation(self):
data_dir = pjoin(settings.MEDIA_ROOT, 'data')
shutil.copytree(settings.DATA_ROOT, data_dir)
ref = Image.open(pjoin(data_dir, '1_topleft.jpg'))
top = ref.getpixel((14, 7))
left = ref.getpixel((7, 14))
engine = PILEngine()
def epsilon(x, y):
if isinstance(x, (tuple, list)):
x = sum(x) / len(x)
if isinstance(y, (tuple, list)):
y = sum(y) / len(y)
return abs(x - y)
data_images = (
'1_topleft.jpg',
'2_topright.jpg',
'3_bottomright.jpg',
'4_bottomleft.jpg',
'5_lefttop.jpg',
'6_righttop.jpg',
'7_rightbottom.jpg',
'8_leftbottom.jpg'
)
for name in data_images:
th = self.backend.get_thumbnail('data/%s' % name, '30x30')
im = engine.get_image(th)
self.assertLess(epsilon(top, im.getpixel((14, 7))), 10)
self.assertLess(epsilon(left, im.getpixel((7, 14))), 10)
exif = im._getexif()
if exif:
self.assertEqual(exif.get(0x0112), 1)
class TemplateTestCaseB(unittest.TestCase):
def tearDown(self):
try:
shutil.rmtree(settings.MEDIA_ROOT)
except Exception:
pass
def test_url(self):
val = render_to_string('thumbnail3.html', {}).strip()
self.assertEqual(val, '<img style="margin:0px 0px 0px 0px" width="20" height="20">')
def test_portrait(self):
val = render_to_string('thumbnail4.html', {
'source': 'http://dummyimage.com/120x100/',
'dims': 'x66',
}).strip()
self.assertEqual(val,
'<img src="/media/test/cache/7b/cd/7bcd20922c6750649f431df7c3cdbc5e.jpg" width="79" height="66" class="landscape">')
def test_empty(self):
val = render_to_string('thumbnail5.html', {}).strip()
self.assertEqual(val, '<p>empty</p>')
class TemplateTestCaseClient(TestCase):
def test_empty_error(self):
with override_custom_settings(settings, THUMBNAIL_DEBUG=False):
from django.core.mail import outbox
client = Client()
response = client.get('/thumbnail9.html')
self.assertEqual(response.content.strip(), b'<p>empty</p>')
self.assertEqual(outbox[0].subject, '[sorl-thumbnail] ERROR: /thumbnail9.html')
end = outbox[0].body.split('\n\n')[-2].split(':')[1].strip()
self.assertEqual(end, '[Errno 2] No such file or directory')
class CropTestCase(SimpleTestCaseBase):
def setUp(self):
super(CropTestCase, self).setUp()
# portrait
name = 'portrait.jpg'
fn = pjoin(settings.MEDIA_ROOT, name)
im = Image.new('L', (100, 200))
im.paste(255, (0, 0, 100, 100))
im.save(fn)
self.portrait = ImageFile(Item.objects.get_or_create(image=name)[0].image)
self.kvstore.delete(self.portrait)
# landscape
name = 'landscape.jpg'
fn = pjoin(settings.MEDIA_ROOT, name)
im = Image.new('L', (200, 100))
im.paste(255, (0, 0, 100, 100))
im.save(fn)
self.landscape = ImageFile(Item.objects.get_or_create(image=name)[0].image)
self.kvstore.delete(self.landscape)
def test_portrait_crop(self):
def mean_pixel(x, y):
values = im.getpixel((x, y))
if not isinstance(values, (tuple, list)):
values = [values]
return sum(values) / len(values)
for crop in ('center', '88% 50%', '50px'):
th = self.backend.get_thumbnail(self.portrait, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
self.assertEqual(mean_pixel(50, 0), 255)
self.assertEqual(mean_pixel(50, 45), 255)
self.assertEqual(250 <= mean_pixel(50, 49) <= 255, True, mean_pixel(50, 49))
self.assertEqual(mean_pixel(50, 55), 0)
self.assertEqual(mean_pixel(50, 99), 0)
for crop in ('top', '0%', '0px'):
th = self.backend.get_thumbnail(self.portrait, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(250 < mean_pixel(x, y) <= 255, True)
for crop in ('bottom', '100%', '100px'):
th = self.backend.get_thumbnail(self.portrait, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(0 <= mean_pixel(x, y) < 5, True)
def test_landscape_crop(self):
def mean_pixel(x, y):
values = im.getpixel((x, y))
if not isinstance(values, (tuple, list)):
values = [values]
return sum(values) / len(values)
for crop in ('center', '50% 200%', '50px 700px'):
th = self.backend.get_thumbnail(self.landscape, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
self.assertEqual(mean_pixel(0, 50), 255)
self.assertEqual(mean_pixel(45, 50), 255)
self.assertEqual(250 < mean_pixel(49, 50) <= 255, True)
self.assertEqual(mean_pixel(55, 50), 0)
self.assertEqual(mean_pixel(99, 50), 0)
for crop in ('left', '0%', '0px'):
th = self.backend.get_thumbnail(self.landscape, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(250 < mean_pixel(x, y) <= 255, True)
for crop in ('right', '100%', '100px'):
th = self.backend.get_thumbnail(self.landscape, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(0 <= mean_pixel(x, y) < 5, True)
def test_smart_crop(self):
# TODO: Complete test for smart crop
thumb = self.backend.get_thumbnail(
'32x32',
'data/white_border.jpg',
crop='smart')
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
class DummyTestCase(TestCase):
def setUp(self):
self.backend = get_module_class(settings.THUMBNAIL_BACKEND)()
def test_dummy_tags(self):
settings.THUMBNAIL_DUMMY = True
val = render_to_string('thumbnaild1.html', {
'anything': 'AINO',
}).strip()
self.assertEqual(val, '<img style="margin:auto" width="200" height="100">')
val = render_to_string('thumbnaild2.html', {
'anything': None,
}).strip()
self.assertEqual(val, '<img src="http://dummyimage.com/300x200" width="300" height="200"><p>NOT</p>')
val = render_to_string('thumbnaild3.html', {
}).strip()
self.assertEqual(val, '<img src="http://dummyimage.com/600x400" width="600" height="400">')
settings.THUMBNAIL_DUMMY = False
class ModelTestCase(SimpleTestCaseBase):
def test_field1(self):
self.kvstore.clear()
item = Item.objects.get(image='100x100.jpg')
im = ImageFile(item.image)
self.assertEqual(None, self.kvstore.get(im))
self.backend.get_thumbnail(im, '27x27')
self.backend.get_thumbnail(im, '81x81')
self.assertNotEqual(None, self.kvstore.get(im))
self.assertEqual(3, len(list(self.kvstore._find_keys(identity='image'))))
self.assertEqual(1, len(list(self.kvstore._find_keys(identity='thumbnails'))))
class BackendTest(SimpleTestCaseBase):
def test_delete(self):
im1 = Item.objects.get(image='100x100.jpg').image
im2 = Item.objects.get(image='500x500.jpg').image
default.kvstore.get_or_set(ImageFile(im1))
# exists in kvstore and in storage
self.assertTrue(bool(default.kvstore.get(ImageFile(im1))))
self.assertTrue(ImageFile(im1).exists())
# delete
delete(im1)
self.assertFalse(bool(default.kvstore.get(ImageFile(im1))))
self.assertFalse(ImageFile(im1).exists())
default.kvstore.get_or_set(ImageFile(im2))
# exists in kvstore and in storage
self.assertTrue(bool(default.kvstore.get(ImageFile(im2))))
self.assertTrue(ImageFile(im2).exists())
# delete
delete(im2, delete_file=False)
self.assertFalse(bool(default.kvstore.get(ImageFile(im2))))
self.assertTrue(ImageFile(im2).exists())
class TestInputCase(unittest.TestCase):
def setUp(self):
if not os.path.exists(settings.MEDIA_ROOT):
os.makedirs(settings.MEDIA_ROOT)
self.name = 'åäö.jpg'
fn = pjoin(settings.MEDIA_ROOT, self.name)
im = Image.new('L', (666, 666))
im.save(fn)
def test_nonascii(self):
# also test the get_thumbnail shortcut
th = get_thumbnail(self.name, '200x200')
hash_file = '/media/test/cache/99/45/9945ad3ee0397274de77abd37d5db7bb.jpg'
self.assertEqual(th.url, hash_file)
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
@skipIf(sys.platform.startswith("win"), "Can't easily count descriptors on windows")
class TestDescriptors(unittest.TestCase):
"""Make sure we're not leaving open descriptors on file exceptions"""
engine = None
def setUp(self):
self.engine = get_module_class(settings.THUMBNAIL_ENGINE)()
def test_no_source_get_image(self):
"""If source image does not exists, properly close all file descriptors"""
source = ImageFile('nonexistent.jpeg')
with same_open_fd_count(self):
with self.assertRaises(IOError):
self.engine.get_image(source)
def test_is_valid_image(self):
with same_open_fd_count(self):
self.engine.is_valid_image(b'invalidbinaryimage.jpg')
@skipIf('pgmagick_engine' in settings.THUMBNAIL_ENGINE and sys.version_info.major == 2,
'No output has been received in the last 10 minutes, this potentially indicates something wrong with the build itself.')
def test_write(self):
with same_open_fd_count(self):
with self.assertRaises(Exception):
self.engine.write(image=self.engine.get_image(StringIO(b'xxx')),
options={'format': 'JPEG', 'quality': 90, 'image_info': {}},
thumbnail=ImageFile('whatever_thumb.jpg', default.storage))
class CommandTests(SimpleTestCase):
def test_clear_action(self):
out = StringIO('')
management.call_command('thumbnail', 'clear', verbosity=1, stdout=out)
self.assertEqual(out.getvalue(), "Clear the Key Value Store ... [Done]\n")
def test_cleanup_action(self):
out = StringIO('')
management.call_command('thumbnail', 'cleanup', verbosity=1, stdout=out)
self.assertEqual(out.getvalue(), "Cleanup thumbnails ... [Done]\n")
class FakeFile(object):
"""
Used to test the _get_format method.
"""
def __init__(self, name):
self.name = name
@override_settings(THUMBNAIL_PRESERVE_FORMAT=True,
THUMBNAIL_FORMAT='XXX')
class PreserveFormatTest(TestCase):
def setUp(self):
self.backend = ThumbnailBackend()
def test_with_various_formats(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.jpg')), 'JPEG')
self.assertEqual(self.backend._get_format(FakeFile('foo.jpeg')), 'JPEG')
self.assertEqual(self.backend._get_format(FakeFile('foo.png')), 'PNG')
def test_double_extension(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.ext.jpg')), 'JPEG')
def test_that_capitalization_doesnt_matter(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.PNG')), 'PNG')
self.assertEqual(self.backend._get_format(FakeFile('foo.JPG')), 'JPEG')
def test_fallback_format(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.txt')), 'XXX')
def test_with_nonascii(self):
self.assertEqual(self.backend._get_format(FakeFile('你好.jpg')), 'JPEG')
|
caioariede/sorl-thumbnail
|
tests/thumbnail_tests/tests.py
|
Python
|
bsd-3-clause
| 29,267
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""
Base class for NCC Orchestration
"""
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import *
from marvin.lib.base import Domain, Account
from marvin.lib.utils import validateList
from marvin.codes import PASS,FAILED
from marvin.cloudstackException import (InvalidParameterException,
GetDetailExceptionInfo)
from os import system
from subprocess import call
import requests, json, urllib
class NCC:
def __init__(self, nccip, nsip, csip, logger=None):
self.nccip = nccip
self.nsip = nsip
self.csip = csip
self.logger = logger
self.__lastError = ''
def registerCCP(self, apiclient):
"""
Register CCP with NCC
"""
auth_keys = self.getAdminKeys(apiclient)
url = "http://"+self.nccip+"/cs/cca/v1/cloudstacks"
cs_url = "http://"+self.csip+":8080/"
payload = {"cloudstack": {
"name": "Cloudstack",
"apikey": auth_keys[0],
"secretkey": auth_keys[1],
"driver_username": "admin",
"driver_password": "nsroot",
"cloudstack_uri": cs_url
}
}
cmd_response = self.sendCmdToNCC(url, payload)
if cmd_response == FAILED:
raise Exception("Error: %s" % self.__lastError)
def registerNS(self):
url = "http://"+self.nccip+"/nitro/v1/config/managed_device/"
payload = 'object={"params":{"action":"add_device"}, "managed_device":{"ip_address":"%s",\
"profile_name":"ns_nsroot_profile", "sync_operation":"false"}}' % self.nsip
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
cmd_response = self.sendCmdToNS(url, payload, header=headers)
if cmd_response == FAILED:
raise Exception("Error: %s" % self.__lastError)
def assignNStoCSZone(self):
cs_zone = self.getCSZoneFromNCC()
if cs_zone == FAILED:
raise Exception("Error: %s" % self.__lastError)
url = "http://"+self.nccip+"/nitro/v1/config/tag/"
payload = 'object={"tag": {"entity_type": "managed_device", "entity_id": "%s",\
"tag_key": "zone", "tag_value": "%s"}}' % (self.nsip, cs_zone)
header = {'Content-Type':'application/x-www-form-urlencoded'}
cmd_response = self.sendCmdToNS(url, payload, header=header)
if cmd_response == FAILED:
raise Exception("Error: %s" % self.__lastError)
def createServicePackages(self, name, platform_type, device_ip, isolation_policy="shared"):
tnt_group = self.createTenantGroup(name)
if tnt_group.status_code != 201:
raise Exception("Error: %s" % self.__lastError)
tnt_group_id = json.loads(tnt_group.content)["tenantgroups"][0]["id"]
dv_group = self.createDeviceGroup(name, platform_type)
if dv_group.status_code != 201:
raise Exception("Error: %s" % self.__lastError)
dv_group_id = json.loads(dv_group.content)["devicegroups"][0]["id"]
if isolation_policy.lower() == "shared":
srv_pkg = self.createServicePackageShared(name, tnt_group_id, dv_group_id, isolation_policy )
elif isolation_policy.lower() == "dedicated":
srv_pkg = self.createServicePackageDedicated(name, tnt_group_id, dv_group_id, isolation_policy )
else:
raise Exception("NS device must be either in shared or dedicated mode")
if srv_pkg.status_code != 201:
raise Exception("Error: %s" % self.__lastError)
dev_add_res =self.addDevicetoServicePackage(dv_group_id, device_ip)
if dev_add_res == FAILED:
raise Exception ("Error: %s" % self.__lastError)
srv_pkg_id = json.loads(srv_pkg.content)["servicepackages"][0]["id"]
publish_srv_pkg_res = self.publishServicePackage(srv_pkg_id)
if publish_srv_pkg_res == FAILED:
raise Exception("Error: %s" % self.__lastError)
return (dv_group_id, tnt_group_id, srv_pkg_id)
def createTenantGroup(self, name):
url = "http://"+self.nccip+"/admin/v1/tenantgroups"
payload = {"tenantgroups": [{"name": name}]}
res = self.sendCmdToNCC(url, payload)
return res
def createDeviceGroup(self, name, platform_type, device_type="netscaler"):
url = "http://"+self.nccip+"/admin/v1/devicegroups"
payload = {"devicegroups":[{"name": name,
"device_type": device_type,
"platform_type": platform_type
}]
}
res = self.sendCmdToNCC(url, payload)
return res
def createServicePackageShared(self, name, tenant_group, device_group, allocation, device_type="netscaler"):
url = "http://"+self.nccip+"/admin/v1/servicepackages"
payload = {"servicepackages":[{"allocationgroups": [{"device_type": device_type,
"allocationpolicy":allocation,
"placement_scheme": "ROUNDROBIN",
"deviceaffinity": "onedevice",
"devicegroup":{"ref": device_group}
}],
"name": name,
"isdefault": "false",
"tenantgroup": {"ref": tenant_group}
}]
}
res = self.sendCmdToNCC(url, payload)
return res
def createServicePackageDedicated(self, name, tenant_group, device_group, allocation, device_type="netscaler"):
url = "http://"+self.nccip+"/admin/v1/servicepackages"
payload = {"servicepackages":[{"allocationgroups": [{"device_type": device_type,
"allocationpolicy":allocation,
#"placement_scheme": "roundrobin or leastentity",
"devicegroup":{"ref": device_group}
}],
"name": name,
"isdefault": "false",
"tenantgroup": {"ref": tenant_group}
}]
}
res = self.sendCmdToNCC(url, payload)
return res
def addDevicetoServicePackage(self, devicegroup_id, device_ip):
url = "http://"+self.nccip+"/admin/v1/devicegroups/"+devicegroup_id+"/devices"
payload = {"devices":[{"ref":device_ip }]}
res = self.sendCmdToNCC(url, payload, method="PUT")
return res
def removeDevicefromServicePackage(self, devicegroup_id):
url = "http://"+self.nccip+"/admin/v1/devicegroups/"+devicegroup_id+"/devices"
payload = {"devices":[]}
res = self.sendCmdToNCC(url, payload, method="PUT")
return res
def publishServicePackage(self, pkg_id):
url = "http://"+self.nccip+"/cs/cca/v1/servicepackages"
payload = {"servicepackages":[{"servicepackageid":pkg_id}]}
res = self.sendCmdToNCC(url, payload)
return res
def getCSZoneFromNCC(self):
url = "http://"+self.nccip+"/cs/cca/v1/zones"
res = self.sendCmdToNCC(url, method="GET")
if res != FAILED:
zoneid = json.loads(res.content)["zones"][0]
return zoneid
else:
return FAILED
def sendCmdToNCC(self, url, payload={}, method="POST", header={'content-type': 'application/json'}):
try:
# self.logger.debug("url :%s" % url)
# self.logger.debug("payload: %s" % payload)
if method == "POST":
#self.logger.debug("====Sending POST Request====")
return self.sendPostRequstToNCC(url, payload, header)
if method == "GET":
#self.logger.debug("====Sending GET Request====")
return self.sendGetRequestToNCC(url, payload, header)
if method == "PUT":
return self.sendPutRequestToNCC(url, payload, header)
if method == "DELETE":
self.logger.debug("Trying delete")
return self.sendDeleteRequestToNCC(url, header)
except Exception as e:
self.__lastError = e
# self.logger.exception("sendCmdToNCC: Exception:%s" %
# GetDetailExceptionInfo(e))
return FAILED
def sendGetRequestToNCC(self, url, payload, header):
try:
res = requests.get(url, json=payload, auth=("nsroot", "nsroot"), headers=header)
return res
except Exception as e:
self.__lastError = e
# self.logger.exception("sendGetRequestToNCC : Exception Occured: %s" %
# str(self.__lastError))
return FAILED
def sendPostRequstToNCC(self, url, payload, header):
try:
res = requests.post(url, json=payload, auth=("nsroot", "nsroot"), headers=header)
return res
except Exception as e:
self.__lastError = e
# self.logger.exception("sendPostRequstToNCC: Exception Occured: %s" %
# str(self.__lastError))
return FAILED
def sendPutRequestToNCC(self, url, payload, header):
try:
res = requests.put(url, json=payload, auth=("nsroot", "nsroot"), headers=header)
return res
except Exception as e:
self.__lastError = e
# self.logger.exception("sendPostRequstToNCC: Exception Occured: %s" %
# str(self.__lastError))
return FAILED
def sendDeleteRequestToNCC(self, url, header):
try:
res = requests.delete (url, auth=("nsroot", "nsroot"), headers=header)
return res
except Exception as e:
self.__lastError = e
# self.logger.exception("sendPostRequstToNCC: Exception Occured: %s" %
# str(self.__lastError))
return FAILED
def sendCmdToNS(self, url, payload={}, method="POST", header={'content-type': 'application/json'}):
try:
# self.logger.debug("url :%s" % url)
# self.logger.debug("payload: %s" % payload)
if method == "POST":
#self.logger.debug("====Sending POST Request====")
return self.sendPostRequstToNS(url, payload, header)
if method == "GET":
#self.logger.debug("====Sending GET Request====")
return self.sendGetRequestToNS(url, payload, header)
except Exception as e:
self.__lastError = e
# self.logger.exception("sendCmdToNCC: Exception:%s" %
# GetDetailExceptionInfo(e))
return FAILED
def sendPostRequstToNS(self, url, payload, header):
try:
res = requests.post(url, data=payload, auth=("nsroot", "nsroot"), headers=header)
return res
except Exception as e:
self.__lastError = e
# self.logger.exception("sendPostRequstToNCC: Exception Occured: %s" %
# str(self.__lastError))
return FAILED
def sendGetRequestToNS(self, url, payload, header):
try:
res = requests.get(url, data=payload, auth=("nsroot", "nsroot"), headers=header)
return res
except Exception as e:
self.__lastError = e
# self.logger.exception("sendGetRequestToNCC : Exception Occured: %s" %
# str(self.__lastError))
return FAILED
def getAdminKeys(self, apiClient):
domains = Domain.list(apiClient, name="ROOT")
listuser = listUsers.listUsersCmd()
listuser.username = "admin"
listuser.domainid = domains[0].id
listuser.listall = True
listuserRes = apiClient.listUsers(listuser)
userId = listuserRes[0].id
apiKey = listuserRes[0].apikey
securityKey = listuserRes[0].secretkey
return [apiKey, securityKey]
def cleanup_ncc(self, device_gp_id, srv_pkg_uuid, srv_pkg_id, tnt_group_id):
self.removeDevicefromServicePackage(device_gp_id)
# Remove service package reference from Cloudplatform
url = "http://"+self.nccip+"/cs/cca/v1/servicepackages/"+srv_pkg_uuid
self.logger.debug("Sending DELETE SP uuid: %s " % url)
res = self.sendCmdToNCC(url, method="DELETE")
# Remove Service package from NCC
url = "http://"+self.nccip+"/admin/v1/servicepackages/"+srv_pkg_id
self.logger.debug("Sending DELETE SP : %s " % url)
res = self.sendCmdToNCC(url, method="DELETE")
# Remove Device group
url = "http://"+self.nccip+"/admin/v1/devicegroups/"+device_gp_id
self.logger.debug("Sending DELETE devicegroup: %s " % url)
res = self.sendCmdToNCC(url, method="DELETE")
# Remove Tenant group
url = "http://"+self.nccip+"/admin/v1/tenantgroups/"+tnt_group_id
self.logger.debug("Sending DELETE tenant group: %s " % url)
res = self.sendCmdToNCC(url, method="DELETE")
self.logger.debug("Result: %s" % res)
return res
|
DaanHoogland/cloudstack
|
tools/marvin/marvin/lib/ncc.py
|
Python
|
apache-2.0
| 14,471
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Processors
"""
from collections import defaultdict
import copy
from rebulk import Rebulk, Rule, CustomRule, POST_PROCESS, PRE_PROCESS, AppendMatch, RemoveMatch
from .common import seps_no_groups
from .common.formatters import cleanup
from .common.comparators import marker_sorted
from .common.date import valid_year
from .common.words import iter_words
class EnlargeGroupMatches(CustomRule):
"""
Enlarge matches that are starting and/or ending group to include brackets in their span.
"""
priority = PRE_PROCESS
def when(self, matches, context):
starting = []
ending = []
for group in matches.markers.named('group'):
for match in matches.starting(group.start + 1):
starting.append(match)
for match in matches.ending(group.end - 1):
ending.append(match)
if starting or ending:
return starting, ending
return False
def then(self, matches, when_response, context):
starting, ending = when_response
for match in starting:
matches.remove(match)
match.start -= 1
match.raw_start += 1
matches.append(match)
for match in ending:
matches.remove(match)
match.end += 1
match.raw_end -= 1
matches.append(match)
class EquivalentHoles(Rule):
"""
Creates equivalent matches for holes that have same values than existing (case insensitive)
"""
priority = POST_PROCESS
consequence = AppendMatch
def when(self, matches, context):
new_matches = []
for filepath in marker_sorted(matches.markers.named('path'), matches):
holes = matches.holes(start=filepath.start, end=filepath.end, formatter=cleanup)
for name in matches.names:
for hole in list(holes):
for current_match in matches.named(name):
if isinstance(current_match.value, str) and \
hole.value.lower() == current_match.value.lower():
if 'equivalent-ignore' in current_match.tags:
continue
new_value = _preferred_string(hole.value, current_match.value)
if hole.value != new_value:
hole.value = new_value
if current_match.value != new_value:
current_match.value = new_value
hole.name = name
hole.tags = ['equivalent']
new_matches.append(hole)
if hole in holes:
holes.remove(hole)
return new_matches
class RemoveAmbiguous(Rule):
"""
If multiple matches are found with same name and different values, keep the one in the most valuable filepart.
Also keep others match with same name and values than those kept ones.
"""
priority = POST_PROCESS
consequence = RemoveMatch
def __init__(self, sort_function=marker_sorted, predicate=None):
super().__init__()
self.sort_function = sort_function
self.predicate = predicate
def when(self, matches, context):
fileparts = self.sort_function(matches.markers.named('path'), matches)
previous_fileparts_names = set()
values = defaultdict(list)
to_remove = []
for filepart in fileparts:
filepart_matches = matches.range(filepart.start, filepart.end, predicate=self.predicate)
filepart_names = set()
for match in filepart_matches:
filepart_names.add(match.name)
if match.name in previous_fileparts_names:
if match.value not in values[match.name]:
to_remove.append(match)
else:
if match.value not in values[match.name]:
values[match.name].append(match.value)
previous_fileparts_names.update(filepart_names)
return to_remove
class RemoveLessSpecificSeasonEpisode(RemoveAmbiguous):
"""
If multiple season/episodes matches are found with different values,
keep the one tagged as 'SxxExx' or in the rightmost filepart.
"""
def __init__(self, name):
super().__init__(
sort_function=(lambda markers, matches:
marker_sorted(list(reversed(markers)), matches,
lambda match: match.name == name and 'SxxExx' in match.tags)),
predicate=lambda match: match.name == name)
def _preferred_string(value1, value2): # pylint:disable=too-many-return-statements
"""
Retrieves preferred title from both values.
:param value1:
:type value1: str
:param value2:
:type value2: str
:return: The preferred title
:rtype: str
"""
if value1 == value2:
return value1
if value1.istitle() and not value2.istitle():
return value1
if not value1.isupper() and value2.isupper():
return value1
if not value1.isupper() and value1[0].isupper() and not value2[0].isupper():
return value1
if _count_title_words(value1) > _count_title_words(value2):
return value1
return value2
def _count_title_words(value):
"""
Count only many words are titles in value.
:param value:
:type value:
:return:
:rtype:
"""
ret = 0
for word in iter_words(value):
if word.value.istitle():
ret += 1
return ret
class SeasonYear(Rule):
"""
If a season is a valid year and no year was found, create an match with year.
"""
priority = POST_PROCESS
consequence = AppendMatch
def when(self, matches, context):
ret = []
if not matches.named('year'):
for season in matches.named('season'):
if valid_year(season.value):
year = copy.copy(season)
year.name = 'year'
ret.append(year)
return ret
class YearSeason(Rule):
"""
If a year is found, no season found, and episode is found, create an match with season.
"""
priority = POST_PROCESS
consequence = AppendMatch
def when(self, matches, context):
ret = []
if not matches.named('season') and matches.named('episode'):
for year in matches.named('year'):
season = copy.copy(year)
season.name = 'season'
ret.append(season)
return ret
class Processors(CustomRule):
"""
Empty rule for ordering post_processing properly.
"""
priority = POST_PROCESS
def when(self, matches, context):
pass
def then(self, matches, when_response, context): # pragma: no cover
pass
class StripSeparators(CustomRule):
"""
Strip separators from matches. Keep separators if they are from acronyms, like in ".S.H.I.E.L.D."
"""
priority = POST_PROCESS
def when(self, matches, context):
return matches
def then(self, matches, when_response, context): # pragma: no cover
for match in matches:
for _ in range(0, len(match.span)):
if match.raw[0] in seps_no_groups and (len(match.raw) < 3 or match.raw[2] not in seps_no_groups):
match.raw_start += 1
for _ in reversed(range(0, len(match.span))):
if match.raw[-1] in seps_no_groups and (len(match.raw) < 3 or match.raw[-3] not in seps_no_groups):
match.raw_end -= 1
def processors(config): # pylint:disable=unused-argument
"""
Builder for rebulk object.
:param config: rule configuration
:type config: dict
:return: Created Rebulk object
:rtype: Rebulk
"""
return Rebulk().rules(EnlargeGroupMatches, EquivalentHoles,
RemoveLessSpecificSeasonEpisode('season'),
RemoveLessSpecificSeasonEpisode('episode'),
RemoveAmbiguous, SeasonYear, YearSeason, Processors, StripSeparators)
|
wackou/guessit
|
guessit/rules/processors.py
|
Python
|
lgpl-3.0
| 8,305
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""A collection of ORM sqlalchemy models for Superset"""
import enum
from cron_descriptor import get_description
from flask_appbuilder import Model
from flask_appbuilder.models.decorators import renders
from sqlalchemy import (
Boolean,
Column,
DateTime,
Float,
ForeignKey,
Integer,
String,
Table,
Text,
)
from sqlalchemy.orm import backref, relationship
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy_utils import UUIDType
from superset.extensions import security_manager
from superset.models.core import Database
from superset.models.dashboard import Dashboard
from superset.models.helpers import AuditMixinNullable
from superset.models.slice import Slice
metadata = Model.metadata # pylint: disable=no-member
class ReportScheduleType(str, enum.Enum):
ALERT = "Alert"
REPORT = "Report"
class ReportScheduleValidatorType(str, enum.Enum):
"""Validator types for alerts"""
NOT_NULL = "not null"
OPERATOR = "operator"
class ReportRecipientType(str, enum.Enum):
EMAIL = "Email"
SLACK = "Slack"
class ReportState(str, enum.Enum):
SUCCESS = "Success"
WORKING = "Working"
ERROR = "Error"
NOOP = "Not triggered"
GRACE = "On Grace"
class ReportDataFormat(str, enum.Enum):
VISUALIZATION = "PNG"
DATA = "CSV"
TEXT = "TEXT"
class ReportCreationMethodType(str, enum.Enum):
CHARTS = "charts"
DASHBOARDS = "dashboards"
ALERTS_REPORTS = "alerts_reports"
report_schedule_user = Table(
"report_schedule_user",
metadata,
Column("id", Integer, primary_key=True),
Column("user_id", Integer, ForeignKey("ab_user.id"), nullable=False),
Column(
"report_schedule_id", Integer, ForeignKey("report_schedule.id"), nullable=False
),
UniqueConstraint("user_id", "report_schedule_id"),
)
class ReportSchedule(Model, AuditMixinNullable):
"""
Report Schedules, supports alerts and reports
"""
__tablename__ = "report_schedule"
__table_args__ = (UniqueConstraint("name", "type"),)
id = Column(Integer, primary_key=True)
type = Column(String(50), nullable=False)
name = Column(String(150), nullable=False)
description = Column(Text)
context_markdown = Column(Text)
active = Column(Boolean, default=True, index=True)
crontab = Column(String(1000), nullable=False)
creation_method = Column(
String(255), server_default=ReportCreationMethodType.ALERTS_REPORTS
)
timezone = Column(String(100), default="UTC", nullable=False)
report_format = Column(String(50), default=ReportDataFormat.VISUALIZATION)
sql = Column(Text())
# (Alerts/Reports) M-O to chart
chart_id = Column(Integer, ForeignKey("slices.id"), nullable=True)
chart = relationship(Slice, backref="report_schedules", foreign_keys=[chart_id])
# (Alerts/Reports) M-O to dashboard
dashboard_id = Column(Integer, ForeignKey("dashboards.id"), nullable=True)
dashboard = relationship(
Dashboard, backref="report_schedules", foreign_keys=[dashboard_id]
)
# (Alerts) M-O to database
database_id = Column(Integer, ForeignKey("dbs.id"), nullable=True)
database = relationship(Database, foreign_keys=[database_id])
owners = relationship(security_manager.user_model, secondary=report_schedule_user)
# (Alerts) Stamped last observations
last_eval_dttm = Column(DateTime)
last_state = Column(String(50), default=ReportState.NOOP)
last_value = Column(Float)
last_value_row_json = Column(Text)
# (Alerts) Observed value validation related columns
validator_type = Column(String(100))
validator_config_json = Column(Text, default="{}")
# Log retention
log_retention = Column(Integer, default=90)
# (Alerts) After a success how long to wait for a new trigger (seconds)
grace_period = Column(Integer, default=60 * 60 * 4)
# (Alerts/Reports) Unlock a possible stalled working state
working_timeout = Column(Integer, default=60 * 60 * 1)
# Store the selected dashboard tabs etc.
extra = Column(Text, default="{}")
# (Reports) When generating a screenshot, bypass the cache?
force_screenshot = Column(Boolean, default=False)
def __repr__(self) -> str:
return str(self.name)
@renders("crontab")
def crontab_humanized(self) -> str:
return get_description(self.crontab)
class ReportRecipients(Model, AuditMixinNullable):
"""
Report Recipients, meant to support multiple notification types, eg: Slack, email
"""
__tablename__ = "report_recipient"
id = Column(Integer, primary_key=True)
type = Column(String(50), nullable=False)
recipient_config_json = Column(Text, default="{}")
report_schedule_id = Column(
Integer, ForeignKey("report_schedule.id"), nullable=False
)
report_schedule = relationship(
ReportSchedule,
backref=backref("recipients", cascade="all,delete,delete-orphan"),
foreign_keys=[report_schedule_id],
)
class ReportExecutionLog(Model): # pylint: disable=too-few-public-methods
"""
Report Execution Log, hold the result of the report execution with timestamps,
last observation and possible error messages
"""
__tablename__ = "report_execution_log"
id = Column(Integer, primary_key=True)
uuid = Column(UUIDType(binary=True))
# Timestamps
scheduled_dttm = Column(DateTime, nullable=False)
start_dttm = Column(DateTime)
end_dttm = Column(DateTime)
# (Alerts) Observed values
value = Column(Float)
value_row_json = Column(Text)
state = Column(String(50), nullable=False)
error_message = Column(Text)
report_schedule_id = Column(
Integer, ForeignKey("report_schedule.id"), nullable=False
)
report_schedule = relationship(
ReportSchedule,
backref=backref("logs", cascade="all,delete,delete-orphan"),
foreign_keys=[report_schedule_id],
)
|
apache/incubator-superset
|
superset/models/reports.py
|
Python
|
apache-2.0
| 6,747
|
# -*- coding: utf-8 -*-
"""CA Observer
Copyright (C) 2015 Michael Davidsaver
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
See LICENSE for details.
"""
from django.http import HttpResponse, JsonResponse
from django.shortcuts import Http404
from django.views.generic import base
from django.utils.timezone import get_current_timezone
import numpy
try:
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.dates import DateFormatter, date2num, num2epoch
udate2num = numpy.vectorize(date2num)
except ImportError:
Figure = None
udate2num = None
class PlotMixin(base.ContextMixin, base.View):
context_key = None # required
cols = []
transform = lambda V:V
set_axis = {}
def data_from_context(self, context):
if not self.context_key:
return self.transform(numpy.zeros((0,0)))
D = context
for K in self.context_key:
D = D[K]
data = numpy.zeros((len(D), len(self.cols)), dtype=numpy.float64)
for j,C in enumerate(self.cols):
if isinstance(C, tuple):
C, F = C
else:
F = lambda X:X
for i,row in enumerate(D):
data[i,j] = F(row[C])
return self.transform(data)
def get(self, req, *args, **kwargs):
json = 'application/json' in req.META.get('HTTP_ACCEPT')
if not json and not Figure:
raise Http404("Can't generate image")
context = self.get_context_data(**kwargs)
data = self.data_from_context(context)
if json:
# convert to list of lists
data[:,0] = num2epoch(data[:,0])
data[:,0] *= 1000 # to ms
ret = [None]*data.shape[0]
for i in range(data.shape[0]):
ret[i] = list(data[i,:])
return JsonResponse({'data':ret})
tz = get_current_timezone()
fig = Figure(dpi=96, figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot_date(data[:,0], data[:,1])
ax.set(**self.set_axis)
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S', tz=tz))
fig.autofmt_xdate()
canva = FigureCanvas(fig)
resp = HttpResponse(content_type='image/png')
canva.print_png(resp)
return resp
|
mdavidsaver/caobserver
|
web/careport/plot.py
|
Python
|
agpl-3.0
| 2,567
|
# coding: utf-8
from __future__ import print_function
import os
import numpy as np
import time
np.random.seed(1337)
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils.np_utils import to_categorical
from keras.layers import Dense, Flatten, Activation
from keras.layers import Convolution1D, MaxPooling1D, Embedding, LSTM
from keras.models import Model
from keras.layers import Input, Dropout
from keras.optimizers import SGD, Adadelta
from keras.models import Sequential
from sklearn.model_selection import train_test_split, KFold
import sys
import csv
MAX_SEQUENCE_LENGTH = 1000
MAX_NB_WORDS = 20000
EMBEDDING_DIM = 100
VALIDATION_SPLIT = 0.1
DROP_OUT = 0.3
Nb_EPOCH = 25
BATCH_SIZE = 10
Classes = 2
K_FOLD = 10
write_Trigger = 0
BASE_DIR = '.'
GLOVE_DIR = BASE_DIR + '/glove.twitter.27B/'
FILENAME = 'glove.twitter.27B.' + str(EMBEDDING_DIM) + 'd.txt'
TEXT_DATA_DIR = BASE_DIR + '/20_newsgroups/'
def write_csv_result(fname, train_accuracy, valid_accuracy, test_accuracy, time):
global header, items
header = [['Cross Validation','Classes', 'Dropout', 'Iterations', 'Batch Size','Embedding Dimension',
'Training Accuracy', 'Validation Accuracy', 'Test Accuracy', 'Time']]
items = [K_FOLD, Classes, DROP_OUT, Nb_EPOCH, BATCH_SIZE, EMBEDDING_DIM,
train_accuracy, valid_accuracy, test_accuracy, time]
header.append(items)
if write_Trigger == 1:
f = open(fname, 'wb')
writer = csv.writer(f)
writer.writerows(header)
f.close()
def embeddings_index(GLOVE_DIR, FILENAME):
global embeddings_index
embeddings_index = {}
fname = os.path.join(GLOVE_DIR, FILENAME)
f = open(fname)
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embeddings_index))
return embeddings_index
print('Processing text dataset')
def load_data(TEXT_DATA_DIR):
texts = [] # list of text samples
labels_index = {} # dictionary mapping label name to numeric id
labels = [] # list of label ids
for name in sorted(os.listdir(TEXT_DATA_DIR)):
path = os.path.join(TEXT_DATA_DIR, name)
if os.path.isdir(path):
label_id = len(labels_index)
labels_index[name] = label_id
for fname in sorted(os.listdir(path)):
if fname.isdigit():
fpath = os.path.join(path, fname)
if sys.version_info < (3,):
f = open(fpath)
else:
f = open(fpath, encoding='latin-1')
texts.append(f.read())
f.close()
labels.append(label_id)
print('Found %s texts.' % len(texts))
global word_index, tokenizer
tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(word_index))
data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
labels = to_categorical(np.asarray(labels))
print('Shape of data tensor:', data.shape)
print('Shape of label tensor:', labels.shape)
return (data, labels, labels_index)
# split the data into a training set and a validation set
def train_Val_Split(data, labels):
trainX, valX, trainY, valY = train_test_split(data, labels, test_size=VALIDATION_SPLIT)
return (trainX, trainY, valX, valY)
# prepare embedding matrix
print('Preparing embedding matrix.')
def embeddingMatrix():
global nb_words, embedding_matrix
nb_words = min(MAX_NB_WORDS, len(word_index))
embedding_matrix = np.zeros((nb_words + 1, EMBEDDING_DIM))
for word, i in word_index.items():
if i > MAX_NB_WORDS:
continue
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
return embedding_matrix
def create_model():
print('Number of class: ||%d||' % (Classes))
model = Sequential()
model.add(Embedding( # Layer 0, Start
input_dim=nb_words + 1, # Size to dictionary, has to be input + 1
output_dim= EMBEDDING_DIM, # Dimensions to generate
weights=[embedding_matrix], # Initialize word weights
input_length=MAX_SEQUENCE_LENGTH,
trainable=False)) # Define length to input sequences in the first layer
model.add(LSTM(128, dropout_W=DROP_OUT, dropout_U=DROP_OUT))
model.add(Dense(Classes))
model.add(Activation('sigmoid'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
def train_and_evaluate_model(model, trainX, trainY, testX, testY):
start = time.time()
history = model.fit(trainX, trainY, nb_epoch=Nb_EPOCH, batch_size=BATCH_SIZE)
trainTime = time.time() - start
print ("Training Time : ", trainTime)
last_epoch_training_accuracy = history.history['acc'][Nb_EPOCH-1]
last_epoch_training_loss = history.history['loss'][Nb_EPOCH-1]
print ("Training Loss: ", last_epoch_training_loss)
print ("Training Accuracy: ", last_epoch_training_accuracy)
eval_loss, eval_accuracy = model.evaluate(testX, testY, verbose=0)
print ("Testing Loss: ", eval_loss)
print ("Testing Accuracy: ", eval_accuracy)
return (last_epoch_training_loss, last_epoch_training_accuracy, eval_loss, eval_accuracy, trainTime)
def main(embeddings_index):
#n_splits = 10
embeddings_index = embeddings_index(GLOVE_DIR, FILENAME)
data, labels, labels_index = load_data(TEXT_DATA_DIR)
embedding_matrix = embeddingMatrix()
skf = KFold(n_splits=K_FOLD, shuffle=True, random_state=1337)
i=1
final_training_acc = 0
final_testing_acc = 0
global_time = time.time()
for (train, test) in skf.split(data):
print ("*****Running fold", i, "/", K_FOLD, " *****")
#print (data[train])
#print (labels[train])
model = None
model = create_model()
last_epoch_training_loss, last_epoch_training_accuracy, eval_loss, eval_accuracy, trainTime = train_and_evaluate_model(model, data[train], labels[train], data[test], labels[test])
final_training_acc = final_training_acc + last_epoch_training_accuracy
final_testing_acc = final_testing_acc + eval_accuracy
i=i+1
total_time = time.time()-global_time
print ("*********Finished compiling ", i-1 , "fold*********")
avg_training_accuracy = final_training_acc/K_FOLD
avg_testing_accuracy = final_testing_acc/K_FOLD
print ("Average Training Accuracy : ", avg_training_accuracy)
print ("Average Testing Accuracy : ", avg_testing_accuracy)
print ("Total Running Time : ", total_time)
write_Trigger = 1
write_csv_result("20news_LSTM_CV_2classes.csv", avg_training_accuracy, 0 , avg_testing_accuracy, total_time)
# import SQLdb as db
# db.updateLSTM(classes = Classes, dropouts = DROP_OUT, iterations = Nb_EPOCH, accuracy = avg_testing_accuracy, remark = total_time)
|
irisliu0616/Short-text-Classification
|
Model/20News/20news_LSTM_CV.py
|
Python
|
mit
| 7,410
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "locationUpdator.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
valarpirai/team-locator
|
manage.py
|
Python
|
mit
| 258
|
from __future__ import division
import numpy as np
from scipy.misc import comb as combinations
from sklearn.utils.random import sample_without_replacement
from sklearn.utils.testing import (
assert_raises,
assert_equal,
assert_true)
###############################################################################
# test custom sampling without replacement algorithm
###############################################################################
def test_invalid_sample_without_replacement_algorithm():
assert_raises(ValueError, sample_without_replacement, 5, 4, "unknown")
def test_sample_without_replacement_algorithms():
methods = ("auto", "tracking_selection", "reservoir_sampling", "pool")
for m in methods:
def sample_without_replacement_method(n_population, n_samples,
random_state=None):
return sample_without_replacement(n_population, n_samples,
method=m,
random_state=random_state)
check_edge_case_of_sample_int(sample_without_replacement_method)
check_sample_int(sample_without_replacement_method)
check_sample_int_distribution(sample_without_replacement_method)
def check_edge_case_of_sample_int(sample_without_replacement):
# n_poluation < n_sample
assert_raises(ValueError, sample_without_replacement, 0, 1)
assert_raises(ValueError, sample_without_replacement, 1, 2)
# n_population == n_samples
assert_equal(sample_without_replacement(0, 0).shape, (0, ))
assert_equal(sample_without_replacement(1, 1).shape, (1, ))
# n_population >= n_samples
assert_equal(sample_without_replacement(5, 0).shape, (0, ))
assert_equal(sample_without_replacement(5, 1).shape, (1, ))
# n_population < 0 or n_samples < 0
assert_raises(ValueError, sample_without_replacement, -1, 5)
assert_raises(ValueError, sample_without_replacement, 5, -1)
def check_sample_int(sample_without_replacement):
# This test is heavily inspired from test_random.py of python-core.
#
# For the entire allowable range of 0 <= k <= N, validate that
# the sample is of the correct length and contains only unique items
n_population = 100
for n_samples in xrange(n_population + 1):
s = sample_without_replacement(n_population, n_samples)
assert_equal(len(s), n_samples)
unique = np.unique(s)
assert_equal(np.size(unique), n_samples)
assert_true(np.all(unique < n_population))
# test edge case n_population == n_samples == 0
assert_equal(np.size(sample_without_replacement(0, 0)), 0)
def check_sample_int_distribution(sample_without_replacement):
# This test is heavily inspired from test_random.py of python-core.
#
# For the entire allowable range of 0 <= k <= N, validate that
# sample generates all possible permutations
n_population = 10
# a large number of trials prevents false negatives without slowing normal
# case
n_trials = 10000
for n_samples in xrange(n_population):
# Counting the number of combinations is not as good as counting the
# the number of permutations. However, it works with sampling algorithm
# that does not provide a random permutation of the subset of integer.
n_expected = combinations(n_population, n_samples, exact=True)
output = {}
for i in xrange(n_trials):
output[frozenset(sample_without_replacement(n_population,
n_samples))] = None
if len(output) == n_expected:
break
else:
raise AssertionError(
"number of combinations != number of expected (%s != %s)" %
(len(output), n_expected))
|
mrshu/scikit-learn
|
sklearn/utils/tests/test_random.py
|
Python
|
bsd-3-clause
| 3,875
|
import json
import unittest
from unittest.mock import MagicMock, patch
from tornado.ioloop import IOLoop
from tornado.testing import AsyncHTTPTestCase
from tornado.web import Application
from handlers import HealthCheck
class TestHealthcheckHandler(AsyncHTTPTestCase):
def setUp(self):
super().setUp()
self.app = MagicMock()
self.request = MagicMock()
def tearDown(self):
super().tearDown()
patch.stopall()
def get_new_ioloop(self):
return IOLoop().instance()
def get_app(self):
return Application([
(r"/healthcheck", HealthCheck),
])
def test_response(self):
res = self.fetch(r'/healthcheck', method='POST', body="{}")
body = json.loads(res.body.decode('utf-8'))
self.assertEqual(res.code, 200)
self.assertEqual(body['status'], 'OK')
self.assertTrue(isinstance(body['number'], int))
|
evemorgen/GdzieJestTenCholernyTramwajProject
|
backend/schedule_worker/tests/unit/handlers/test_healthcheck_handler.py
|
Python
|
mit
| 929
|
# -*- coding: utf-8 -*-
# Copyright 2018 OpenSynergy Indonesia
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import api, fields, models
class AccomplishParticipant(models.TransientModel):
_name = "hr.accomplish_participant"
_description = "Accomplish Participant"
@api.model
def _default_training_id(self):
return self.env.context.get("active_id", False)
@api.model
def _default_detail_ids(self):
training_id = self.env.context.get("active_id", False)
obj_participant = self.env["hr.training_partisipant"]
criteria = [("training_id", "=", training_id), ("state", "=", "draft")]
participants = obj_participant.search(criteria)
result = []
for participant in participants:
data = {
"participant_id": participant.id,
"employee_id": participant.partisipant_id.id,
}
result.append((0, 0, data))
return result
training_id = fields.Many2one(
string="Training",
comodel_name="hr.training",
required=True,
default=lambda self: self._default_training_id(),
)
detail_ids = fields.One2many(
string="Participants",
comodel_name="hr.accomplish_participant_detail",
inverse_name="wizard_id",
default=lambda self: self._default_detail_ids(),
)
@api.multi
def action_confirm(self):
for wiz in self:
wiz._confirm_accomplishment()
@api.multi
def _confirm_accomplishment(self):
self.ensure_one()
for detail in self.detail_ids:
detail._confirm_accomplishment()
class AccomplishParticipantDetail(models.TransientModel):
_name = "hr.accomplish_participant_detail"
_description = "Detail Accomplish Participant"
wizard_id = fields.Many2one(
string="Wizard",
comodel_name="hr.accomplish_participant",
)
participant_id = fields.Many2one(
string="Participant",
comodel_name="hr.training_partisipant",
)
employee_id = fields.Many2one(
string="Employee",
comodel_name="hr.employee",
related="participant_id.partisipant_id",
store=False,
)
@api.multi
def _confirm_accomplishment(self):
self.ensure_one()
self.participant_id.button_accomplish()
|
open-synergy/opnsynid-hr
|
hr_employee_training/wizards/participant_accomplish.py
|
Python
|
agpl-3.0
| 2,383
|
# -*- coding: utf-8 -*-
import re
from module.network.HTTPRequest import BadHeader
from module.network.RequestFactory import getURL as get_url
from .Crypter import Crypter
from .misc import parse_name, parse_time, replace_patterns
class SimpleCrypter(Crypter):
__name__ = "SimpleCrypter"
__type__ = "crypter"
__version__ = "0.92"
__status__ = "testing"
__pattern__ = r'^unmatchable$'
__config__ = [("activated", "bool", "Activated", True),
("use_premium", "bool", "Use premium account if available", True),
("folder_per_package", "Default;Yes;No",
"Create folder for each package", "Default"),
("max_wait", "int", "Reconnect if waiting time is greater than minutes", 10)]
__description__ = """Simple decrypter plugin"""
__license__ = "GPLv3"
__authors__ = [("Walter Purcaro", "vuolter@gmail.com")]
"""
Following patterns should be defined by each crypter:
LINK_PATTERN: Download link or regex to catch links in group(1)
example: LINK_PATTERN = r'<div class="link"><a href="(.+?)"'
NAME_PATTERN: (optional) folder name or page title
example: NAME_PATTERN = r'<title>Files of: (?P<N>.+?) folder</title>'
OFFLINE_PATTERN: (optional) Checks if the page is unreachable
example: OFFLINE_PATTERN = r'File (deleted|not found)'
TEMP_OFFLINE_PATTERN: (optional) Checks if the page is temporarily unreachable
example: TEMP_OFFLINE_PATTERN = r'Server maintainance'
You can override the get_links method if you need a more sophisticated way to extract the links.
If the links are splitted on multiple pages you can define the PAGES_PATTERN regex:
PAGES_PATTERN: (optional) group(1) should be the number of overall pages containing the links
example: PAGES_PATTERN = r'Pages: (\d+)'
and its load_page method:
def load_page(self, page_n):
return the html of the page number page_n
"""
NAME_REPLACEMENTS = []
URL_REPLACEMENTS = []
COOKIES = True #: or False or list of tuples [(domain, name, value)]
#: Set to True to looking for direct link (as defined in handle_direct method), set to None to do it if self.account is True else False
DIRECT_LINK = True
LOGIN_ACCOUNT = False #: Set to True to require account login
LOGIN_PREMIUM = False #: Set to True to require premium account login
#: Set to encoding name if encoding value in http header is not correct
TEXT_ENCODING = True
LINK_PATTERN = None
LINK_FREE_PATTERN = None
LINK_PREMIUM_PATTERN = None
PAGES_PATTERN = None
NAME_PATTERN = None
OFFLINE_PATTERN = r'[^\w](404\s|[Ii]nvalid|[Oo]ffline|[Dd]elet|[Rr]emov|([Nn]o(t|thing)?|sn\'t) (found|(longer )?(available|exist)))'
TEMP_OFFLINE_PATTERN = r'[^\w](503\s|[Mm]aint(e|ai)nance|[Tt]emp([.-]|orarily)|[Mm]irror)'
WAIT_PATTERN = None
PREMIUM_ONLY_PATTERN = None
IP_BLOCKED_PATTERN = None
SIZE_LIMIT_PATTERN = None
ERROR_PATTERN = None
@classmethod
def api_info(cls, url):
return {}
@classmethod
def get_info(cls, url="", html=""):
info = super(SimpleCrypter, cls).get_info(url)
info.update(cls.api_info(url))
if not html and info['status'] != 2:
if not url:
info['error'] = "missing url"
info['status'] = 1
elif info['status'] in (3, 7):
try:
html = get_url(
url, cookies=cls.COOKIES, decode=cls.TEXT_ENCODING)
except BadHeader, e:
info['error'] = "%d: %s" % (e.code, e.content)
except Exception:
pass
if html:
if cls.OFFLINE_PATTERN and re.search(
cls.OFFLINE_PATTERN, html) is not None:
info['status'] = 1
elif cls.TEMP_OFFLINE_PATTERN and re.search(cls.TEMP_OFFLINE_PATTERN, html) is not None:
info['status'] = 6
elif cls.NAME_PATTERN:
m = re.search(cls.NAME_PATTERN, html)
if m is not None:
info['status'] = 2
info['pattern'].update(m.groupdict())
if 'N' in info['pattern']:
name = replace_patterns(
info['pattern']['N'],
cls.NAME_REPLACEMENTS)
info['name'] = parse_name(name)
return info
#@TODO: Remove in 0.4.10
def setup_base(self):
account_name = self.classname.rsplit("Folder", 1)[0]
if self.account:
self.req = self.pyload.requestFactory.getRequest(
account_name, self.account.user)
# @NOTE: Don't call get_info here to reduce overhead
self.premium = self.account.info['data']['premium']
else:
self.req = self.pyload.requestFactory.getRequest(account_name)
self.premium = False
Crypter.setup_base(self)
#@TODO: Remove in 0.4.10
def load_account(self):
class_name = self.classname
self.__class__.__name__ = class_name.rsplit("Folder", 1)[0]
Crypter.load_account(self)
self.__class__.__name__ = class_name
def handle_direct(self, pyfile):
self._preload()
link = self.last_header.get('url')
if re.match(self.__pattern__, link) is None:
self.links.append(link)
def _preload(self):
if self.data:
return
self.data = self.load(self.pyfile.url,
cookies=self.COOKIES,
ref=False,
decode=self.TEXT_ENCODING)
def _prepare(self):
self.direct_dl = False
if self.LOGIN_PREMIUM and not self.premium:
self.fail(_("Required premium account not found"))
if self.LOGIN_ACCOUNT and not self.account:
self.fail(_("Required account not found"))
self.req.setOption("timeout", 120)
if self.LINK_PATTERN:
if self.LINK_FREE_PATTERN is None:
self.LINK_FREE_PATTERN = self.LINK_PATTERN
if self.LINK_PREMIUM_PATTERN is None:
self.LINK_PREMIUM_PATTERN = self.LINK_PATTERN
if self.DIRECT_LINK is None:
self.direct_dl = bool(self.premium)
else:
self.direct_dl = self.DIRECT_LINK
self.pyfile.url = replace_patterns(
self.pyfile.url, self.URL_REPLACEMENTS)
def decrypt(self, pyfile):
self._prepare()
if self.direct_dl:
self.log_info(_("Looking for direct link..."))
self.handle_direct(pyfile)
if self.links or self.packages:
self.log_info(_("Direct link detected"))
else:
self.log_info(_("Direct link not found"))
if not self.links and not self.packages:
self._preload()
self.check_errors()
links = self.get_links()
self.links.extend(links)
if self.PAGES_PATTERN:
self.handle_pages(pyfile)
def handle_free(self, pyfile):
if not self.LINK_FREE_PATTERN:
self.log_warning(_("Free decrypting not implemented"))
links = re.findall(self.LINK_FREE_PATTERN, self.data)
if not links:
self.error(_("Free decrypted link not found"))
else:
self.links.extend(links)
def handle_premium(self, pyfile):
if not self.LINK_PREMIUM_PATTERN:
self.log_warning(_("Premium decrypting not implemented"))
self.restart(premium=False)
links = re.findall(self.LINK_PREMIUM_PATTERN, self.data)
if not links:
self.error(_("Premium decrypted link found"))
else:
self.links.extend(links)
def get_links(self):
"""
Returns the links extracted from self.data
You should override this only if it's impossible to extract links using only the LINK_PATTERN.
"""
if self.premium:
self.log_info(_("Decrypting as premium link..."))
self.handle_premium(self.pyfile)
elif not self.LOGIN_ACCOUNT:
self.log_info(_("Decrypting as free link..."))
self.handle_free(self.pyfile)
links = self.links
self.links = []
return links
def load_page(self, number):
raise NotImplementedError
def handle_pages(self, pyfile):
try:
pages = int(re.search(self.PAGES_PATTERN, self.data).group(1))
except Exception:
pages = 1
links = self.links
for p in range(2, pages + 1):
self.data = self.load_page(p)
links.extend(self.get_links())
self.links = links
def check_errors(self):
self.log_info(_("Checking for link errors..."))
if not self.data:
self.log_warning(_("No data to check"))
return
if self.IP_BLOCKED_PATTERN and re.search(
self.IP_BLOCKED_PATTERN, self.data):
self.fail(
_("Connection from your current IP address is not allowed"))
elif not self.premium:
if self.PREMIUM_ONLY_PATTERN and re.search(
self.PREMIUM_ONLY_PATTERN, self.data):
self.fail(_("Link can be decrypted by premium users only"))
elif self.SIZE_LIMIT_PATTERN and re.search(self.SIZE_LIMIT_PATTERN, self.data):
self.fail(_("Link list too large for free decrypt"))
if self.ERROR_PATTERN:
m = re.search(self.ERROR_PATTERN, self.data)
if m is not None:
try:
errmsg = m.group(1)
except (AttributeError, IndexError):
errmsg = m.group(0)
finally:
errmsg = re.sub(r'<.*?>', " ", errmsg.strip())
self.info['error'] = errmsg
self.log_warning(errmsg)
if re.search(self.TEMP_OFFLINE_PATTERN, errmsg):
self.temp_offline()
elif re.search(self.OFFLINE_PATTERN, errmsg):
self.offline()
elif re.search(r'limit|wait|slot', errmsg, re.I):
wait_time = parse_time(errmsg)
self.wait(
wait_time, reconnect=wait_time > self.config.get(
'max_wait', 10) * 60)
self.restart(_("Download limit exceeded"))
elif re.search(r'country|ip|region|nation', errmsg, re.I):
self.fail(
_("Connection from your current IP address is not allowed"))
elif re.search(r'captcha|code', errmsg, re.I):
self.retry_captcha()
elif re.search(r'countdown|expired', errmsg, re.I):
self.retry(10, 60, _("Link expired"))
elif re.search(r'503|maint(e|ai)nance|temp|mirror', errmsg, re.I):
self.temp_offline()
elif re.search(r'up to|size', errmsg, re.I):
self.fail(_("Link list too large for free decrypt"))
elif re.search(r'404|sorry|offline|delet|remov|(no(t|thing)?|sn\'t) (found|(longer )?(available|exist))',
errmsg, re.I):
self.offline()
elif re.search(r'filename', errmsg, re.I):
self.fail(_("Invalid url"))
elif re.search(r'premium', errmsg, re.I):
self.fail(_("Link can be decrypted by premium users only"))
else:
self.wait(60, reconnect=True)
self.restart(errmsg)
elif self.WAIT_PATTERN:
m = re.search(self.WAIT_PATTERN, self.data)
if m is not None:
try:
waitmsg = m.group(1).strip()
except (AttributeError, IndexError):
waitmsg = m.group(0).strip()
wait_time = parse_time(waitmsg)
self.wait(
wait_time,
reconnect=wait_time > self.config.get(
'max_wait',
10) * 60)
self.log_info(_("No errors found"))
self.info.pop('error', None)
|
Velociraptor85/pyload
|
module/plugins/internal/SimpleCrypter.py
|
Python
|
gpl-3.0
| 12,499
|
"""Support for N26 switches."""
import logging
from homeassistant.components.switch import SwitchDevice
from . import DEFAULT_SCAN_INTERVAL, DOMAIN
from .const import CARD_STATE_ACTIVE, CARD_STATE_BLOCKED, DATA
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = DEFAULT_SCAN_INTERVAL
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the N26 switch platform."""
if discovery_info is None:
return
api_list = hass.data[DOMAIN][DATA]
switch_entities = []
for api_data in api_list:
for card in api_data.cards:
switch_entities.append(N26CardSwitch(api_data, card))
add_entities(switch_entities)
class N26CardSwitch(SwitchDevice):
"""Representation of a N26 card block/unblock switch."""
def __init__(self, api_data, card: dict):
"""Initialize the N26 card block/unblock switch."""
self._data = api_data
self._card = card
@property
def unique_id(self):
"""Return the unique ID of the entity."""
return self._card["id"]
@property
def name(self) -> str:
"""Friendly name of the sensor."""
return "card_{}".format(self._card["id"])
@property
def is_on(self):
"""Return true if switch is on."""
return self._card["status"] == CARD_STATE_ACTIVE
def turn_on(self, **kwargs):
"""Block the card."""
self._data.api.unblock_card(self._card["id"])
self._card["status"] = CARD_STATE_ACTIVE
def turn_off(self, **kwargs):
"""Unblock the card."""
self._data.api.block_card(self._card["id"])
self._card["status"] = CARD_STATE_BLOCKED
def update(self):
"""Update the switch state."""
self._data.update_cards()
self._card = self._data.card(self._card["id"], self._card)
|
fbradyirl/home-assistant
|
homeassistant/components/n26/switch.py
|
Python
|
apache-2.0
| 1,836
|
from iomedia.plonemail.plonemail import EmailBase
from Products.Five.browser import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
import logging; logger=logging.getLogger('iomedia.plonemail.examples')
class SampleEmail(BrowserView,EmailBase):
""" Simple browserview to send an email """
test_email = ViewPageTemplateFile('emails/email.pt')
def __call__(self):
self.recipient = self.getRecipient()
self.sender= self.getSender()
if self.request.get('send-test-email'):
logger.info('Sending test email to %s' % self.recipient['email'])
self.subject='Test Email'
self.message=self.test_email()
self.send_email()
return super(SampleEmail, self).__call__()
def getSender(self):
return {
'firstname':'Firstname',
'lastname':'Lastname',
'email':'test@example.com'
}
def getRecipient(self):
return {
'firstname':'Firstname',
'lastname':'Lastname',
'email':'test@example.com'
}
|
iomedia/iomedia.plonemail
|
iomedia/plonemail/examples/form.py
|
Python
|
gpl-2.0
| 1,115
|
spell_check_dict={
'steele stake': 'steel stake',
'gas mowe': 'gas mower',
'metal plate cover gcfi': 'metal plate cover gfci',
'lawn sprkinler': 'lawn sprinkler',
'ourdoor patio tile': 'outdoor patio tile',
'6 teir shelving': '6 tier shelving',
'storage shelve': 'storage shelf',
'American Standard Bone round toliet': 'American Standard Bone round toilet',
'6 stell': '6 steel',
'fece posts metal': 'fence posts metal',
'cushions outdoorlounge': 'cushions outdoor lounge',
'pricepfister kitchen faucet g135': 'price pfister kitchen faucet g135',
'glaciar bay toiled': 'glacier bay toilet',
'glacie bay dual flush': 'glacier bay dual flush',
'glacier bay tiolet tank lid': 'glacier bay toilet tank lid',
'handycap toilets': 'handicap toilets',
'high boy tolet': 'highboy toilet',
'gas wayer heaters': 'gas water heaters',
'basemetnt window': 'basement window',
'rustollum epoxy': 'rustoleum epoxy',
'air /heaterconditioner window': 'air /heat conditioner window',
'spliter ac unit': 'splitter ac unit',
'berh deck over': 'behr deck over',
'28 snow thower': '28 snow thrower',
'base board molding boundle': 'baseboard molding bundle',
'1 infloor flange': '1 in floor flange',
'10 window sping rod': '10 window spring rod',
'combo powertool kit': 'combo power tool kit',
'desalt impact 18': 'dewalt impact 18',
'rigid lithium ion batteries fuego drill': 'ridgid lithium ion batteries fuego drill',
'fiberglass repir kit': 'fiberglass repair kit',
'portable air condtioners': 'portable air conditioners',
'wall pannels': 'wall panels',
'2X4 SRUDS': '2X4 STUDS',
'frostking window shrink film': 'frost king window shrink film',
'Florescent Light Bulbs': 'Fluorescent Light Bulbs',
'violet flourescent light': 'violet fluorescent light',
'lawn mower- electic': 'lawn mower- electric',
'closetmade': 'closetmaid',
'greecianmarble floor tile': 'grecian marble floor tile',
'join compound wall tile': 'joint compound wall tile',
'montagnia contina floor tile': 'montagna cortina floor tile',
'porcelin floor tile 6x24': 'porcelain floor tile 6x24',
'three wayy': 'three way',
'incide wall heater': 'inside wall heater',
'westminster pedistal combo': 'westminster pedestal combo',
'water softners': 'water softeners',
'miricale': 'miracle',
'sliding windos locks': 'sliding window locks',
'20v dewalt kombo': '20v dewalt combo',
'DEWALT VACCUM': 'DEWALT VACUUM',
'lithium 20 dewalt': 'lithium 20v dewalt',
'water heather': 'water heater',
'riobi blower vac 9056': 'ryobi blower vac 9056',
'DRAWEER PULLS': 'DRAWER PULLS',
'bagged cinder mulch': 'bagged cedar mulch',
'hindges': 'hinges',
'chair rail hieght': 'chair rail height',
'celling light': 'ceiling light',
'tub repair kit procelian': 'tub repair kit porcelain',
'dewalr tools': 'dewalt tools',
'zinc plated flatbraces': 'zinc plated flat braces',
'cieling': 'ceiling',
'control celing fan': 'control ceiling fan',
'roll roofing lap cemet': 'roll roofing lap cement',
'cedart board': 'cedar board',
'lg stcking kit': 'lg stacking kit',
'ajustable ladder feet': 'adjustable ladder feet',
'milwakee M12': 'milwaukee M12',
'garden sprayer non pump': 'garden sprayer no pump',
'roof rdge flashing': 'roof edge flashing',
'cable prime line emergensy open': 'cable prime line emergency open',
'roybi l18v': 'ryobi l18v',
'milwaukee 18-volt lithium-ion cordlessrotary hammerss': 'milwaukee 18-volt lithium-ion cordless rotary hammers',
'bath sinnk': 'bath sink',
'bathro sinks': 'bathroom sinks',
'bathroom pedelal sink': 'bathroom pedestal sink',
'epoxy concrete pain': 'epoxy concrete paint',
'pool suppll': 'pool supply',
'3-3 galvinized tubing': '3-3 galvanized tubing',
'portable air conditionar and heater': 'portable air conditioner and heater',
'vynal windows': 'vinyl windows',
'aluminun tread plate': 'aluminum tread plate',
'3/4 vlve': '3/4 valve',
'kitchen ceiling lightening': 'kitchen ceiling lighting',
'led fixtues for the kitchen': 'led fixtures for the kitchen',
'wall design cermic': 'wall design ceramic',
'door chim buttons': 'door chime buttons',
'plastice corrugated panels': 'plastic corrugated panels',
'doors gaurds': 'doors guards',
'24 inche sink and vanity for bath': '24 inch sink and vanity for bath',
'24 swantone vanity top': '24 swanstone vanity top',
'40 wattsolar charged lights': '40 watt solar charged lights',
'buikids toilet seat': 'buy kids toilet seat',
'toliet seats': 'toilet seats',
'land scaping timbers': 'landscaping timbers',
'everblit heavy duty canvas dropcloth': 'everbilt heavy duty canvas drop cloth',
'3/4 sharkbits': '3/4 sharkbite',
'bath rom toilets': 'bathroom toilets',
'alumanam sheets': 'aluminum sheets',
'huskvarna': 'husqvarna',
'treate 2x4': 'treated 2x4',
'12000 btuair conditioners window': '12000 btu air conditioners window',
'air conditioner vbration': 'air conditioner vibration',
'heith-zenith motion lights': 'heath-zenith motion lights',
'small paint rollerss': 'small paint rollers',
'fencde posts': 'fence posts',
'knoty pine fencing': 'knotty pine fencing',
'metal sheet underpenning': 'metal sheet underpinning',
'plastic untility shelves': 'plastic utility shelves',
'christmass lights': 'christmas lights',
'garlend lights': 'garland lights',
'ceilig fan mount': 'ceiling fan mount',
'paito table and chairs': 'patio table and chairs',
'glacier bay one pice flapper': 'glacier bay one piece flapper',
'dcanvas drop cloth': 'canvas drop cloth',
'lawn mowre covers': 'lawn mower covers',
'vaccum for dw745': 'vacuum for dw745',
'Club cadet primer bulb': 'Cub cadet primer bulb',
'interior door lcoks': 'interior door locks',
'dremel toll kit': 'dremel tool kit',
'round up nozzle replacment': 'roundup nozzle replacement',
'ceder mulch': 'cedar mulch',
'sikalatexr concrete vonding adhesive': 'sikalatex concrete bonding adhesive',
'rigid air compressor': 'ridgid air compressor',
'garge doors': 'garage doors',
'ridding mowers': 'riding mowers',
'ridiing lawnmower': 'riding lawn mower',
'sliding mirror bathroom medicn cabinets': 'sliding mirror bathroom medicine cabinets',
'pastic qtr round': 'plastic quarter round',
'robutussin dh 835 replacement wick': 'robitussin dh 835 replacement wick',
'brick wall panles': 'brick wall panels',
'kitchen floor tikles': 'kitchen floor tiles',
'buffer polishewr': 'buffer polisher',
'keorsene heater wicks': 'kerosene heater wicks',
'1x6 cedar boaed': '1x6 cedar board',
'infered heaters': 'infrared heaters',
'1-1/2in. x 1ft. blk pipe': '1-1/2in. x 1 ft. black pipe',
'show me all 60 inch vaniteis': 'show me all 60 inch vanities',
'cieling fan': 'ceiling fan',
'instant waater heater gas lp': 'instant water heater gas lp',
'woodebn fence panels': 'wooden fence panels',
'hardiboard siding': 'hardie board siding',
'craft an lawn mower': 'craftsman lawn mower',
'kohler wellworth tpoilet': 'kohler wellworth toilet',
'moen dhower faucet': 'moen shower faucet',
'dewalt hand toolsg saw cordless': 'dewalt hand tools saw cordless',
'hindged l bracket': 'hinged l bracket',
'ceiling fan canopie for flst ceiling': 'ceiling fan canopy for flat ceiling',
'furnance vent delfector': 'furnace vent deflector',
'flourescent shop light': 'fluorescent shop light',
'bateries': 'batteries',
'bath wall tile chanpayne': 'bath wall tile champagne',
'floor ceramick': 'floor ceramic',
'stone are mb11': 'stone care mb11',
'traffic master porcelin ceramic tile portland stone': 'trafficmaster porcelain ceramic tile portland stone',
'celing fans hampton bay': 'ceiling fans hampton bay',
'outdoor ceilikng fan with light': 'outdoor ceiling fan with light',
'36in vinale fence': '36in vinyl fence',
'extention ladder little gaint': 'extension ladder little giant',
'closet rod 8 n9ickel': 'closet rod 8 nickel',
'closetmaid wire eight itier organizer': 'closetmaid wire eight tier organizer',
'shorten pendent lighting': 'shorten pendant lighting',
'chainlink gate': 'chain link gate',
'4 flourescent': '4 fluorescent',
'lithium batties': 'lithium batteries',
'24x73 book shelve case white': '24x73 bookshelf case white',
'linoliuml adhesive': 'linoleum adhesive',
'vynal flooring': 'vinyl flooring',
'vynal grip strip': 'vinyl grip strip',
'hagchet': 'hatchet',
'frameless mirro mount': 'frameless mirror mount',
'microwarve cart': 'microwave cart',
'mosia grout sealer': 'mosaic grout sealer',
'backsplach': 'backsplash',
'dimable ceiling strip lights': 'dimmable ceiling strip lights',
'lithum leaf blower': 'lithium leaf blower',
'rayoby batteries': 'ryobi batteries',
'pressure washerparts': 'pressure washer parts',
'rigid 18v lituim ion nicad': 'ridgid 18v lithium ion nicad',
'artric air portable': 'arctic air portable',
'8ft wht veranda post sleeve': '8 ft white veranda post sleeve',
'vynal fence': 'vinyl fence',
'solar naturlas salt': 'solar naturals salt',
'metl flashing': 'metal flashing',
'dog fence batt': 'dog fence battery',
'onda pressure washer': 'honda pressure washer',
'pressue washer': 'pressure washer',
'fridgdare air conditioners': 'frigidaire air conditioners',
'double pain windows': 'double pane windows',
'round flat topmetal post caps': 'round flat top metal post caps',
'1/2\' plyweood': '1/2\' plywood',
'ddummy door knobs interior': 'dummy door knobs interior',
'robi battery lawn trimmer': 'ryobi battery lawn trimmer',
'weewacker edger': 'weed wacker edger',
'prunning shears': 'pruning shears',
'steel enrty doors': 'steel entry doors',
'forimca': 'formica',
'satin nickle door hinge 4 in': 'satin nickel door hinge 4 in',
'garden hose repir cuplings': 'garden hose repair couplings',
'1/3 hoursepower garbage disposal': '1/3 horsepower garbage disposal',
'chicken wire 16 gauze': 'chicken wire 16 gauge',
'wheelbarow': 'wheelbarrow',
'didger': 'dodger',
'hhigh efficiency round toilet in white': 'high efficiency round toilet in white',
'accordian door venetian': 'accordion door venetian',
'patio flurniture covers': 'patio furniture covers',
'through thewall air conditioner': 'through the wall air conditioner',
'Whirpool washer': 'Whirlpool washer',
'4x6treaded wood': '4x6 treated wood',
'preature treated lumber 2in. x12in.x12 ft.': 'pressure treated lumber 2in. x 12 in.x 12 ft.',
'closetmade wood': 'closetmaid wood',
'steam cleanerm mop': 'steam cleaner mop',
'steqamers': 'steamers',
'pendant shads': 'pendant shades',
'battery operated flashingm light': 'battery operated flashing light',
'metal flexable water hose': 'metal flexible water hose',
'air filter for lawn equitment': 'air filter for lawn equipment',
'fiber glass pip insulation': 'fiberglass pipe insulation',
'insallation': 'installation',
'insullation': 'insulation',
'contracor string light': 'contractor string light',
'gas furnace and hotwater': 'gas furnace and hot water',
'rust oleum cabinet stain kit': 'rustoleum cabinet stain kit',
'sjhelf': 'shelf',
'small brackets for selves': 'small brackets for shelves',
'hecurles': 'hercules',
'anderson window grate': 'andersen window grate',
'anderson windows': 'andersen windows',
'lasron slider windows': 'larson slider windows',
'samsung 25.6 french door refridgerator': 'samsung 25.6 french door refrigerator',
'closet doors oganizers': 'closet doors organizers',
'koehler cimarron bathroom sink': 'kohler cimarron bathroom sink',
'kohler pedestal sink cimeron': 'kohler pedestal sink cimarron',
'cover for pole structue': 'cover for pole structure',
'drils': 'drills',
'surface mount channe': 'surface mount channel',
'outside corner- dentil': 'outside corner- dental',
'14heightx24withx15depth air conditioner': '14 heightx24 with 15 depth air conditioner',
'r30 demin insulation': 'r30 denim insulation',
'6 metal tee posts': '6 metal t posts',
'metal fence postsd': 'metal fence posts',
'aluminum l cahnnel': 'aluminum l channel',
'conner trim moulding': 'corner trim moulding',
'cornor board': 'corner board',
'pvc planel glue': 'pvc panel glue',
'3 in 1 vacum, ryobi': '3 in 1 vacuum, ryobi',
'toliet bowl rebuilding kits': 'toilet bowl rebuilding kits',
'swing set accesories': 'swing set accessories',
'ventenatural gas heater': 'vented natural gas heater',
'square ube wood': 'square cube wood',
'swivrl wood anchors': 'swivel wood anchors',
'ge gridle': 'ge griddle',
'pendant shafe': 'pendant shade',
'3/8 pipe galvinized': '3/8 pipe galvanized',
'vaporbarrier, crawl space': 'vapor barrier, crawl space',
'self sealant membrane': 'self sealing membrane',
'husky work bemch': 'husky work bench',
'vanity light fictures': 'vanity light fixtures',
'bed frames headboaed': 'bed frames headboard',
'replace plasticbathroom towel holder': 'replace plastic bathroom towel holder',
'whirlpool diswasher weather stripping': 'whirlpool dishwasher weather stripping',
'36 inch front dooe with casing': '36 inch front door with casing',
'glass back doorr': 'glass back door',
'pre hu door': 'pre hung door',
'backsplash paneks': 'backsplash panels',
'jeffery court mozaic tile': 'jeffrey court mosaic tile',
'floo shets': 'floor sheets',
'gazhose for dryer machine': 'gas hose for dryer machine',
'electric fireplacewater heaters': 'electric fireplace water heaters',
'ceiling mounted lighting fixures': 'ceiling mounted lighting fixtures',
'tools bloowers': 'tools blowers',
'artifical ground cover': 'artificial ground cover',
'waxhers and electric dryers': 'washers and electric dryers',
'outdoor tilees': 'outdoor tiles',
'owens corning ashingles': 'owens corning shingles',
'peper towel holder wall mount': 'paper towel holder wall mount',
'genecrac generators': 'generac generators',
'robyi gas weeder': 'ryobi gas weeder',
'acrtlic tape': 'acrylic tape',
'foam insulaion panels': 'foam insulation panels',
'rumbl;estone': 'rumblestone',
'famed sliding door $289.00': 'framed sliding door $289.00',
'padio door': 'patio door',
'cement boards ciding': 'cement boards siding',
'upholstry': 'upholstery',
'miror interior doors': 'mirror interior doors',
'recessed medicien cabinet': 'recessed medicine cabinet',
'bulked washed sand and gravel': 'bulk washed sand and gravel',
'sheet stock floorinh': 'sheet stock flooring',
'polycarbonite': 'polycarbonate',
'dedwalt cordless drill': 'dewalt cordless drill',
'ryobi power chalking gun': 'ryobi power caulking gun',
'poulan pro lawn motor blades': 'poulan pro lawn mower blades',
'diining set outdoor': 'dining set outdoor',
'granite countertop glu': 'granite countertop glue',
'cyculer saw': 'circular saw',
'kitchenaid frenchdoor ref': 'kitchenaid french door ref',
'rigid wet dry vac': 'ridgid wet dry vac',
'whirlpool caprios 4.3': 'whirlpool cabrio 4.3',
'micro wave ovens': 'microwave ovens',
'8 valleta edger': '8 valletta edger',
'decking hardsware': 'decking hardware',
'utility traiter': 'utility trailer',
'ceilin storage': 'ceiling storage',
'white wall bathroon cabinets': 'white wall bathroom cabinets',
'tsnkless hot water heater': 'tankless hot water heater',
'weed killer consertrated': 'weed killer concentrate',
'milwaukee ha,,er drill': 'milwaukee hammer drill',
'23 ince': '23 inch',
'stone outside tile': 'stone outdoor tile',
'galvanized outdoor celing fan': 'galvanized outdoor ceiling fan',
'oil rubbered bronze dor': 'oil rubbed bronze door',
'vynik tiles peel stick': 'vinyl tiles peel stick',
'window aircondiioner 12000 but': 'window air conditioner 12000 btu',
'60 lb hi strength concrete': '60 lb high strength concrete',
'plexy glass 24 x 24': 'plexiglass 24 x 24',
'porch liht fixture': 'porch light fixture',
'moving trollie': 'moving trolley',
'shoipping cart': 'shopping cart',
'accesory bags': 'accessory bags',
'garage door 70 lb extention spring': 'garage door 70 lb extension spring',
'riobi shop vac filter': 'ryobi shop vac filter',
'wet carpet cleaninig': 'wet carpet cleaning',
'pvd electrical conduit': 'pvc electrical conduit',
'roller up window blinds': 'roll up window blinds',
'uplihght': 'uplight',
'metal shelfs': 'metal shelves',
'dewalt 20v recepicating saw': 'dewalt 20v reciprocating saw',
'outdooor carpet': 'outdoor carpet',
'step latter': 'step ladder',
'kitchen cabinte hardware blue knob': 'kitchen cabinet hardware blue knob',
'pivotangle lock hinge': 'pivot angle lock hinge',
'plasticl panels': 'plastic panels',
'varigated fiber board': 'variegated fiber board',
'battery chages': 'battery charges',
'1/2 inch blk iron coupling': '1/2 inch black iron coupling',
'defiant led armer max': 'defiant led armormax',
'defiant led ight': 'defiant led light',
'led flashlightts': 'led flashlights',
'pfister pasedena 4 center set faucet': 'pfister pasadena 4 center set faucet',
'meguire plastic cleaner': 'meguiars plastic cleaner',
'single board pannel': 'single board panel',
'foundation fent covers': 'foundation vent covers',
'bottom freezer refrdgerators': 'bottom freezer refrigerators',
'colbolt drill bits': 'cobalt drill bits',
'soundfroofing material': 'soundproofing material',
'hanging light masn gar': 'hanging light mason jar',
'drywall mudd': 'drywall mud',
'delta bathroom falcet': 'delta bathroom faucet',
'ridgid 10000 watt': 'rigid 10000 watt',
'pvc edgetape white': 'pvc edge tape white',
'fireplace mantle': 'fireplace mantel',
'drop in sink ovel': 'drop in sink oval',
'40ft aluminumm ladder': '40 ft aluminum ladder',
'rigid shop vac filter': 'ridgid shop vac filter',
'moen single handle valvue rebuild': 'moen single handle valve rebuild',
'hunter ceiling fans accesories strip': 'hunter ceiling fans accessories strip',
'wheel barrel': 'wheelbarrow',
'16 aluminuim ladder': '16 aluminum ladder',
'1/2\' olastic pipe': '1/2\' plastic pipe',
'moen 7570 single hanlel faucet': 'moen 7570 single handle faucet',
'padtio heater': 'patio heater',
'rachet scret drivers': 'ratchet screwdrivers',
'water fountain nozle': 'water fountain nozzle',
'rigid sander': 'ridgid sander',
'anderson 4000 windows': 'andersen 4000 windows',
'doublew stainless': 'double stainless',
'milwakee m12 cordless heated jacket': 'milwaukee m12 cordless heated jacket',
'french door scree doorsscreen door': 'french door screen doors screen door',
'samsung refridegrator': 'samsung refrigerator',
'flurorescent light bulbs': 'fluorescent light bulbs',
'phillips 40t12cw plus florescent tube': 'phillips 40t12cw plus fluorescent tube',
'black and decker timmer parts st4500': 'black and decker trimmer parts st4500',
'gas range slide inove': 'gas range slide in love',
'baldwin lock stets': 'baldwin lock sets',
'6 ft ceder fence': '6 ft cedar fence',
'storeage': 'storage',
'beckett fountin pump': 'beckett fountain pump',
'polyeurethane exterior': 'polyurethane exterior',
'ceiling pannel': 'ceiling panel',
'70 celing fan': '70 ceiling fan',
'vynil barackets': 'vinyl brackets',
'moen kitchen fauchet': 'moen kitchen faucet',
'ridgid model wd1680 filter': 'rigid model wd1680 filter',
'point of use electtric': 'point of use electric',
'stell finished french patio door': 'steel finished french patio door',
'lg elec laundry suite': 'lg electric laundry suite',
'outdoor screem': 'outdoor screen',
'patio chair cushions/marth stewart': 'patio chair cushions/martha stewart',
'24 hollow core closet dor': '24 hollow core closet door',
'rigid miter saw': 'ridgid miter saw',
'ruotor table': 'router table',
'airconditioner decoritive cover unit': 'air conditioner decorative cover unit',
'miwaukee 18v battery and charger': 'milwaukee 18v battery and charger',
'potable air conditioner': 'portable air conditioner',
'perhung 30x80 interior door': 'prehung 30 x 80 interior door',
'6 dewalt skill saw': '6 dewalt skil saw',
'1x8x8 toung and grove': '1x8x8 tongue and groove',
'river feather door threashold': 'river feather door threshold',
'range connnector': 'range connector',
'ligt fixture covers': 'light fixture covers',
'window flasheing': 'window flashing',
'backet metal': 'bracket metal',
'horizantel fence panel': 'horizontal fence panel',
'rug pad 8 x 10': 'rug pad 8x10',
'frigadaire appliances': 'frigidaire appliances',
'bath si k cabinets': 'bath sink cabinets',
'8x10 outside storage': '8x10 outdoor storage',
'earthgrow mulch': 'earthgro mulch',
'10 60 tooth blde': '10 60 tooth blade',
'sink faucet with soap dispencer': 'sink faucet with soap dispenser',
'ridgid job max attatchmens': 'ridgid jobmax attachments',
'ridgid wrachet head': 'ridgid ratchet head',
'celliling light': 'ceiling light',
'waterroo concrete paint': 'waterproof concrete paint',
'americian standard champion 4 toliets': 'american standard champion 4 toilets',
'4 ftawning frame': '4 ft awning frame',
'restour for concrete': 'restore for concrete',
'econo florecent bulb': 'econo fluorescent bulb',
'florecent bulb holder': 'fluorescent bulb holder',
'light fictures': 'light fixtures',
'lihonia 4 led work light': 'lithonia 4 led work light',
'interrior frnch doors': 'interior french doors',
'hamptom bay cusion': 'hampton bay cushion',
'wndows': 'windows',
'porcalain thinset': 'porcelain thinset',
'versabon 50lb': 'versabond 50 lb',
'table for outsde': 'table for outside',
'hoinda gas edger': 'honda gas edger',
'installing sockets for flor': 'installing sockets for floor',
'laguna porcelin tile': 'laguna porcelain tile',
'showe heads in oil rubbed bronze': 'shower heads in oil rubbed bronze',
'chase lounge cushions': 'chaise lounge cushions',
'electric detector in simming pool water': 'electric detector in swimming pool water',
'elongagated toilet seat': 'elongated toilet seat',
'towbehind lawn spreaders': 'tow behind lawn spreaders',
'cable poter': 'cable porter',
'fraiming nailer electric': 'framing nailer electric',
'12 x 12 porcelian floor and wall tile': '12 x 12 porcelain floor and wall tile',
'marrazi': 'marazzi',
'range hoodu': 'range hood',
'whirpool range': 'whirlpool range',
'subway title 3 x 6': 'subway tile 3 x 6',
'untique stone': 'antique stone',
'post sleeveee': 'post sleeve',
'dinning chair seats': 'dining chair seats',
'christmas lights icicle colerful': 'christmas lights icicle colorful',
'colpay garage door molding': 'clopay garage door molding',
'light for public ligthining': 'light for public lightning',
'slate timberland shingle': 'slate timberline shingle',
'cicular saw blad': 'circular saw blade',
'varbide 7 1/4 circular saw blade': 'carbide 7 1/4 circular saw blade',
'10 flourescent bulbs': '10 fluorescent bulbs',
'kids outside furnature': 'kids outside furniture',
'whirpool gas range': 'whirlpool gas range',
'starter fertillzer': 'starter fertilizer',
'toro snowerblower light kit': 'toro snowblower light kit',
'High Wheel String Trimer': 'High Wheel String Trimmer',
'insided house door': 'inside house door',
'3 1/2 non-mortison hinges satin finish': '3 1/2 non-mortise hinges satin finish',
'miracle grow garden soil': 'miracle gro garden soil',
'miracle grow spray dispensers': 'miracle gro spray dispensers',
'alure flooring black oak': 'allure flooring black oak',
'sweeping atatchment for weed wacker': 'sweeping attachment for weed wacker',
'retangle bathroom sinks': 'rectangular bathroom sinks',
'underthe cabinet microwaves': 'under the cabinet microwaves',
'24 inch lover doors': '24 inch louvered doors',
'window drip egedg': 'window drip edge',
'rechargable portable air compressor': 'rechargeable portable air compressor',
'birkmann 5 burner': 'brinkmann 5 burner',
'whirlpool gasnstove self cleaning oven': 'whirlpool gas stove self cleaning oven',
'havc brush': 'hvac brush',
'discharge hose 1.5 inces': 'discharge hose 1.5 inches',
'6 ft laminite countertop': '6 ft laminate countertop',
'pool vaccum': 'pool vacuum',
'1/2 in.x 1/2 in. thread albow male to male': '1/2 in.x 1/2 in. threaded elbow male to male',
'sofet': 'soffit',
'sliding patio doort': 'sliding patio door',
'30inch flourescent tubes': '30 inch fluorescent tubes',
'phillips light bulbs': 'philips light bulbs',
'stainless steel sinl': 'stainless steel sink',
'burgular bars for front porch': 'burglar bars for front porch',
'oach lights': 'coach lights',
'2 in lnsulated bushings': '2 in insulated bushings',
'motion lught': 'motion light',
'residental light sensor security lights': 'residential light sensor security lights',
'vertical blind accsesories': 'vertical blind accessories',
'1/2 in ree bar': '1/2 in rebar',
'cloths rod and shelf brackets': 'clothes rod and shelf brackets',
'fire rated buildng materials': 'fire rated building materials',
'hot point water filer': 'hotpoint water filter',
'bathroom cabinet without fermaldehyde': 'bathroom cabinet without formaldehyde',
'9.6 bvolt': '9.6 volt',
'rustoleum bright coach metallic': 'rustoleum bright coat metallic',
'stone effect sante cecilia top': 'stone effects santa cecilia top',
'suspanded ceiling': 'suspended ceiling',
'4x8 plywood pressure treeted': '4x8 plywood pressure treated',
'acess panel': 'access panel',
'genie excellartor garage door opener': 'genie excelerator garage door opener',
'ge dish washer with 46 dba rating': 'ge dishwasher with 46 dba rating',
'wood and concret stain': 'wood and concrete stain',
'8 foot flour sent': '8 foot fluorescent',
'infared grills': 'infrared grills',
'wirless interconnected smoke dedector': 'wireless interconnected smoke detector',
'luever': 'leuver',
'3 in roung head bolt': '3 in round head bolt',
'rachet': 'ratchet',
'rigid 12 volt': 'ridgid 12 volt',
'sharkbit': 'sharkbite',
'hamiltton collectin': 'hamilton collection',
'kitchen aide wine and beverage refrigerator': 'kitchenaid wine and beverage refrigerator',
'paint markers burgondy color': 'paint markers burgundy color',
'glass washer with sucktion cups': 'glass washer with suction cups',
'andersor doors': 'anderson doors',
'hickory cabinett': 'hickory cabinet',
'repacement can type light bulbs': 'replacement can type light bulbs',
'ceeling patio shades': 'ceiling patio shades',
'white vainty 8 faucet': 'white vanity 8 faucet',
'daylight florisant bulb 36inch': 'daylight fluorescent bulb 36 inch',
'contact paoer': 'contact paper',
'air bathtubes': 'air bathtubs',
'cushions for wecker furniture': 'cushions for wicker furniture',
'galvinized poles 20long': 'galvanized poles 20 long',
'siegel light pendent': 'siegel light pendant',
'spaonges': 'sponges',
'extorior shatters': 'exterior shutters',
'led blubs': 'led bulbs',
'4 inch back flow prenter': '4 inch backflow preventer',
'silding closet doors track': 'sliding closet doors track',
'10000 btu windowair condiioner': '10000 btu window air conditioner',
'sewer pipe hoider': 'sewer pipe holder',
'vinal blind paint': 'vinyl blind paint',
'fuacet': 'faucet',
'picinic tables': 'picnic tables',
'all in one topmount kraus sinks': 'all in one top mount kraus sinks',
'solar post lmapy': 'solar post lamp',
'transormations': 'transformations',
'daltiles sandy beach': 'daltile sandy beach',
'wallmount indoor lights with plug': 'wall mounted indoor lights with plug',
'kennal kit': 'kennel kit',
'46 high output grow florescent bulb': '46 high output grow fluorescent bulb',
'frost fee freezers': 'frost free freezers',
'stainles steel door handle': 'stainless steel door handle',
'combo drill makita 20v': 'combi drill makita 20v',
'shop vacumm': 'shop vacuum',
'primer for led paint': 'primer for lead paint',
'outdoor gas fiepits': 'outdoor gas firepits',
'hallway pendendant lighting': 'hallway pendant lighting',
'chesapeke oak flooring': 'chesapeake oak flooring',
'ryobi multi tool acccessories': 'ryobi multi tool accessories',
'ryobi raidos': 'ryobi radios',
'milwaukee skill saw': 'milwaukee skil saw',
'ligh chrismas hanging tree': 'light christmas hanging tree',
'galvinized screws': 'galvanized screws',
'led circuline bulbs': 'led circline bulbs',
'kholer elongated toilet seat': 'kohler elongated toilet seat',
'tolet seats': 'toilet seats',
'ock blade knife piece 3': 'lock blade knife piece 3',
'portable airconditioner': 'portable air conditioner',
'window aircondition': 'window air conditioner',
'36 vx 72 commercial outdoor mats': '36 x 72 commercial outdoor mats',
'runner commerical': 'runner commercial',
'montagna dappy gray': 'montagna dapple gray',
'soil temperture test kit': 'soil temperature test kit',
'basement tolet': 'basement toilet',
'32 door threshhold': '32 door threshold',
'hampton bay oak bast cabinets': 'hampton bay oak base cabinets',
'charbroil parts': 'char broil parts',
'qucikie mop': 'quickie mop',
'concret anchor bolts': 'concrete anchor bolts',
'24 whtie storage cabinet': '24 white storage cabinet',
'door handle deabolt kit': 'door handle deadbolt kit',
'ge profile 30 inch charcoal folters': 'ge profile 30 inch charcoal filters',
'49 inch napolian vanity top': '49 inch napoleon vanity top',
'4in pvc franco cuppling': '4in pvc fernco coupling',
'graveless gravaless sewer pipe': 'graveless graveless sewer pipe',
'shower fllor': 'shower floor',
'riverera screen doors': 'riviera screen doors',
'animal deterent': 'animal deterrent',
'woodpeckers repellant': 'woodpeckers repellent',
'wood buring insert 200-250': 'wood burning insert 200-250',
'spectrazide ant': 'spectracide ant',
'gas grill accesories': 'gas grill accessories',
'elecronic insect repeller': 'electronic insect repeller',
'slyvanna motion nite light': 'sylvania motion nite light',
'4 in pvs end cap': '4 in pvc end cap',
'delta portor shower and tub trim': 'delta porter shower and tub trim',
'replacment mini bulbs': 'replacement mini bulbs',
'braxilian cherry laminate': 'brazilian cherry laminate',
'15 amp tampe resistant outlets': '15 amp tamper resistant outlets',
'hydraulic jack renat': 'hydraulic jack rental',
'32 x 32 shower baser': '32 x 32 shower base',
'electronic bed bug repellant': 'electronic bed bug repellent',
'ridgid auger': 'rigid auger',
'2000 psi force nozzzle': '2000 psi force nozzle',
'25 height beveragecooler': '25 height beverage cooler',
'anderson windows 400 seriesimpact resistant': 'andersen windows 400 series impact resistant',
'drill 20 lithium battery': 'drill 20v lithium battery',
'extertal air vent cover': 'external air vent cover',
'resin shesd': 'resin sheds',
'8x8x4 conctete block': '8x8x4 concrete block',
'tun faucet spout': 'tub faucet spout',
'continuos curtain rods': 'continuous curtain rods',
'upholstry cleaner': 'upholstery cleaner',
'ureka vaccuum': 'eureka vacuum',
'30 towel rods brushed nicol': '30 towel rods brushed nickel',
'1/2 gal thermos': '1/2 gallon thermos',
'unbralla fabric top only': 'umbrella fabric top only',
'outdoor cieling fans': 'outdoor ceiling fans',
'20 amps cros hinghs breaker': '20 amps cross highs breaker',
'mixing tubn': 'mixing tub',
'gfi circuit breaker': 'gfci circuit breaker',
'wrought iuron fence panels': 'wrought iron fence panels',
'ac air vent sleave': 'ac air vent sleeve',
'air ventalation deflector': 'air ventilation deflector',
'buddahs hand tree': 'buddha\'s hand tree',
'lawm mowers': 'lawn mowers',
'asathbula 7 piece': 'ashtabula 7 piece',
'recessed lightjs': 'recessed lights',
'hing pin door dtop': 'hinge pin door stop',
'elerical outlets plates': 'electrical outlets plates',
'bed tool boc': 'bed tool box',
'16 inch fabn': '16 inch fan',
'battery poerated motion sensor': 'battery operated motion sensor',
'grqss': 'grass',
'troy build trimmer extension': 'troy bilt trimmer extension',
'mansonry impact bit': 'masonry impact bit',
'high output basebord': 'high output baseboard',
'shower door sealparts': 'shower door seal parts',
'12 inch hight wall cabinet': '12 inch height wall cabinet',
'light s for sno throwers': 'lights for snow throwers',
'ceiling medallians': 'ceiling medallions',
'medalion': 'medallion',
'everbilt sloted': 'everbilt slotted',
'transparant redwood stain': 'transparent redwood stain',
'black and decker scub buster extreme': 'black and decker scrub buster extreme',
'mobilehome siding': 'mobile home siding',
'shutter screwws': 'shutter screws',
'hampton pation set with firepit': 'hampton patio set with firepit',
'industreial wire': 'industrial wire',
'vegtable seeds': 'vegetable seeds',
'masterpeice 72': 'masterpiece 72',
'5/4 lumbe': '5/4 lumber',
'dawn to dusk lig': 'dawn to dusk light',
'dusk to dawn motion sensoroutdoor lighting fixtures': 'dusk to dawn motion sensor outdoor lighting fixtures',
'cordless sweeperr': 'cordless sweeper',
'mill valley colle': 'mill valley college',
'outdoorstorage bin': 'outdoor storage bin',
'haging wire': 'hanging wire',
'4 in white recessed haol baffle in soft white': '4 in white recessed led baffle in soft white',
'11 1/2x25 1/2 white aluminun': '11 1/2 x 25 1/2 white aluminum',
'saratoga hickorya': 'saratoga hickory',
'surface gringer': 'surface grinder',
'kidie co2': 'kidde co2',
'batterys and charger kits': 'batteries and charger kits',
'nutru ninja': 'nutri ninja',
'23.5 shower door nickle': '23.5 shower door nickel',
'glass panel retiner': 'glass panel retainer',
'12v replacement blubs': '12v replacement bulbs',
'martha steward': 'martha stewart',
'1 1/2inchbrasswalltube18 inch': '1 1/2 inch brass wall tube 18 inch',
'brown color scheem': 'brown color scheme',
'spiral latters': 'spiral letters',
'24 incyh range': '24 inch range',
'8x8 ezup canopie cover': '8x8 ez up canopy cover',
'kitcheen door blind': 'kitchen door blind',
'flourescent balast 120-2/32is': 'fluorescent ballast 120-2/32is',
'vinyl lattiace': 'vinyl lattice',
'1/4 28 threadded connector': '1/4 28 threaded connector',
'kitchaid 3 burner': 'kitchenaid 3 burner',
'10 condiut pvc': '10 conduit pvc',
'WEBER GRILL GENIS 310': 'WEBER GRILL GENESIS 310',
'wall mount tub fauet moen': 'wall mount tub faucet moen',
'sower cleaner': 'shower cleaner',
'batteryfor alarm system': 'battery for alarm system',
'bed gugs': 'bed bugs',
'show the pric of washer and dryer': 'show the price of washer and dryer',
'washer electic dryer': 'washer electric dryer',
'ho hub couplings': 'no hub couplings',
'battey string trimmers': 'battery string trimmers',
'3/4 in. wide quarteround': '3/4 in. wide quarter round',
'ac dip pans': 'ac drip pans',
'rutland wood stove termometer': 'rutland wood stove thermometer',
'outdoor daucets': 'outdoor faucets',
'badless vacuum cleaners': 'bagless vacuum cleaners',
'dewalt 20 volt xr hamer': 'dewalt 20 volt xr hammer',
'dewalt drillimpact tool 20 volt xr': 'dewalt drill impact tool 20 volt xr',
'martha steward bath mirror': 'martha stewart bath mirror',
'infared thermometer': 'infrared thermometer',
'millwaukee 1/2 ele.c drill': 'milwaukee 1/2 elec drill',
'25 watt 4 foot flourescent': '25 watt 4 foot fluorescent',
'boscj bit': 'bosch bit',
'barbque grills': 'barbecue grills',
'brinkman grill burner': 'brinkmann grill burner',
'malbu replacement led light bubles': 'malibu replacement led light bulbs',
'natural stone tiele': 'natural stone tile',
'stone vaneer': 'stone veneer',
'stone venner sequia': 'stone veneer sequoia',
'ceiling fan replacement clades': 'ceiling fan replacement blades',
'transformet for flurescent tube lights': 'transformer for fluorescent tube lights',
'refrigerator frenchdoor': 'refrigerator french door',
'flourescent paint': 'fluorescent paint',
'marking baint': 'marking paint',
'mirrir hanger': 'mirror hanger',
'chrisymas tree bags': 'christmas tree bags',
'comercial food processor': 'commercial food processor',
'picture haning kitpicture hanging kit': 'picture hanging kit picture hanging kit',
'bathroom vanity cabinetwithouttops': 'bathroom vanity cabinets without tops',
'amcrest survelliance systems': 'amcrest surveillance systems',
'30 inch refigrator': '30 inch refrigerator',
'chain saw eletric': 'chainsaw electric',
'power dprayer': 'power sprayer',
'douglas fur fake christmas trees': 'douglas fir fake christmas trees',
'brinkman grill': 'brinkmann grill',
'dual switch dimer': 'dual switch dimmer',
'Ortho Wed B Gone max': 'Ortho Weed B Gon max',
'ortho weed be gone': 'ortho weed b gon',
'4ft flourescent bulb t8': '4ft fluorescent bulb t8',
'18 volt 1/2 roter hammer': '18 volt 1/2 roto hammer',
'cabinents with drawers': 'cabinets with drawers',
'7 mil trash bgs': '7 mil trash bags',
'1/2 ntp to 1/2': '1/2 npt to 1/2',
'3/8 rachert set': '3/8 ratchet set',
'hunter shower eshaust fan with light': 'hunter shower exhaust fan with light',
'vanity in mahogany mirros': 'vanity in mahogany mirrors',
'hasmmock bed': 'hammock bed',
'composit fencing': 'composite fencing',
'post insurts': 'post inserts',
'3500 psi pressue washer': '3500 psi pressure washer',
'idylus air purifier': 'idylis air purifier',
'garden solenoide valves': 'garden solenoid valves',
'window plastic instulation': 'window plastic insulation',
'engineered wood floorcleaners': 'engineered wood floor cleaners',
'parquee flooring': 'parquet flooring',
'dermal saw max ultra': 'dremel saw max ultra',
'external structual connector screw': 'external structural connector screw',
'tv shelv': 'tv shelf',
'kithen cabinets 18 white': 'kitchen cabinets 18 white',
'1 1/2 couplingg': '1 1/2 coupling',
'porceline faucet handle': 'porcelain faucet handle',
'duplex outlet and ubs charger': 'duplex outlet and usb charger',
'1/4 quarter round cherries jublilee': '1/4 quarter round cherries jubilee',
'lg hausys viaterra': 'lg hausys viatera',
'bear semi transparent cedar stain': 'behr semi transparent cedar stain',
'27 mivrowave': '27 microwave',
'gardinias': 'gardenias',
'ull spectrum plant light': 'full spectrum plant light',
'942196brinkmann 2 burner': '942196 brinkmann 2 burner',
'gargage storage ideas': 'garage storage ideas',
'outside horizontal storage sheds': 'outdoor horizontal storage sheds',
'bouganvilla': 'bougainvillea',
'led recressed lighting': 'led recessed lighting',
'3 x3 marle tile': '3x3 marble tile',
'concrete saw dewall': 'concrete saw dewalt',
'replacement glass for pellet stive': 'replacement glass for pellet stove',
'porcelin tile black pencil tile': 'porcelain tile black pencil tile',
'smoke dectectors': 'smoke detectors',
'humidifier fulters': 'humidifier filters',
'3/4 in. pvc assesories': '3/4 in. pvc accessories',
'12 inch sower head': '12 inch shower head',
'22 mm impact ocket': '22mm impact socket',
'garvanized wood screws': 'galvanized wood screws',
'interlocking rubbber floor mats': 'interlocking rubber floor mats',
'Hose end nozzel': 'Hose end nozzle',
'led energy efficient kitchen lites': 'led energy efficient kitchen lights',
'barn syslet door': 'barn style door',
'rat or mice poision': 'rat or mice poison',
'led ressed deameable lights': 'led recessed dimmable lights',
'prelit tree mutli': 'pre lit tree multi',
'sodering iron': 'soldering iron',
'tub suround': 'tub surround',
'fireplace screen assessories': 'fireplace screen accessories',
'acrilic white paint': 'acrylic white paint',
'gibraltor locking': 'gibraltar locking',
'air conditioner sideays': 'air conditioner sideways',
'white inyrtior paint': 'white interior paint',
'100 watt candlebra': '100 watt candelabra',
'llhampton bay patio rocker': 'hampton bay patio rocker',
'lock brushed nicke;': 'lock brushed nickel;',
'structered media': 'structured media',
'summit 24 inch ss gaqs range': 'summit 24 inch ss gas range',
'ryobl battery': 'ryobi battery',
'replacement carbrator for robyi': 'replacement carburetor for ryobi',
'balist': 'ballast',
'pressuer washer': 'pressure washer',
'22 storage shelve': '22 storage shelf',
'32\' strorm door': '32\' storm door',
'hazardous locationlight fixture globe': 'hazardous location light fixture globe',
'john deer bagger': 'john deere bagger',
'ridinng lawn mowers mulching': 'riding lawn mowers mulching',
'1/2 fpt x 1/2 inch pex': '1/2 npt x 1/2 inch pex',
'2 kindorff straps': '2 kindorf straps',
'telemechanic square d': 'telemecanique square d',
'thresh hold': 'threshold',
'24x24 framless recessed mount mirrored medicine': '24x24 frameless recessed mount mirrored medicine',
'600 connector cylander': '600 connector cylinder',
'well pump submerciable': 'well pump submersible',
'security gate pannel': 'security gate panel',
'1/4-20 jamb nuts': '1/4-20 jam nuts',
'american standard flush valvu': 'american standard flush valve',
'stove adopter': 'stove adapter',
'kitchenaide dishwasher': 'kitchenaid dishwasher',
'roofing leadders': 'roofing ladders',
'heath zenity 180 security light': 'heath zenith 180 security light',
'solar powerd lights': 'solar powered lights',
'24 white walloven': '24 white wall oven',
'kitchen aide mixer': 'kitchenaid mixer',
'10 in w 30 in l inetrior vent': '10 in w 30 in l interior vent',
'co smoke detector kiddie': 'co smoke detector kidde',
'vacum aa bag 58236c': 'vacuum aa bag 58236c',
'sealant for sideing': 'sealant for siding',
'come along and chaincome along and chain': 'come along and chain come along and chain',
'wall paper bprder': 'wallpaper border',
'cararra tile': 'carrara tile',
'14 gauge strranded wire': '14 gauge stranded wire',
'30 gal electirc water heater': '30 gal electric water heater',
'guarter round tile': 'quarter round tile',
'summit gril': 'summit grill',
'gavanized pipe 20 feet': 'galvanized pipe 20 feet',
'melamine sheliving': 'melamine shelving',
'composite fiscia board': 'composite fascia board',
'spunge mop refill': 'sponge mop refill',
'wall mount outside motion dector': 'wall mount outdoor motion detector',
'bisquit tub refinish kit': 'biscuit tub refinish kit',
'patternn paint rollers': 'pattern paint rollers',
'built in wall nitch': 'built in wall niche',
'ironboard built in': 'iron board built in',
'behr melrot': 'behr merlot',
'led shoplightmakita light': 'led shop light makita light',
'armazone': 'amazon',
'soild 6 panel interior door': 'solid 6 panel interior door',
'dishs for 8': 'dishes for 8',
'1 1/4 steel ppes': '1 1/4 steel pipes',
'pull out drw': 'pull out draw',
'swffer mop': 'swiffer mop',
'milwaukee m18 tootls': 'milwaukee m18 tools',
'bronzw phone wall jack cover': 'bronze phone wall jack cover',
'flourscent lights size 18x24': 'fluorescent lights size 18x24',
'berber carpeting destiny doeskin': 'berber carpet destiny doeskin',
'spring heavy dut': 'spring heavy duty',
'2 in pvc pipe incresers': '2 in pvc pipe increasers',
'lifetime rouind table': 'lifetime round table',
'16x26 recesssed medicine cabinets': '16x26 recessed medicine cabinets',
'rolling barn dorr hardware': 'rolling barn door hardware',
'huricane panel caps': 'hurricane panel caps',
'73 inch anderson patio screen doors': '73 inch andersen patio screen doors',
'barbque grill temperature guage': 'barbecue grill temperature gauge',
'bath tub shower repair lit': 'bathtub shower repair kit',
'entery door sidelights': 'entry door sidelights',
'5 burnerner brikman gas grill': '5 burner brinkmann gas grill',
'battub floor mat': 'bathtub floor mat',
'outlet wallplate with cover': 'outlet wall plate with cover',
'fungacide': 'fungicide',
'tuband tile latex caulk': 'tub and tile latex caulk',
'natural gas barbeque': 'natural gas barbecue',
'hallogen bulb flood': 'halogen bulb flood',
'roudulf': 'rudolf',
'cellular shade 23.75x37': 'cellular shade 23.75x 37',
'wyndham vanities with no tops': 'wyndham vanities without tops',
'frigidare gas range': 'frigidaire gas range',
'frigidare refrigerator': 'frigidaire refrigerator',
'dishwasher moiunting kit': 'dishwasher mounting kit',
'black refrigeratore': 'black refrigerator',
'barcello estates light fi': 'bercello estates light fi',
'kohler ch730 maintance kits': 'kohler ch730 maintenance kits',
'phillips led slimline a19': 'philips led slimline a19',
'asburn mahogany medicine cabinate': 'ashburn mahogany medicine cabinet',
'stove top replacement patr': 'stove top replacement part',
'hampton bay pendent light parts': 'hampton bay pendant light parts',
'wall mountreading light': 'wall mount reading light',
'heat on malamine tape': 'heat on melamine tape',
'vinal plank selection': 'vinyl plank selection',
'marble qwhite': 'marble white',
'reheem performance 75 gal water heater': 'rheem performance 75 gal water heater',
'cover for a double barrow grill': 'cover for a double barrel grill',
'water taste kits': 'water test kits',
'roybi gas trimmer repair kit': 'ryobi gas trimmer repair kit',
'masonary dril bits': 'masonry drill bits',
'bath and shower facet set': 'bath and shower faucet set',
'sanding sponce': 'sanding sponge',
'silestone sammples': 'silestone samples',
'ge mwr filter': 'ge mwf filter',
'rectangele garbage can': 'rectangle garbage can',
'light podt sensor': 'light post sensor',
'honewell wireless doorbell': 'honeywell wireless doorbell',
'vertical door slide mechanis': 'vertical door slide mechanism',
'2 inch bye 6 inch thick board': '2 inch by 6 inch thick board',
'28x80 contl splt rh': '28x80 control split rh',
'doors exterior with top windo': 'doors exterior with top window',
'water filter for vanitys': 'water filter for vanities',
'hampton bay geogian wall plates aged bronze': 'hampton bay georgian wall plates aged bronze',
'18 wat let lamps': '18 watt led lamps',
'qstatic cling window film': 'static cling window film',
'eletric pole hedge clippers': 'electric pole hedge clippers',
'moen voss lightin': 'moen voss lighting',
'dreamline showeruni door': 'dreamline shower door',
'dewaqlt air nailers': 'dewalt air nailers',
'hex drill chcuck': 'hex drill chuck',
'vinal siding per box': 'vinyl siding per box',
'verticle blind': 'vertical blind',
'chome framed mirror': 'chrome framed mirror',
'b onnet': 'bonnet',
'dowel sprial': 'dowel spiral',
'deck tdiles': 'deck tiles',
'driveing bits': 'driving bits',
'water putifiers': 'water purifiers',
'clyvus': 'clivus',
'old style nailshand forgednails': 'old style nails hand forged nails',
'grohe essencekitchen faucet': 'grohe essence kitchen faucet',
'femle end hose repair': 'female end hose repair',
'garden hose reair kits': 'garden hose repair kits',
'bathroom facets': 'bathroom faucets',
'kitchenaid refrigerator bottom frrezer': 'kitchenaid refrigerator bottom freezer',
'chrome/polished brass 2-handle 4-in centerset bathroom fauc': 'chrome/polished brass 2-handle 4-in centerset bathroom faucet',
'spackilng knife': 'spackling knife',
'cadelabra light bulbs led': 'candelabra light bulbs led',
'roller bracker for frameless shower doors': 'roller bracket for frameless shower doors',
'morola tile metro penny': 'merola tile metro penny',
'48 inchled tube': '48 inch led tube',
'corner sorage': 'corner storage',
'glaciar bay crystal shower': 'glacier bay crystal shower',
'tosco ivory tile': 'tosca ivory tile',
'elecric screw driver batteries': 'electric screwdriver batteries',
'mobilehome wall paint': 'mobile home wall paint',
'chainsaw rplacement chains': 'chainsaw replacement chains',
'electric guage cable': 'electric gauge cable',
'f15 t5 florescent': 'f15 t5 fluorescent',
'sprinkler conroller': 'sprinkler controller',
'wireless light sitch': 'wireless light switch',
'16x16x60boxes for moving': '16x16x60 boxes for moving',
'engeenered wood': 'engineered wood',
'frigidare microwave': 'frigidaire microwave',
'nals for subfloor': 'nails for subfloor',
'verathane': 'varathane',
'remote controlle light dimmer': 'remote controlled light dimmer',
'koehler shower door': 'kohler shower door',
'burgluar bar tool': 'burglar bar tool',
'greem roofing shingles': 'green roofing shingles',
'milwoki circular saw': 'milwaukee circular saw',
'tub faucets bronza': 'tub faucets bronze',
'bathtubdoor towel racks': 'bathtub door towel racks',
'ac exhaust extention': 'ac exhaust extension',
'outside deck boards composit': 'outside deck boards composite',
'4inch ligh junction box': '4 inch light junction box',
'gardenn containers': 'garden containers',
'plant continers': 'plant containers',
'3 paint bbrush': '3 paint brush',
'26 in woodsaddle stool': '26 in wood saddle stool',
'adhensive with nozzle': 'adhesive with nozzle',
'swanstone kitchen sink accesories': 'swanstone kitchen sink accessories',
'pvc to corragated connector': 'pvc to corrugated connector',
'unsanded grout bisquit': 'unsanded grout biscuit',
'spray paint rust-oleum gray': 'spray paint rustoleum gray',
'brushes drils': 'brushed drills',
'indoor mounting tpe': 'indoor mounting tape',
'indoor grow light blubs': 'indoor grow light bulbs',
'thinset morter': 'thin set mortar',
'flourescent g25 60watt': 'fluorescent g25 60 watt',
'diatemaceous earth': 'diatomaceous earth',
'23\' biview surface mount med cab chestnut': '23\' bi view surface mount med cab chestnut',
'72 hour carpt': '72 hour carpet',
'2 \' galvanise street 90': '2 \' galvanized street 90',
'maytab bravos': 'maytag bravos',
'600w incandecent toggle dimmer': '600w incandescent toggle dimmer',
'galvanized wire 10 guage': 'galvanized wire 10 gauge',
'assemble hight 17 inches': 'assembled height 17 inches',
'pvc t coulpler': 'pvc t coupler',
'water heatere drain pan': 'water heater drain pan',
'faucet steam washers': 'faucet stem washers',
'heat window filtm': 'heat window film',
'dewalt circlular saw blades': 'dewalt circular saw blades',
'5plinth block': 'plinth block',
'french pation doors with sidepanels': 'french patio doors with side panels',
'30 unfinish filler': '30 unfinished filler',
'home depot in cambrige': 'home depot in cambridge',
'faucet siphon hose connecter': 'faucet siphon hose connector',
'black out doors spray paint': 'black outdoor spray paint',
'anderson storm door full view easy install': 'andersen storm door full view easy install',
'ice marker water kits': 'ice maker water kits',
'adhesive magnetized roll': 'adhesive magnetic roll',
'metal kkitchen cabines': 'metal kitchen cabinets',
'2\' x 1 1/2 reducing busing thread': '2\' x 1 1/2 reducing bushing threaded',
'abs rambit pipe saver': 'abs rambut pipe saver',
'33 in w x 18 icnh depth vanity': '33 in w x 18 inch depth vanity',
'built in landry shelving': 'built in laundry shelving',
'grey rubbermaid trash barrells': 'grey rubbermaid trash barrels',
'sawall blades': 'sawzall blades',
'9v battery ackup': '9v battery backup',
'1/2 in. fip x 7/16 in. or 1/2 in. slip joint angle stop valv': '1/2 in. fip x 7/16 in. or 1/2 in. slip joint angle stop valve',
'peir block': 'pier block',
'under ceiling garag storage': 'under ceiling garage storage',
'stone effects backsplash cool fushion': 'stone effects backsplash cool fusion',
'desoldering vacum pump': 'desoldering vacuum pump',
'elrctric welders': 'electric welders',
'unfinushed kitchen cabinets': 'unfinished kitchen cabinets',
'3 pole range reciptical': '3 pole range receptacle',
'sink cutting oard': 'sink cutting board',
'steel tubing falanges': 'steel tubing flanges',
'outdoor unskid tiles': 'outdoor non skid tiles',
'6 round headlag bolt': '6 round head lag bolt',
'cyprees fence': 'cypress fence',
'75 qrt cooler with wheels': '75 quart cooler with wheels',
'buit in themostat': 'built in thermostat',
'speacalty bit set': 'specialty bit set',
'curtain rod classic sqaure finial': 'curtain rod classic square finial',
'silk poinsetia': 'silk poinsettia',
'1 1/4 pvcsch 80': '1 1/4 pvc sch 80',
'grill ousite door': 'grill outside door',
'lumionaire': 'luminaire',
'adienne bathroom vanity light': 'adrienne bathroom vanity light',
'chashing led lights': 'chasing led lights',
'24 inch vessal tops': '24 inch vessel tops',
'co2 detector kiddie': 'co2 detector kidde',
'white glazed 4 tilw': 'white glazed 4 tile',
'wood lattace': 'wood lattice',
'premaid stair railing': 'premade stair railing',
'3 function double walll switch': '3 function double wall switch',
'koehler shower faucet with spray': 'kohler shower faucet with spray',
'askley electric fireplace': 'ashley electric fireplace',
'blind for paladian': 'blind for paladin',
'regancy railin': 'regency railing',
'weatherside purit': 'weatherside purity',
'vent a hood dampr': 'vent a hood damper',
'light tropper 2x4': 'light troffer 2x4',
'30 amp generater receptical': '30 amp generator receptacle',
'prefab wood gate panals': 'prefab wood gate panels',
'floating corner shelfing': 'floating corner shelving',
'fridgidaire dehumidifier': 'frigidaire dehumidifier',
'pegs for cabinent shelves': 'pegs for cabinet shelves',
'100 amp to 200a lit': '100 amp to 200 a lot',
'decorative metal sceen': 'decorative metal screen',
'lacross weather pro center': 'lacrosse weather pro center',
'behr flat white marque': 'behr flat white marquee',
'high output floresant': 'high output fluorescent',
'behr hawian paint': 'behr hawaiian paint',
'pressure vaccuum breaker o-ring': 'pressure vacuum breaker o-ring',
'psint gun': 'paint gun',
'wine coller': 'wine cooler',
'rug ruunners': 'rug runners',
'clock control for fridgidare gas stove': 'clock control for frigidaire gas stove',
'outlet expsnsion surge protector': 'outlet expansion surge protector',
'rigid pipe threader': 'ridgid pipe threader',
'electical box': 'electrical box',
'insect granuels': 'insect granules',
'compsit outside corner': 'composite outside corner',
'cabinet kitchen ligth': 'cabinet kitchen light',
'dewalt ratchet srewdriver': 'dewalt ratchet screwdriver',
'18.5 outside chair cushiobs': '18.5 outside chair cushions',
'fenching and gate latches': 'fencing and gate latches',
'heater for refrigertor': 'heater for refrigerator',
'motion detect indoor': 'motion detector indoor',
'refrigerater french doors ge brand': 'refrigerator french doors ge brand',
'tiki tourches': 'tiki torches',
'gren house kits': 'greenhouse kits',
'5000 btu aircondition': '5000 btu air conditioner',
'airator dishwasher': 'aerator dishwasher',
'2x6 metal brakets': '2x6 metal brackets',
'weldn 3': 'weldon 3',
'ceiling paint pray': 'ceiling paint spray',
'flourescent fixture metal parts': 'fluorescent fixture metal parts',
'natural hickery kitchen cabinets': 'natural hickory kitchen cabinets',
'kitchen aide dishwasher': 'kitchenaid dishwasher',
'led track lightning systems': 'led track lighting systems',
'duplex receptacle nickle': 'duplex receptacle nickel',
'12 foot ceadar': '12 foot cedar',
'faux wood shade 100 jnches': 'faux wood shade 100 inches',
'contracto0r hose': 'contractor hose',
'lspacers for toilet bowl': 'spacers for toilet bowl',
'aftificial prelit christmas trees': 'artificial prelit christmas trees',
'paint colores by rooms': 'paint colors by rooms',
'warm whit led bulb': 'warm white led bulb',
'clamps for unistruct': 'clamps for unistrut',
'kitchen trviso price phister': 'kitchen treviso price pfister',
'10guage copper wire 3 stand': '10 gauge copper wire 3 stand',
'deep frezer with glass cover': 'deep freezer with glass cover',
'powder clorine shock treatment': 'powder chlorine shock treatment',
'galvanaized can': 'galvanized can',
'prebent aluminum facia': 'prebent aluminum fascia',
'vinyl scrapper for jack hammer': 'vinyl scraper for jack hammer',
'dwaft outside plants': 'dwarf outside plants',
'tilebath walls small': 'tile bath walls small',
'2 ton aircondition': '2 ton air conditioner',
'martha stewart metalic paint gallon': 'martha stewart metallic paint gallon',
'schilage electronic deadbolts locks': 'schlage electronic deadbolts locks',
'60x65shower doors': '60x65 shower doors',
'tile slide cuter': 'tile slide cutter',
'eagle peak hoickory': 'eagle peak hickory',
'gas black range worldpool': 'gas black range whirlpool',
'trigger makita skillsaw': 'trigger makita skil saw',
'hardi lap hanger': 'hardie lap hanger',
'master flow insolated duct wrap': 'master flow insulated duct wrap',
'replacment stove knobs': 'replacement stove knobs',
'outdoor alrm': 'outdoor alarm',
'wireless outdoor thermom': 'wireless outdoor thermometer',
'faun paint': 'fawn paint',
'wireless security caamera': 'wireless security camera',
'fiet electric led gu10': 'feit electric led gu10',
'stair unners': 'stair runners',
'stainstess steel spray paint': 'stainless steel spray paint',
'mount blanv': 'mont blanc',
'riobi power tool combo': 'ryobi power tool combo',
'24 sydey collection': '24 sydney collection',
'air compresser': 'air compressor',
'no tresspassing signs': 'no trespassing signs',
'flexable 6 inch': 'flexible 6 inch',
'wall beveled framelessmirror': 'wall beveled frameless mirror',
'slidein range bisque': 'slide in range bisque',
'router templit kits letters': 'router template kits letters',
'american sandard 1660.225,': 'american standard 1660.225,',
'onyx sand porcelian': 'onyx sand porcelain',
'watherproof electrical boxes': 'weatherproof electrical boxes',
'carpet remmnant': 'carpet remnant',
'8\' sigle wall gal pipe': '8\' single wall galv pipe',
'byfold hinges': 'bi fold hinges',
'terra cota quarry stones': 'terracotta quarry stones',
'rustolem appliance touch up paint': 'rustoleum appliance touch up paint',
'rain nickle': 'rain nickel',
'whirlpool light bulb part 8206232': 'whirlpool light bulb part 8206232a',
'Vigaro fall fertilizer': 'Vigoro fall fertilizer',
'pneumatic cynlinder': 'pneumatic cylinder',
'20 ft electical romex': '20 ft electrical romex',
'medicine cabinets recessable black': 'medicine cabinets recessed black',
'krass 30 inch kitchen sink': 'kraus 30 inch kitchen sink',
'stainless steel grat': 'stainless steel grate',
'suncort 8\' duct fans': 'suncourt 8\' duct fans',
'nutmag mirrors': 'nutmeg mirrors',
'clawfoot tub faucit kit': 'clawfoot tub faucet kit',
'protective pper': 'protective paper',
'touchless dishwashing kintchen dispenser': 'touchless dishwashing kitchen dispenser',
'air temperture contorl valve': 'air temperature control valve',
'melinger hand truck wheals': 'melinger hand truck wheels',
'watt premiere water filters': 'watt premier water filters',
'weed killer spray contaner': 'weed killer spray container',
'18in hardware coth': '18in hardware cloth',
'ac window supprt': 'ac window support',
'vegetable plannter': 'vegetable planter',
'soap punp': 'soap pump',
'wall paper murial glue': 'wallpaper mural glue',
'vertical binds hardware': 'vertical blinds hardware',
'rubbermaid verital sheds': 'rubbermaid vertical sheds',
'1/2 in. extension joint': '1/2 in. expansion joint',
'curtin rods': 'curtain rods',
'edge glued rounda': 'edge glued rounds',
'plywood edge taope': 'plywood edge tape',
'36\' copoktop': '36\' cooktop',
'curtains non black out': 'curtains not blackout',
'honolule center drain': 'honolulu center drain',
'toliet snake': 'toilet snake',
'black and deckerbattery pack': 'black and decker battery pack',
'beer and wine combination frigerator': 'beer and wine combination refrigerator',
'mess wire fencing': 'mesh wire fencing',
'ecosmart 90 led daylight br30': 'ecosmart 90w led daylight br30',
'miniture bulbs 2 pin': 'miniature bulbs 2 pin',
'dishwasher water connection vlave': 'dishwasher water connection valve',
'ant bait raps': 'ant bait traps',
'coragated aluimin special order': 'corrugated aluminum special order',
'carpot canopy 10x20': 'carport canopy 10x20',
'10 foot white ethjernet cable': '10 foot white ethernet cable',
'polished chrome cbinet pulls': 'polished chrome cabinet pulls',
'cooper tubing': 'copper tubing',
'dwarf pereniel plants': 'dwarf perennial plants',
'lampost motion detector': 'lamp post motion detector',
'3 gutter oulets': '3 gutter outlets',
'kohler shower ddoors for tubs in nickel': 'kohler shower doors for tubs in nickel',
'zep liquid air fresher': 'zep liquid air freshener',
'rewiring built in oven': 'wiring built in oven',
'10/4 SJ CABLE': '10/4 SJO CABLE',
'tempered glass wndow': 'tempered glass window',
'mataeials needed for paver patio': 'materials needed for paver patio',
'tankles water heater gas outdoor': 'tankless water heater gas outdoor',
'ypermethrin': 'cypermethrin',
'kwikset halifax door leaver': 'kwikset halifax door lever',
'ryobi coordless 18v starter kit': 'ryobi cordless 18v starter kit',
'habor gazeebo': 'harbor gazebo',
'electric barbeque grills': 'electric barbecue grills',
'rasin raised garden bed': 'resin raised garden bed',
'barbeque grills big and easy': 'barbecue grills big and easy',
'floor warming matt': 'floor warming mat',
'machette': 'machete',
'cool tube lgts': 'cool tube lights',
'universal faucet connect': 'universal faucet connector',
'daltile hexgon': 'daltile hexagon',
'hurracaine brackets': 'hurricane brackets',
'martha stewart curtiins': 'martha stewart curtains',
'byfold doors': 'bifold doors',
'2 tier adjustable cabinet orgainzer': '2 tier adjustable cabinet organizer',
'7w compact flourescent bulb': '7w compact fluorescent bulb',
'singel wall stove pipe': 'single wall stove pipe',
'wheeld trimmer': 'wheeled trimmer',
'boader rocks': 'border rocks',
'crown moldinf jig': 'crown molding jig',
'small refridgerators': 'small refrigerators',
'blind courner': 'blind corner',
'asphault gap repair': 'asphalt gap repair',
'no. 30 ridgid cutting wheel': 'no. 30 rigid cutting wheel',
'battery cable conector': 'battery cable connector',
'coranado baseboard pine': 'coronado baseboard pine',
'cerrowire 18 gauge': 'cerro wire 18 gauge',
'universal exstention cord': 'universal extension cord',
'wirlpool counterdepth side by side refrigrator': 'whirlpool counter depth side by side refrigerator',
'cedar bahr 502 stain': 'cedar behr 502 stain',
'small tracerse rods': 'small traverse rods',
'yelloe safet tape': 'yellow safety tape',
'elctric heating lamps': 'electric heating lamps',
't8 flourescent bulbs': 't8 fluorescent bulbs',
'u bents fluorescent': 'u bend fluorescent',
'pergo lamate flooring': 'pergo laminate flooring',
'sweenys mole and gopher repelant': 'sweeney\'s mole and gopher repellent',
'rg6 connecto': 'rg6 connector',
'ge electriv burners': 'ge electric burners',
'replacement part for koehler toilet kb3': 'replacement part for kohler toilet kb3',
'furiture paint, stain and varnish': 'furniture paint, stain and varnish',
'mission prarie camber top slab': 'mission prairie camber top slab',
'mirr edge': 'mirror edge',
'orbital sanding disck': 'orbital sanding disc',
'quickrete 50 lb mix': 'quikrete 50 lb mix',
'high efficiency dust baf rigid vac': 'high efficiency dust bag ridgid vac',
'liminate flooring cleaning': 'laminate flooring cleaning',
'gtxworks trimmer spools': 'gt worx trimmer spools',
'securty bar mounts': 'security bar mounts',
'fall supression kit': 'fall suppression kit',
'weatherproof boom box': 'waterproof boombox',
'geld wen 2500 96 x 36': 'jeld wen 2500 96 x 36',
'enfineered floors drifting sand': 'engineered floors drifting sand',
'well pump back presure valve': 'well pump back pressure valve',
'heavy duty shevlving': 'heavy duty shelving',
'mmodel': 'model',
'frigidare stainless refrig': 'frigidaire stainless refrig',
'rusteoulm spray paint': 'rustoleum spray paint',
't5 high output ligh': 't5 high output light',
'sandpap': 'sandpaper',
'cerowire 12 gauge': 'cerro wire 12 gauge',
'what rings for toitets': 'what rings for toilets',
'infrared theomomter': 'infrared thermometer',
'1x6 toungh groove': '1x6 tongue groove',
'v ceader board': 'v cedar board',
'sodpstone': 'soapstone',
'10 yeaer smoke detectors/carbon monoxide combo': '10 year smoke detectors/carbon monoxide combo',
'kkohler toilet seat': 'kohler toilet seat',
'pink toliet seat elongated': 'pink toilet seat elongated',
'flexiblr bit': 'flexible bit',
'coleman instasmart grill': 'coleman instastart grill',
'exide battery 75,car battrey': 'exide battery 75,car battery',
'black cherry stainer': 'black cherry stain',
'1x4 pre primed mfd trim': '1 x 4 pre primed mdf trim',
'mnt movr combo shovel': 'mnt move combo shovel',
'100 watt candlabra bulb': '100 watt candelabra bulb',
'samsung black stainles': 'samsung black stainless',
'dewalt jig saw blad': 'dewalt jig saw blade',
'alluminum downspout connector': 'aluminum downspout connector',
'alltyp of fences': 'all type of fences',
'clow hammer 16 0z': 'claw hammer 16 0z',
'tomatoe plants': 'tomato plants',
'white lacquer wall selves': 'white lacquer wall shelves',
'pressure guage': 'pressure gauge',
'slid pad': 'slide pad',
'female hose connectore': 'female hose connector',
'solor lamp outside': 'solar lamp outside',
'daltile urban camoflogue': 'daltile urban camouflage',
'deocorative screws for hanging pictures': 'decorative screws for hanging pictures',
'kitchen composie double sinks': 'kitchen composite double sinks',
'whitesilicone': 'white silicone',
'self contained recepticles': 'self contained receptacles',
'brass handel door': 'brass handle door',
'charley brown christmas trees': 'charlie brown christmas trees',
'carbon fiber vinel': 'carbon fiber vinyl',
'phillips fluorescent 40': 'philips fluorescent 40',
'36 inxh return air grill': '36 inch return air grill',
'garden pond pump impellor': 'garden pond pump impeller',
'vinal flooring 25 year warranty': 'vinyl flooring 25 year warranty',
'mulcing blades for troy built': 'mulching blades for troy bilt',
'5 1/4 deckboard': '5 1/4 deck board',
'plaste dip': 'plasti dip',
'cemnt pads for makita bo5030': 'cement pads for makita bo5030',
'ge beverage refriderator': 'ge beverage refrigerator',
'bathroom plummbing': 'bathroom plumbing',
'gas pire column': 'gas fire column',
'confrence': 'conference',
'clock cuitain rod wood': 'clock curtain rod wood',
'decrotive outdoor lighting': 'decorative outdoor lighting',
'ballast for single t12 fluorscent bulb': 'ballast for single t12 fluorescent bulb',
'workstar cordless and recharable work light': 'workstar cordless and rechargeable work light',
'light bulb 250 cfl': 'light bulb 250w cfl',
'rubber gromet': 'rubber grommet',
'spray metallicpaint': 'spray metallic paint',
'paint quart zise': 'paint quart size',
'blinds for portch': 'blinds for porch',
'sable browj 95': 'sable brown 95',
'1/2 conduet': '1/2 conduit',
'wooden curton rod brackets': 'wooden curtain rod brackets',
'corbels and shelfs': 'corbels and shelves',
'seimens typ qt breaker': 'siemens type qt breaker',
'steel builco': 'steel bilco',
'metal joinst': 'metal joist',
'externol patio doors': 'external patio doors',
'FENSE LIGHTING': 'FENCE LIGHTING',
'oil bronzed wine glass rack': 'oiled bronze wine glass rack',
'klien lether pouch': 'klein leather pouch',
'shark rocket filtes': 'shark rocket filters',
'4x7 ruggs': '4 x 7 rugs',
'24 elicreic stove': '24 electric stove',
'grill hasmilton': 'grill hamilton',
'air vents for plumping': 'air vents for plumbing',
'gazebo with shelfs': 'gazebo with shelves',
'expanding plastic sleeves for scews': 'expanding plastic sleeves for screws',
'oli rubbed bronze drain': 'oil rubbed bronze drain',
'clothsline rope': 'clothesline rope',
'stove gas replacement knops': 'stove gas replacement knobs',
'rechargale batteries for solar lights': 'rechargeable batteries for solar lights',
'standard artificial grasa synthetic lawn turf': 'standard artificial grass synthetic lawn turf',
'new deck for rtz 50': 'new deck for rzt 50',
'wire shelv liner': 'wire shelf liner',
'wood paint with primerin blue': 'wood paint with primer in blue',
'fabreeze': 'febreze',
'ceilng fan': 'ceiling fan',
'manuel for 425 - 1649': 'manual for 425 - 1649',
'14 in dimond circular saw blade': '14 in diamond circular saw blade',
'berhr solid 213 deep': 'behr solid 213 deep',
'driveway m arkers': 'driveway markers',
'commercil threshold': 'commercial threshold',
'multinozzle spray painting': 'multi nozzle spray painting',
'shower nitch': 'shower niche',
'1/2x1/2 quater round': '1/2 x 1/2 quarter round',
'Insulted work gloves': 'Insulated work gloves',
'5000 lumnes': '5000 lumens',
'magnets for gromets': 'magnets for grommets',
'toro springkler': 'toro sprinkler',
'motion sensoring black decorative lamp': 'motion sensing black decorative lamp',
'proclean concentrated drain cleaner': 'pro clean concentrated drain cleaner',
'feather river doorsth sidelights': 'feather river doors sidelights',
'ridgid powerwasher parts': 'ridgid power washer parts',
'skill pressure sander': 'skil pressure sander',
'outdoor vertical sheda': 'outdoor vertical sheds',
'brick web thin brick flats': 'brickweb thin brick flats',
'airguard undelayment': 'airguard underlayment',
'toyotaa': 'toyota',
'round rug for kitch': 'round rug for kitchen',
'round one piece tiolet': 'round one piece toilet',
'sppeed square': 'speed square',
'adirondak chair': 'adirondack chair',
'hickory hadwre touch of spring': 'hickory hardware touch of spring',
'garge door handle': 'garage door handle',
'whiteled tree': 'white led tree',
'airosol epoxy paint': 'aerosol epoxy paint',
'ice ring machine': 'ice rink machine',
'deep expresso walnut/new ellenton': 'deep espresso walnut/new ellenton',
'interior walls bieges brown': 'interior walls beige brown',
'pet disinfectent': 'pet disinfectant',
'altra furniture parsons credenza desk with drawer and bookc': 'altra furniture parsons credenza desk with drawer and books',
'gorilla gold cpvc gluetm': 'gorilla gold cpvc glue',
'aligator clips': 'alligator clips',
'irrigation pipe connectoer': 'irrigation pipe connector',
'citronella fire pot fue': 'citronella fire pot fuel',
'garden spreklers heads': 'garden sprinklers heads',
'light swith insulation': 'light switch insulation',
'dual lock 3m veclro': 'dual lock 3m velcro',
'water proof mc connecter': 'waterproof dc connector',
'snow blowerr scraper blade': 'snowblower scraper blade',
'vesel tub': 'vessel tub',
'carrrs': 'careers',
'odl 6\' x 6\'retractable screens': 'odl 6\' x 6 retractable screens',
'outdoord storage locker': 'outdoor storage locker',
'standing seam roof panals': 'standing seam roof panels',
'phillips 65w 2 pack': 'philips 65w 2 pack',
'2 squares double 5 vinly siding': '2 squares double 5 vinyl siding',
'fabric steam cleamer': 'fabric steam cleaner',
'scikkens stain': 'sikkens stain',
'polyethylne cap': 'polyethylene cap',
'decorative interor glass doors': 'decorative interior glass doors',
'vanity top for two vessell': 'vanity top for two vessel',
'giant bird of paridise': 'giant bird of paradise',
'almeda hickory': 'alameda hickory',
'cabinet ba rpulls in bronze': 'cabinet bar pulls in bronze',
'l screwa': 'l screws',
'johan deer 0 turns': 'john deere 0 turns',
'milwankee 7 pc set': 'milwaukee 7 pc set',
'faucet pl801l 18 guage': 'faucet pl801l 18 gauge',
'12 light bronze chandilier': '12 light bronze chandelier',
'flourecent light plastic covers': 'fluorescent light plastic covers',
'roof pannel foam': 'roof panel foam',
'under cabinet lighting ro-hs': 'under cabinet lighting rohs',
'round lshower kit': 'round shower kit',
'concreet enchors': 'concrete anchors',
'woodwen pallet': 'wooden pallet',
'shigles': 'shingles',
'comercial plank doors': 'commercial plank doors',
'stainless steel kithen faucet with soap dispenser': 'stainless steel kitchen faucet with soap dispenser',
'm4 50 srcew': 'm4 50 screw',
'splitbolt connector': 'split bolt connector',
'charming 18 roll': 'charmin 18 roll',
'table glass oatu': 'table glass oahu',
'kohlor flush for toilet tank 4421': 'kohler flush for toilet tank 4421',
'outdoor pendant lioghting': 'outdoor pendant lighting',
'24 inflex gas line': '24 in flex gas line',
'lawn mower rechargeable batterys': 'lawn mower rechargeable batteries',
'merola metalic tile': 'merola metallic tile',
'above ground pool vaccume': 'above ground pool vacuum',
'bosss water softner': 'boss water softener',
'moen one handel kitchen faucet repair parts': 'moen one handle kitchen faucet repair parts',
'sanding machinehardwood floors': 'sanding machine hardwood floors',
'super patch driverway sealler': 'super patch driveway sealer',
'sschlueter shower system': 'schluter shower system',
'offset flang': 'offset flange',
'aluminium tube rectangle': 'aluminium tube rectangular',
'legrad keystone cat5e jack': 'legrand keystone cat5e jack',
'yellow jacket extenison cord': 'yellow jacket extension cord',
'Habachi': 'Hibachi',
'mini pendant braket': 'mini pendant bracket',
'hose to presure washer': 'hose to pressure washer',
'gliddon speed wall': 'glidden speed wall',
'new age produucts': 'new age products',
'archor tub and shower faucet trim': 'archer tub and shower faucet trim',
'space saving stoage': 'space saving storage',
'vinyl flooring that clicks togther': 'vinyl flooring that clicks together',
'gladden smooth stone': 'glidden smooth stone',
'knape vogt baseket': 'knape vogt basket',
'ul liquidthight 25': 'ul liquidtight 25',
'white glossy furniture pain': 'white gloss furniture paint',
'square bannister': 'square banister',
'greenh wall paint': 'green wall paint',
'tile medalions for the floor or wall': 'tile medallions for the floor or wall',
'milwalke brewers garden flag': 'milwaukee brewers garden flag',
'versatiube': 'versatube',
'kenocen can nozzle': 'kenken can nozzle',
'mosaic esterior': 'mosaic exterior',
'winow wheels': 'window wheels',
'stud popers': 'stud poppers',
'trane 2.5 toon 13 seer heat pump': 'trane 2.5 ton 13 seer heat pump',
'ultra vue quick screeen': 'ultra vue quick screen',
'watterproof cleated boots': 'waterproof cleated boots',
'hdx pneumaitic paint': 'hdx pneumatic paint',
'biscue dishwashers': 'bisque dishwashers',
'sunbrella sipcovers': 'sunbrella slipcovers',
'miracle grow water absorbing crystals': 'miracle gro water absorbing crystals',
'disposal rim and stopperkohler': 'disposal rim and stopper kohler',
'long brakets': 'long brackets',
'freplace gloves': 'fireplace gloves',
'ridgid power drve pipe threadrs': 'ridgid power drive pipe threader',
'12x24 shefl': '12x24 shelf',
'1x6 prime molding': '1x6 primed molding',
'countertop soap dispensor': 'countertop soap dispenser',
'bushbutton for door bell': 'push button for doorbell',
'cauk saver': 'caulk saver',
'rubber stipper': 'rubber stopper',
'16 inch flourescent': '16 inch fluorescent',
'pendents amber': 'pendants amber',
'newtone broan round 751': 'nutone broan round 751',
'danze shower vlve': 'danze shower valve',
'wooden track drawer replacment': 'wooden track drawer replacement',
'single granit bathroom vanity': 'single granite bathroom vanity',
'oval steele tubs': 'oval steel tubs',
'liquid weed and feeed': 'liquid weed and feed',
'outodoor oatoman': 'outdoor ottoman',
'nutone vaccum wall plate': 'nutone vacuum wall plate',
'collor clamp': 'collar clamp',
'pure air ultra filtration syste,m': 'pure air ultra filtration system',
'llantana': 'lantana',
'white melimine cabinet': 'white melamine cabinet',
'2-handlet diverter repair kit': '2-handle diverter repair kit',
'mosiac lamps': 'mosaic lamps',
'exterior pipeinsulation': 'exterior pipe insulation',
'warm espresso bamboo quarteround': 'warm espresso bamboo quarter round',
'hardwood medialons': 'hardwood medallions',
'tub/hand shoer diverter with trim': 'tub/hand shower diverter with trim',
'locite 2 plus 1': 'loctite 2 plus 1',
'kwiksest door handle delta': 'kwikset door handle delta',
'frame nail hitschi': 'frame nailer hitachi',
'30 mirrow medicine cabinet': '30 mirrored medicine cabinet',
'pecane trees': 'pecan trees',
'lifeproof carpet sample lower trasure': 'lifeproof carpet sample lower treasure',
'umbrell hole ring': 'umbrella hole ring',
'melmane wood': 'melamine wood',
'melomine accessories': 'melamine accessories',
'windows single hang': 'windows single hung',
'portabe bar': 'portable bar',
'crystable table set lamps': 'crystal table set lamps',
'schlage handleset bermingham': 'schlage handleset birmingham',
'lp gas converion kit': 'lp gas conversion kit',
'quart exterior semi glass enamel': 'quart exterior semi gloss enamel',
'woodrx ultra natural': 'wood rx ultra natural',
'brushed barringnton': 'brushed barrington',
'leather lgue': 'leather glue',
'moen bronze low arch faucet': 'moen bronze low arc faucet',
'18 inch linen closit': '18 inch linen closet',
'bear paint green myth': 'behr paint green myth',
'solar light rechargable batteries': 'solar light rechargeable batteries',
'solar powered emergancy unit': 'solar powered emergency unit',
'kohler 3 handle shower reapair kit': 'kohler 3 handle shower repair kit',
'thermadore black cast kitchen sink': 'thermador black cast kitchen sink',
'dental shelf door': 'dentil shelf door',
'seed starting mixx': 'seed starting mix',
'rubberaid dust mop': 'rubbermaid dust mop',
'phillips bugle-head finethread sharp': 'phillips bugle-head fine thread sharp',
'black laminate shelfing': 'black laminate shelving',
'ice maker cylinoid ge': 'ice maker solenoid ge',
'home decorators mantle green': 'home decorators mantel green',
'perrenial white daisy like': 'perennial white daisy like',
'chamber-top halifax glass dooor': 'chamber-top halifax glass door',
'depp well socket set': 'deep well socket set',
'hanger racc vertical': 'hanger rack vertical',
'tool package with pilers,needlenose': 'tool package with pliers,needlenose',
'fome core board': 'foam core board',
'colaroo outdoor shades corded': 'coolaroo outdoor shades corded',
'decoator chain': 'decorator chain',
'rust oleum dark hunter green spray enamel paint': 'rustoleum dark hunter green spray enamel paint',
'lights and siloutte': 'lights and silhouette',
'real live orchred plants': 'real live orchid plants',
'2ftx3ft industrail rbber mat': '2ftx3ft industrial rubber mat',
'fernace vent shut off': 'furnace vent shut off',
'cedar wood balisters': 'cedar wood balusters',
'gliden premium semi gloss quart': 'glidden premium semi gloss quart',
'mosaic tile costal mist': 'mosaic tile coastal mist',
'toilet lever kphler brass': 'toilet lever kohler brass',
'front doors - poinye zinc': 'front doors - pointe zinc',
'matte bailey mohogany': 'matte bailey mahogany',
'wesleyand': 'wesleyan',
'plasic diffuser': 'plastic diffuser',
'cover kage for pet': 'cover page for pet',
'network agapter': 'network adapter',
'whitehaus bathroom sinl': 'whitehaus bathroom sink',
'icey tech': 'icey tek',
'kaorik wine': 'kalorik wine',
'susbenders': 'suspenders',
'policarbonate case': 'polycarbonate case',
'shaw livng rugs model rac66': 'shaw living rugs model rac66',
'carpet in bassment': 'carpet in basement',
'bifold doorsfold plantation': 'bi fold doors fold plantation',
'handheld seed speader': 'handheld seed spreader',
'hot dipped galvinized coil nails': 'hot dipped galvanized coil nails',
'hand saw sharpner': 'hand saw sharpener',
'mattress foam protecter': 'mattress foam protector',
'n utdriver bit': 'nut driver bit',
'lattice wwod tone': 'lattice wood tone',
'our door receptacles': 'outdoor receptacles',
'great outdors': 'great outdoors',
'exterior string ligts': 'exterior string lights',
'dog ,cat,repellant': 'dog ,cat,repellent',
'20a wht nylon duple': '20a wht nylon duplex',
'fatmax leveler premier': 'fatmax level premier',
'ralph laren brown paints': 'ralph lauren brown paints',
'liquid bi fuels': 'liquid biofuels',
'scrubbin sponge': 'scrubbing sponge',
'ceramic tile tooth brush and soap holder': 'ceramic tile toothbrush and soap holder',
'cultured marbl;e shower walls': 'cultured marble shower walls',
'did recorder player': 'dvd recorder player',
'golith': 'goliath',
'black maytag french door refrigirator': 'black maytag french door refrigerator',
'stair nose santos maogani': 'stair nose santos mahogany',
'l tub fauctes': 'l tub faucets',
'eyebolt brass': 'eye bolt brass',
'terracotta exteriorpaint': 'terracotta exterior paint',
'manuel venting sky light': 'manual venting skylight',
'bathroom fan motion sencer': 'bathroom fan motion sensor',
'hard start capacitator': 'hard start capacitor',
'windows gazing bead': 'windows glazing bead',
'vanitiy top back splach': 'vanity top backsplash',
'large yellow screw inground anchors': 'large yellow screw in ground anchors',
'heavy duty polyurathane': 'heavy duty polyurethane',
'folfable stool': 'foldable stool',
'charlston south carolina': 'charleston south carolina',
'pine flooring, tang end grove': 'pine flooring, tongue and groove',
'starter fuil': 'starter fuel',
'granite colr group prices': 'granite color group prices',
'calanvreas': 'calaveras',
'golden krome spray': 'gold chrome spray',
'g e micewave': 'g e microwave',
'sheet meatal hole cutter': 'sheet metal hole cutter',
'zurn hot short stemcartridge': 'zurn hot short stem cartridge',
'outdoor picture ftames': 'outdoor picture frames',
'shower pad porceleain': 'shower pan porcelain',
'battery under counter lightening': 'battery under counter lighting',
'elictric door bail': 'electric door bell',
'barbeque insert': 'barbecue insert',
'barclay glass bathroom shelfs': 'barclay glass bathroom shelves',
'preserva wood caryon': 'preserva wood crayon',
'white grey floor tile mosiac': 'white grey floor tile mosaic',
'minwax wood puty': 'minwax wood putty',
'the govenore': 'the governor',
'diverter 5 in. tub spout with slip fit connection in chrom': 'diverter 5 in. tub spout with slip fit connection in chrome',
'vinyl plank blue slatr': 'vinyl plank blue slate',
'frameless shwoer panel': 'frameless shower panel',
'virtue usa huntshire': 'virtu usa huntshire',
'3.5 Hindge': '3.5 Hinge',
'round plastic tablrs': 'round plastic tables',
'paint storage contaiers': 'paint storage containers',
'centerset 2-handle weall': 'centerset 2-handle wall',
'wax ring with self taping bolts': 'wax ring with self tapping bolts',
'gama sonic winsor pier base': 'gama sonic windsor pier base',
'pilla windows': 'pella windows',
'dresser acessories': 'dresser accessories',
'duel compression 1/2 x 3/8 valve': 'dual compression 1/2 x 3/8 valve',
'american atanderd plebe 4086': 'american standard plebe 4086',
'dyson ball allergy vaccume': 'dyson ball allergy vacuum',
'low woltage relay': 'low voltage relay',
'hand steam cleanere': 'hand steam cleaner',
'eiectric concrte mixer': 'electric concrete mixer',
'pemco sill extender': 'pemko sill extender',
'silver branzing rods': 'silver brazing rods',
'sanding beltsr': 'sanding belts',
'dorr faceplates': 'door faceplates',
'stainless steel ball beating for hinges': 'stainless steel ball bearing for hinges',
'stabilty': 'stability',
'hose bibb replacement valve': 'hose bib replacement valve',
'long shower curtins': 'long shower curtains',
'crub rubber': 'crumb rubber',
'swivel saftey cover': 'swivel safety cover',
'makita oscilating saw': 'makita oscillating saw',
'whithaus faucet speckled brass': 'whitehaus faucet speckled brass',
'energy efficent skylight': 'energy efficient skylight',
'garden seed packs': 'garden seed packets',
'boshe double bevel sliding miter saw': 'bosch double bevel sliding miter saw',
'taylor test lit': 'taylor test kit',
'chargril grill': 'charbroil grill',
'over ran': 'overran',
'recipricating saw 15 amp': 'reciprocating saw 15 amp',
'mikita 18v 2.6 ah': 'makita 18v 2.6 ah',
'no burn spry': 'no burn spray',
'cuctis soil': 'cactus soil',
'brushed stainless cabin ate hardware': 'brushed stainless cabinet hardware',
'fork lift strps': 'forklift straps',
'electrian': 'electrician',
'doorbell chimes and transformr': 'doorbell chimes and transformer',
'faux diamondplate': 'faux diamond plate',
'milstead vintage maple engineered flooring': 'millstead vintage maple engineered flooring',
'ce tech coaxial cablenail in clips': 'ce tech coaxial cable nail in clips',
'bq heat distributipn plates': 'bbq heat distribution plates',
'metal lath stuko': 'metal lath stucco',
'cord less drill portcable': 'cordless drill porter cable',
'round bulb sting lights': 'round bulb string lights',
'lp coversion kit maytag dryer': 'lp conversion kit maytag dryer',
'chase lounger covers': 'chaise lounge covers',
'insl-x pure step': 'insl-x sure step',
'gerber knife tactiical': 'gerber knife tactical',
'deecals number': 'decals number',
'hampton bat 26\'. w tilt out hamper white': 'hampton bay 26\'. w tilt out hamper white',
'outdoor chritstmas light remote': 'outdoor christmas light remote',
'wood fuelpellets': 'wood fuel pellets',
'cpipe lamp': 'pipe lamp',
'wiemans stainless cleaner': 'weimans stainless cleaner',
'10 roll up outside blinds': '10 roll up outdoor blinds',
'wainscote': 'wainscot',
'heat resistant spicket': 'heat resistant spigot',
'garage shelve': 'garage shelf',
'shevles': 'shelves',
'storage shelfs': 'storage shelves',
'proipane': 'propane',
'ventless gas heters': 'ventless gas heaters',
'vinal fencing': 'vinyl fencing',
'toliet bowl': 'toilet bowl',
'toliet bowl wrench': 'toilet bowl wrench',
'fanc wire': 'fancy wire',
't post fence assesories': 't post fence accessories',
'telescooping ladder': 'telescoping ladder',
'spring haven brown all weather wicked': 'spring haven brown all weather wicker',
'36 exterior steele door': '36 exterior steel door',
'faucetskitchen': 'faucets kitchen',
'batt insulatiom': 'batt insulation',
'congolium': 'congoleum',
'vinal flooring': 'vinyl flooring',
'vynil floorring': 'vinyl flooring',
'clacier bay toliet': 'glacier bay toilet',
'GLAZER BAY TOILET': 'GLACIER BAY TOILET',
'norton hot water heater ingniter': 'norton hot water heater igniter',
'undercounter lighs': 'under counter lights',
'stainless refridgerator': 'stainless refrigerator',
'stainless steel refridgerator': 'stainless steel refrigerator',
'window ac manuel operation': 'window ac manual operation',
'rustolem': 'rustoleum',
'18v drill brushles': '18v drill brushless',
'dining sets outdo?': 'dining sets outdoor?',
'eat resistant epoxy': 'heat resistant epoxy',
'cordless drils': 'cordless drills',
'3 piece bfush set': '3 piece brush set',
'kitchen faucet installtion tools': 'kitchen faucet installation tools',
'Moen Kitchen sink fauset': 'Moen Kitchen sink faucet',
'plaqstic bucket': 'plastic bucket',
'3m winow film': '3m window film',
'water softner': 'water softener',
'flourescent light bulp': 'fluorescent light bulb',
'closermaid cabinet': 'closetmaid cabinet',
'raised panel extirior doors': 'raised panel exterior doors',
'blcktop repair kit': 'blacktop repair kit',
'peal and stick flashning': 'peel and stick flashing',
'marshaltown 6 inch': 'marshalltown 6 inch',
'vynel wall tiles': 'vinyl wall tiles',
'presusre treated post': 'pressure treated post',
'LAWN LEAF VACUM': 'LAWN LEAF VACUUM',
'space heatres': 'space heaters',
'alumium fence 6 ft 6ft': 'aluminum fence 6 ft 6 ft',
'bathroom sinks kholer': 'bathroom sinks kohler',
'pedistal': 'pedestal',
'clear eppoxy': 'clear epoxy',
'wood fir plank flooring': 'wood for plank flooring',
'quickcrete waterproof cement': 'quikrete waterproof cement',
'rood rake': 'roof rake',
'propane gas tank meater': 'propane gas tank meter',
'ac cooling fin straightenrs': 'ac cooling fin straightener',
'slidng panel lock': 'sliding panel lock',
'closet maiid cabinets': 'closet maid cabinets',
'ridge power tools combo packs': 'ridgid power tools combo packs',
'backsplash tiiles': 'backsplash tiles',
'cabinet knobsd': 'cabinet knobs',
'cabnet knobs': 'cabinet knobs',
'dealt air compressor parts': 'dewalt air compressor parts',
'spgot': 'spigot',
'paver bricks scolloped': 'paver bricks scalloped',
'CHASE LOUNGE': 'CHAISE LOUNGE',
'layndry tu': 'laundry tu',
'submeribale pedistal sump pump': 'submersible pedestal sump pump',
'celling fans': 'ceiling fans',
'wall sconse': 'wall sconce',
'93 inch widecellular shades': '93 inch wide cellular shades',
'post white ligth': 'post white light',
'palmero brushed nickel ceiling fan': 'palermo brushed nickel ceiling fan',
'aromaticeatern red cedar planking': 'aromatic eastern red cedar planking',
'black and decker hobby crafter': 'black and decker hobbycrafter',
'front load fridaire': 'front load frigidaire',
'pedestial washer': 'pedestal washer',
'whilrpool front loader washer': 'whirlpool front loader washer',
'extrior louvored wood door 30x80': 'exterior louvered wood door 30x80',
'interior doorser': 'interior doors',
'dill battery 12v model g0805': 'drill battery 12v model g0805',
'10 stair lader': '10 stair ladder',
'milwakee 1/2 impact cordless': 'milwaukee 1/2 impact cordless',
'kolher': 'kohler',
'floor slealer': 'floor sealer',
'high traffic floor polurethane paint': 'high traffic floor polyurethane paint',
'sawzall blades miluakee': 'sawzall blades milwaukee',
'vaccum hose': 'vacuum hose',
'vynal repalcement windows': 'vinyl replacement windows',
'vinil for flors': 'vinyl for floors',
'led withe': 'led white',
'squar flushmount lights': 'square flush mount lights',
'huskey 18': 'husky 18',
'remove oder from kerosine': 'remove odor from kerosene',
'25ft huskt tape': '25 ft husky tape',
'plastic corrougeted roofing': 'plastic corrugated roofing',
'kholerhighland white toilet': 'kohler highline white toilet',
'toilet seat for briggs toliet': 'toilet seat for briggs toilet',
'steel shelve': 'steel shelf',
'dig irritation drip': 'dig irrigation drip',
'kohler pedastal sink': 'kohler pedestal sink',
'high loss natural jabota': 'high loss natural jatoba',
'Huskavarna': 'Husqvarna',
'power cordclass 2 power model xy_2900600_u': 'power cord class 2 power model xy_2900600_u',
'treaated plywood': 'treated plywood',
'air condtioning wall unit': 'air conditioning wall unit',
'wall air conditioneer': 'wall air conditioner',
'window ac insaller': 'window ac installer',
'sensor porch ligts': 'sensor porch lights',
'miricile applet or and tray': 'miracle applet or and tray',
'paint refil tray': 'paint refill tray',
'door knobs exteria': 'door knobs exterior',
'exhaustless portable airconditioner': 'exhaustless portable air conditioner',
'portable aircondition': 'portable air conditioner',
'oscilliating too': 'oscillating tool',
'PYWOOD': 'PLYWOOD',
'rigid nailer': 'ridgid nailer',
'bankoft toilet biscuit': 'bancroft toilet biscuit',
'mown pull down faucet': 'moen pull down faucet',
'lo gas water heater': 'low gas water heater',
'richman water heater': 'richmond water heater',
'tall toliet': 'tall toilet',
'ridding mower covers': 'riding mower covers',
'hole angel jig': 'hole angle jig',
'10 deep kitchen sink porcelin': '10 deep kitchen sink porcelain',
'plastic tiles pcv': 'plastic tiles pvc',
'vinyl sheeti': 'vinyl sheet',
'samsungelectric ranges': 'samsung electric ranges',
'frameless shoer doors': 'frameless shower doors',
'webber charcoal grill': 'weber charcoal grill',
'kerosine heaters': 'kerosene heaters',
'kersone heaters': 'kerosene heaters',
'propain heater': 'propane heater',
'heating elements for dyer whirlpool': 'heating elements for dryer whirlpool',
'safty glasses': 'safety glasses',
'eletric stove': 'electric stove',
'Schecule 40 Pipe': 'Schedule 40 Pipe',
'bayonett saw blades': 'bayonet saw blades',
'sconses': 'sconces',
'52\' pinacle ceiling fan': '52\' pinnacle ceiling fan',
'atic fans with lubers': 'attic fans with louvers',
'cealing fans': 'ceiling fans',
'hampton bay out door celing fan': 'hampton bay outdoor ceiling fan',
'out door celing fan': 'outdoor ceiling fan',
'kitchen exaust fan': 'kitchen exhaust fan',
'Cimmaron': 'Cimarron',
'fridgedaire': 'frigidaire',
'frigidaire washer door striker/catch': 'frigidaire washer door striker/latch',
'lawn mover wrench': 'lawn mower wrench',
'bmboo lattecie': 'bamboo lattice',
'1 handle tub and shower faucet shower and tub vlaves': '1 handle tub and shower faucet shower and tub valves',
'hansgroph faucets bathroom': 'hansgrohe faucets bathroom',
'led light bulbsbulbs': 'led light bulbs bulbs',
'landscape srone': 'landscape stone',
'braid nailer combo kit': 'brad nailer combo kit',
'doors for mobilhomes': 'doors for mobile homes',
'smaller closet lights': 'small closet lights',
'traficmaster': 'trafficmaster',
'hardi board smooth': 'hardie board smooth',
'wainscoating': 'wainscoting',
'galvanisedround fire pit ring': 'galvanized round fire pit ring',
'electrichot water heaters residential': 'electric hot water heaters residential',
'garage shelf unjit': 'garage shelf unit',
'stone baxksplash': 'stone backsplash',
'pendent cealing fixture': 'pendant ceiling fixture',
'undercabinet ligghts': 'under cabinet lights',
'martha stewartcabinet pull': 'martha stewart cabinet pull',
'4 fluorescant fixture covers': '4 fluorescent fixture covers',
'exterior vanyl french door': 'exterior vinyl french door',
'adheasive': 'adhesive',
'lineulium floor': 'linoleum floor',
'plexiglass selves': 'plexiglass shelves',
'Allure mellowood flooring': 'Allure mellow wood flooring',
'allure tile sedon?': 'allure tile sedona?',
'allure vinyl tilecordoba': 'allure vinyl tile cordoba',
'wood veener facing for kitchen cabinets': 'wood veneer facing for kitchen cabinets',
'painters plastice': 'painters plastic',
'granitne sealer': 'granite sealer',
'55 inch cultured marble vanity tope': '55 inch cultured marble vanity top',
'mirros': 'mirrors',
'garge floor paint': 'garage floor paint',
'weather indoor and outpoor temp': 'weather indoor and outdoor temp',
'ryobi blower with batery': 'ryobi blower with battery',
'powerwasher hose': 'power washer hose',
'mikita 9.5 volt drill': 'makita 9.5 volt drill',
'vinal fence straps': 'vinyl fence straps',
'black chandelier wjth black shades': 'black chandelier with black shades',
'medecine cabinet': 'medicine cabinet',
'medicient cabinet': 'medicine cabinet',
'serface mount medicine cabinets': 'surface mount medicine cabinets',
'husqvarna presure washer': 'husqvarna pressure washer',
'back yard weather forecasteer': 'backyard weather forecaster',
'chain link fenceing': 'chain link fencing',
'jogsaw tool': 'jigsaw tool',
'lg ruff wall instalation': 'lg ruff wall installation',
'pcv pipe sement': 'pvc pipe cement',
'hardi trim': 'hardietrim',
'vynal siding insol': 'vinyl siding insol',
'cheapete gas 40 gallon hot water heater': 'cheapest gas 40 gallon hot water heater',
'powervent water heater': 'power vent water heater',
'exterieur door 32 inch': 'exterior door 32 inch',
'vynal floor matting': 'vinyl floor matting',
'door knobsw': 'door knobs',
'black decke weed eaters': 'black decker weed eaters',
'lectric string trimmer cst1200r': 'electric string trimmer cst1200r',
'1.4 mircowave over the stove': '1.4 microwave over the stove',
'stove excaust fan': 'stove exhaust fan',
'mobile home extior doors': 'mobile home exterior doors',
'wood lathesw': 'wood lathes',
'anderson replacement double hung window 34.5x36.5': 'andersen replacement double hung window 34.5x 36.5',
'contrcator baseboard': 'contractor baseboard',
'moehn kitchen facet 87211srssd': 'moen kitchen faucet 87211srs',
'repare kit for 2-handle side sprayer kitchen faucet': 'repair kit for 2-handle side sprayer kitchen faucet',
'ecco friendly garden hose': 'eco friendly garden hose',
'flex gardn hose': 'flex garden hose',
'garden host 50': 'garden hose 50',
'bathroon lighting': 'bathroom lighting',
'lanscape timber': 'landscape timber',
'bathroom valnity lights': 'bathroom vanity lights',
'gas pressure regular': 'gas pressure regulator',
'ashely 48 in electric chi': 'ashley 48 in electric chi',
'2x6 treted 8ft long': '2x6 treated 8ft long',
'wheel borrow': 'wheelbarrow',
'whellbarrow': 'wheelbarrow',
'scement bags': 'cement bags',
'accordian door': 'accordion door',
'Electic Lawn Mowers': 'Electric Lawn Mowers',
'hampton bay cabinetscornor cabinetupper': 'hampton bay cabinets corner cabinet upper',
'electric pump for sprying': 'electric pump for spraying',
'front foor 2 siding': 'front door 2 siding',
'whirlpool lgas dryer': 'whirlpool gas dryer',
'pressure treated lumber spaint': 'pressure treated lumber paint',
'rhee. 40 gallon water heaters': 'rheem. 40 gallon water heaters',
'8x96 white decrotive shelf': '8x96 white decorative shelf',
'bathroom pendastal': 'bathroom pedestal',
'r25/r30 faced insullation': 'r25/r30 faced insulation',
'heavy dutty letter support': 'heavy duty letter support',
'ceder decking': 'cedar decking',
'negitave air machine': 'negative air machine',
'outdoor maouse traps': 'outdoor mouse traps',
'storeage shed': 'storage shed',
'car canoply': 'car canopy',
'commerical tile': 'commercial tile',
'1 1/2 colated rock screws': '1 1/2 collated rock screws',
'sheeet rock mud': 'sheetrock mud',
'counterdepth fridge': 'counter depth fridge',
'maytag refregirator': 'maytag refrigerator',
'whirlpool french door frig 30 wide': 'whirlpool french door fridge 30 wide',
'wirlpool 30 wide french door': 'whirlpool 30 wide french door',
'dleta shower faucet handles': 'delta shower faucet handles',
'38 grainte composit sink': '38 granite composite sink',
'blown in insulaation': 'blown in insulation',
'foam insulatino': 'foam insulation',
'doors interiorwith door jams': 'doors interior with door jams',
'residentialsteel door and frame': 'residential steel door and frame',
'wood swimg set kits': 'wood swing set kits',
'quickcrete resurfacer': 'quikrete resurfacer',
'2 inch srew cap': '2 inch screw cap',
'30 gar builtin ranges': '30 gas built in ranges',
'samsong stive': 'samsung stove',
'chissel': 'chisel',
'rigid compound miter saw': 'ridgid compound miter saw',
'rigid compound miter saw dust pouch': 'ridgid compound miter saw dust pouch',
'shampoo and lotion automatice dispenser': 'shampoo and lotion automatic dispenser',
'wall scone': 'wall sconce',
'rubber for refridgerators': 'rubber for refrigerators',
'water proofing shower membrame': 'waterproofing shower membrane',
'fridigdaire back gas range': 'frigidaire black gas range',
'cabrio dryder': 'cabrio dryer',
'whilrpool cabrio dryer': 'whirlpool cabrio dryer',
'light switcht sensor': 'light switch sensor',
'calutta marble laminate countertop': 'calcutta marble laminate countertop',
'vinylcorner boards 4 inch': 'vinyl corner boards 4 inch',
'plastix box': 'plastic box',
'scurity screen doors': 'security screen doors',
'nonadhesive vinyl flooring': 'non adhesive vinyl flooring',
'trafficmaster interloclk': 'trafficmaster interlock',
'anntenias': 'antennas',
'clothes dryer srand': 'clothes dryer stand',
'eletric water heater': 'electric water heater',
'sharkbike push to connect 3/4': 'sharkbite push to connect 3/4',
'fuel nozzle furnance': 'fuel nozzle furnace',
'ryobi one batery': 'ryobi one battery',
'5/8 floring plywood weatherproof': '5/8 flooring plywood weatherproof',
'mitter saw manual': 'miter saw manual',
'selenoid for dryer': 'solenoid for dryer',
'presure coated wood': 'pressure coated wood',
'composote lumber': 'composite lumber',
'14 awgsoilid wire': '14 awg solid wire',
'welded wire fenching 12 gauge': 'welded wire fencing 12 gauge',
'patio chair cusions': 'patio chair cushions',
'viynl patches': 'vinyl patches',
'7 in. stove pie': '7 in. stove pipe',
'whirlpoolgas stove': 'whirlpool gas stove',
'whirpool microwave 1.4 cu ft': 'whirlpool microwave 1.4 cu ft',
'whirpool refrigerator': 'whirlpool refrigerator',
'3\' nailes': '3\' nails',
'nailer tooal': 'nailer tool',
'weed barier': 'weed barrier',
'oped garage door indicator': 'open garage door indicator',
'styrafoam': 'styrofoam',
'10 foot step laddert': '10 foot step ladder',
'3 1/2 hardwar': '3 1/2 hardware',
'double control shower vavle': 'double control shower valve',
'replacement shower encosure rod': 'replacement shower enclosure rod',
'baby gurad gate': 'baby guard gate',
'joint compund light weight': 'joint compound lightweight',
'sheetrock high preformance joint compound': 'sheetrock high performance joint compound',
'1x2 appearnce boards': '1x2 appearance boards',
'lumber 2x8 composit': 'lumber 2x8 composite',
'floot ball': 'float ball',
'dewalt empact driver': 'dewalt impact driver',
'bosh cordless combo set': 'bosch cordless combo set',
'ryobi 18v battwery': 'ryobi 18v battery',
'kihchen cabinet slidr shelves': 'kitchen cabinet slide shelves',
'chesnut border edging': 'chestnut border edging',
'outdoor seat cushions 24.5 whte': 'outdoor seat cushions 24.5 white',
'12x12 tile msaic': '12x12 tile mosaic',
'skill screwdriver battery': 'skil screwdriver battery',
'manual for airens lawnmower': 'manual for ariens lawn mower',
'gas stabilisor': 'gas stabilizer',
'4 x 4 white pocelain tile': '4 x 4 white porcelain tile',
'rigid pipe cutter': 'ridgid pipe cutter',
'24 regrigerators': '24 refrigerators',
'refrigerato 33 inch wide': 'refrigerator 33 inch wide',
'smudge proof stainless steele': 'smudge proof stainless steel',
'whirpool amana': 'whirlpool amana',
'moen banbury 24 in. doubletowel bar': 'moen banbury 24 in. double towel bar',
'4\' r;ubber top set base': '4\' rubber top set base',
'extension springes': 'extension springs',
'grass string trimmer electric homelight': 'grass string trimmer electric homelite',
'craftman style lights': 'craftsman style lights',
'glacier bay delmare expresso wall mirror': 'glacier bay del mar espresso wall mirror',
'dollie 600 lbs': 'dolly 600 lbs',
'patio tille': 'patio tile',
'eucalptus white board': 'eucalyptus white board',
'vynal tile': 'vinyl tile',
'heat reducing window flim': 'heat reducing window film',
'Porach Light': 'Porch Light',
'brissell zing vacuum bags': 'bissell zing vacuum bags',
'toillet': 'toilet',
'kitchen aid refrigirator light bulb:': 'kitchenaid refrigerator light bulb:',
'chadelier': 'chandelier',
'cararra marble': 'carrara marble',
'coedless makita chainsaw with batteries': 'cordless makita chainsaw with batteries',
'mikita cordless drill': 'makita cordless drill',
'antique brass hindges for doors': 'antique brass hinges for doors',
'riobi battery': 'ryobi battery',
'feerzer': 'freezer',
'schlade wirell door lock': 'schlage wireless door lock',
'water proff board': 'waterproof board',
'celing light holder': 'ceiling light holder',
'wood toold': 'wood tools',
'4 inch insolation': '4 inch insulation',
'Urehtane Foam Sheet': 'Urethane Foam Sheet',
'4 center lavatory facuet': '4 center lavatory faucet',
'Shower facuet': 'Shower faucet',
'electric dyrer heater elemnet': 'electric dryer heater element',
'milluakee drill bits': 'milwaukee drill bits',
'scrren wire': 'screen wire',
'safegaurd 30 synthetic felt': 'safeguard 30 synthetic felt',
'hampden bay chandelier': 'hampton bay chandelier',
'1/2 inch pnumatic stapler': '1/2 inch pneumatic stapler',
'12\' firetreat 2x4': '12\' fire treated 2x4',
'american-standarfairfield elongated one-piece 1.6 gpf toilet': 'american-standard fairfield elongated one-piece 1.6 gpf toilet',
'toilet aquaia': 'toilet aquia',
'Comercial electric': 'Commercial electric',
'light puff defuser': 'light puff diffuser',
'ryobi drill prass': 'ryobi drill press',
'110v ectric dryers': '110v electric dryers',
'FIRE RESTISTANT BOARD': 'FIRE RESISTANT BOARD',
'vinyle plankj': 'vinyl plank',
'cordless backpack vaccume': 'cordless backpack vacuum',
'hampton baysolar bird lights': 'hampton bay solar bird lights',
'kohler chair height elongated toliet': 'kohler chair height elongated toilet',
'electic fireplace': 'electric fireplace',
'hampton bay jmestown': 'hampton bay jamestown',
'surfacemount kitchen sink': 'surface mount kitchen sink',
'rigid wet nozzelsqueegee': 'ridgid wet nozzle squeegee',
'vacumns': 'vacuums',
'gble vent': 'gable vent',
'ventalation': 'ventilation',
'biinds and shades': 'blinds and shades',
'copact drills cordless': 'compact drills cordless',
'ridge 18v hammer': 'ridgid 18v hammer',
'heavy dutty garden hose': 'heavy duty garden hose',
'1/2\' extirior plywood': '1/2\' exterior plywood',
'gutter water reflector': 'gutter water deflector',
'under cabinet led light accesory pack': 'under cabinet led light accessory pack',
'armstroung floor adhesive': 'armstrong floor adhesive',
'whirlpoolstainless steel refrig': 'whirlpool stainless steel refrig',
'black and decker elctric': 'black and decker electric',
'cordless edgere': 'cordless edger',
'white electrtical outlets': 'white electrical outlets',
'tan unmbrella': 'tan umbrella',
'gothic fence picketts': 'gothic fence pickets',
'vinyl 1 bilnd': 'vinyl 1 blinds',
'console tab;le': 'console table',
'T-5 florescent light fixtures': 'T-5 fluorescent light fixtures',
'royobi pedestal grinder wheel': 'ryobi pedestal grinder wheel',
'wall panaling': 'wall paneling',
'PORCH STAIR RAILLING': 'PORCH STAIR RAILING',
'micro fibe': 'microfiber',
'champion toliet part': 'champion toilet parts',
'rr vaccum filter': 'rr vacuum filter',
'exhust fan': 'exhaust fan',
'corragated metal': 'corrugated metal',
'gasolene generaters and inverters': 'gasoline generators and inverters',
'stailess steel top stoves': 'stainless steel top stoves',
'top freezer refrigeratot': 'top freezer refrigerator',
'3/4 inche rock': '3/4 inch rock',
'12 roofing pannel': '12 roofing panel',
'blakck in decker edger': 'black and decker edger',
'tile scrapper': 'tile scraper',
'brick morter': 'brick mortar',
'cement blodks': 'cement blocks',
'unmortified mortor': 'unmodified mortar',
'bifold door hardw': 'bifold door hardware',
'metal scerews': 'metal screws',
'sliding doos for backyard': 'sliding doors for backyard',
'screen fame corner': 'screen frame corner',
'electric lawn mowerectrical': 'electric lawn mower electrical',
'clacer bay all n one sink': 'glacier bay all in one sink',
'sola water fountain': 'solar water fountain',
'closet clothes rackclosetmaid': 'closet clothes rack closetmaid',
'passload': 'paslode',
'kitchen tile backspl': 'kitchen tile backsplash',
'viyle fencing': 'vinyl fencing',
'flexible tourche extension': 'flexible torch extension',
'6 pnl molded': '6 panel molded',
'soild core flush pre hung door': 'solid core flush prehung door',
'convction heater': 'convection heater',
'closet orginizer shoe rack wire': 'closet organizer shoe rack wire',
'freesstanding': 'free standing',
'mmirror closet doors': 'mirror closet doors',
'maratha stewart monogram wreath': 'martha stewart monogram wreath',
'edsel heavy duty 5': 'edsal heavy duty 5',
'11 ft extension cord groud': '11 ft extension cord ground',
'indoor/otdoor extensions cords e176194': 'indoor/outdoor extension cords e176194',
'outdoor extention cords e': 'outdoor extension cords e',
'unface insulation 23 inches wide': 'unfaced insulation 23 inches wide',
'porble toilets': 'portable toilets',
'toilet saftey seat': 'toilet safety seat',
'silca sand': 'silica sand',
'tall 18 in storage cabnet': 'tall 18 in storage cabinet',
'20x8 storge shed': '20 x 8 storage shed',
'rubbermade shed': 'rubbermaid shed',
'rubbermaid resin storage cabnetsn': 'rubbermaid resin storage cabinets',
'cedar wod chips': 'cedar wood chips',
'hidraulic tools': 'hydraulic tools',
'celing fans with lighting and remote': 'ceiling fans with lighting and remote',
'fridigidaire drop in oven': 'frigidaire drop in oven',
'tub surround pices': 'tub surround prices',
'allure flooring oak expresso': 'allure flooring oak espresso',
'pass and seymore light cover switch': 'pass and seymour light cover switch',
'28x54 replacment window': '28x54 replacement windows',
'anderson windows new constraction': 'anderson windows new construction',
'swamp oolers': 'swamp coolers',
'wahing machines': 'washing machines',
'interior primed mdf crown mouldin': 'interior primed mdf crown moulding',
'built in convectionoven': 'built in convection oven',
'flpwers for your garden': 'flowers for your garden',
'closetr rod': 'closet rod',
'unfinished wide bplanked hickory flooring': 'unfinished wide plank hickory flooring',
'48v to 110 invertor': '48v to 110v inverter',
'landscape wateting': 'landscape watering',
'sockets for fluorescence fixtres': 'sockets for fluorescent fixtures',
'woodceramic floor tile': 'wood ceramic floor tile',
'brigsg and stations 500 seris': 'briggs and stations 500 series',
'green carpert': 'green carpet',
'pressure treated step tread 6ft': 'pressure treated stair tread 6ft',
'hand pump gfor water': 'hand pump for water',
'rutic lighting': 'rustic lighting',
'cender blocks': 'cinder blocks',
'talsrar': 'talstar',
'rybi power tools': 'ryobi power tools',
'portercable 6 gal': 'porter cable 6 gal',
'table covers waterproff': 'table covers waterproof',
'solid alium square tubing': 'solid aluminum square tubing',
'deck post jhardware': 'deck post hardware',
'hunter new bronzel fans': 'hunter new bronze fans',
'16d framin': '16d framing',
'moen brushed nickel batharoom': 'moen brushed nickel bathroom',
'barriar plastic': 'barrier plastic',
'window ac/hehat units': 'window ac/heat units',
'icycle lights': 'icicle lights',
'4 gallon expanion': '4 gallon expansion',
'floor mount lawndry seek': 'floor mount laundry sink',
'high addhesion primer': 'high adhesion primer',
'24 gauge wire connectorsa': '24 gauge wire connectors',
'sterio wire for indoor speakers': 'stereo wire for indoor speakers',
'garage bicyclestorage': 'garage bicycle storage',
'how mustall tankless water heater': 'how install tankless water heater',
'chelsea white acrylic oval in rectangl': 'chelsea white acrylic oval in rectangle',
'cleaning jeta for whirlpool': 'cleaning jets for whirlpool',
'bathroom faucet replacment valve': 'bathroom faucet replacement valve',
'3x5 cemet board': '3x5 cement board',
'vaccumm': 'vacuum',
'ghroe shower headstrong shower heads': 'grohe shower headstrong shower heads',
'mial boxes': 'mail boxes',
'claw tups': 'claw tips',
'facia corner brace': 'fascia corner brace',
'pegisas sink top': 'pegasus sink top',
'mirroes for doors': 'mirrors for doors',
'counter depth refridgidere': 'counter depth refrigerator',
'corrigaed fiberglass roofing': 'corrugated fiberglass roofing',
'window airconditionerwith heaters': 'window air conditioners with heaters',
'extention rail for opener': 'extension rail for opener',
'whitecomposite fascia board': 'white composite fascia board',
'vanity topp 31 white': 'vanity top 31 white',
'underhood range fan': 'under hood range fan',
'price pfister trevisa': 'price pfister treviso',
'milwaukee cordlees tools': 'milwaukee cordless tools',
'pendent light': 'pendant light',
'pre-emergent weed contro': 'pre-emergent weed control',
'is this item in stoes?': 'is this item in store?',
'door home secutity': 'door home security',
'3oo watt haalogen bulbs': '3oo watt halogen bulbs',
'96 in flourescent bulbs': '96 in fluorescent bulbs',
'shop ceiling fane': 'shop ceiling fan',
'aaa batteries everready gold': 'aaa batteries eveready gold',
'buth tub faucet': 'bathtub faucet',
'delta montecello tub faucet': 'delta monticello tub faucet',
'ge spring water heater': 'geospring water heater',
'ge water heater egnighter': 'ge water heater igniter',
'31x19 one piecs bathroom sink': '31x19 one piece bathroom sink',
'replacment clips for wire rack': 'replacement clips for wire rack',
'ac air diverer': 'ac air diverter',
'3 sewer pipce': '3 sewer pipe',
'3\' electical pipe': '3\' electrical pipe',
'large outside horizontal storage shed': 'large outdoor horizontal storage shed',
'swing hangar hardware': 'swing hanger hardware',
'dim able balafon flood light': 'dimmable balafon flood light',
'phillips exterior led': 'philips exterior led',
'banity 11 watt light bulb': 'vanity 11 watt light bulb',
'kithchen install': 'kitchen install',
'magnet stainless steel for diswasher': 'magnet stainless steel for dishwasher',
'phone spliter': 'phone splitter',
'receptical': 'receptacle',
'water resistent electrical outlets': 'water resistant electrical outlets',
'kitchenaid superb oven': 'kitchenaid superba oven',
'403esprit 2x4 ceing tile': '403 esprit 2x4 ceiling tile',
'wall excess panel': 'wall access panel',
'drop celing tiles': 'drop ceiling tiles',
'pvc drop in celing tiles': 'pvc drop in ceiling tiles',
'pl gas hose': 'lp gas hose',
'12 v landscaping ligtening fixture': '12v landscape lighting fixture',
'behr white external semigloss paint': 'behr white exterior semi gloss paint',
'GRAGE DOOR OPENER': 'GARAGE DOOR OPENER',
'grage doors': 'garage doors',
'24 inch med oak base': '24 inch medium oak base',
'okeefes working hands': 'o\'keeffe\'s working hands',
'phenofin': 'penofin',
'8 foot galvinezed': '8 foot galvanized',
'12 mobil home air duct': '12 mobile home air duct',
'door hinges for americana refrigator': 'door hinges for americana refrigerator',
'tub drain kit bronz': 'tub drain kit bronze',
'halligon light bulb': 'halogen light bulb',
'husky rachet': 'husky ratchet',
'andersen vnyl windows': 'andersen vinyl windows',
'balwind double cilynder lock': 'baldwin double cylinder lock',
'drop down ceiling ppanel': 'drop down ceiling panel',
'arearugs and mats': 'area rugs and mats',
'dark expresso paint for wood': 'dark espresso paint for wood',
'melamine shelvees': 'melamine shelves',
'mosaic whitel and black tile': 'mosaic white and black tile',
'8 wre wheel': '8 wire wheel',
'9\' plna replament blade': '9\' plane replacement blade',
'saw zall blades': 'sawzall blades',
'pain pot': 'paint pot',
'drain cleaneraner machines': 'drain cleaner machines',
'anderson storm doors pet': 'andersen storm doors pet',
'basement window replacement insructions': 'basement window replacement instructions',
'grill cover brinkman double grill': 'grill cover brinkmann double grill',
'gerber daisies': 'gerbera daisies',
'gerber daisy': 'gerbera daisy',
'exterior wood stainolid color': 'exterior wood stain color',
'2700 br30 led': '2700k br30 led',
'3m wheather stripping': '3m weather stripping',
'barn doorhinges': 'barn door hinges',
'plywood progect': 'plywood project',
'28 guage screen': '28 gauge screen',
'lampsade pendent light': 'lamp shade pendant light',
'kitchen cabiner corner': 'kitchen cabinet corner',
'paatio swings': 'patio swings',
'12 bar chian for echo': '12 bar chain for echo',
'bix max 7x7': 'big max 7x7',
'bathtub faucethandle replacement parts': 'bathtub faucet handle replacement parts',
'prelit spiral trees': 'pre lit spiral trees',
'12 sthel chainsaws': '12 stihl chainsaws',
'10 ft drain house': '10 ft drain hose',
'american standard tiolet flappers': 'american standard toilet flappers',
'solar out doors post lights': 'solar outdoor post lights',
'kitchen cabinet with counertop': 'kitchen cabinet with countertop',
'Painting Cabniets': 'Painting Cabinets',
'18x18 teracota porcelain floor tiles': '18x18 terracotta porcelain floor tiles',
'drywal': 'drywall',
'pencle trim tile': 'pencil trim tile',
'vinyl latice': 'vinyl lattice',
'angle findeer': 'angle finder',
'laminate tile comercial': 'laminate tile commercial',
'couner deep refrigerators': 'counter deep refrigerators',
'chritmas tree': 'christmas tree',
'plug in carbon monoxcide': 'plug in carbon monoxide',
'cabinet handels': 'cabinet handles',
'frigidair drop in': 'frigidaire drop in',
'7\' hex hed bolt': '7\' hex head bolt',
'vent fllters': 'vent filters',
'horizontall': 'horizontal',
'3 x 6 blace tile': '3 x 6 black tile',
'rostoluem spray paint': 'rustoleum spray paint',
'power drill battery an charger': 'power drill battery and charger',
'rayobi blue charger': 'ryobi blue charger',
'robyi': 'ryobi',
'5/4 pressure treaded decking': '5/4 pressure treated decking',
'white carrara herring bome': 'white carrara herringbone',
'sailr blue': 'sailor blue',
'charbroil classic': 'char broil classic',
'14 electric concrete saw with vc-u dch300': '14 electric concrete saw with vac-u dch 300',
'potable air conditioners': 'portable air conditioners',
'fin heating tubeing': 'fin heating tubing',
'fine/line baseboarrd': 'fine/line baseboard',
'hot water heating eliment': 'hot water heating element',
'toiet': 'toilet',
'hole house fan': 'whole house fan',
'montaga bay tile': 'montego bay tile',
'40 gal liquid propan': '40 gal liquid propane',
'4 x 4 pos cap': '4x4 post cap',
'white quartz cointertop': 'white quartz countertop',
'elongated bone toilest': 'elongated bone toilet',
'white acryl paint': 'white acrylic paint',
'foundstion vents': 'foundation vents',
'sqeaky carpet stair kit': 'squeaky carpet stair kit',
'defusiers for floors': 'diffusers for floors',
'8\' galvanized roll top edginh': '8\' galvanized roll top edging',
'marithon water heater element': 'marathon water heater element',
'wirerless light switch': 'wireless light switch',
'moen posi-temp tim kit': 'moen posi-temp trim kit',
'shower dooroil rubbed bronze': 'shower door oil rubbed bronze',
'wireing': 'wiring',
'kitchen aid architecs series 11': 'kitchenaid architect series 11',
'wall oven combon': 'wall oven combo',
'survival babkpack': 'survival backpack',
'wire dstaples': 'wire staples',
'4in drain gratewhite': '4in drain grate white',
'shitch cover': 'switch cover',
'vitarera quartz': 'viatera quartz',
'5/8-in masonary drill bit': '5/8-in masonry drill bit',
'brinkman grill grates': 'brinkmann grill grates',
'pest repellant': 'pest repellent',
'bathun drain plunger': 'bathtub drain plunger',
'incounter gas cook range': 'encounter gas cook range',
'peat moss bails': 'peat moss bales',
'3-piece bath accessory kit in chrom': '3-piece bath accessory kit in chrome',
'alameda hickey laminate': 'alameda hickory laminate',
'flooring moisture barier': 'flooring moisture barrier',
'vinylcove base': 'vinyl cove base',
'ge diswasher': 'ge dishwasher',
'b10 led bub': 'b10 led bulb',
'cub cadetcordless hedge trimmer': 'cub cadet cordless hedge trimmer',
'hampton bay jewelery armoire wht': 'hampton bay jewelry armoire white',
'perenials': 'perennials',
'heat ventss': 'heat vents',
'mobil home glass door': 'mobile home glass door',
'lamanet floor cutter': 'laminate floor cutter',
'on off valvefor tub faucet': 'on off valve for tub faucet',
'assie grill fire and ash': 'aussie grill fire and ash',
'hanging worklight fixtures ceiling': 'hanging work light fixtures ceiling',
'20 amp tamper resitance duplex receptacle': '20 amp tamper resistant duplex receptacle',
'liqwuid nail': 'liquid nail',
'1/2 tee pvcp': '1/2 tee pvc',
'toilet repair kit cadet 3 flowise 2-piece 1.28 gpf round fro': 'toilet repair kit cadet 3 flowise 2-piece 1.28 gpf round front',
'50 amp turn look plug': '50 amp turn lock plug',
'6x6 colunm caps': '6x6 column caps',
'12 valleta': '12 valletta',
'pellitized lime': 'pelletized lime',
'concrete sonic tub': 'concrete sonic tube',
'110 air conditior an heat': '110 air conditioner and heat',
'what is best for settingfence posts in soil?': 'what is best for setting fence posts in soil?',
'washer dryer folding worksurface': 'washer dryer folding work surface',
'outdoor spigot spliter': 'outdoor spigot splitter',
'alumiunm gate': 'aluminum gate',
'lawm mower': 'lawn mower',
'door floor plate slideing doors': 'door floor plate sliding doors',
'akkegro': 'allegro',
'wead burner': 'weed burner',
'galvinized nails 3': 'galvanized nails 3',
'artifical turf border': 'artificial turf border',
'oppeuss light trim ring': 'oppeus light trim ring',
'12 ft john boat': '12ft jon boat',
'outdoor coucg': 'outdoor couch',
'drywall panel hoisst': 'drywall panel hoist',
'ego hainsaw': 'ego chainsaw',
'hibascus plant': 'hibiscus plant',
'pullbehind fertilizer spreader': 'pull behind fertilizer spreader',
'door latch uard': 'door latch guard',
'water suppy box': 'water supply box',
'octagon eve vents': 'octagon eave vents',
'el ctrical s ez': 'electrical sez',
'varnishe': 'varnish',
'klien rg6': 'klein rg6',
'floor matt': 'floor mat',
'60 shower ddor': '60 shower door',
'blue tapeexhaust fan/light': 'blue tape exhaust fan/light',
'rocks hydrophonics': 'rocks hydroponics',
'mesquito spray': 'mosquito spray',
'alumiun grove in': 'aluminum grove in',
'lithonia outdoor wall paks': 'lithonia outdoor wall packs',
'60 in. shower door brushed nicker': '60 in. shower door brushed nickel',
'makit 12v': 'makita 12v',
'black and yellow non skip tape': 'black and yellow non skid tape',
'skylifghts': 'skylights',
'led hale gin g9': 'led halogen g9',
'electrical pipe flexable': 'electrical pipe flexible',
'emt stroas': 'emt straps',
'ridged 1 emt conduit': 'rigid 1 emt conduit',
'baliey window roller shades': 'bailey window roller shades',
'hampton bay reswood valley 5 pc patio seating set with fire': 'hampton bay redwood valley 5 pc patio seating set with fire',
'lawn grass catchbag': 'lawn grass catcher bag',
'1/4 lauwan under layment': '1/4 lauan underlayment',
'window tintinig': 'window tinting',
'4 inch round bellbox cover': '4 inch round bell box cover',
'vinal latice fence': 'vinyl lattice fence',
'solar pest repelers': 'solar pest repellers',
'barn doorspring latches': 'barn door spring latches',
'3 gauge copper phhn': '3 gauge copper thhn',
'three wire hottube': 'three wire hot tub',
'shope cloths': 'shop clothes',
'bbostitch tool set': 'bostitch tool set',
'outdoor hightop dining': 'outdoor high top dining',
'delata raincan': 'delta raincan',
'soap wash maching tilde': 'soap wash machine tilde',
'16 ftdecking boards': '16 ft decking boards',
'1 amp receptical': '1 amp receptacle',
'outdoor gfi': 'outdoor gfci',
'bbq burner replacment': 'bbq burner replacement',
'levin 25 wat usb': 'levin 25 watt usb',
'delta diverte rhandle in rb': 'delta diverter handle in rb',
'3 pane craftsman door': '3 panel craftsman door',
'charolettetown': 'charlottetown',
'raised toelit sseat': 'raised toilet seat',
'webber spirit gas grill': 'weber spirit gas grill',
'adapter for extention cord': 'adapter for extension cord',
'bathrub and shower wall kits': 'bathtub and shower wall kits',
'sofit vents 4x16': 'soffit vents 4 x 16',
'1/2 inch isp water supply line': '1/2 inch ips water supply line',
'eurothem thermostatic valve': 'eurotherm thermostatic valve',
'plactic totes 36 inches wide': 'plastic totes 36 inches wide',
'pest control diat': 'pest control diet',
'black cobwoys star': 'black cowboys star',
'whirpool oven 5.1': 'whirlpool oven 5.1',
'min fridges for campers': 'mini fridges for campers',
'howards restore a finish': 'howards restor a finish',
'ge just cut fraiser fur': 'ge just cut fraser fir',
'25 watt warmlight bulb': '25 watt warm light bulb',
'kichen island': 'kitchen island',
'duel mount stainless steel sinks': 'dual mount stainless steel sinks',
'home sevalance cameras': 'home surveillance cameras',
'marbel vinyl tile': 'marble vinyl tile',
'30 entry door 9 litr': '30 entry door 9 lite',
'roxul sale n sound': 'roxul safe n sound',
'4 guage use': '4 gauge use',
'jigsaw tblades': 'jigsaw t blades',
'jigsaww blades': 'jigsaw blades',
'clawfoot tub cutain': 'clawfoot tub curtain',
'raised garden ed': 'raised garden bed',
'58.75x80 sliding glass door': '58.75x 80 sliding glass door',
'1/4 nich tee': '1/4 inch tee',
'alluminun wire splice': 'aluminum wire splice',
'2 sheet metal screrw': '2 sheet metal screw',
'non electically conductive epoxy': 'non electrically conductive epoxy',
'led fluoreecent light replacement': 'led fluorescent light replacement',
't8 8 ft 4-light flourescent fixture': 't8 8 ft 4-light fluorescent fixture',
'othor ant killer': 'ortho ant killer',
'spectacide for lawnscarpenter ants': 'spectracide for lawns carpenter ants',
'ccurved shower door': 'curved shower door',
'4in pvc electrcial boxes': '4in pvc electrical boxes',
'hampton bay fan replacemtn': 'hampton bay fan replacement',
'6\' remodel can valted celing cans': '6\' remodel can vaulted ceiling cans',
'roman tub faucers': 'roman tub faucets',
'flourescent paint by rustoleum': 'fluorescent paint by rustoleum',
'hidden fastners': 'hidden fasteners',
'otdoor sola': 'outdoor solar',
'solar post l8ghts': 'solar post lights',
'plus 3 tintet': 'plus 3 tinted',
'barbeque tools': 'barbecue tools',
'circular flourecent lights': 'circular fluorescent lights',
'rain barrells': 'rain barrels',
'gagarage storage cabinets': 'garage storage cabinets',
'brown blasplash tile': 'brown backsplash tile',
'evap cooler theromsat': 'evap cooler thermostat',
'undergroud telephone wire': 'underground telephone wire',
'cop mail adapter': 'cop male adapter',
'set crews for glass': 'set screws for glass',
'roybi lazer circular saw': 'ryobi laser circular saw',
'walnuit stain': 'walnut stain',
'ruber door extension': 'rubber door extension',
'home decorators cinamon': 'home decorators cinnamon',
'apoxy patch': 'epoxy patch',
'batroom fan heater light': 'bathroom fan heater light',
'commercial radient ceiling heaters': 'commercial radiant ceiling heaters',
'surveilance camera': 'surveillance camera',
'tub facet set': 'tub faucet set',
'solistone pebbble': 'solistone pebble',
'1 1/4 galvenized steel pipe fittings': '1 1/4 galvanized steel pipe fittings',
'22.4 cubit feet refrigerator': '22.4 cubic feet refrigerator',
'behr premium plus ultrta': 'behr premium plus ultra',
'autoficial grass': 'artificial grass',
'huskey scocket set': 'husky socket set',
'husky black toll boxes': 'husky black tool boxes',
'isunderlayment requiered for metal roof': 'is underlayment required for metal roof',
'safety glass with perscription': 'safety glass with prescription',
'polished brass 8 spread lavitory faucet': 'polished brass 8 spread lavatory faucet',
'heat only therostats': 'heat only thermostats',
'65 watt dim able': '65 watt dimmable',
'1-1/4 pocket hole screwsw': '1-1/4 pocket hole screws',
'wwod floor runner': 'wood floor runner',
'bostic wood floor glue': 'bostik wood floor glue',
'hand shovles': 'hand shovels',
'garage orgnize': 'garage organizer',
'diamond plate storge unit': 'diamond plate storage unit',
'silcone': 'silicone',
'packing suplies': 'packing supplies',
'ridgid planner': 'ridgid planer',
'shower fiberglas': 'shower fiberglass',
'curtain rod wrp': 'curtain rod wrap',
'fire place accessories gas loggs': 'fireplace accessories gas logs',
'recesseingd light housing': 'recessed light housing',
'100 amps circuit braker': '100 amps circuit breaker',
'delta satin nickle shower systems': 'delta satin nickel shower systems',
'auqatic shower & bath': 'aquatic shower',
'termini mosquito garlic spray': 'terminix mosquito garlic spray',
'arbourist safety climbing belt': 'arborist safety climbing belt',
'vynal wood fence': 'vinyl wood fence',
'acrylic primere': 'acrylic primer',
'20\' facia board': '20\' fascia board',
'17 1/2 high tolite': '17 1/2 high toilet',
'howard restore a finish': 'howard restor a finish',
'tub enclouseure with tub': 'tub enclosure with tub',
'leaf guards for stomr windows': 'leaf guards for storm windows',
'sliding tub soors': 'sliding tub doors',
'amdry wallpanel': 'amdry wall panel',
'22.1 refrierator': '22.1 refrigerator',
'fram boxes': 'frame boxes',
'patio tbricks': 'patio bricks',
'6 foot treshold': '6 foot threshold',
'florencet light cover': 'fluorescent light cover',
'taracota drain pan': 'terracotta drain pan',
'smaller single deadbolt lock': 'small single deadbolt lock',
'lmainate boards': 'laminate boards',
'acuria lattace panels': 'acurio lattice panels',
'adirondeck cusion': 'adirondack cushion',
'oscilating fan': 'oscillating fan',
'washing machine plug adapator': 'washing machine plug adapter',
'concrette pier': 'concrete pier',
'southren gray tile': 'southern gray tile',
'dealt portable table saw table': 'dewalt portable table saw table',
'matte heat resistant pain': 'matte heat resistant paint',
'White Temper Resistant Duplex Outlet': 'White Tamper Resistant Duplex Outlet',
'screws for deckin': 'screws for decking',
'20 gl. hose end sprayer': '20 gal. hose end sprayer',
'sliding door storage cabi nets': 'sliding door storage cabinets',
'tinted masonary sealer': 'tinted masonry sealer',
'kids toilet seateat': 'kids toilet seat eat',
'anderson storm door screen roller': 'andersen storm door screen roller',
'vaccuum cleaners for hardwood and carpet': 'vacuum cleaners for hardwood and carpet',
'copper baluseter': 'copper baluster',
'aluninion circular blade': 'aluminium circular blade',
'ceiling light nickle 2-light': 'ceiling light nickel 2-light',
'adirondac, patio chair': 'adirondack, patio chair',
'flourescent tube': 'fluorescent tube',
'polyurethane adhesiv': 'polyurethane adhesive',
'extirior clear spray paint': 'exterior clear spray paint',
'outdoor faucwts': 'outdoor faucets',
'asphaul based coating': 'asphalt based coating',
'3/8 couipling': '3/8 coupling',
'2x4x10 pressure treater': '2x4x10 pressure treated',
'koehler faucet': 'kohler faucet',
'led rop light clips': 'led rope light clips',
'square d double brakers': 'square d double breakers',
'30 inchesbathroom vanity': '30 inches bathroom vanity',
'1/2 \' copper fiting': '1/2 \' copper fitting',
'capital cap for colum': 'capital cap for column',
'grass turf pavewrs': 'grass turf pavers',
'lowvoltage indoor accent lights': 'low voltage indoor accent lights',
'dremel minimate cordless moto tool': 'dremel minimite cordless moto tool',
'96 right hand miter tyhoon ice': '96 right hand miter typhoon ice',
'magnet base tool loight': 'magnetic base tool light',
'robi 18v saw': 'ryobi 18v saw',
'5 light hanging chandielier': '5 light hanging chandelier',
'Moem faucet repair': 'Moen faucet repair',
'3x6 daltile white 101 kohler': '3x6 daltile white k101 kohler',
'lock cmbo': 'lock combo',
'trimmer/edger\'s, gas powered': 'trimmer/edgers, gas powered',
'generaor for fridge': 'generator for fridge',
'led light bulbs dimable spot': 'led light bulbs dimmable spot',
'outdoor seatting cushions': 'outdoor seating cushions',
'full size frigde': 'full size fridge',
'ASHPHALT SEALER': 'ASPHALT SEALER',
'behr ultra pint': 'behr ultra paint',
'emparador mosaic bamboo brick': 'emperador mosaic bamboo brick',
'bath mirror cabintes': 'bath mirror cabinets',
'floor squeege': 'floor squeegee',
'squeege': 'squeegee',
'allure golden oaksku579331': 'allure golden oak sku 579331',
'artificial turf for petrs': 'artificial turf for pets',
'8 foot florescent light bulb': '8 foot fluorescent light bulb',
'3x3 diamond thread plate': '3x3 diamond tread plate',
'handical rail': 'handicap rail',
'moen grab bar securemount': 'moen grab bar secure mount',
'ceiling mount electical box': 'ceiling mount electrical box',
'stainless steal hose clamps': 'stainless steel hose clamps',
'sod grass san agustino': 'sod grass san agustin',
'bateries 9v': 'batteries 9v',
'kohler brushed nickle framless shower doors': 'kohler brushed nickel frameless shower doors',
'mirro shower doors': 'mirror shower doors',
'daylillies': 'daylilies',
'fridgedaire fridge': 'frigidaire fridge',
'storage buiding 12\' x 20\'': 'storage building 12\' x 20\'',
'pvc valvez': 'pvc valves',
'socket magnectic extension': 'socket magnetic extension',
'shop vac aacessories': 'shop vac accessories',
'roll jp door': 'roll up door',
'rollup door': 'roll up door',
'steibler eltron': 'stiebel eltron',
'liquid itght non metalic': 'liquid tight non metallic',
'metalic lquid tight': 'metallic liquid tight',
'22 bin plastic drawer parts storage organiz': '22 bin plastic drawer parts storage organizer',
'marroon roof screws': 'maroon roof screws',
'battery opererated lighting': 'battery operated lighting',
'roybi pop up': 'ryobi pop up',
'connectorv 30': 'connector 30',
'ge gfi braker 30amp': 'ge gfci breaker 30 amp',
'pipe swer': 'pipe sewer',
'treaded pvc pipe fitting': 'threaded pvc pipe fitting',
'cornewr bathtub': 'corner bathtub',
'whirlpool apron bathtup': 'whirlpool apron bathtub',
'veranda facia': 'veranda fascia',
'rrecessed light trim ring': 'recessed light trim ring',
'1 light steele sconce': '1 light steel sconce',
'7\' 90 elboq': '7\' 90 elbow',
'drawer guides and slides': 'drawer glides and slides',
'christmsa dog': 'christmas dog',
'light weight coccrete': 'lightweight concrete',
'hardwoo flooring 2 1/4 in': 'hardwood flooring 2 1/4 in',
'garden hose filter attactchent': 'garden hose filter attachment',
'milwaukie saw blades': 'milwaukee saw blades',
'dewalt extention cord': 'dewalt extension cord',
'hampton bay high gloss jabot laminate': 'hampton bay high gloss jatoba laminate',
'20v blacker and decker charger': '20v black and decker charger',
'15 water depth bathub': '15 water depth bathtub',
'magnetized wall covering': 'magnetic wall covering',
'fire brick and morter': 'fire brick and mortar',
'anderson french wood patio door 400 series': 'andersen frenchwood patio door 400 series',
'outdoor baners': 'outdoor banners',
'osciallating blade to cut tile': 'oscillating blade to cut tile',
'one way valae': 'one way valve',
'black decker matris': 'black decker matrix',
'makita skill saw': 'makita skil saw',
'tuscon patio pavers': 'tucson patio pavers',
'plastic florring': 'plastic flooring',
'fungicidal seed innoculant': 'fungicidal seed inoculant',
'pcv coated hardware cloth': 'pvc coated hardware cloth',
'2x2 ceiling tilepantq22s': '2x2 ceiling tile paint 22s',
'rectangulat wihite ceramic sink bathroom': 'rectangular white ceramic sink bathroom',
'battery operataed wall light': 'battery operated wall light',
'72 inchtrack light': '72 inch track light',
'suny citrus fertilizer': 'sunny citrus fertilizer',
'48 inch aluminum shower curtin rod': '48 inch aluminum shower curtain rod',
'dehumidifyer': 'dehumidifier',
'earthquaike': 'earthquake',
'phillips led sparkle light bulbs': 'philips led sparkle light bulbs',
'metalic silver spray': 'metallic silver spray',
'all retaing wall': 'all retaining wall',
'high temperate sealant': 'high temperature sealant',
'greecian white porcelein marble': 'greecian white porcelain marble',
'shelves stailess stel': 'shelves stainless steel',
'wallmounted garage shelves': 'wall mounted garage shelves',
'remote meat thermom': 'remote meat thermometer',
'pvc threaded elbo': 'pvc threaded elbow',
'summit 20 in elctric range': 'summit 20 in electric range',
'groung fault electric outlet': 'ground fault electrical outlet',
'prenneols flower seeds': 'perennials flower seeds',
'hyrdaulic oil for kohler': 'hydraulic oil for kohler',
'hot/cold porcelin handles': 'hot/cold porcelain handles',
'white vanites with tops': 'white vanities with tops',
'exterier door keypad': 'exterior door keypad',
'purpor power': 'purple power',
'automatic drower closer': 'automatic drawer closer',
'potable firepace': 'portable fireplace',
'azelas': 'azaleas',
'mta distributions log splitter': 'mta distributors log splitter',
'standing town rack': 'standing towel rack',
'zinser stain cover': 'zinsser stain cover',
'weed trimer push type': 'weed trimmer push type',
'centipe grass seed': 'centipede grass seed',
'36 curved showered curtain rod': '36 curved shower curtain rod',
'4 quck grip 101': '4 quick grip 101',
'metal gringing weel 5/8': 'metal grinding wheel 5/8',
'weelbarrow': 'wheelbarrow',
'baraar emy': 'bazaar emy',
'wetbar sink and faucet': 'wet bar sink and faucet',
'perenial flowers': 'perennial flowers',
'infred turkey fryer': 'infrared turkey fryer',
'oil rubbed bronse bathroom lighting': 'oil rubbed bronze bathroom lighting',
'solor power lighting for exterior': 'solar power lighting for exterior',
'infloor heating antifreeze': 'in floor heating antifreeze',
'galvinized conduit pipe': 'galvanized conduit pipe',
'double curtain rod connecter': 'double curtain rod connector',
'drop cieling tiles 2ft by 4 ft': 'drop ceiling tiles 2ft by 4ft',
'plug in led night lite photocell': 'plug in led night light photocell',
'rough limber': 'rough lumber',
'48x48 windoww': '48x48 window',
'high intensity t5 flourescent lights': 'high intensity t5 fluorescent lights',
'brinly hardy 40 inc tow behind': 'brinly hardy 40 inch tow behind',
'ornge 5x7 rugs': 'orange 5x7 rugs',
'kitchenmaid built-in double drawer': 'kitchenaid built-in double drawer',
'safety latter': 'safety ladder',
'blind replacemetn': 'blind replacement',
'stainless steeel collated nails': 'stainless steel collated nails',
'hang rials barnyard doors': 'hang rails barnyard doors',
'tall black toliet': 'tall black toilet',
'fint tube': 'find tube',
'24 inches rerefrigerator': '24 inches refrigerator',
'ge microwave wall oven comb': 'ge microwave wall oven combo',
'presure treated': 'pressure treated',
'husky 46 9 drawer mobil': 'husky 46 9 drawer mobile',
'apartment size ge refrigertor stainless steel': 'apartment size ge refrigerator stainless steel',
'penedtrating stain': 'penetrating stain',
'briggsstraton 11 horse air filter': 'briggs stratton 11 horse air filter',
'hoovwe cordless vacuum cleaners': 'hoover cordless vacuum cleaners',
'tumbler dryer hose and claps': 'tumble dryer hose and clamps',
'antique truch': 'antique truck',
'hohler black and tan': 'kohler black and tan',
'spray and forget house nad deck': 'spray and forget house and deck',
'apriaire humidifier water panel': 'aprilaire humidifier water panel',
'unsanded groutr': 'unsanded grout',
'60 wat soft watt 2700k a19 dimibal led': '60 watt soft watt 2700k a19 dimmable led',
'7.5 mconnection for 9000 btu': '7.5 connection for 9000 btu',
'dimer switch and fan control': 'dimmer switch and fan control',
'granitecounter top cararra': 'granite countertop carrara',
'20 amp decor outlet ivory': '20 amp decora outlet ivory',
'rock wall papper': 'rock wallpaper',
'thin set fray': 'thin set gray',
'glass mirrior doors 72x80': 'glass mirror doors 72x80',
'heirloom whie': 'heirloom white',
'wood shelfing': 'wood shelving',
'kohler top mont bathroom sink': 'kohler top mount bathroom sink',
'outdoor dust to dawn light': 'outdoor dusk to dawn light',
'windowbalance': 'window balance',
'gunstock oak liamate': 'gunstock oak laminate',
'gardden benches': 'garden benches',
'strended electrical wire': 'stranded electrical wire',
'counter refinsher': 'counter refinishing',
'unfinished wood p-lant stand': 'unfinished wood plant stand',
'celing fan 60': 'ceiling fan 60',
'porta nailor': 'porta nailer',
't fittin': 't fitting',
'bousch lazer level gll2-80p': 'bosch laser level gll2-80p',
'2 1/2 inch nail boxe': '2 1/2 inch nail box',
'bonda body filler': 'bondo body filler',
'window manganetic lock': 'window magnetic lock',
'cat 5 cable uv restance': 'cat 5 cable uv resistance',
'3 4 toilet phlange': '3 4 toilet flange',
'aa batteried': 'aa batteries',
'6 pvc flixible coupling pipe': '6 pvc flexible coupling pipe',
'7 footaluminum awning': '7 foot aluminum awning',
'carburator': 'carburetor',
'water mainfold': 'water manifold',
'kholer bathroom wall lights': 'kohler bathroom wall lights',
'toro belt pully': 'toro belt pulley',
'paper lawn tefuse bags': 'paper lawn refuse bags',
'wadrobe moving boxes': 'wardrobe moving boxes',
'ultra clarifer, pool': 'ultra clarifier, pool',
'trash caninet slide': 'trash cabinet slide',
'craftig pvc cabinets': 'crafting pvc cabinets',
'plastic organozers': 'plastic organizers',
'rj45 crinp tool': 'rj45 crimp tool',
'darby 18 inch dishwasher': 'danby 18 inch dishwasher',
'10 x 10 gaxebo garden house': '10x10 gazebo garden house',
'colonial caseing': 'colonial casing',
'tarp for outsid furniture': 'tarp for outside furniture',
'phlne batteries': 'phone batteries',
'eatrhwise mower blades': 'earthwise mower blades',
'outdoor artifical lawn': 'outdoor artificial lawn',
'dual mount porcelin kitchen sinks': 'dual mount porcelain kitchen sinks',
'sflexible shower': 'flexible shower',
'savfavieh rug pad': 'safavieh rug pad',
'tigerwood perigo laminate flooring': 'tigerwood pergo laminate flooring',
'2\' flourescent lighting': '2\' fluorescent lighting',
'concerte stair railings': 'concrete stair railings',
'indoor infered heaters': 'indoor infrared heaters',
'tensil ties': 'tinsel ties',
'20 ampweather proof recepticles': '20 amp weatherproof receptacles',
'hdmi cabl': 'hdmi cable',
'matage double oven ranges': 'maytag double oven ranges',
'navarra sierra passage doorknob set': 'navarra sierra passage door knob set',
'outdoor furniture cover martha steward': 'outdoor furniture cover martha stewart',
'divonshire': 'devonshire',
'marine grade painr': 'marine grade paint',
'counter and appliance gaperaser': 'counter and appliance gap eraser',
'whirpool range hood 36': 'whirlpool range hood 36',
'flourecent': 'fluorescent',
'drain spoutts': 'drain spouts',
'1/4 shut off velves': '1/4 shut off valves',
'porta cool': 'portacool',
'yard walll': 'yard wall',
'kohler elongaterd toilet seat': 'kohler elongated toilet seat',
'kohler lighted tolet seats': 'kohler lighted toilet seats',
'cree led bub 6-pack': 'cree led bulb 6-pack',
'concrere chisel': 'concrete chisel',
'pedistal sink, 27\'': 'pedestal sink, 27\'',
'florsent replacement diffuser': 'fluorescent replacement diffuser',
'chlorox': 'clorox',
'core aeretor': 'core aerator',
'water proofing connector': 'waterproof connector',
'washer/dryr': 'washer/dryer',
'cambria java refridgerator': 'cambria java refrigerator',
'decrotive metal deck rail incecerts': 'decorative metal deck rail inserts',
'whirl pool water heater pilot': 'whirlpool water heater pilot',
'siemens double pole gfi': 'siemens double pole gfci',
'hampton bay alenxander oak': 'hampton bay alexander oak',
'32 inchvinyl screen doors': '32 inch vinyl screen doors',
'hamptonbay shaker cabinets wall': 'hampton bay shaker cabinets wall',
'3/8 entension': '3/8 extension',
'10x12 outdoor gazabos': '10x12 outdoor gazebos',
'seet metal tools': 'sheet metal tools',
'boch gll': 'bosch gll',
'dealt 8v screwdriver': 'dewalt 8v screwdriver',
'hand heald showers and ada grab bars': 'hand held showers and ada grab bars',
'200 amp outdoor circut breaker panel': '200 amp outdoor circuit breaker panel',
'fingerprint lockset': 'fingerprint locks',
'weekender powerwasher extension arms': 'weekender power washer extension arms',
'makita drill batterie charger': 'makita drill battery charger',
'ridgid fan': 'rigid fan',
'swifer wet cloth': 'swiffer wet cloth',
'hot water recirculator': 'hot water recirculation',
'riding mower blabes': 'riding mower blades',
'chain sherpeners': 'chain sharpeners',
'relief valve for rudd hot water heater': 'relief valve for ruud hot water heater',
'ceiling light brackt': 'ceiling light bracket',
'perferated pipe': 'perforated pipe',
'bath room sink accecories': 'bathroom sink accessories',
'ding room set': 'dining room set',
'2 ton expoxy': '2 ton epoxy',
'cutkler hammer breaker': 'cutler hammer breaker',
'red color cauking': 'red color caulking',
'strap and t hindge': 'strap and t hinge',
'screw driver 10 iches': 'screwdriver 10 inches',
'shower glass slelves': 'shower glass shelves',
'playststion 4 destiny bundle': 'playstation 4 destiny bundle',
'air conditiooning filter 14\'': 'air conditioning filter 14\'',
'sliding reversable patio door': 'sliding reversible patio door',
'rust oleam pinters touch black': 'rust oleum painters touch black',
'apron sink firecaly two bowl': 'apron sink fireclay two bowl',
'condesate pump': 'condensate pump',
'bronze outdoor ceiling dan': 'bronze outdoor ceiling fan',
'8 guage wire': '8 gauge wire',
'capacitor for quaterhorse motor 110 volts': 'capacitor for quarter horse motor 110 volts',
'anderson storm doors antique bronze': 'andersen storm doors antique bronze',
'gas enthonal free': 'gas ethanol free',
'is item at homedop': 'is item at home depot',
'drain stopper exstension': 'drain stopper extension',
'no tresspassing': 'no trespassing',
'100 gallon storage ben': '100 gallon storage bin',
'paint hardner': 'paint hardener',
'mystick permanent adhesive value pack': 'mystik permanent adhesive value pack',
'clear vlyvynal an rolls': 'clear polyvinyl and rolls',
'kliz primers': 'kilz primers',
'one way scrue removal tool': 'one way screw removal tool',
'stainless dishwaser smugde proof': 'stainless dishwasher smudge proof',
'hex shank drill bitt sets': 'hex shank drill bit sets',
'3.9 high effeciency front load washer': '3.9 high efficiency front load washer',
'concret patio floor': 'concrete patio floor',
'in the ground rodiron plant hanger': 'in the ground rod iron plant hanger',
'anderson storm door series 2500 sandtone polished brass': 'andersen storm door series 2500 sandstone polished brass',
'stainless steele screws': 'stainless steel screws',
'spray sealent for showers': 'spray sealant for showers',
'split line air conditioing': 'split line air conditioning',
'water softner pellet': 'water softener pellet',
'shelac': 'shellac',
'helti tools': 'hilti tools',
'PHILLIPS POST LIGHT BULB': 'PHILIPS POST LIGHT BULB',
'post light bulbl': 'post light bulb',
'tiolet': 'toilet',
'indoor home decor raindeer': 'indoor home decor reindeer',
'dinning tables': 'dining tables',
'patio dinning tables': 'patio dining tables',
'dremel router acessary': 'dremel router accessory',
'accordion door harware': 'accordion door hardware',
'edget tape': 'edge tape',
'verneer edging tool': 'veneer edging tool',
'drywall fastner': 'drywall fastener',
'heat pump acessories': 'heat pump accessories',
'scroll saw spirsl blade': 'scroll saw spiral blade',
'kitchen mat boack': 'kitchen mat black',
'chamberlain chain and pulliepaarts': 'chamberlain chain and pulley parts',
'swivle fitting for gas': 'swivel fitting for gas',
'SOLDERING IRORN': 'SOLDERING IRON',
'oaint marker': 'paint marker',
'upsidedowncan marker paint': 'upside down can marker paint',
'rope chritsmas lights': 'rope christmas lights',
'shower curtin rod': 'shower curtain rod',
'scoaring pads': 'scouring pads',
'spring set for price fister': 'spring set for price pfister',
'laquer thinner': 'lacquer thinner',
'mout faucet water filter': 'mount faucet water filter',
'NEUMATIC DOOR ARM': 'PNEUMATIC DOOR ARM',
'ceiling tile square fotage': 'ceiling tile square footage',
'ne angle base': 'neo angle base',
'1/4 in.-20 x 1 in. stainless steel flat-head socket cap scre': '1/4 in.-20 x 1 in. stainless steel flat-head socket cap screw',
'flexable pipe for propane': 'flexible pipe for propane',
'daltile accent peices': 'daltile accent pieces',
'specticide weed and grass rtu refill': 'spectracide weed and grass rtu refill',
'wood ddeck kits': 'wood deck kits',
'closetmaid hang9ing shelf': 'closetmaid hanging shelf',
'asb shower with curtian': 'asb shower with curtain',
'ptouch labeling tape': 'p touch labeling tape',
'misquito': 'mosquito',
'yard fooger': 'yard fogger',
'plastic splash guarf': 'plastic splash guard',
'3 light celling mount': '3 light ceiling mount',
'textered wallpaper': 'textured wallpaper',
'thermostat w remote senser': 'thermostat w remote sensor',
'spray oil prier': 'spray oil primer',
'maxx shower door': 'maax shower door',
'corion shower base': 'corian shower base',
'stapler hammers': 'staple hammers',
'2in non metalic standing coupling': '2in non metallic standing coupling',
'backyard xs capes': 'backyard xscapes',
'kraylon non skid': 'krylon non skid',
'pendent lights wit conversion kits': 'pendant lights with conversion kits',
'american wood charllotesville natural hickory': 'american wood charlottesville natural hickory',
'1/0 aqg': '1/0 awg',
'artci shag rug': 'arctic shag rug',
'omen single hole bathroom faucet': 'moen single hole bathroom faucet',
'john deere d100 sereissnow blade': 'john deere d100 series snow blade',
'brownbrick wallpaper': 'brown brick wallpaper',
'clear corrougated sheets': 'clear corrugated sheets',
'pressuer control valve': 'pressure control valve',
'white acryllic sheet': 'white acrylic sheet',
'wg307work jaw saw': 'wg307 worx jawsaw',
'plaskolight ceiling panel': 'plaskolite ceiling panel',
'charger y maintainer': 'charger and maintainer',
'waterless urinal conversion kist': 'waterless urinal conversion kit',
'hot water heating recirculitating pumps': 'hot water heater recirculating pumps',
'two gang carlton switch red dpt': 'two gang carlton switch red dot',
'kohler shower cartidges': 'kohler shower cartridges',
'rigid portable tool boxes': 'ridgid portable tool boxes',
'magniflier lamp': 'magnifier lamp',
'irragation controler': 'irrigation controller',
'minala rope': 'manila rope',
'wood sculture tool': 'wood sculpture tool',
'combination fan and lightwall switches': 'combination fan and light wall switches',
'acid stian': 'acid stain',
'bathtub deck mouted faucet with sprayer': 'bathtub deck mounted faucet with sprayer',
'attachments for zero turn touro': 'attachments for zero turn toro',
'wood pellats for grills': 'wood pellets for grills',
'whirpool 7000 washer': 'whirlpool 7000 washer',
'kitchenover sink lighting': 'kitchen over sink lighting',
'pegasus antique black side spalsh': 'pegasus antique black side splash',
'lock tight pl': 'loctite pl',
'landscasping ms international polish black stone': 'landscaping ms international polish black stone',
'1.4 cubit ft micro wave': '1.4 cubic ft microwave',
'square soffet vents': 'square soffit vents',
'exterior for pastic shutters': 'exterior for plastic shutters',
'exterior hous shutters': 'exterior house shutters',
'nutone ventiliation fan parts': 'nutone ventilation fan parts',
'belt anf tie rack': 'belt and tie rack',
'no elecetrity lights': 'no electricity lights',
'merola porcelain mosiac': 'merola porcelain mosaic',
'knotches': 'notches',
'savavieh soho': 'safavieh soho',
'double doors with security licks': 'double doors with security locks',
'glass tile backsp gpxtpnrf': 'glass tile backsp gpx pnrf',
'cabibet shelf pins': 'cabinet shelf pins',
'kolher repair': 'kohler repair',
'mantle brakets': 'mantle brackets',
'masonry painnt': 'masonry paint',
'muliti locks': 'multi locks',
'serger sewimg machine': 'serger sewing machine',
'mirror installation hardwawrd': 'mirror installation hardware',
'walnut porcelian': 'walnut porcelain',
'40 airens mulching kit': '40 ariens mulching kit',
'porcelaine cleaner': 'porcelain cleaner',
'monococcon 8x8 ceramic azuvi tile': 'monococcion 8x8 ceramic azuvi tile',
'black patioo set': 'black patio set',
'3/8 viyl j channel': '3/8 vinyl j channel',
'5/8 j chann': '5/8 j channel',
'home alerty': 'home alert',
'linen storage cabnit': 'linen storage cabinet',
'natur gas heat': 'natural gas heat',
'repacement toilet handle': 'replacement toilet handle',
'poyurethane clear satin': 'polyurethane clear satin',
'garbage desposal': 'garbage disposal',
'fire restaint paint': 'fire resistant paint',
'bathroom floting ball': 'bathroom floating ball',
'kitchen aid processer': 'kitchenaid processor',
'fire extinguishhers': 'fire extinguishers',
'trex fenc': 'trex fence',
'circular sawshop vac': 'circular saw shop vac',
'arylic wood paint': 'acrylic wood paint',
'appache mills plush tiles': 'apache mills plush tiles',
'phillips tuvpl-l 36': 'philips tuv pl-l 36',
'framed inerior door': 'framed interior door',
'end squicky floor': 'end squeaky floor',
'hoover prower scub deluxe': 'hoover power scrub deluxe',
'pernennial grass seed': 'perennial grass seed',
'phone linesplice connectors': 'phone line splice connectors',
'grow boz and pots': 'grow box and pots',
'organic leafgrow soil': 'organic leaf grow soil',
'6 foot pation table': '6 foot patio table',
'replacement patio unbrella pole': 'replacement patio umbrella pole',
'exteriro door 30 * 80': 'exterior door 30 * 80',
'oilrubbed bronze 3/8in riser': 'oil rubbed bronze 3/8in riser',
'latge storage containers': 'large storage containers',
'fridgidaire water filter': 'frigidaire water filter',
'sheeking for log cabin': 'seeking for log cabin',
'modern shower facuet': 'modern shower faucet',
'mirror, brushed nichel': 'mirror, brushed nickel',
'antic brass chandelier': 'antique brass chandelier',
'bufflo box wrench': 'buffalo box wrench',
'armstrong hardwood flooring422250z5p': 'armstrong hardwood flooring 422250z5p',
'mixet math faucet': 'mixet bath faucet',
'24 port patch pane': '24 port patch panel',
'black postlantern': 'black post lantern',
'needel valve': 'needle valve',
'wood ballusters': 'wood balusters',
'sharkbite sprinler': 'sharkbite sprinkler',
'1/2 hp genie screw drive garage door openner': '1/2 hp genie screw drive garage door opener',
'black dimmable gimble lights': 'black dimmable gimbal lights',
'power gable mount attic fac': 'power gable mount attic fan',
'door threshholds': 'door thresholds',
'rubber office chair sweel': 'rubber office chair wheel',
'16x7 garage door sandtone': '16x7 garage door sandstone',
'dal tile 12x24 porcelaine black tile': 'daltile 12x24 porcelain black tile',
'non ferroue saw blade': 'non ferrous saw blade',
'aluminum three way swich': 'aluminum three way switch',
'racheting wrench': 'ratcheting wrench',
'shower wal hook': 'shower wall hook',
'inflatable pool pumper': 'inflatable pool pump',
'cub cadet 46 balde': 'cub cadet 46 blade',
'spade terminalsnylon insulated': 'spade terminals nylon insulated',
'jimmyproof lock': 'jimmy proof lock',
'braSS pie fittings': 'braSS pipe fittings',
'brushed nichol hanging lights': 'brushed nickel hanging lights',
'lockbox keydoor lock': 'lockbox key door lock',
'white cabnet 30 inch base': 'white cabinet 30 inch base',
'ryobi replacemet batteries': 'ryobi replacement batteries',
'bath bord': 'bath board',
'aerp garden': 'aerogarden',
'white sign lettters': 'white sign letters',
'sqaure vessel sink': 'square vessel sink',
'i beam brackest': 'i beam brackets',
'paint for aluminun siding': 'paint for aluminum siding',
'digital temp monotor': 'digital temp monitor',
'floatinf shelving': 'floating shelving',
'light buld for stinger zapper': 'light bulb for stinger zapper',
'custom counterto': 'custom countertop',
'replacement delta faucet cartrigdge': 'replacement delta faucet cartridge',
'laundry bnasket': 'laundry basket',
'air conditon cooper soft': 'air conditioner copper soft',
'wood qwik bolts': 'wood kwik bolts',
'bolt conrete anchors': 'bolt concrete anchors',
'outdoor dining se?': 'outdoor dining set?',
'glass sheet mosiacs': 'glass sheet mosaics',
'whites parkle': 'white sparkle',
'fiskers titanium 1 1/2 loppers': 'fiskars titanium 1 1/2 loppers',
'cement mason bit': 'cement masonry bit',
'bananna leaves plant': 'banana leaves plant',
'fi nish screws': 'finish screws',
'tolet handle left hand': 'toilet handle left hand',
'sika repair shp': 'sika repair shop',
'murry circuit breakers 20 amps': 'murray circuit breakers 20 amps',
'hand pipe theader': 'hand pipe threader',
'powermate walkbehind trimmer': 'powermate walk behind trimmer',
'metal clothes handing carts': 'metal clothes hanging carts',
'electric radiatior heat': 'electric radiator heat',
'shopvac filter hepa': 'shop vac filter hepa',
'hampton bay fenving': 'hampton bay fencing',
'knife sharppener': 'knife sharpener',
'atttic heat barrier': 'attic heat barrier',
'wondow curtains': 'window curtains',
'american standard town square widespread facet': 'american standard town square widespread faucet',
'5.0 chest freezerz': '5.0 chest freezers',
'20 amp surger protector': '20 amp surge protector',
'f 30 flourescent light fixture': 'f30 fluorescent light fixture',
'1/2 inch rubber lep tips': '1/2 inch rubber leg tips',
'threader rod end coupler': 'threaded rod end coupler',
'lamated counter tops': 'laminate countertops',
'railing kit system round ballusters': 'railing kit system round balusters',
'sintetic grass': 'synthetic grass',
'landry sink': 'laundry sink',
'solar led light dust to dawn': 'solar led light dusk to dawn',
'pegro xp coffee step': 'pergo xp coffee step',
'maytag two door refridgerator': 'maytag two door refrigerator',
'reprobramable combination lock': 'programmable combination lock',
'pnematic flooring nails 16 gauge': 'pneumatic flooring nailer 16 gauge',
'outide dog kennel': 'outside dog kennel',
'6 incn door knocker': '6 inch door knocker',
'non programmable vertical thermost': 'non programmable vertical thermostat',
'windser light coco': 'windsor light coco',
'cooling towes': 'cooling towers',
'glacier bay shower catridge': 'glacier bay shower cartridge',
'ge discontinnued top freezers': 'ge discontinued top freezers',
'security camaras': 'security cameras',
'toiles partes': 'toilet parts',
'pegasus ntique brass': 'pegasus antique brass',
'water pic shower head chrome': 'waterpik shower head chrome',
'85 gall tall 4500': '85 gal tall 4500',
'contempery ceiling fans': 'contemporary ceiling fans',
'toile seat lid': 'toilet seat lid',
'milwaukee noncontact tester': 'milwaukee non contact tester',
'emser ocuntry': 'emser country',
'front screen for a gazeebo': 'front screen for a gazebo',
'fatpack 18v': 'fat pack 18v',
'bathroom kraft made': 'bathroom kraftmaid',
'1/4 qk connect x 1/8 mip': '1/4 quick connect x 1/8 mip',
'plate for faucet stoper': 'plate for faucet stopper',
'femaie gas fitting quick disonnect': 'female gas fitting quick disconnect',
'recesse light bulbs': 'recessed light bulbs',
'3m 60926 vapor catridges': '3m 60926 vapor cartridges',
'weather strip for commerial door': 'weather strip for commercial door',
'arcadia mettal locks': 'arcadia metal locks',
'gekko gauges': 'gecko gauges',
'frigidaire water firlters': 'frigidaire water filters',
'30 par haolgen bulbs': '30 par halogen bulbs',
'red devil scraperreplacement bldes': 'red devil scraper replacement blades',
'gcfi outlet': 'gfci outlet',
'mohawk oak wood fllors': 'mohawk oak wood floors',
'all porpose stools': 'all purpose stools',
'primered floor molding': 'primed floor molding',
'glass cleaner concintrete': 'glass cleaner concentrate',
'30 amp surface mount recepticle': '30 amp surface mount receptacle',
'60 x 100 aluminun mesh': '60 x 100 aluminum mesh',
'tile border black and whit': 'tile border black and white',
'peir mount black': 'pier mount black',
'xtra wide baby gates': 'extra wide baby gates',
'roffing caulk': 'roofing caulk',
'1/2 inc pvc treaded connector': '1/2 inch pvc threaded connector',
'electric hock for lift': 'electric shock for lift',
'greak': 'greek',
'airfilter 20x24': 'air filter 20x24',
'extenion cord storage': 'extension cord storage',
'shluter': 'schluter',
'circular saw rrip fence': 'circular saw rip fence',
'HEATED TOLIET SEAT': 'HEATED TOILET SEAT',
'rount magnet': 'round magnet',
'handi cap sink faucett': 'handicap sink faucet',
'arc fault circute breaker 1pole 15 amp': 'arc fault circuit breaker 1 pole 15 amp',
'oreck full reease carpet cleaner': 'oreck full release carpet cleaner',
'min split mounting brackets': 'mini split mounting brackets',
'kholer sink 20x17': 'kohler sink 20x17',
'heavy duty extensoion cordyellow only': 'heavy duty extension cord yellow only',
'3 newll post': '3 newel post',
'veraluz 4 light bathroom vanity': 'varaluz 4 light bathroom vanity',
'anual combo': 'annual combo',
'ciling pan': 'ceiling pan',
'syllicone lube': 'silicone lube',
'hdx 20\' hight velocity floor fan': 'hdx 20\' high velocity floor fan',
'30 inch kitchenaide cooktops': '30 inch kitchenaid cooktops',
'kusshuln concrete mixer': 'kushlan concrete mixer',
'roles of concreate mesh': 'roles of concrete mesh',
'hardward for pull out waste bin': 'hardware for pull out waste bin',
'glass towel bar braket': 'glass towel bar bracket',
'living room cabnets': 'living room cabinets',
'1-1/4 extention pvc': '1-1/4 extension pvc',
'metal double gain boxes': 'metal double gang boxes',
'fabric umbella': 'fabric umbrella',
'club cadet 46 belt': 'cub cadet 46 belt',
'window air conditionerriding lawn mowers': 'window air conditioner riding lawn mowers',
'digital cammera': 'digital camera',
'prppane pan': 'propane pan',
'oride plant': 'pride plant',
'home decorator outoddor patio cordless shades': 'home decorator outdoor patio cordless shades',
'1x1 square tubeing': '1x1 square tubing',
'water filter for frigidaire refrigirator': 'water filter for frigidaire refrigerator',
'linier track pendant': 'linear track pendant',
'medal stud finder': 'metal stud finder',
'mke m12 heated hoddie kit': 'mke m12 heated hoodie kit',
'bilt in pool': 'built in pool',
'buit in shower base': 'built in shower base',
'grohsafe roughin valve 35015': 'grohsafe rough in valve 35015',
'tank insualation': 'tank insulation',
'khols double toilet bowl': 'kohl\'s double toilet bowl',
'atlantiic can racks': 'atlantic can racks',
'skylites': 'skylights',
'kwikset passive door knob': 'kwikset passage door knob',
'loadspeaker': 'loudspeaker',
'koehler enamel cast iron sink': 'kohler enameled cast iron sink',
'tood handle lock': 'todd handle lock',
'sable brow grout': 'sable brown grout',
'rewd bird feeder': 'red bird feeder',
'lilac aera rug': 'lilac area rug',
'lightsavannah 3-light burnished ing fixtures': 'light savannah 3-light burnished ing fixtures',
'clear vynil for patio': 'clear vinyl for patio',
'intersate battery': 'interstate battery',
'jeldewen prairie mission door': 'jeld wen prairie mission door',
'honey oak tmolding': 'honey oak t molding',
'COMPLET SHOWER KIT': 'COMPLETE SHOWER KIT',
'36\' florescent light bulb': '36\' fluorescent light bulb',
'melon sunbrellap': 'melon sunbrella',
'28 kg washign machine': '28 kg washing machine',
'metal trash cas': 'metal trash cans',
'front door with side transome': 'front door with side transom',
'tribecia': 'tribeca',
'exterior shutters byrgundy': 'exterior shutters burgundy',
'light switchvers for little girls': 'light switches for little girls',
'miraposa whirlpool tub': 'mariposa whirlpool tub',
'schoolhouse pendqnt light': 'schoolhouse pendant light',
'cablrail': 'cable rail',
'vinly seat cleaner': 'vinyl seat cleaner',
'metal 3 tiertrolley': 'metal 3 tier trolley',
'white pendant uplight': 'white pendant light',
'lbathroom vanity lights chrome 3': 'bathroom vanity lights chrome 3',
'brushed nickel knobw': 'brushed nickel knobs',
'Renassaince': 'Renaissance',
'simpon strong tie wedge': 'simpson strong tie wedge',
'silocone repairs': 'silicone repairs',
'chocolate brown blackspash': 'chocolate brown backsplash',
'portabel tabel, plastic': 'portable table, plastic',
'safavieh courtyard dark biege area rug': 'safavieh courtyard dark beige area rug',
'theromometer smart': 'thermometer smart',
'hummngbird feeders': 'hummingbird feeders',
'diverter handels': 'diverter handles',
'dynamic desighn planters': 'dynamic design planters',
'pri meld flush bi fold doors': 'primed flush bifold doors',
'fisher and penkel': 'fisher and paykel',
'price of 1 gal beher marquee paint': 'price of 1 gal behr marquee paint',
'makersbot': 'makerbot',
'shelter logic sun sahde': 'shelterlogic sun shade',
'moen 4 port pex vavle': 'moen 4 port pex valve',
'ceiling fan extension wre': 'ceiling fan extension wire',
'single knobreplacement for shower kohler': 'single knob replacement for shower kohler',
'high gloss waterborne acrylic enamal': 'high gloss waterborne acrylic enamel',
'cattale': 'cattle',
'double deountable': 'double demountable',
'fantsastic': 'fantastic',
'milwaulkee battery charger': 'milwaukee battery charger',
'tandom 30 20': 'tandem 30 20',
'schluter kurdie': 'schluter kerdi',
'square buckes': 'square buckets',
'pro series vinal post': 'pro series vinyl post',
'krud cutter rust': 'krud kutter rust',
'warm espresso distresed': 'warm espresso distressed',
'levinton phone tv combo': 'leviton phone tv combo',
'makita planner knives': 'makita planer knives',
'barictric walk in tubs': 'bariatric walk in tubs',
'woper blades': 'wiper blades',
'kidcraft 18 doll furniture': 'kidkraft 18 doll furniture',
'stickon shower wall tower': 'stick on shower wall tower',
'riding lawn mower accesores': 'riding lawn mower accessories',
'towel bar nickel gracier 18\'': 'towel bar nickel glacier 18\'',
'compreshion repair kit': 'compression repair kit',
'huskie air compressors accessories': 'husky air compressors accessories',
'36 inch neo angle glass doooors': '36 inch neo angle glass doors',
'gerber cohort fine edg knife': 'gerber cohort fine edge knife',
'work force prpane heatr': 'workforce propane heater',
'progress lighting nottingdon': 'progress lighting nottington',
'dog leash atachments': 'dog leash attachments',
'elaphent ear': 'elephant ear',
'veeneer wood tape': 'veneer wood tape',
'siccsers': 'scissors',
'klien folding 6ft ruler': 'klein folding 6ft ruler',
'wall socket covedrs': 'wall socket covers',
'klein 8 inch plies': 'klein 8 inch pliers',
'screen doors: screen tight doors 32 in. unfinished wood t-ba': 'screen doors: screen tight doors 32 in. unfinished wood t-bar',
'g e dishwaaher': 'g e dishwasher',
'white semigloass': 'white semi gloss',
'shop swiming pools': 'shop swimming pools',
'rectangular baulaster': 'rectangular baluster',
'cedar 0roofing shingles': 'cedar roofing shingles',
'prehung door fanlite': 'prehung door fan lite',
'martha suart carpet tobacco leaf': 'martha stewart carpet tobacco leaf',
'furnance gas upflow': 'furnace gas upflow',
'spalted m aple': 'spalted maple',
'crimpling pleirs': 'crimping pliers',
'cold stem for glacer bay faucets': 'cold stem for glacier bay faucets',
'holegen flood light 35w': 'halogen flood light 35w',
'ridgid ipact wrench': 'rigid impact wrench',
'twin wsher dryer gas': 'twin washer dryer gas',
'Diamond HArd Acrylic Enamal': 'Diamond HArd Acrylic Enamel',
'stainless steel wall pannels': 'stainless steel wall panels',
'perenial bulb': 'perennial bulb',
'caroilne avenue 36 in single vanity in white marble top in l': 'caroline avenue 36 in single vanity in white marble top in l',
'broadway collectionchrome vanity fixture': 'broadway collection chrome vanity fixture',
'vogoro flower': 'vigoro flower',
'guarge parnel': 'gauge panel',
'sweeep pan': 'sweep pan',
'dewalt magnetic drive quide': 'dewalt magnetic drive guide',
'milwuakee magnetic drive guide': 'milwaukee magnetic drive guide',
'stainlss steel wire wheels': 'stainless steel wire wheels',
'deltile 3x6 ceramic blue': 'daltile 3x6 ceramic blue',
'discontinuedbrown and tan area rug': 'discontinued brown and tan area rug',
'frost protectionm': 'frost protection',
'5 tier chandalier': '5 tier chandelier',
'perry hickory laminte': 'perry hickory laminate',
'carpet chessnut': 'carpet chestnut',
'midnight blue irridecent': 'midnight blue iridescent',
'under cabinet black flourescent': 'under cabinet black fluorescent',
'concord charcole runner': 'concord charcoal runner',
'gibrallar post series cedar post': 'gibraltar post series cedar post',
'jefrrey court 3x12': 'jeffrey court 3x12',
'baking panb': 'baking pan',
'dustless ginder': 'dustless grinder',
'paw print doorbe;;': 'paw print doorbell;;',
'rustolium paint american accesnts': 'rustoleum paint american accents',
'costum key': 'custom key',
'halh circle glass shelf': 'half circle glass shelf',
'pedestial snk': 'pedestal sink',
'cordless celullar': 'cordless cellular',
'scounces wall light outside': 'sconces wall light outside',
'gas powere wood chipper': 'gas powered wood chipper',
'hampton bay brillant maple laminate': 'hampton bay brilliant maple laminate',
't8 flourescent bulbs 4 ft 2 pack': 't8 fluorescent bulbs 4 ft 2 pack',
'leminate floor alexandrea': 'laminate floor alexandria',
'reflector 50w flurecent': 'reflector 50w fluorescent',
'he xl 44 range': 'ge xl44 range',
'branch protctor paint': 'branch protector paint',
'rehargeable aa batteries for landscape lighting': 'rechargeable aa batteries for landscape lighting',
'msa safet work hat': 'msa safety work hat',
'conemporary hanging outdoor light fixture': 'contemporary hanging outdoor light fixture',
'piano door hing': 'piano door hinge',
'kohler whole houser generator': 'kohler whole house generator',
'dynasty collecion': 'dynasty collection',
'chesapeke nightstand in cherry': 'chesapeake nightstand in cherry',
'kohler glas shower door 4ft': 'kohler glass shower door 4ft',
'apartment size refreidgerator': 'apartment size refrigerator',
'centerpise': 'centerprise',
'motar for large tilw': 'mortar for large tile',
'bathroom lightning 48 inch': 'bathroom lighting 48 inch',
'panle clamp': 'panel clamp',
'roll up door fo shed': 'roll up door for shed',
'oil rubbed bronze airgap for dishwasher': 'oil rubbed bronze air gap for dishwasher',
'multi plub adapter': 'multi plug adapter',
'decorative clarance': 'decorative clarence',
'tamper resistant combo outet black': 'tamper resistant combo outlet black',
'polyurethane collors': 'polyurethane colors',
'scrool lever': 'scroll lever',
'gentec smoke detector': 'gentex smoke detector',
'kohler claxton biscuit sink': 'kohler caxton biscuit sink',
'strapping for cielings': 'strapping for ceilings',
'wall mounteddrop leaf table': 'wall mounted drop leaf table',
'chamberlain intercomm': 'chamberlain intercom',
'sumpter oask': 'sumpter oak',
'torino chandler 5 light bn': 'torino chandelier 5 light bn',
'allure red mahoghany': 'allure red mahogany',
'ge personal eletrical home security': 'ge personal electric home security',
'for rent sighn': 'for rent sign',
'coper clad aluminum': 'copper clad aluminum',
'homeywell cool moisture humidifier filters': 'honeywell cool moisture humidifier filters',
'hdc fairlawm jasper cane': 'hdc fairlawn jasper cane',
'wire fen c e': 'wire fence',
'cap screww everbilt 1/4in x2in': 'cap screw everbilt 1/4in x2in',
'metal urathane': 'metal urethane',
'blitz colth': 'blitz cloth',
'commercial accunts': 'commercial accounts',
'electic chainsaw worx': 'electric chainsaw worx',
'power toll accesories': 'power tool accessories',
'leviton - decora 3 gang midway nylon wall plate - light almo': 'leviton - decora 3 gang midway nylon wall plate - light almond',
'pond filter mediumpond filter pads': 'pond filter media pond filter pads',
'tall wine cabnet': 'tall wine cabinet',
'bulk calking': 'bulk caulking',
'insolated cooler with a strap': 'insulated cooler with a strap',
'concete placer': 'concrete placer',
'transmissin leak stopper': 'transmission leak stopper',
'toilet in buisk': 'toilet in buick',
'black wire hidder': 'black wire hider',
'braid trim ceramic title molding': 'braid trim ceramic tile molding',
'laundry tub fosets valves': 'laundry tub faucets valves',
'schlage plymoth orbit oil rubbed bronze': 'schlage plymouth orbit oil rubbed bronze',
'romanic poetry flat interior paint': 'romantic poetry flat interior paint',
'worklight 500 watt bullbs': 'worklight 500 watt bulbs',
'elvies ornament': 'elvis ornament',
'dpcam camera': 'dropcam camera',
'clorine tabs for septic': 'chlorine tabs for septic',
'interor door framed': 'interior door frame',
'hot dipped galvanized screwes': 'hot dipped galvanized screws',
'14 ft. w x29 ft. l x 14 ft.h': '14 ft. w x 29 ft. x 14 ft.h',
'water resistent top': 'water resistant top',
'galvinize 2 in box of screws': 'galvanized 2 in box of screws',
'taupe teasure carpet': 'taupe treasure carpet',
'nickle vanity lighting mosaics': 'nickel vanity lighting mosaics',
'heat circualtor': 'heat circulator',
'flexible pvc joing': 'flexible pvc joint',
'14 metal abresive blade': '14 metal abrasive blade',
'foldin g patio doors': 'folding patio doors',
'primeline mirror sliding doors': 'prime line mirror sliding doors',
'sanora maple flooring': 'sonora maple flooring',
'plastic paint containwes with lid': 'plastic paint containers with lid',
'deck fasting systems': 'deck fastening systems',
'long handled squeege window cleaning': 'long handled squeegee window cleaning',
'lsnd scape trim edger': 'landscape trim edger',
'rust oleum aged iron': 'rustoleum aged iron',
'redi ledge cooner': 'redi ledge corner',
'milwakee work radio': 'milwaukee work radio',
'progress piedmot': 'progress piedmont',
'home security camera cablee': 'home security camera cable',
'white rock daltale': 'white rock daltile',
'japenes lilacs': 'japanese lilacs',
'thickrubber mat': 'thick rubber mat',
'topdown bottom up shades': 'top down bottom up shades',
'locktite 9oz 2in1 premium sealant': 'loctite 9oz 2in1 premium sealant',
'evaporative thermstate': 'evaporative thermostat',
'red devil paint cleanaer': 'red devil paint cleaner',
'beer wine refrigeratr': 'beer wine refrigerator',
'forced air vents covrs': 'forced air vents covers',
'ew drops marquee paint': 'dew drops marquee paint',
'kitchen sink and fawcet black dual mount': 'kitchen sink and faucet black dual mount',
'dimmable fluoreecent': 'dimmable fluorescent',
'textured 6 pannel hollow core primed composite prehung inter': 'textured 6 panel hollow core primed composite prehung inter',
'dakato 4 light': 'dakota 4 light',
'playset handels': 'playset handles',
'vauhhan hammers': 'vaughan hammers',
'sterling frosted glass shower ath doors': 'sterling frosted glass shower bath doors',
'autom tic drawer lite': 'automatic drawer light',
'all trellisses': 'all trellises',
'american standard 5324.019 enlongate toilet seat': 'american standard 5324.019 elongated toilet seat',
'15 in built in maytag trash compactorr': '15 in built in maytag trash compactor',
'3 butto pico pj-3b': '3 button pico pj-3b',
'ligth': 'light',
'sissors': 'scissors'
}
|
hamid-omid/search_relevance
|
spell_corr.py
|
Python
|
mit
| 170,663
|
# Copyright 2015, Google 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 Google Inc. nor the names of its
# contributors 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.
"""Abstract tests against the interfaces of the base layer of RPC Framework."""
import threading
import time
from grpc.framework.base import interfaces
from grpc.framework.base import util
from grpc.framework.foundation import stream
from grpc.framework.foundation import stream_testing
from grpc.framework.foundation import stream_util
TICK = 0.1
SMALL_TIMEOUT = TICK * 50
STREAM_LENGTH = 100
SYNCHRONOUS_ECHO = 'synchronous echo'
ASYNCHRONOUS_ECHO = 'asynchronous echo'
IMMEDIATE_FAILURE = 'immediate failure'
TRIGGERED_FAILURE = 'triggered failure'
WAIT_ON_CONDITION = 'wait on condition'
EMPTY_OUTCOME_DICT = {
interfaces.Outcome.COMPLETED: 0,
interfaces.Outcome.CANCELLED: 0,
interfaces.Outcome.EXPIRED: 0,
interfaces.Outcome.RECEPTION_FAILURE: 0,
interfaces.Outcome.TRANSMISSION_FAILURE: 0,
interfaces.Outcome.SERVICER_FAILURE: 0,
interfaces.Outcome.SERVICED_FAILURE: 0,
}
def _synchronous_echo(output_consumer):
return stream_util.TransformingConsumer(lambda x: x, output_consumer)
class AsynchronousEcho(stream.Consumer):
"""A stream.Consumer that echoes its input to another stream.Consumer."""
def __init__(self, output_consumer, pool):
self._lock = threading.Lock()
self._output_consumer = output_consumer
self._pool = pool
self._queue = []
self._spinning = False
def _spin(self, value, complete):
while True:
if value:
if complete:
self._output_consumer.consume_and_terminate(value)
else:
self._output_consumer.consume(value)
elif complete:
self._output_consumer.terminate()
with self._lock:
if self._queue:
value, complete = self._queue.pop(0)
else:
self._spinning = False
return
def consume(self, value):
with self._lock:
if self._spinning:
self._queue.append((value, False))
else:
self._spinning = True
self._pool.submit(self._spin, value, False)
def terminate(self):
with self._lock:
if self._spinning:
self._queue.append((None, True))
else:
self._spinning = True
self._pool.submit(self._spin, None, True)
def consume_and_terminate(self, value):
with self._lock:
if self._spinning:
self._queue.append((value, True))
else:
self._spinning = True
self._pool.submit(self._spin, value, True)
class TestServicer(interfaces.Servicer):
"""An interfaces.Servicer with instrumented for testing."""
def __init__(self, pool):
self._pool = pool
self.condition = threading.Condition()
self._released = False
def service(self, name, context, output_consumer):
if name == SYNCHRONOUS_ECHO:
return _synchronous_echo(output_consumer)
elif name == ASYNCHRONOUS_ECHO:
return AsynchronousEcho(output_consumer, self._pool)
elif name == IMMEDIATE_FAILURE:
raise ValueError()
elif name == TRIGGERED_FAILURE:
raise NotImplementedError
elif name == WAIT_ON_CONDITION:
with self.condition:
while not self._released:
self.condition.wait()
return _synchronous_echo(output_consumer)
else:
raise NotImplementedError()
def release(self):
with self.condition:
self._released = True
self.condition.notify_all()
class EasyServicedIngestor(interfaces.ServicedIngestor):
"""A trivial implementation of interfaces.ServicedIngestor."""
def __init__(self, consumer):
self._consumer = consumer
def consumer(self, operation_context):
"""See interfaces.ServicedIngestor.consumer for specification."""
return self._consumer
class FrontAndBackTest(object):
"""A test suite usable against any joined Front and Back."""
# Pylint doesn't know that this is a unittest.TestCase mix-in.
# pylint: disable=invalid-name
def testSimplestCall(self):
"""Tests the absolute simplest call - a one-ticket fire-and-forget."""
self.front.operate(
SYNCHRONOUS_ECHO, None, True, SMALL_TIMEOUT,
util.none_serviced_subscription(), 'test trace ID')
util.wait_for_idle(self.front)
self.assertEqual(
1, self.front.operation_stats()[interfaces.Outcome.COMPLETED])
# Assuming nothing really pathological (such as pauses on the order of
# SMALL_TIMEOUT interfering with this test) there are a two different ways
# the back could have experienced execution up to this point:
# (1) The ticket is still either in the front waiting to be transmitted
# or is somewhere on the link between the front and the back. The back has
# no idea that this test is even happening. Calling wait_for_idle on it
# would do no good because in this case the back is idle and the call would
# return with the ticket bound for it still in the front or on the link.
back_operation_stats = self.back.operation_stats()
first_back_possibility = EMPTY_OUTCOME_DICT
# (2) The ticket arrived at the back and the back completed the operation.
second_back_possibility = dict(EMPTY_OUTCOME_DICT)
second_back_possibility[interfaces.Outcome.COMPLETED] = 1
self.assertIn(
back_operation_stats, (first_back_possibility, second_back_possibility))
# It's true that if the ticket had arrived at the back and the back had
# begun processing that wait_for_idle could hold test execution until the
# back completed the operation, but that doesn't really collapse the
# possibility space down to one solution.
def testEntireEcho(self):
"""Tests a very simple one-ticket-each-way round-trip."""
test_payload = 'test payload'
test_consumer = stream_testing.TestConsumer()
subscription = util.full_serviced_subscription(
EasyServicedIngestor(test_consumer))
self.front.operate(
ASYNCHRONOUS_ECHO, test_payload, True, SMALL_TIMEOUT, subscription,
'test trace ID')
util.wait_for_idle(self.front)
util.wait_for_idle(self.back)
self.assertEqual(
1, self.front.operation_stats()[interfaces.Outcome.COMPLETED])
self.assertEqual(
1, self.back.operation_stats()[interfaces.Outcome.COMPLETED])
self.assertListEqual([(test_payload, True)], test_consumer.calls)
def testBidirectionalStreamingEcho(self):
"""Tests sending multiple tickets each way."""
test_payload_template = 'test_payload: %03d'
test_payloads = [test_payload_template % i for i in range(STREAM_LENGTH)]
test_consumer = stream_testing.TestConsumer()
subscription = util.full_serviced_subscription(
EasyServicedIngestor(test_consumer))
operation = self.front.operate(
SYNCHRONOUS_ECHO, None, False, SMALL_TIMEOUT, subscription,
'test trace ID')
for test_payload in test_payloads:
operation.consumer.consume(test_payload)
operation.consumer.terminate()
util.wait_for_idle(self.front)
util.wait_for_idle(self.back)
self.assertEqual(
1, self.front.operation_stats()[interfaces.Outcome.COMPLETED])
self.assertEqual(
1, self.back.operation_stats()[interfaces.Outcome.COMPLETED])
self.assertListEqual(test_payloads, test_consumer.values())
def testCancellation(self):
"""Tests cancelling a long-lived operation."""
test_consumer = stream_testing.TestConsumer()
subscription = util.full_serviced_subscription(
EasyServicedIngestor(test_consumer))
operation = self.front.operate(
ASYNCHRONOUS_ECHO, None, False, SMALL_TIMEOUT, subscription,
'test trace ID')
operation.cancel()
util.wait_for_idle(self.front)
self.assertEqual(
1, self.front.operation_stats()[interfaces.Outcome.CANCELLED])
util.wait_for_idle(self.back)
self.assertListEqual([], test_consumer.calls)
# Assuming nothing really pathological (such as pauses on the order of
# SMALL_TIMEOUT interfering with this test) there are a two different ways
# the back could have experienced execution up to this point:
# (1) Both tickets are still either in the front waiting to be transmitted
# or are somewhere on the link between the front and the back. The back has
# no idea that this test is even happening. Calling wait_for_idle on it
# would do no good because in this case the back is idle and the call would
# return with the tickets bound for it still in the front or on the link.
back_operation_stats = self.back.operation_stats()
first_back_possibility = EMPTY_OUTCOME_DICT
# (2) Both tickets arrived within SMALL_TIMEOUT of one another at the back.
# The back started processing based on the first ticket and then stopped
# upon receiving the cancellation ticket.
second_back_possibility = dict(EMPTY_OUTCOME_DICT)
second_back_possibility[interfaces.Outcome.CANCELLED] = 1
self.assertIn(
back_operation_stats, (first_back_possibility, second_back_possibility))
def testExpiration(self):
"""Tests that operations time out."""
timeout = TICK * 2
allowance = TICK # How much extra time to
condition = threading.Condition()
test_payload = 'test payload'
subscription = util.termination_only_serviced_subscription()
start_time = time.time()
outcome_cell = [None]
termination_time_cell = [None]
def termination_action(outcome):
with condition:
outcome_cell[0] = outcome
termination_time_cell[0] = time.time()
condition.notify()
with condition:
operation = self.front.operate(
SYNCHRONOUS_ECHO, test_payload, False, timeout, subscription,
'test trace ID')
operation.context.add_termination_callback(termination_action)
while outcome_cell[0] is None:
condition.wait()
duration = termination_time_cell[0] - start_time
self.assertLessEqual(timeout, duration)
self.assertLess(duration, timeout + allowance)
self.assertEqual(interfaces.Outcome.EXPIRED, outcome_cell[0])
util.wait_for_idle(self.front)
self.assertEqual(
1, self.front.operation_stats()[interfaces.Outcome.EXPIRED])
util.wait_for_idle(self.back)
self.assertLessEqual(
1, self.back.operation_stats()[interfaces.Outcome.EXPIRED])
|
gameduell/kythe
|
third_party/grpc/src/python/src/grpc/framework/base/interfaces_test_case.py
|
Python
|
apache-2.0
| 11,724
|
from umlfri2.application.commands.base import Command
from umlfri2.application.events.diagram import ConnectionMovedEvent
class MoveConnectionLabelCommand(Command):
def __init__(self, connection_label, delta):
self.__diagram_name = connection_label.connection.diagram.get_display_name()
self.__connection_label = connection_label
self.__delta = delta
self.__label_position = None
@property
def description(self):
return "Moved label on connection in diagram {0}".format(self.__diagram_name)
def _do(self, ruler):
self.__label_position = self.__connection_label.get_position(ruler)
self._redo(ruler)
def _redo(self, ruler):
self.__connection_label.move(ruler, self.__label_position + self.__delta)
def _undo(self, ruler):
self.__connection_label.move(ruler, self.__label_position)
def get_updates(self):
yield ConnectionMovedEvent(self.__connection_label.connection)
|
umlfri/umlfri2
|
umlfri2/application/commands/diagram/moveconnectionlabel.py
|
Python
|
gpl-3.0
| 1,001
|
import os
import platform
import unittest
from conans.model.ref import ConanFileReference
from conans.test.utils.tools import TestClient
class ShortPathsTest(unittest.TestCase):
@unittest.skipUnless(platform.system() == "Windows", "Requires Windows")
def inconsistent_cache_test(self):
conanfile = """
import os
from conans import ConanFile, tools
class TestConan(ConanFile):
name = "test"
version = "1.0"
short_paths = {0}
exports_sources = "source_file.cpp"
def source(self):
for item in os.listdir(self.source_folder):
self.output.info("SOURCE: " + str(item))
def build(self):
tools.save(os.path.join(self.build_folder, "artifact"), "")
for item in os.listdir(self.build_folder):
self.output.info("BUILD: " + str(item))
def package(self):
self.copy("source_file.cpp")
self.copy("artifact")
for item in os.listdir(self.build_folder):
self.output.info("PACKAGE: " + str(item))
"""
client = TestClient()
client.save({"conanfile.py": conanfile.format("False"),
"source_file.cpp": ""})
client.run("create . danimtb/testing")
conan_ref = ConanFileReference("test", "1.0", "danimtb", "testing")
source_folder = os.path.join(client.client_cache.conan(conan_ref), "source")
build_folder = os.path.join(client.client_cache.conan(conan_ref), "build",
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
package_folder = os.path.join(client.client_cache.conan(conan_ref), "package",
"5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
self.assertIn("SOURCE: source_file.cpp", client.out)
self.assertEqual(["source_file.cpp"], os.listdir(source_folder))
self.assertIn("BUILD: source_file.cpp", client.out)
self.assertIn("BUILD: artifact", client.out)
self.assertEqual(
sorted(["artifact", "conanbuildinfo.txt", "conaninfo.txt", "source_file.cpp"]),
sorted(os.listdir(build_folder)))
self.assertIn("PACKAGE: source_file.cpp", client.out)
self.assertIn("PACKAGE: artifact", client.out)
self.assertEqual(
sorted(["artifact", "conaninfo.txt", "conanmanifest.txt", "source_file.cpp"]),
sorted(os.listdir(package_folder)))
client.save({"conanfile.py": conanfile.format("True")})
client.run("create . danimtb/testing")
self.assertIn("SOURCE: source_file.cpp", client.out)
self.assertEqual([".conan_link"], os.listdir(source_folder))
self.assertIn("BUILD: source_file.cpp", client.out)
self.assertIn("BUILD: artifact", client.out)
self.assertEqual([".conan_link"], os.listdir(build_folder))
self.assertIn("PACKAGE: source_file.cpp", client.out)
self.assertIn("PACKAGE: artifact", client.out)
self.assertEqual([".conan_link"], os.listdir(package_folder))
@unittest.skipUnless(platform.system() == "Windows", "Requires Windows")
def package_output_test(self):
conanfile = """
import os
from conans import ConanFile, tools
class TestConan(ConanFile):
name = "test"
version = "1.0"
short_paths = True
"""
client = TestClient()
client.save({"conanfile.py": conanfile,
"source_file.cpp": ""})
client.run("create . danimtb/testing")
self.assertNotIn("test/1.0@danimtb/testing: Package '1' created", client.out)
self.assertIn(
"test/1.0@danimtb/testing: Package '5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9' created",
client.out)
# try local flow still works, but no pkg id available
client.run("install .")
client.run("package .")
self.assertIn("PROJECT: Package 'package' created", client.out)
# try export-pkg with package folder
client.run("remove test/1.0@danimtb/testing --force")
client.run("export-pkg . test/1.0@danimtb/testing --package-folder package")
self.assertIn(
"test/1.0@danimtb/testing: Package '5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9' created",
client.out)
# try export-pkg without package folder
client.run("remove test/1.0@danimtb/testing --force")
client.run("export-pkg . test/1.0@danimtb/testing --install-folder .")
self.assertIn(
"test/1.0@danimtb/testing: Package '5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9' created",
client.out)
# try conan get
client.run("get test/1.0@danimtb/testing . -p 5ab84d6acfe1f23c4fae0ab88f26e3a396351ac9")
self.assertIn("conaninfo.txt", client.out)
self.assertIn("conanmanifest.txt", client.out)
|
luckielordie/conan
|
conans/test/functional/short_paths_test.py
|
Python
|
mit
| 4,784
|
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016, 2017 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from xdg import BaseDirectory
class SnapcraftCache:
"""Generic cache base class.
This class is responsible for cache location, notification and pruning.
"""
def __init__(self):
self.cache_root = os.path.join(
BaseDirectory.xdg_cache_home, 'snapcraft')
def cache(self):
raise NotImplementedError
def get(self, *args, **kwargs):
raise NotImplementedError
def prune(self, *args, **kwargs):
raise NotImplementedError
class SnapcraftProjectCache(SnapcraftCache):
"""Project specific cache"""
def __init__(self, *, project_name):
super().__init__()
self.project_cache_root = os.path.join(
self.cache_root, 'projects', project_name)
class SnapcraftStagePackageCache(SnapcraftCache):
"""Cache specific to stage-packages."""
def __init__(self):
super().__init__()
self.stage_package_cache_root = os.path.join(
self.cache_root, 'stage-packages')
|
josepht/snapcraft
|
snapcraft/internal/cache/_cache.py
|
Python
|
gpl-3.0
| 1,674
|
# Copyright 2016, 2017 Peter Zybrick and others.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
ProcessSimHumidityToMister
:author: Pete Zybrick
:contact: pzybrick@gmail.com
:version: 1.0.0
"""
import logging
import time
import uuid
import sys
from iote2epyclient.launch.clientutils import ClientUtils
from iote2epyclient.schema.iote2erequest import Iote2eRequest
logger = logging.getLogger(__name__)
class ProcessSimHumidityToMister(object):
'''
Simulate Humidity Sensor and Mister
'''
def __init__(self, loginVo, sensorName):
self.loginVo = loginVo
self.sensorName = sensorName
self.humidityDirectionIncrease = True
self.HUMIDITY_MIN = 82.0
self.HUMIDITY_MAX = 93.0
self.HUMIDITY_INCR = .5
self.humidityNow = 90.0
def createIote2eRequest(self ):
time.sleep(2)
logger.info('ProcessSimHumidityToMister createIote2eRequest:')
if self.humidityDirectionIncrease and self.humidityNow < self.HUMIDITY_MAX:
self.humidityNow += self.HUMIDITY_INCR
elif (not self.humidityDirectionIncrease) and self.humidityNow > self.HUMIDITY_MIN:
self.humidityNow -= self.HUMIDITY_INCR;
logger.info( "humidityNow: {}".format(self.humidityNow))
if self.humidityNow <= self.HUMIDITY_MIN or self.humidityNow >= self.HUMIDITY_MAX:
logger.error("Humidity exceeded: {}".format(self.humidityNow))
# TODO: need to throw an exception or something so the calling thread exits
sys.exit(8)
# TODO: read humidity from sensor here
pairs = { self.sensorName: str(self.humidityNow)}
iote2eRequest = Iote2eRequest( login_name=self.loginVo.loginName,source_name=self.loginVo.sourceName, source_type='humidity',
request_uuid=str(uuid.uuid4()),
request_timestamp=ClientUtils.nowIso8601(),
pairs=pairs, operation='SENSORS_VALUES')
return iote2eRequest
def handleIote2eResult(self, iote2eResult ):
# TODO: turn on/off actuator (fan) here
logger.info('ProcessSimHumidityToMister handleIote2eResult: ' + str(iote2eResult))
actuatorValue = iote2eResult.pairs['actuatorValue'];
logger.info('actuatorValue {}'.format(actuatorValue))
if 'off' == actuatorValue:
self.humidityDirectionIncrease = False;
elif 'on' == actuatorValue:
self.humidityDirectionIncrease = True;
|
petezybrick/iote2e
|
iote2e-pyclient/src/iote2epyclient/processsim/processsimhumiditytomister.py
|
Python
|
apache-2.0
| 3,105
|
#
# Copyright (C) 2013-2015 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY expressed or implied, including the implied warranties of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details. You should have received a copy of the
# GNU General Public License along with this program; if not, write to the
# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA. Any Red Hat trademarks that are incorporated in the
# source code or documentation are not subject to the GNU General Public
# License and may only be used or replicated with the express permission of
# Red Hat, Inc.
#
# Red Hat Author(s): Vratislav Podzimek <vpodzime@redhat.com>
#
# This module was taken from the sources of the Anaconda installer.
#
"""Module providing thread-safe and mainloop-safe DBus operations."""
import gi
gi.require_version("GLib", "2.0")
gi.require_version("Gio", "2.0")
from gi.repository import GLib, Gio
import os
DEFAULT_DBUS_TIMEOUT = -1
DBUS_PROPS_IFACE = "org.freedesktop.DBus.Properties"
DBUS_INTRO_IFACE = "org.freedesktop.DBus.Introspectable"
class SafeDBusError(Exception):
"""Class for exceptions defined in this module."""
class DBusCallError(SafeDBusError):
"""Class for the errors related to calling methods over DBus."""
class DBusPropertyError(DBusCallError):
"""Class for the errors related to getting property values over DBus."""
def get_new_system_connection():
"""Return a new connection to the system bus."""
return Gio.DBusConnection.new_for_address_sync(
Gio.dbus_address_get_for_bus_sync(Gio.BusType.SYSTEM, None),
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT |
Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
None, None)
def get_new_session_connection():
"""
Get a connection handle for the per-user-login-session message bus.
!!! RUN THIS EARLY !!! like, before any other threads start. Connections to
the session bus must be made with the effective UID of the login user,
which in live installs is not the UID of anaconda. This means we need to
call seteuid in this method, and doing that after threads have started will
probably do something weird.
Live installs use consolehelper to run as root, which sets the original
UID in $USERHELPER_UID.
:return: the session connection handle
:rtype: Gio.DBusConnection
:raise DBusCallError: if some DBus related error appears
:raise OSError: if unable to set the effective UID
"""
old_euid = None
if "USERHELPER_UID" in os.environ:
old_euid = os.geteuid()
os.seteuid(int(os.environ["USERHELPER_UID"]))
try:
connection = Gio.DBusConnection.new_for_address_sync(
Gio.dbus_address_get_for_bus_sync(Gio.BusType.SESSION, None),
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT |
Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
None, None)
except GLib.GError as gerr:
raise DBusCallError("Unable to connect to session bus: %s" % gerr)
finally:
if old_euid is not None:
os.seteuid(old_euid)
if connection.is_closed():
raise DBusCallError("Connection is closed")
return connection
def call_sync(service, obj_path, iface, method, args,
connection=None):
"""
Safely call a given method on a given object of a given service over DBus
passing given arguments. If a connection is given, it is used, otherwise a
new connection is established. Safely means that it is a synchronous,
thread-safe call not using any main loop.
:param service: DBus service to use
:type service: str
:param obj_path: object path of the object to call method on
:type obj_path: str
:param iface: interface to use
:type iface: str
:param method: name of the method to call
:type method: str
:param args: arguments to pass to the method
:type args: GVariant
:param connection: connection to use (if None, a new connection is
established)
:type connection: Gio.DBusConnection
:return: unpacked value returned by the method
:rtype: tuple with elements that depend on the method
:raise DBusCallError: if some DBus related error appears
"""
if not connection:
try:
connection = get_new_system_connection()
except GLib.GError as gerr:
raise DBusCallError("Unable to connect to system bus: %s" % gerr)
if connection.is_closed():
raise DBusCallError("Connection is closed")
try:
ret = connection.call_sync(service, obj_path, iface, method, args,
None, Gio.DBusCallFlags.NONE,
DEFAULT_DBUS_TIMEOUT, None)
except GLib.GError as gerr:
msg = "Failed to call %s method on %s with %s arguments: %s" % \
(method, obj_path, args, gerr.message) # pylint: disable=no-member
raise DBusCallError(msg)
if ret is None:
msg = "No return from %s method on %s with %s arguments" % (method, obj_path, args)
raise DBusCallError(msg)
return ret.unpack()
def get_property_sync(service, obj_path, iface, prop_name,
connection=None):
"""
Get value of a given property of a given object provided by a given service.
:param service: DBus service to use
:type service: str
:param obj_path: object path
:type obj_path: str
:param iface: interface to use
:type iface: str
:param prop_name: name of the property
:type prop_name: str
:param connection: connection to use (if None, a new connection is
established)
:type connection: Gio.DBusConnection
:return: unpacked value of the property
:rtype: tuple with elements that depend on the type of the property
:raise DBusCallError: when the internal dbus_call_safe_sync invocation
raises an exception
:raise DBusPropertyError: when the given object doesn't have the given
property
"""
args = GLib.Variant('(ss)', (iface, prop_name))
ret = call_sync(service, obj_path, DBUS_PROPS_IFACE, "Get", args,
connection)
if ret is None:
msg = "No value for the %s object's property %s" % (obj_path, prop_name)
raise DBusPropertyError(msg)
return ret
def check_object_available(service, obj_path, iface=None):
intro_data = call_sync(service, obj_path, DBUS_INTRO_IFACE, "Introspect", None)
node_info = Gio.DBusNodeInfo.new_for_xml(intro_data[0])
if not iface:
# just check if any interface is available (there are none for
# non-existing objects)
return bool(node_info.interfaces)
else:
return any(intface.name == iface for intface in node_info.interfaces)
|
rvykydal/blivet
|
blivet/safe_dbus.py
|
Python
|
lgpl-2.1
| 7,233
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import sys
import copy
import reportlab
import re
from reportlab.pdfgen import canvas
from reportlab import platypus
import utils
import color
import os
import logging
from lxml import etree
import base64
from reportlab.platypus.doctemplate import ActionFlowable
from openerp.tools.safe_eval import safe_eval as eval
from reportlab.lib.units import inch,cm,mm
from openerp.tools.misc import file_open
from reportlab.pdfbase import pdfmetrics
from reportlab.lib.pagesizes import A4, letter
try:
from cStringIO import StringIO
_hush_pyflakes = [ StringIO ]
except ImportError:
from StringIO import StringIO
_logger = logging.getLogger(__name__)
encoding = 'utf-8'
def select_fontname(fontname, default_fontname):
if fontname not in pdfmetrics.getRegisteredFontNames()\
or fontname not in pdfmetrics.standardFonts:
# let reportlab attempt to find it
try:
pdfmetrics.getFont(fontname)
except Exception:
_logger.warning('Could not locate font %s, substituting default: %s',
fontname, default_fontname)
fontname = default_fontname
return fontname
def _open_image(filename, path=None):
"""Attempt to open a binary file and return the descriptor
"""
if os.path.isfile(filename):
return open(filename, 'rb')
for p in (path or []):
if p and os.path.isabs(p):
fullpath = os.path.join(p, filename)
if os.path.isfile(fullpath):
return open(fullpath, 'rb')
try:
if p:
fullpath = os.path.join(p, filename)
else:
fullpath = filename
return file_open(fullpath)
except IOError:
pass
raise IOError("File %s cannot be found in image path" % filename)
class NumberedCanvas(canvas.Canvas):
def __init__(self, *args, **kwargs):
canvas.Canvas.__init__(self, *args, **kwargs)
self._saved_page_states = []
def showPage(self):
self._saved_page_states.append(dict(self.__dict__))
self._startPage()
def save(self):
"""add page info to each page (page x of y)"""
for state in self._saved_page_states:
self.__dict__.update(state)
self.draw_page_number()
canvas.Canvas.showPage(self)
canvas.Canvas.save(self)
def draw_page_number(self):
page_count = len(self._saved_page_states)
self.setFont("Helvetica", 8)
self.drawRightString((self._pagesize[0]-30), (self._pagesize[1]-40),
" %(this)i / %(total)i" % {
'this': self._pageNumber,
'total': page_count,
}
)
class PageCount(platypus.Flowable):
def __init__(self, story_count=0):
platypus.Flowable.__init__(self)
self.story_count = story_count
def draw(self):
self.canv.beginForm("pageCount%d" % self.story_count)
self.canv.setFont("Helvetica", utils.unit_get(str(8)))
self.canv.drawString(0, 0, str(self.canv.getPageNumber()))
self.canv.endForm()
class PageReset(platypus.Flowable):
def draw(self):
self.canv._doPageReset = True
class _rml_styles(object,):
def __init__(self, nodes, localcontext):
self.localcontext = localcontext
self.styles = {}
self.styles_obj = {}
self.names = {}
self.table_styles = {}
self.default_style = reportlab.lib.styles.getSampleStyleSheet()
for node in nodes:
for style in node.findall('blockTableStyle'):
self.table_styles[style.get('id')] = self._table_style_get(style)
for style in node.findall('paraStyle'):
sname = style.get('name')
self.styles[sname] = self._para_style_update(style)
if self.default_style.has_key(sname):
for key, value in self.styles[sname].items():
setattr(self.default_style[sname], key, value)
else:
self.styles_obj[sname] = reportlab.lib.styles.ParagraphStyle(sname, self.default_style["Normal"], **self.styles[sname])
for variable in node.findall('initialize'):
for name in variable.findall('name'):
self.names[ name.get('id')] = name.get('value')
def _para_style_update(self, node):
data = {}
for attr in ['textColor', 'backColor', 'bulletColor', 'borderColor']:
if node.get(attr):
data[attr] = color.get(node.get(attr))
for attr in ['bulletFontName', 'fontName']:
if node.get(attr):
fontname= select_fontname(node.get(attr), None)
if fontname is not None:
data['fontName'] = fontname
for attr in ['bulletText']:
if node.get(attr):
data[attr] = node.get(attr)
for attr in ['fontSize', 'leftIndent', 'rightIndent', 'spaceBefore', 'spaceAfter',
'firstLineIndent', 'bulletIndent', 'bulletFontSize', 'leading',
'borderWidth','borderPadding','borderRadius']:
if node.get(attr):
data[attr] = utils.unit_get(node.get(attr))
if node.get('alignment'):
align = {
'right':reportlab.lib.enums.TA_RIGHT,
'center':reportlab.lib.enums.TA_CENTER,
'justify':reportlab.lib.enums.TA_JUSTIFY
}
data['alignment'] = align.get(node.get('alignment').lower(), reportlab.lib.enums.TA_LEFT)
return data
def _table_style_get(self, style_node):
styles = []
for node in style_node:
start = utils.tuple_int_get(node, 'start', (0,0) )
stop = utils.tuple_int_get(node, 'stop', (-1,-1) )
if node.tag=='blockValign':
styles.append(('VALIGN', start, stop, str(node.get('value'))))
elif node.tag=='blockFont':
styles.append(('FONT', start, stop, str(node.get('name'))))
elif node.tag=='blockTextColor':
styles.append(('TEXTCOLOR', start, stop, color.get(str(node.get('colorName')))))
elif node.tag=='blockLeading':
styles.append(('LEADING', start, stop, utils.unit_get(node.get('length'))))
elif node.tag=='blockAlignment':
styles.append(('ALIGNMENT', start, stop, str(node.get('value'))))
elif node.tag=='blockSpan':
styles.append(('SPAN', start, stop))
elif node.tag=='blockLeftPadding':
styles.append(('LEFTPADDING', start, stop, utils.unit_get(node.get('length'))))
elif node.tag=='blockRightPadding':
styles.append(('RIGHTPADDING', start, stop, utils.unit_get(node.get('length'))))
elif node.tag=='blockTopPadding':
styles.append(('TOPPADDING', start, stop, utils.unit_get(node.get('length'))))
elif node.tag=='blockBottomPadding':
styles.append(('BOTTOMPADDING', start, stop, utils.unit_get(node.get('length'))))
elif node.tag=='blockBackground':
styles.append(('BACKGROUND', start, stop, color.get(node.get('colorName'))))
if node.get('size'):
styles.append(('FONTSIZE', start, stop, utils.unit_get(node.get('size'))))
elif node.tag=='lineStyle':
kind = node.get('kind')
kind_list = [ 'GRID', 'BOX', 'OUTLINE', 'INNERGRID', 'LINEBELOW', 'LINEABOVE','LINEBEFORE', 'LINEAFTER' ]
assert kind in kind_list
thick = 1
if node.get('thickness'):
thick = float(node.get('thickness'))
styles.append((kind, start, stop, thick, color.get(node.get('colorName'))))
return platypus.tables.TableStyle(styles)
def para_style_get(self, node):
style = False
sname = node.get('style')
if sname:
if sname in self.styles_obj:
style = self.styles_obj[sname]
else:
_logger.debug('Warning: style not found, %s - setting default!', node.get('style'))
if not style:
style = self.default_style['Normal']
para_update = self._para_style_update(node)
if para_update:
# update style only is necessary
style = copy.deepcopy(style)
style.__dict__.update(para_update)
return style
class _rml_doc(object):
def __init__(self, node, localcontext=None, images=None, path='.', title=None):
if images is None:
images = {}
if localcontext is None:
localcontext = {}
self.localcontext = localcontext
self.etree = node
self.filename = self.etree.get('filename')
self.images = images
self.path = path
self.title = title
def docinit(self, els):
from reportlab.lib.fonts import addMapping
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
for node in els:
for font in node.findall('registerFont'):
name = font.get('fontName').encode('ascii')
fname = font.get('fontFile').encode('ascii')
if name not in pdfmetrics._fonts:
pdfmetrics.registerFont(TTFont(name, fname))
#by default, we map the fontName to each style (bold, italic, bold and italic), so that
#if there isn't any font defined for one of these style (via a font family), the system
#will fallback on the normal font.
addMapping(name, 0, 0, name) #normal
addMapping(name, 0, 1, name) #italic
addMapping(name, 1, 0, name) #bold
addMapping(name, 1, 1, name) #italic and bold
#if registerFontFamily is defined, we register the mapping of the fontName to use for each style.
for font_family in node.findall('registerFontFamily'):
family_name = font_family.get('normal').encode('ascii')
if font_family.get('italic'):
addMapping(family_name, 0, 1, font_family.get('italic').encode('ascii'))
if font_family.get('bold'):
addMapping(family_name, 1, 0, font_family.get('bold').encode('ascii'))
if font_family.get('boldItalic'):
addMapping(family_name, 1, 1, font_family.get('boldItalic').encode('ascii'))
def setTTFontMapping(self,face, fontname, filename, mode='all'):
from reportlab.lib.fonts import addMapping
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
if fontname not in pdfmetrics._fonts:
pdfmetrics.registerFont(TTFont(fontname, filename))
if mode == 'all':
addMapping(face, 0, 0, fontname) #normal
addMapping(face, 0, 1, fontname) #italic
addMapping(face, 1, 0, fontname) #bold
addMapping(face, 1, 1, fontname) #italic and bold
elif (mode== 'normal') or (mode == 'regular'):
addMapping(face, 0, 0, fontname) #normal
elif mode == 'italic':
addMapping(face, 0, 1, fontname) #italic
elif mode == 'bold':
addMapping(face, 1, 0, fontname) #bold
elif mode == 'bolditalic':
addMapping(face, 1, 1, fontname) #italic and bold
def _textual_image(self, node):
rc = ''
for n in node:
rc +=( etree.tostring(n) or '') + n.tail
return base64.decodestring(node.tostring())
def _images(self, el):
result = {}
for node in el.findall('.//image'):
rc =( node.text or '')
result[node.get('name')] = base64.decodestring(rc)
return result
def render(self, out):
el = self.etree.findall('.//docinit')
if el:
self.docinit(el)
el = self.etree.findall('.//stylesheet')
self.styles = _rml_styles(el,self.localcontext)
el = self.etree.findall('.//images')
if el:
self.images.update( self._images(el[0]) )
el = self.etree.findall('.//template')
if len(el):
pt_obj = _rml_template(self.localcontext, out, el[0], self, images=self.images, path=self.path, title=self.title)
el = utils._child_get(self.etree, self, 'story')
pt_obj.render(el)
else:
self.canvas = canvas.Canvas(out)
pd = self.etree.find('pageDrawing')[0]
pd_obj = _rml_canvas(self.canvas, self.localcontext, None, self, self.images, path=self.path, title=self.title)
pd_obj.render(pd)
self.canvas.showPage()
self.canvas.save()
class _rml_canvas(object):
def __init__(self, canvas, localcontext, doc_tmpl=None, doc=None, images=None, path='.', title=None):
if images is None:
images = {}
self.localcontext = localcontext
self.canvas = canvas
self.styles = doc.styles
self.doc_tmpl = doc_tmpl
self.doc = doc
self.images = images
self.path = path
self.title = title
if self.title:
self.canvas.setTitle(self.title)
def _textual(self, node, x=0, y=0):
text = node.text and node.text.encode('utf-8') or ''
rc = utils._process_text(self, text)
for n in node:
if n.tag == 'seq':
from reportlab.lib.sequencer import getSequencer
seq = getSequencer()
rc += str(seq.next(n.get('id')))
if n.tag == 'pageCount':
if x or y:
self.canvas.translate(x,y)
self.canvas.doForm('pageCount%s' % (self.canvas._storyCount,))
if x or y:
self.canvas.translate(-x,-y)
if n.tag == 'pageNumber':
rc += str(self.canvas.getPageNumber())
rc += utils._process_text(self, n.tail)
return rc.replace('\n','')
def _drawString(self, node):
v = utils.attr_get(node, ['x','y'])
text=self._textual(node, **v)
text = utils.xml2str(text)
try:
self.canvas.drawString(text=text, **v)
except TypeError as e:
_logger.error("Bad RML: <drawString> tag requires attributes 'x' and 'y'!")
raise e
def _drawCenteredString(self, node):
v = utils.attr_get(node, ['x','y'])
text=self._textual(node, **v)
text = utils.xml2str(text)
self.canvas.drawCentredString(text=text, **v)
def _drawRightString(self, node):
v = utils.attr_get(node, ['x','y'])
text=self._textual(node, **v)
text = utils.xml2str(text)
self.canvas.drawRightString(text=text, **v)
def _rect(self, node):
if node.get('round'):
self.canvas.roundRect(radius=utils.unit_get(node.get('round')), **utils.attr_get(node, ['x','y','width','height'], {'fill':'bool','stroke':'bool'}))
else:
self.canvas.rect(**utils.attr_get(node, ['x','y','width','height'], {'fill':'bool','stroke':'bool'}))
def _ellipse(self, node):
x1 = utils.unit_get(node.get('x'))
x2 = utils.unit_get(node.get('width'))
y1 = utils.unit_get(node.get('y'))
y2 = utils.unit_get(node.get('height'))
self.canvas.ellipse(x1,y1,x2,y2, **utils.attr_get(node, [], {'fill':'bool','stroke':'bool'}))
def _curves(self, node):
line_str = node.text.split()
lines = []
while len(line_str)>7:
self.canvas.bezier(*[utils.unit_get(l) for l in line_str[0:8]])
line_str = line_str[8:]
def _lines(self, node):
line_str = node.text.split()
lines = []
while len(line_str)>3:
lines.append([utils.unit_get(l) for l in line_str[0:4]])
line_str = line_str[4:]
self.canvas.lines(lines)
def _grid(self, node):
xlist = [utils.unit_get(s) for s in node.get('xs').split(',')]
ylist = [utils.unit_get(s) for s in node.get('ys').split(',')]
self.canvas.grid(xlist, ylist)
def _translate(self, node):
dx = utils.unit_get(node.get('dx')) or 0
dy = utils.unit_get(node.get('dy')) or 0
self.canvas.translate(dx,dy)
def _circle(self, node):
self.canvas.circle(x_cen=utils.unit_get(node.get('x')), y_cen=utils.unit_get(node.get('y')), r=utils.unit_get(node.get('radius')), **utils.attr_get(node, [], {'fill':'bool','stroke':'bool'}))
def _place(self, node):
flows = _rml_flowable(self.doc, self.localcontext, images=self.images, path=self.path, title=self.title, canvas=self.canvas).render(node)
infos = utils.attr_get(node, ['x','y','width','height'])
infos['y']+=infos['height']
for flow in flows:
w,h = flow.wrap(infos['width'], infos['height'])
if w<=infos['width'] and h<=infos['height']:
infos['y']-=h
flow.drawOn(self.canvas,infos['x'],infos['y'])
infos['height']-=h
else:
raise ValueError("Not enough space")
def _line_mode(self, node):
ljoin = {'round':1, 'mitered':0, 'bevelled':2}
lcap = {'default':0, 'round':1, 'square':2}
if node.get('width'):
self.canvas.setLineWidth(utils.unit_get(node.get('width')))
if node.get('join'):
self.canvas.setLineJoin(ljoin[node.get('join')])
if node.get('cap'):
self.canvas.setLineCap(lcap[node.get('cap')])
if node.get('miterLimit'):
self.canvas.setDash(utils.unit_get(node.get('miterLimit')))
if node.get('dash'):
dashes = node.get('dash').split(',')
for x in range(len(dashes)):
dashes[x]=utils.unit_get(dashes[x])
self.canvas.setDash(node.get('dash').split(','))
def _image(self, node):
import urllib
import urlparse
from reportlab.lib.utils import ImageReader
nfile = node.get('file')
if not nfile:
if node.get('name'):
image_data = self.images[node.get('name')]
_logger.debug("Image %s used", node.get('name'))
s = StringIO(image_data)
else:
newtext = node.text
if self.localcontext:
res = utils._regex.findall(newtext)
for key in res:
newtext = eval(key, {}, self.localcontext) or ''
image_data = None
if newtext:
image_data = base64.decodestring(newtext)
if image_data:
s = StringIO(image_data)
else:
_logger.debug("No image data!")
return False
else:
if nfile in self.images:
s = StringIO(self.images[nfile])
else:
try:
up = urlparse.urlparse(str(nfile))
except ValueError:
up = False
if up and up.scheme:
# RFC: do we really want to open external URLs?
# Are we safe from cross-site scripting or attacks?
_logger.debug("Retrieve image from %s", nfile)
u = urllib.urlopen(str(nfile))
s = StringIO(u.read())
else:
_logger.debug("Open image file %s ", nfile)
s = _open_image(nfile, path=self.path)
try:
img = ImageReader(s)
(sx,sy) = img.getSize()
_logger.debug("Image is %dx%d", sx, sy)
args = { 'x': 0.0, 'y': 0.0, 'mask': 'auto'}
for tag in ('width','height','x','y'):
if node.get(tag):
args[tag] = utils.unit_get(node.get(tag))
if ('width' in args) and (not 'height' in args):
args['height'] = sy * args['width'] / sx
elif ('height' in args) and (not 'width' in args):
args['width'] = sx * args['height'] / sy
elif ('width' in args) and ('height' in args):
if (float(args['width'])/args['height'])>(float(sx)>sy):
args['width'] = sx * args['height'] / sy
else:
args['height'] = sy * args['width'] / sx
self.canvas.drawImage(img, **args)
finally:
s.close()
# self.canvas._doc.SaveToFile(self.canvas._filename, self.canvas)
def _path(self, node):
self.path = self.canvas.beginPath()
self.path.moveTo(**utils.attr_get(node, ['x','y']))
for n in utils._child_get(node, self):
if not n.text :
if n.tag=='moveto':
vals = utils.text_get(n).split()
self.path.moveTo(utils.unit_get(vals[0]), utils.unit_get(vals[1]))
elif n.tag=='curvesto':
vals = utils.text_get(n).split()
while len(vals)>5:
pos=[]
while len(pos)<6:
pos.append(utils.unit_get(vals.pop(0)))
self.path.curveTo(*pos)
elif n.text:
data = n.text.split() # Not sure if I must merge all TEXT_NODE ?
while len(data)>1:
x = utils.unit_get(data.pop(0))
y = utils.unit_get(data.pop(0))
self.path.lineTo(x,y)
if (not node.get('close')) or utils.bool_get(node.get('close')):
self.path.close()
self.canvas.drawPath(self.path, **utils.attr_get(node, [], {'fill':'bool','stroke':'bool'}))
def setFont(self, node):
fontname = select_fontname(node.get('name'), self.canvas._fontname)
return self.canvas.setFont(fontname, utils.unit_get(node.get('size')))
def render(self, node):
tags = {
'drawCentredString': self._drawCenteredString,
'drawRightString': self._drawRightString,
'drawString': self._drawString,
'rect': self._rect,
'ellipse': self._ellipse,
'lines': self._lines,
'grid': self._grid,
'curves': self._curves,
'fill': lambda node: self.canvas.setFillColor(color.get(node.get('color'))),
'stroke': lambda node: self.canvas.setStrokeColor(color.get(node.get('color'))),
'setFont': self.setFont ,
'place': self._place,
'circle': self._circle,
'lineMode': self._line_mode,
'path': self._path,
'rotate': lambda node: self.canvas.rotate(float(node.get('degrees'))),
'translate': self._translate,
'image': self._image
}
for n in utils._child_get(node, self):
if n.tag in tags:
tags[n.tag](n)
class _rml_draw(object):
def __init__(self, localcontext, node, styles, images=None, path='.', title=None):
if images is None:
images = {}
self.localcontext = localcontext
self.node = node
self.styles = styles
self.canvas = None
self.images = images
self.path = path
self.canvas_title = title
def render(self, canvas, doc):
canvas.saveState()
cnv = _rml_canvas(canvas, self.localcontext, doc, self.styles, images=self.images, path=self.path, title=self.canvas_title)
cnv.render(self.node)
canvas.restoreState()
class _rml_Illustration(platypus.flowables.Flowable):
def __init__(self, node, localcontext, styles, self2):
self.localcontext = (localcontext or {}).copy()
self.node = node
self.styles = styles
self.width = utils.unit_get(node.get('width'))
self.height = utils.unit_get(node.get('height'))
self.self2 = self2
def wrap(self, *args):
return self.width, self.height
def draw(self):
drw = _rml_draw(self.localcontext ,self.node,self.styles, images=self.self2.images, path=self.self2.path, title=self.self2.title)
drw.render(self.canv, None)
# Workaround for issue #15: https://bitbucket.org/rptlab/reportlab/issue/15/infinite-pages-produced-when-splitting
original_pto_split = platypus.flowables.PTOContainer.split
def split(self, availWidth, availHeight):
res = original_pto_split(self, availWidth, availHeight)
if len(res) > 2 and len(self._content) > 0:
header = self._content[0]._ptoinfo.header
trailer = self._content[0]._ptoinfo.trailer
if isinstance(res[-2], platypus.flowables.UseUpSpace) and len(header + trailer) == len(res[:-2]):
return []
return res
platypus.flowables.PTOContainer.split = split
class _rml_flowable(object):
def __init__(self, doc, localcontext, images=None, path='.', title=None, canvas=None):
if images is None:
images = {}
self.localcontext = localcontext
self.doc = doc
self.styles = doc.styles
self.images = images
self.path = path
self.title = title
self.canvas = canvas
def _textual(self, node):
rc1 = utils._process_text(self, node.text or '')
for n in utils._child_get(node,self):
txt_n = copy.deepcopy(n)
for key in txt_n.attrib.keys():
if key in ('rml_except', 'rml_loop', 'rml_tag'):
del txt_n.attrib[key]
if not n.tag == 'bullet':
if n.tag == 'pageNumber':
txt_n.text = self.canvas and str(self.canvas.getPageNumber()) or ''
else:
txt_n.text = utils.xml2str(self._textual(n))
txt_n.tail = n.tail and utils.xml2str(utils._process_text(self, n.tail.replace('\n',''))) or ''
rc1 += etree.tostring(txt_n)
return rc1
def _table(self, node):
children = utils._child_get(node,self,'tr')
if not children:
return None
length = 0
colwidths = None
rowheights = None
data = []
styles = []
posy = 0
for tr in children:
paraStyle = None
if tr.get('style'):
st = copy.deepcopy(self.styles.table_styles[tr.get('style')])
for si in range(len(st._cmds)):
s = list(st._cmds[si])
s[1] = (s[1][0],posy)
s[2] = (s[2][0],posy)
st._cmds[si] = tuple(s)
styles.append(st)
if tr.get('paraStyle'):
paraStyle = self.styles.styles[tr.get('paraStyle')]
data2 = []
posx = 0
for td in utils._child_get(tr, self,'td'):
if td.get('style'):
st = copy.deepcopy(self.styles.table_styles[td.get('style')])
for s in st._cmds:
s[1][1] = posy
s[2][1] = posy
s[1][0] = posx
s[2][0] = posx
styles.append(st)
if td.get('paraStyle'):
# TODO: merge styles
paraStyle = self.styles.styles[td.get('paraStyle')]
posx += 1
flow = []
for n in utils._child_get(td, self):
if n.tag == etree.Comment:
n.text = ''
continue
fl = self._flowable(n, extra_style=paraStyle)
if isinstance(fl,list):
flow += fl
else:
flow.append( fl )
if not len(flow):
flow = self._textual(td)
data2.append( flow )
if len(data2)>length:
length=len(data2)
for ab in data:
while len(ab)<length:
ab.append('')
while len(data2)<length:
data2.append('')
data.append( data2 )
posy += 1
if node.get('colWidths'):
assert length == len(node.get('colWidths').split(','))
colwidths = [utils.unit_get(f.strip()) for f in node.get('colWidths').split(',')]
if node.get('rowHeights'):
rowheights = [utils.unit_get(f.strip()) for f in node.get('rowHeights').split(',')]
if len(rowheights) == 1:
rowheights = rowheights[0]
table = platypus.LongTable(data = data, colWidths=colwidths, rowHeights=rowheights, **(utils.attr_get(node, ['splitByRow'] ,{'repeatRows':'int','repeatCols':'int'})))
if node.get('style'):
table.setStyle(self.styles.table_styles[node.get('style')])
for s in styles:
table.setStyle(s)
return table
def _illustration(self, node):
return _rml_Illustration(node, self.localcontext, self.styles, self)
def _textual_image(self, node):
return base64.decodestring(node.text)
def _pto(self, node):
sub_story = []
pto_header = None
pto_trailer = None
for node in utils._child_get(node, self):
if node.tag == etree.Comment:
node.text = ''
continue
elif node.tag=='pto_header':
pto_header = self.render(node)
elif node.tag=='pto_trailer':
pto_trailer = self.render(node)
else:
flow = self._flowable(node)
if flow:
if isinstance(flow,list):
sub_story = sub_story + flow
else:
sub_story.append(flow)
return platypus.flowables.PTOContainer(sub_story, trailer=pto_trailer, header=pto_header)
def _flowable(self, node, extra_style=None):
if node.tag=='pto':
return self._pto(node)
if node.tag=='para':
style = self.styles.para_style_get(node)
if extra_style:
style.__dict__.update(extra_style)
result = []
for i in self._textual(node).split('\n'):
result.append(platypus.Paragraph(i, style, **(utils.attr_get(node, [], {'bulletText':'str'}))))
return result
elif node.tag=='barCode':
try:
from reportlab.graphics.barcode import code128
from reportlab.graphics.barcode import code39
from reportlab.graphics.barcode import code93
from reportlab.graphics.barcode import common
from reportlab.graphics.barcode import fourstate
from reportlab.graphics.barcode import usps
from reportlab.graphics.barcode import createBarcodeDrawing
except ImportError:
_logger.warning("Cannot use barcode renderers:", exc_info=True)
return None
args = utils.attr_get(node, [], {'ratio':'float','xdim':'unit','height':'unit','checksum':'int','quiet':'int','width':'unit','stop':'bool','bearers':'int','barWidth':'float','barHeight':'float'})
codes = {
'codabar': lambda x: common.Codabar(x, **args),
'code11': lambda x: common.Code11(x, **args),
'code128': lambda x: code128.Code128(str(x), **args),
'standard39': lambda x: code39.Standard39(str(x), **args),
'standard93': lambda x: code93.Standard93(str(x), **args),
'i2of5': lambda x: common.I2of5(x, **args),
'extended39': lambda x: code39.Extended39(str(x), **args),
'extended93': lambda x: code93.Extended93(str(x), **args),
'msi': lambda x: common.MSI(x, **args),
'fim': lambda x: usps.FIM(x, **args),
'postnet': lambda x: usps.POSTNET(x, **args),
'ean13': lambda x: createBarcodeDrawing('EAN13', value=str(x), **args),
'qrcode': lambda x: createBarcodeDrawing('QR', value=x, **args),
}
code = 'code128'
if node.get('code'):
code = node.get('code').lower()
return codes[code](self._textual(node))
elif node.tag=='name':
self.styles.names[ node.get('id')] = node.get('value')
return None
elif node.tag=='xpre':
style = self.styles.para_style_get(node)
return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int','frags':'int'})))
elif node.tag=='pre':
style = self.styles.para_style_get(node)
return platypus.Preformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str','dedent':'int'})))
elif node.tag=='illustration':
return self._illustration(node)
elif node.tag=='blockTable':
return self._table(node)
elif node.tag=='title':
styles = reportlab.lib.styles.getSampleStyleSheet()
style = styles['Title']
return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'})))
elif re.match('^h([1-9]+[0-9]*)$', (node.tag or '')):
styles = reportlab.lib.styles.getSampleStyleSheet()
style = styles['Heading'+str(node.tag[1:])]
return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText':'str'})))
elif node.tag=='image':
image_data = False
if not node.get('file'):
if node.get('name'):
if node.get('name') in self.doc.images:
_logger.debug("Image %s read ", node.get('name'))
image_data = self.doc.images[node.get('name')].read()
else:
_logger.warning("Image %s not defined", node.get('name'))
return False
else:
import base64
newtext = node.text
if self.localcontext:
newtext = utils._process_text(self, node.text or '')
image_data = base64.decodestring(newtext)
if not image_data:
_logger.debug("No inline image data")
return False
image = StringIO(image_data)
else:
_logger.debug("Image get from file %s", node.get('file'))
image = _open_image(node.get('file'), path=self.doc.path)
return platypus.Image(image, mask=(250,255,250,255,250,255), **(utils.attr_get(node, ['width','height'])))
elif node.tag=='spacer':
if node.get('width'):
width = utils.unit_get(node.get('width'))
else:
width = utils.unit_get('1cm')
length = utils.unit_get(node.get('length'))
return platypus.Spacer(width=width, height=length)
elif node.tag=='section':
return self.render(node)
elif node.tag == 'pageNumberReset':
return PageReset()
elif node.tag in ('pageBreak', 'nextPage'):
return platypus.PageBreak()
elif node.tag=='condPageBreak':
return platypus.CondPageBreak(**(utils.attr_get(node, ['height'])))
elif node.tag=='setNextTemplate':
return platypus.NextPageTemplate(str(node.get('name')))
elif node.tag=='nextFrame':
return platypus.CondPageBreak(1000) # TODO: change the 1000 !
elif node.tag == 'setNextFrame':
from reportlab.platypus.doctemplate import NextFrameFlowable
return NextFrameFlowable(str(node.get('name')))
elif node.tag == 'currentFrame':
from reportlab.platypus.doctemplate import CurrentFrameFlowable
return CurrentFrameFlowable(str(node.get('name')))
elif node.tag == 'frameEnd':
return EndFrameFlowable()
elif node.tag == 'hr':
width_hr=node.get('width') or '100%'
color_hr=node.get('color') or 'black'
thickness_hr=node.get('thickness') or 1
lineCap_hr=node.get('lineCap') or 'round'
return platypus.flowables.HRFlowable(width=width_hr,color=color.get(color_hr),thickness=float(thickness_hr),lineCap=str(lineCap_hr))
else:
sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (node.tag,))
return None
def render(self, node_story):
def process_story(node_story):
sub_story = []
for node in utils._child_get(node_story, self):
if node.tag == etree.Comment:
node.text = ''
continue
flow = self._flowable(node)
if flow:
if isinstance(flow,list):
sub_story = sub_story + flow
else:
sub_story.append(flow)
return sub_story
return process_story(node_story)
class EndFrameFlowable(ActionFlowable):
def __init__(self,resume=0):
ActionFlowable.__init__(self,('frameEnd',resume))
class TinyDocTemplate(platypus.BaseDocTemplate):
def beforeDocument(self):
# Store some useful value directly inside canvas, so it's available
# on flowable drawing (needed for proper PageCount handling)
self.canv._doPageReset = False
self.canv._storyCount = 0
def ___handle_pageBegin(self):
self.page += 1
self.pageTemplate.beforeDrawPage(self.canv,self)
self.pageTemplate.checkPageSize(self.canv,self)
self.pageTemplate.onPage(self.canv,self)
for f in self.pageTemplate.frames: f._reset()
self.beforePage()
self._curPageFlowableCount = 0
if hasattr(self,'_nextFrameIndex'):
del self._nextFrameIndex
for f in self.pageTemplate.frames:
if f.id == 'first':
self.frame = f
break
self.handle_frameBegin()
def afterPage(self):
if self.canv._doPageReset:
# Following a <pageReset/> tag:
# - we reset page number to 0
# - we add an new PageCount flowable (relative to the current
# story number), but not for NumeredCanvas at is handle page
# count itself)
# NOTE: _rml_template render() method add a PageReset flowable at end
# of each story, so we're sure to pass here at least once per story.
if not isinstance(self.canv, NumberedCanvas):
self.handle_flowable([ PageCount(story_count=self.canv._storyCount) ])
self.canv._pageCount = self.page
self.page = 0
self.canv._flag = True
self.canv._pageNumber = 0
self.canv._doPageReset = False
self.canv._storyCount += 1
class _rml_template(object):
def __init__(self, localcontext, out, node, doc, images=None, path='.', title=None):
if images is None:
images = {}
if not localcontext:
localcontext={'internal_header':True}
self.localcontext = localcontext
self.images= images
self.path = path
self.title = title
pagesize_map = {'a4': A4,
'us_letter': letter
}
pageSize = A4
if self.localcontext.get('company'):
pageSize = pagesize_map.get(self.localcontext.get('company').paper_format, A4)
if node.get('pageSize'):
ps = map(lambda x:x.strip(), node.get('pageSize').replace(')', '').replace('(', '').split(','))
pageSize = ( utils.unit_get(ps[0]),utils.unit_get(ps[1]) )
self.doc_tmpl = TinyDocTemplate(out, pagesize=pageSize, **utils.attr_get(node, ['leftMargin','rightMargin','topMargin','bottomMargin'], {'allowSplitting':'int','showBoundary':'bool','rotation':'int','title':'str','author':'str'}))
self.page_templates = []
self.styles = doc.styles
self.doc = doc
self.image=[]
pts = node.findall('pageTemplate')
for pt in pts:
frames = []
for frame_el in pt.findall('frame'):
frame = platypus.Frame( **(utils.attr_get(frame_el, ['x1','y1', 'width','height', 'leftPadding', 'rightPadding', 'bottomPadding', 'topPadding'], {'id':'str', 'showBoundary':'bool'})) )
if utils.attr_get(frame_el, ['last']):
frame.lastFrame = True
frames.append( frame )
try :
gr = pt.findall('pageGraphics')\
or pt[1].findall('pageGraphics')
except Exception: # FIXME: be even more specific, perhaps?
gr=''
if len(gr):
# self.image=[ n for n in utils._child_get(gr[0], self) if n.tag=='image' or not self.localcontext]
drw = _rml_draw(self.localcontext,gr[0], self.doc, images=images, path=self.path, title=self.title)
self.page_templates.append( platypus.PageTemplate(frames=frames, onPage=drw.render, **utils.attr_get(pt, [], {'id':'str'}) ))
else:
drw = _rml_draw(self.localcontext,node,self.doc,title=self.title)
self.page_templates.append( platypus.PageTemplate(frames=frames,onPage=drw.render, **utils.attr_get(pt, [], {'id':'str'}) ))
self.doc_tmpl.addPageTemplates(self.page_templates)
def render(self, node_stories):
if self.localcontext and not self.localcontext.get('internal_header',False):
del self.localcontext['internal_header']
fis = []
r = _rml_flowable(self.doc,self.localcontext, images=self.images, path=self.path, title=self.title, canvas=None)
story_cnt = 0
for node_story in node_stories:
if story_cnt > 0:
# Reset Page Number with new story tag
fis.append(PageReset())
fis.append(platypus.PageBreak())
fis += r.render(node_story)
story_cnt += 1
try:
if self.localcontext and self.localcontext.get('internal_header',False):
self.doc_tmpl.afterFlowable(fis)
self.doc_tmpl.build(fis,canvasmaker=NumberedCanvas)
else:
self.doc_tmpl.build(fis)
except platypus.doctemplate.LayoutError, e:
e.name = 'Print Error'
e.value = 'The document you are trying to print contains a table row that does not fit on one page. Please try to split it in smaller rows or contact your administrator.'
raise
def parseNode(rml, localcontext=None, fout=None, images=None, path='.', title=None):
node = etree.XML(rml)
r = _rml_doc(node, localcontext, images, path, title=title)
#try to override some font mappings
try:
from customfonts import SetCustomFonts
SetCustomFonts(r)
except ImportError:
# means there is no custom fonts mapping in this system.
pass
except Exception:
_logger.warning('Cannot set font mapping', exc_info=True)
pass
fp = StringIO()
r.render(fp)
return fp.getvalue()
def parseString(rml, localcontext=None, fout=None, images=None, path='.', title=None):
node = etree.XML(rml)
r = _rml_doc(node, localcontext, images, path, title=title)
#try to override some font mappings
try:
from customfonts import SetCustomFonts
SetCustomFonts(r)
except Exception:
pass
if fout:
fp = file(fout,'wb')
r.render(fp)
fp.close()
return fout
else:
fp = StringIO()
r.render(fp)
return fp.getvalue()
def trml2pdf_help():
print 'Usage: trml2pdf input.rml >output.pdf'
print 'Render the standard input (RML) and output a PDF file'
sys.exit(0)
if __name__=="__main__":
if len(sys.argv)>1:
if sys.argv[1]=='--help':
trml2pdf_help()
print parseString(file(sys.argv[1], 'r').read()),
else:
print 'Usage: trml2pdf input.rml >output.pdf'
print 'Try \'trml2pdf --help\' for more information.'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
frouty/odoogoeen
|
openerp/report/render/rml2pdf/trml2pdf.py
|
Python
|
agpl-3.0
| 45,807
|
import pytest
from github3 import AuthenticationFailed, GitHubError
from github3.github import GitHub
from .helper import UnitHelper, UnitIteratorHelper
def url_for(path=''):
"""Simple function to generate URLs with the base GitHub URL."""
return 'https://api.github.com/' + path.strip('/')
class TestGitHub(UnitHelper):
described_class = GitHub
example_data = None
def test_authorization(self):
"""Show that a user can retrieve a specific authorization by id."""
self.instance.authorization(10)
self.session.get.assert_called_once_with(
url_for('authorizations/10'),
)
def test_authorize(self):
"""Show an authorization can be created for a user."""
self.instance.authorize('username', 'password', ['user', 'repo'])
self.session.temporary_basic_auth.assert_called_once_with(
'username', 'password'
)
self.post_called_with(
url_for('authorizations'),
data={'note': '', 'note_url': '', 'client_id': '',
'client_secret': '', 'scopes': ['user', 'repo']}
)
def test_check_authorization(self):
"""Test an app's ability to check a authorization token."""
self.instance.set_client_id('client-id', 'client-secret')
self.instance.check_authorization('super-fake-access-token')
self.session.get.assert_called_once_with(
url_for('applications/client-id/tokens/super-fake-access-token'),
params={'client_id': None, 'client_secret': None},
auth=('client-id', 'client-secret')
)
def test_create_gist(self):
"""Test the request to create a gist."""
self.instance.create_gist('description', {
'example.py': {'content': '# example contents'}
})
self.post_called_with(
url_for('gists'),
data={
'description': 'description',
'files': {
'example.py': {
'content': '# example contents'
}
},
'public': True,
}
)
def test_create_key(self):
"""Test the request to create a key."""
self.instance.create_key('key_name', 'key text')
self.post_called_with(
url_for('user/keys'),
data={
'title': 'key_name',
'key': 'key text'
}
)
def test_create_key_requires_a_key(self):
"""Test that no request is made with an empty key."""
self.instance.create_key('title', '')
assert self.session.post.called is False
def test_create_key_requires_a_title(self):
"""Test that no request is made with an empty title."""
self.instance.create_key('', 'key text')
assert self.session.post.called is False
def test_create_repository(self):
"""Test the request to create a repository."""
self.instance.create_repository('repo-name')
self.post_called_with(
url_for('user/repos'),
data={
'name': 'repo-name',
'description': '',
'homepage': '',
'private': False,
'has_issues': True,
'has_wiki': True,
'auto_init': False,
'gitignore_template': ''
}
)
def test_emojis(self):
"""Test the request to retrieve GitHub's emojis."""
self.instance.emojis()
self.session.get.assert_called_once_with(url_for('emojis'))
def test_follow(self):
"""Test the request to follow a user."""
self.instance.follow('username')
self.session.put.assert_called_once_with(
url_for('user/following/username')
)
def test_follow_requires_a_username(self):
"""Test that GitHub#follow requires a username."""
self.instance.follow(None)
assert self.session.put.called is False
def test_gist(self):
"""Test the request to retrieve a specific gist."""
self.instance.gist(10)
self.session.get.assert_called_once_with(url_for('gists/10'))
def test_gitignore_template(self):
"""Test the request to retrieve a gitignore template."""
self.instance.gitignore_template('Python')
self.session.get.assert_called_once_with(
url_for('gitignore/templates/Python')
)
def test_gitignore_templates(self):
"""Test the request to retrieve gitignore templates."""
self.instance.gitignore_templates()
self.session.get.assert_called_once_with(
url_for('gitignore/templates')
)
def test_is_following(self):
"""Test the request to check if the user is following a user."""
self.instance.is_following('username')
self.session.get.assert_called_once_with(
url_for('user/following/username')
)
def test_is_starred(self):
"""Test the request to check if the user starred a repository."""
self.instance.is_starred('username', 'repository')
self.session.get.assert_called_once_with(
url_for('user/starred/username/repository')
)
def test_is_starred_requires_an_owner(self):
"""Test that GitHub#is_starred requires an owner."""
self.instance.is_starred(None, 'repo')
assert self.session.get.called is False
def test_is_starred_requires_a_repo(self):
"""Test that GitHub#is_starred requires an repo."""
self.instance.is_starred('username', None)
assert self.session.get.called is False
def test_issue(self):
"""Test the request to retrieve a single issue."""
self.instance.issue('owner', 'repo', 1)
self.session.get.assert_called_once_with(
url_for('repos/owner/repo/issues/1')
)
def test_issue_requires_username(self):
"""Test GitHub#issue requires a non-None username."""
self.instance.issue(None, 'foo', 1)
assert self.session.get.called is False
def test_issue_requires_repository(self):
"""Test GitHub#issue requires a non-None repository."""
self.instance.issue('foo', None, 1)
assert self.session.get.called is False
def test_issue_requires_positive_issue_id(self):
"""Test GitHub#issue requires positive issue id."""
self.instance.issue('foo', 'bar', -1)
assert self.session.get.called is False
def test_me(self):
"""Test the ability to retrieve the authenticated user's info."""
self.instance.me()
self.session.get.assert_called_once_with(url_for('user'))
def test_repository(self):
""""Verify the GET request for a repository."""
self.instance.repository('user', 'repo')
self.session.get.assert_called_once_with(url_for('repos/user/repo'))
def test_repository_with_invalid_repo(self):
"""Verify there is no call made for invalid repo combos."""
self.instance.repository('user', None)
assert self.session.get.called is False
def test_repository_with_invalid_user(self):
"""Verify there is no call made for invalid username combos."""
self.instance.repository(None, 'repo')
assert self.session.get.called is False
def test_repository_with_invalid_user_and_repo(self):
"""Verify there is no call made for invalid user/repo combos."""
self.instance.repository(None, None)
assert self.session.get.called is False
def test_repository_with_id(self):
"""Test the ability to retrieve a repository by its id."""
self.instance.repository_with_id(10)
self.session.get.assert_called_once_with(url_for('repositories/10'))
def test_repository_with_id_requires_a_positive_id(self):
"""Test the ability to retrieve a repository by its id."""
self.instance.repository_with_id(-10)
assert self.session.get.called is False
def test_repository_with_id_accepts_a_string(self):
"""Test the ability to retrieve a repository by its id."""
self.instance.repository_with_id('10')
self.session.get.assert_called_once_with(url_for('repositories/10'))
def test_two_factor_login(self):
"""Test the ability to pass two_factor_callback."""
self.instance.login('username', 'password',
two_factor_callback=lambda *args: 'foo')
def test_can_login_without_two_factor_callback(self):
"""Test that two_factor_callback is not required."""
self.instance.login('username', 'password')
self.instance.login(token='token')
def test_update_me(self):
"""Verify the request to update the authenticated user's profile."""
self.instance.update_me(name='New name', email='email@example.com',
blog='http://blog.example.com', company='Corp',
location='here')
self.patch_called_with(
url_for('user'),
data={'name': 'New name', 'email': 'email@example.com',
'blog': 'http://blog.example.com', 'company': 'Corp',
'location': 'here', 'hireable': False}
)
def test_user(self):
"""Test that a user can retrieve information about any user."""
self.instance.user('username')
self.session.get.assert_called_once_with(
url_for('users/username'),
)
def test_user_with_id(self):
"""Test that any user's information can be retrieved by id."""
self.instance.user_with_id(10)
self.session.get.assert_called_once_with(url_for('user/10'))
def test_user_with_id_requires_a_positive_id(self):
"""Test that user_with_id requires a positive parameter."""
self.instance.user_with_id(-10)
assert self.session.get.called is False
def test_user_with_id_accepts_a_string(self):
"""Test that any user's information can be retrieved by id."""
self.instance.user_with_id('10')
self.session.get.assert_called_once_with(url_for('user/10'))
class TestGitHubIterators(UnitIteratorHelper):
described_class = GitHub
example_data = None
def test_all_events(self):
"""Show that one can iterate over all public events."""
i = self.instance.all_events()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('events'),
params={'per_page': 100},
headers={}
)
def test_all_organizations(self):
"""Show that one can iterate over all organizations."""
i = self.instance.all_organizations()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('organizations'),
params={'per_page': 100},
headers={}
)
def test_all_organizations_per_page(self):
"""Show that one can iterate over all organizations with per_page."""
i = self.instance.all_organizations(per_page=25)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('organizations'),
params={'per_page': 25},
headers={}
)
def test_all_organizations_since(self):
"""Show that one can limit the organizations returned."""
since = 100000
i = self.instance.all_organizations(since=since)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('organizations'),
params={'per_page': 100, 'since': since},
headers={}
)
def test_all_repositories(self):
"""Show that one can iterate over all repositories."""
i = self.instance.all_repositories()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('repositories'),
params={'per_page': 100},
headers={}
)
def test_all_repositories_per_page(self):
"""Show that one can iterate over all repositories with per_page."""
i = self.instance.all_repositories(per_page=25)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('repositories'),
params={'per_page': 25},
headers={}
)
def test_all_repositories_since(self):
"""Show that one can limit the repositories returned."""
since = 100000
i = self.instance.all_repositories(since=since)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('repositories'),
params={'per_page': 100, 'since': since},
headers={}
)
def test_all_users(self):
"""Show that one can iterate over all users."""
i = self.instance.all_users()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users'),
params={'per_page': 100},
headers={}
)
def test_all_users_per_page(self):
"""Show that one can iterate over all users with per_page."""
i = self.instance.all_users(per_page=25)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users'),
params={'per_page': 25},
headers={}
)
def test_all_users_since(self):
"""Show that one can limit the users returned."""
since = 100000
i = self.instance.all_users(since=since)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users'),
params={'per_page': 100, 'since': since},
headers={}
)
def test_authorizations(self):
"""
Show that an authenticated user can iterate over their authorizations.
"""
i = self.instance.authorizations()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('authorizations'),
params={'per_page': 100},
headers={}
)
def test_emails(self):
"""Show that an authenticated user can iterate over their emails."""
i = self.instance.emails()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/emails'),
params={'per_page': 100},
headers={}
)
def test_followers(self):
"""
Show that an authenticated user can iterate over their followers.
"""
i = self.instance.followers()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/followers'),
params={'per_page': 100},
headers={}
)
def test_followers_require_auth(self):
"""Show that one needs to authenticate to use #followers."""
self.session.has_auth.return_value = False
with pytest.raises(GitHubError):
self.instance.followers()
def test_followers_of(self):
"""Show that one can authenticate over the followers of a user."""
i = self.instance.followers_of('sigmavirus24')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/followers'),
params={'per_page': 100},
headers={}
)
def test_following(self):
"""
Show that an authenticated user can iterate the users they are
following.
"""
i = self.instance.following()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/following'),
params={'per_page': 100},
headers={}
)
def test_following_require_auth(self):
"""Show that one needs to authenticate to use #following."""
self.session.has_auth.return_value = False
with pytest.raises(GitHubError):
self.instance.following()
def test_followed_by(self):
"""
Show that one can authenticate over the users followed by another.
"""
i = self.instance.followed_by('sigmavirus24')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/following'),
params={'per_page': 100},
headers={}
)
def test_gists(self):
"""Show that an authenticated user can iterate over their gists."""
i = self.instance.gists()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('gists'),
params={'per_page': 100},
headers={}
)
def test_gists_by(self):
"""Show that an user's gists can be iterated over."""
i = self.instance.gists_by('sigmavirus24')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/gists'),
params={'per_page': 100},
headers={}
)
def test_issues(self):
"""Show that an authenticated user can iterate over their issues."""
i = self.instance.issues()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('issues'),
params={'per_page': 100},
headers={}
)
def test_issues_with_params(self):
"""Show that issues can be filtered."""
params = {'filter': 'assigned', 'state': 'closed', 'labels': 'bug',
'sort': 'created', 'direction': 'asc',
'since': '2012-05-20T23:10:27Z'}
p = {'per_page': 100}
p.update(params)
i = self.instance.issues(**params)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('issues'),
params=p,
headers={}
)
def test_keys(self):
"""
Show that an authenticated user can iterate over their public keys.
"""
i = self.instance.keys()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/keys'),
params={'per_page': 100},
headers={}
)
def test_notifications(self):
"""
Show that an authenticated user can iterate over their notifications.
"""
i = self.instance.notifications()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('notifications'),
params={'per_page': 100},
headers={},
)
def test_notifications_participating_in(self):
"""Show that the user can filter by pariticpating."""
i = self.instance.notifications(participating=True)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('notifications'),
params={'per_page': 100, 'participating': 'true'},
headers={}
)
def test_notifications_all(self):
"""Show that the user can iterate over all of their notifications."""
i = self.instance.notifications(all=True)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('notifications'),
params={'per_page': 100, 'all': 'true'},
headers={}
)
def test_organization_issues(self):
"""Show that one can iterate over an organization's issues."""
i = self.instance.organization_issues('org')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('orgs/org/issues'),
params={'per_page': 100},
headers={}
)
def test_organization_issues_with_params(self):
"""Show that one can pass parameters to #organization_issues."""
params = {'filter': 'assigned', 'state': 'closed', 'labels': 'bug',
'sort': 'created', 'direction': 'asc',
'since': '2012-05-20T23:10:27Z'}
i = self.instance.organization_issues('org', **params)
self.get_next(i)
p = {'per_page': 100}
p.update(params)
self.session.get.assert_called_once_with(
url_for('orgs/org/issues'),
params=p,
headers={}
)
def test_organizations(self):
"""
Show that one can iterate over all of the authenticated user's orgs.
"""
i = self.instance.organizations()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/orgs'),
params={'per_page': 100},
headers={}
)
def test_organizations_with(self):
"""Show that one can iterate over all of a user's orgs."""
i = self.instance.organizations_with('sigmavirus24')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/orgs'),
params={'per_page': 100},
headers={}
)
def test_public_gists(self):
"""Show that all public gists can be iterated over."""
i = self.instance.public_gists()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('gists/public'),
params={'per_page': 100},
headers={}
)
def test_respositories(self):
"""
Show that an authenticated user can iterate over their repositories.
"""
i = self.instance.repositories()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/repos'),
params={'per_page': 100},
headers={}
)
def test_respositories_accepts_params(self):
"""Show that an #repositories accepts params."""
i = self.instance.repositories(type='all',
direction='desc',
sort='created')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/repos'),
params={'per_page': 100, 'type': 'all', 'direction': 'desc',
'sort': 'created'},
headers={}
)
def test_issues_on(self):
"""Show that a user can iterate over a repository's issues."""
i = self.instance.issues_on('owner', 'repo')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('repos/owner/repo/issues'),
params={'per_page': 100},
headers={}
)
def test_issues_on_with_params(self):
"""Show that #issues_on accepts multiple parameters."""
params = {'milestone': 1, 'state': 'all', 'assignee': 'owner',
'mentioned': 'someone', 'labels': 'bug,high'}
i = self.instance.issues_on('owner', 'repo', **params)
self.get_next(i)
params.update(per_page=100)
self.session.get.assert_called_once_with(
url_for('repos/owner/repo/issues'),
params=params,
headers={}
)
def test_starred(self):
"""
Show that one can iterate over an authenticated user's stars.
"""
i = self.instance.starred()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/starred'),
params={'per_page': 100},
headers={}
)
def test_starred_by(self):
"""Show that one can iterate over a user's stars."""
i = self.instance.starred_by('sigmavirus24')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/starred'),
params={'per_page': 100},
headers={}
)
def test_subscriptions(self):
"""
Show that one can iterate over an authenticated user's subscriptions.
"""
i = self.instance.subscriptions()
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/subscriptions'),
params={'per_page': 100},
headers={}
)
def test_subscriptions_for(self):
"""Show that one can iterate over a user's subscriptions."""
i = self.instance.subscriptions_for('sigmavirus24')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/subscriptions'),
params={'per_page': 100},
headers={}
)
def test_user_issues(self):
"""Test that one can iterate over a user's issues."""
i = self.instance.user_issues()
# Get the next item from the iterator
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/issues'),
params={'per_page': 100},
headers={}
)
def test_user_issues_with_parameters(self):
"""Test that one may pass parameters to GitHub#user_issues."""
# Set up the parameters to be sent
params = {'filter': 'assigned', 'state': 'closed', 'labels': 'bug',
'sort': 'created', 'direction': 'asc',
'since': '2012-05-20T23:10:27Z', 'per_page': 25}
# Make the call with the paramters
i = self.instance.user_issues(**params)
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('user/issues'),
params=params,
headers={}
)
def test_repositories_by(self):
"""Test that one can iterate over a user's repositories."""
i = self.instance.repositories_by('sigmavirus24')
# Get the next item from the iterator
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/repos'),
params={'per_page': 100},
headers={}
)
def test_repositories_by_with_type(self):
"""
Test that one can iterate over a user's repositories with a type.
"""
i = self.instance.repositories_by('sigmavirus24', 'all')
self.get_next(i)
self.session.get.assert_called_once_with(
url_for('users/sigmavirus24/repos'),
params={'per_page': 100, 'type': 'all'},
headers={}
)
class TestGitHubRequiresAuthentication(UnitHelper):
"""Test methods that require authentication."""
described_class = GitHub
example_data = None
def after_setup(self):
"""Disable authentication on the session."""
self.session.auth = None
self.session.has_auth.return_value = False
def test_authorization(self):
"""A user must be authenticated to retrieve an authorization."""
with pytest.raises(AuthenticationFailed):
self.instance.authorization(1)
def test_authorizations(self):
"""Show that one needs to authenticate to use #authorizations."""
with pytest.raises(AuthenticationFailed):
self.instance.authorizations()
def test_create_issue(self):
"""Show that GitHub#create_issue requires auth."""
with pytest.raises(AuthenticationFailed):
self.instance.create_issue('owner', 'repo', 'title')
def test_create_key(self):
"""Show that GitHub#create_key requires auth."""
with pytest.raises(AuthenticationFailed):
self.instance.create_key('title', 'key')
def test_create_repository(self):
"""Show that GitHub#create_repository requires auth."""
with pytest.raises(AuthenticationFailed):
self.instance.create_repository('repo')
def test_emails(self):
"""Show that one needs to authenticate to use #emails."""
with pytest.raises(AuthenticationFailed):
self.instance.emails()
def test_follow(self):
"""Show that one needs to authenticate to use #follow."""
with pytest.raises(AuthenticationFailed):
self.instance.follow('foo')
def test_gists(self):
"""Show that one needs to authenticate to use #gists."""
with pytest.raises(AuthenticationFailed):
self.instance.gists()
def test_is_following(self):
"""Show that GitHub#is_following requires authentication."""
with pytest.raises(AuthenticationFailed):
self.instance.is_following('foo')
def test_is_starred(self):
"""Show that GitHub#is_starred requires authentication."""
with pytest.raises(AuthenticationFailed):
self.instance.is_starred('foo', 'bar')
def test_issues(self):
"""Show that one needs to authenticate to use #issues."""
with pytest.raises(AuthenticationFailed):
self.instance.issues()
def test_keys(self):
"""Show that one needs to authenticate to use #keys."""
with pytest.raises(AuthenticationFailed):
self.instance.keys()
def test_me(self):
"""Show that GitHub#me requires authentication."""
with pytest.raises(AuthenticationFailed):
self.instance.me()
def test_notifications(self):
"""Show that one needs to authenticate to use #gists."""
with pytest.raises(AuthenticationFailed):
self.instance.notifications()
def test_organization_issues(self):
"""Show that one needs to authenticate to use #organization_issues."""
with pytest.raises(AuthenticationFailed):
self.instance.organization_issues('org')
def test_organizations(self):
"""Show that one needs to authenticate to use #organizations."""
with pytest.raises(AuthenticationFailed):
self.instance.organizations()
def test_repositories(self):
"""Show that one needs to authenticate to use #repositories."""
with pytest.raises(AuthenticationFailed):
self.instance.repositories()
def test_starred(self):
"""Show that one needs to authenticate to use #starred."""
with pytest.raises(AuthenticationFailed):
self.instance.starred()
def test_user_issues(self):
"""Show that GitHub#user_issues requires authentication."""
with pytest.raises(AuthenticationFailed):
self.instance.user_issues()
class TestGitHubAuthorizations(UnitHelper):
described_class = GitHub
example_data = None
def create_session_mock(self, *args):
session = super(TestGitHubAuthorizations,
self).create_session_mock(*args)
session.retrieve_client_credentials.return_value = ('id', 'secret')
return session
def test_revoke_authorization(self):
"""Test that GitHub#revoke_authorization calls the expected methods.
It should use the session's delete and temporary_basic_auth methods.
"""
self.instance.revoke_authorization('access_token')
self.session.delete.assert_called_once_with(
'https://api.github.com/applications/id/tokens/access_token',
params={'client_id': None, 'client_secret': None}
)
self.session.temporary_basic_auth.assert_called_once_with(
'id', 'secret'
)
def test_revoke_authorizations(self):
"""Test that GitHub#revoke_authorizations calls the expected methods.
It should use the session's delete and temporary_basic_auth methods.
"""
self.instance.revoke_authorizations()
self.session.delete.assert_called_once_with(
'https://api.github.com/applications/id/tokens',
params={'client_id': None, 'client_secret': None}
)
self.session.temporary_basic_auth.assert_called_once_with(
'id', 'secret'
)
|
icio/github3.py
|
tests/unit/test_github.py
|
Python
|
bsd-3-clause
| 31,906
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'python-memcached',
'pyramid',
'apache-libcloud',
'PasteScript',
'paramiko',
'pyyaml',
'pycrypto',
'requests',
'nose',
'behaving',
'sphinxcontrib-httpdomain',
'sphinx-bootstrap-theme',
'celery',
'gevent',
'gevent-subprocess',
'amqp',
'netaddr',
'amqp',
'websocket-client',
'sockjs-tornado',
'pika',
]
setup(name='mist.io',
version='0.9.9',
license='AGPLv3',
description='server management, monitoring & automation across clouds from any web device',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='mist.io',
author_email='info@mist.io',
url='https://mist.io',
keywords='web cloud server management monitoring automation mobile libcloud pyramid amazon aws rackspace openstack linode softlayer digitalocean gce',
packages=find_packages('src'),
package_dir={'': 'src'},
namespace_packages=['mist'],
include_package_data=True,
zip_safe=False,
install_requires=requires,
tests_require=requires,
test_suite="mist.io",
entry_points="""\
[paste.app_factory]
main = mist.io:main
""",
)
|
DimensionDataCBUSydney/mist.io
|
setup.py
|
Python
|
agpl-3.0
| 1,708
|
from django import forms
from rest_framework.compat import parse_datetime
class ISO8601DateTimeField(forms.DateTimeField):
def strptime(self, value, format):
return parse_datetime(value)
|
jgmize/rna
|
rna/fields.py
|
Python
|
mpl-2.0
| 202
|
# Copyright 2012 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.common import cred_provider
from tempest import config
from tempest import exceptions
from tempest.lib import auth
CONF = config.CONF
class Manager(object):
"""Base manager class
Manager objects are responsible for providing a configuration object
and a client object for a test case to use in performing actions.
"""
def __init__(self, credentials):
"""Initialization of base manager class
Credentials to be used within the various client classes managed by the
Manager object must be defined.
:param credentials: type Credentials or TestResources
"""
self.credentials = credentials
# Check if passed or default credentials are valid
if not self.credentials.is_valid():
raise exceptions.InvalidCredentials()
self.auth_version = CONF.identity.auth_version
# Tenant isolation creates TestResources, but
# PreProvisionedCredentialProvider and some tests create Credentials
if isinstance(credentials, cred_provider.TestResources):
creds = self.credentials.credentials
else:
creds = self.credentials
# Creates an auth provider for the credentials
self.auth_provider = get_auth_provider(creds, pre_auth=True)
def get_auth_provider_class(credentials):
if isinstance(credentials, auth.KeystoneV3Credentials):
return auth.KeystoneV3AuthProvider, CONF.identity.uri_v3
else:
return auth.KeystoneV2AuthProvider, CONF.identity.uri
def get_auth_provider(credentials, pre_auth=False):
default_params = {
'disable_ssl_certificate_validation':
CONF.identity.disable_ssl_certificate_validation,
'ca_certs': CONF.identity.ca_certificates_file,
'trace_requests': CONF.debug.trace_requests
}
if credentials is None:
raise exceptions.InvalidCredentials(
'Credentials must be specified')
auth_provider_class, auth_url = get_auth_provider_class(
credentials)
_auth_provider = auth_provider_class(credentials, auth_url,
**default_params)
if pre_auth:
_auth_provider.set_auth()
return _auth_provider
|
HybridF5/tempest_debug
|
tempest/manager.py
|
Python
|
apache-2.0
| 2,876
|
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2012 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Implementation of paginate query."""
import sqlalchemy
from cinder import exception
from cinder.i18n import _, _LW
from cinder.openstack.common import log as logging
LOG = logging.getLogger(__name__)
# copied from glance/db/sqlalchemy/api.py
def paginate_query(query, model, limit, sort_keys, marker=None,
sort_dir=None, sort_dirs=None):
"""Returns a query with sorting / pagination criteria added.
Pagination works by requiring a unique sort_key, specified by sort_keys.
(If sort_keys is not unique, then we risk looping through values.)
We use the last row in the previous page as the 'marker' for pagination.
So we must return values that follow the passed marker in the order.
With a single-valued sort_key, this would be easy: sort_key > X.
With a compound-values sort_key, (k1, k2, k3) we must do this to repeat
the lexicographical ordering:
(k1 > X1) or (k1 == X1 && k2 > X2) or (k1 == X1 && k2 == X2 && k3 > X3)
We also have to cope with different sort_directions.
Typically, the id of the last row is used as the client-facing pagination
marker, then the actual marker object must be fetched from the db and
passed in to us as marker.
:param query: the query object to which we should add paging/sorting
:param model: the ORM model class
:param limit: maximum number of items to return
:param sort_keys: array of attributes by which results should be sorted
:param marker: the last item of the previous page; we returns the next
results after this value.
:param sort_dir: direction in which results should be sorted (asc, desc)
:param sort_dirs: per-column array of sort_dirs, corresponding to sort_keys
:rtype: sqlalchemy.orm.query.Query
:return: The query with sorting/pagination added.
"""
if 'id' not in sort_keys:
# TODO(justinsb): If this ever gives a false-positive, check
# the actual primary key, rather than assuming its id
LOG.warn(_LW('Id not in sort_keys; is sort_keys unique?'))
assert(not (sort_dir and sort_dirs))
# Default the sort direction to ascending
if sort_dirs is None and sort_dir is None:
sort_dir = 'asc'
# Ensure a per-column sort direction
if sort_dirs is None:
sort_dirs = [sort_dir for _sort_key in sort_keys]
assert(len(sort_dirs) == len(sort_keys))
# Add sorting
for current_sort_key, current_sort_dir in zip(sort_keys, sort_dirs):
sort_dir_func = {
'asc': sqlalchemy.asc,
'desc': sqlalchemy.desc,
}[current_sort_dir]
try:
sort_key_attr = getattr(model, current_sort_key)
except AttributeError:
raise exception.InvalidInput(reason='Invalid sort key')
query = query.order_by(sort_dir_func(sort_key_attr))
# Add pagination
if marker is not None:
marker_values = []
for sort_key in sort_keys:
v = getattr(marker, sort_key)
marker_values.append(v)
# Build up an array of sort criteria as in the docstring
criteria_list = []
for i in xrange(0, len(sort_keys)):
crit_attrs = []
for j in xrange(0, i):
model_attr = getattr(model, sort_keys[j])
crit_attrs.append((model_attr == marker_values[j]))
model_attr = getattr(model, sort_keys[i])
if sort_dirs[i] == 'desc':
crit_attrs.append((model_attr < marker_values[i]))
elif sort_dirs[i] == 'asc':
crit_attrs.append((model_attr > marker_values[i]))
else:
raise ValueError(_("Unknown sort direction, "
"must be 'desc' or 'asc'"))
criteria = sqlalchemy.sql.and_(*crit_attrs)
criteria_list.append(criteria)
f = sqlalchemy.sql.or_(*criteria_list)
query = query.filter(f)
if limit is not None:
query = query.limit(limit)
return query
|
Akrog/cinder
|
cinder/common/sqlalchemyutils.py
|
Python
|
apache-2.0
| 4,861
|
# -*- coding: utf-8 -*-
#
#
# Author: Guewen Baconnier
# Copyright 2013-2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
{'name': 'Sale Procurement Group by Line',
'summary': 'Base module for multiple procurement group by Sale order',
'version': '8.0.1.0.0',
'author': "Camptocamp,Odoo Community Association (OCA)",
'category': 'Warehouse',
'license': 'AGPL-3',
'complexity': 'expert',
'images': [],
'website': "http://www.camptocamp.com",
'depends': ['sale_stock',
],
'demo': [],
'data': [],
'test': [],
'auto_install': False,
'installable': True,
}
|
Eficent/sale-workflow
|
sale_procurement_group_by_line/__openerp__.py
|
Python
|
agpl-3.0
| 1,247
|
###########################################################
#
# Copyright (c) 2005-2008, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['SpreadsheetElementWdg']
from pyasm.common import TacticException, FormatValue, jsonloads
from tactic.ui.common import SimpleTableElementWdg
from pyasm.web import DivWdg
class SpreadsheetElementWdg(SimpleTableElementWdg):
ARGS_KEYS = {
'column': {
'description': 'The column from which a runnint total should be calculated from.',
'category': 'Options'
},
'format': {
'description': 'The template with which to forman resulting value.',
'category': 'Options'
},
}
def is_sortable(my):
return False
def is_editable(my):
return True
def init(my):
my.total = 0
def get_value(my):
return my.total
def get_text_value(my):
column = my.get_option("column")
sobject = my.get_current_sobject()
sobj_value = sobject.get_value(column)
if sobj_value:
my.total += sobj_value
return my.total
def get_display(my):
top = my.top
sobjects = my.sobjects
sobject = my.get_current_sobject()
index = my.get_current_index()
column = my.get_option("column")
sobject = my.get_current_sobject()
sobj_value = sobject.get_value(column)
if sobj_value:
my.total += sobj_value
format_str = my.get_option('format')
if format_str:
format = FormatValue()
#display = format.get_format_value(value, "$#,###.##")
display = format.get_format_value(my.total, format_str)
else:
display = my.total
value_div = DivWdg()
top.add(value_div)
value_div.add_style("float: right")
value_div.add(display)
name = my.get_name()
sobject.set_value(name, my.total)
#sobject.commit()
return top
def test(my):
# Neeed a way to refer to another colum spreadsheet style
# This will get the cost from the previous sobject
expr = "@GET(sobject[$INDEX-1].cost)"
# or do we have a special keyword
expr = "@COLOR(palette.color, [10, -10, 10])"
|
sadanandb/pmt
|
src/tactic/ui/table/spreadsheet_element_wdg.py
|
Python
|
epl-1.0
| 2,490
|
from keras.models import Sequential, Model
from keras.layers import Input, BatchNormalization, Conv2D
from keras.layers.merge import add
from keras.layers.core import Activation, Flatten
from AlphaGo.util import flatten_idx
from AlphaGo.models.nn_util import Bias, NeuralNetBase, neuralnet
import numpy as np
@neuralnet
class CNNPolicy(NeuralNetBase):
"""uses a convolutional neural network to evaluate the state of the game
and compute a probability distribution over the next action
"""
def _select_moves_and_normalize(self, nn_output, moves, size):
"""helper function to normalize a distribution over the given list of moves
and return a list of (move, prob) tuples
"""
if len(moves) == 0:
return []
move_indices = [flatten_idx(m, size) for m in moves]
# get network activations at legal move locations
distribution = nn_output[move_indices]
distribution = distribution / distribution.sum()
return zip(moves, distribution)
def batch_eval_state(self, states, moves_lists=None):
"""Given a list of states, evaluates them all at once to make best use of GPU
batching capabilities.
Analogous to [eval_state(s) for s in states]
Returns: a parallel list of move distributions as in eval_state
"""
n_states = len(states)
if n_states == 0:
return []
state_size = states[0].get_size()
if not all([st.get_size() == state_size for st in states]):
raise ValueError("all states must have the same size")
# concatenate together all one-hot encoded states along the 'batch' dimension
nn_input = np.concatenate([self.preprocessor.state_to_tensor(s) for s in states], axis=0)
# pass all input through the network at once (backend makes use of
# batches if len(states) is large)
network_output = self.forward(nn_input)
# default move lists to all legal moves
moves_lists = moves_lists or [st.get_legal_moves() for st in states]
results = [None] * n_states
for i in range(n_states):
results[i] = self._select_moves_and_normalize(network_output[i], moves_lists[i],
state_size)
return results
def eval_state(self, state, moves=None):
"""Given a GameState object, returns a list of (action, probability) pairs
according to the network outputs
If a list of moves is specified, only those moves are kept in the distribution
"""
tensor = self.preprocessor.state_to_tensor(state)
# run the tensor through the network
network_output = self.forward(tensor)
moves = moves or state.get_legal_moves()
return self._select_moves_and_normalize(network_output[0], moves, state.get_size())
@staticmethod
def create_network(**kwargs):
"""construct a convolutional neural network.
Keword Arguments:
- input_dim: depth of features to be processed by first layer (no default)
- board: width of the go board to be processed (default 19)
- filters_per_layer: number of filters used on every layer (default 128)
- filters_per_layer_K: (where K is between 1 and <layers>) number of filters
used on layer K (default #filters_per_layer)
- layers: number of convolutional steps (default 12)
- filter_width_K: (where K is between 1 and <layers>) width of filter on
layer K (default 3 except 1st layer which defaults to 5).
Must be odd.
"""
defaults = {
"board": 19,
"filters_per_layer": 128,
"layers": 12,
"filter_width_1": 5
}
# copy defaults, but override with anything in kwargs
params = defaults
params.update(kwargs)
# create the network:
# a series of zero-paddings followed by convolutions
# such that the output dimensions are also board x board
network = Sequential()
# create first layer
network.add(Conv2D(
input_shape=(params["input_dim"], params["board"], params["board"]),
filters=params.get("filters_per_layer_1", params["filters_per_layer"]),
kernel_size=(params["filter_width_1"], params["filter_width_1"]),
kernel_initializer='uniform',
activation='relu',
padding='same',
kernel_constraint=None,
activity_regularizer=None,
trainable=True,
strides=[1, 1],
use_bias=True,
bias_regularizer=None,
bias_constraint=None,
data_format="channels_first",
kernel_regularizer=None))
# create all other layers
for i in range(2, params["layers"] + 1):
# use filter_width_K if it is there, otherwise use 3
filter_key = "filter_width_%d" % i
filter_width = params.get(filter_key, 3)
# use filters_per_layer_K if it is there, otherwise use default value
filter_count_key = "filters_per_layer_%d" % i
filter_nb = params.get(filter_count_key, params["filters_per_layer"])
network.add(Conv2D(
filters=filter_nb,
kernel_size=(filter_width, filter_width),
kernel_initializer='uniform',
activation='relu',
padding='same',
kernel_constraint=None,
activity_regularizer=None,
trainable=True,
strides=[1, 1],
use_bias=True,
bias_regularizer=None,
bias_constraint=None,
data_format="channels_first",
kernel_regularizer=None))
# the last layer maps each <filters_per_layer> feature to a number
network.add(Conv2D(
filters=1,
kernel_size=(1, 1),
kernel_initializer='uniform',
padding='same',
kernel_constraint=None,
activity_regularizer=None,
trainable=True,
strides=[1, 1],
use_bias=True,
bias_regularizer=None,
bias_constraint=None,
data_format="channels_first",
kernel_regularizer=None))
# reshape output to be board x board
network.add(Flatten())
# add a bias to each board location
network.add(Bias())
# softmax makes it into a probability distribution
network.add(Activation('softmax'))
return network
@neuralnet
class ResnetPolicy(CNNPolicy):
"""Residual network architecture as per He at al. 2015
"""
@staticmethod
def create_network(**kwargs):
"""construct a convolutional neural network with Resnet-style skip connections.
Arguments are the same as with the default CNNPolicy network, except the default
number of layers is 20 plus a new n_skip parameter
Keword Arguments:
- input_dim: depth of features to be processed by first layer (no default)
- board: width of the go board to be processed (default 19)
- filters_per_layer: number of filters used on every layer (default 128)
- layers: number of convolutional steps (default 20)
- filter_width_K: (where K is between 1 and <layers>) width of filter on
layer K (default 3 except 1st layer which defaults to 5).
Must be odd.
- n_skip_K: (where K is as in filter_width_K) number of convolutional
layers to skip with the linear path starting at K. Only valid
at K >= 1. (Each layer defaults to 1)
Note that n_skip_1=s means that the next valid value of n_skip_* is 3
A diagram may help explain (numbers indicate layer):
1 2 3 4 5 6
I--C--B--R--C--B--R--C--M--B--R--C--B--R--C--B--R--C--M ... M --R--F--O
\__________________/ \___________________________/ \ ... /
[n_skip_1 = 2] [n_skip_3 = 3]
I - input
B - BatchNormalization
R - ReLU
C - Conv2D
F - Flatten
O - output
M - merge
The input is always passed through a Conv2D layer, the output of which
layer is counted as '1'. Each subsequent [R -- C] block is counted as
one 'layer'. The 'merge' layer isn't counted; hence if n_skip_1 is 2,
the next valid skip parameter is n_skip_3, which will start at the
output of the merge
"""
defaults = {
"board": 19,
"filters_per_layer": 128,
"layers": 20,
"filter_width_1": 5
}
# copy defaults, but override with anything in kwargs
params = defaults
params.update(kwargs)
# create the network using Keras' functional API,
# since this isn't 'Sequential'
model_input = Input(shape=(params["input_dim"], params["board"], params["board"]))
# create first layer
convolution_path = Conv2D(
input_shape=(),
filters=params["filters_per_layer"],
kernel_size=(params["filter_width_1"], params["filter_width_1"]),
kernel_initializer='uniform',
activation='linear', # relu activations done inside resnet modules
padding='same',
kernel_constraint=None,
activity_regularizer=None,
trainable=True,
strides=[1, 1],
use_bias=True,
bias_regularizer=None,
bias_constraint=None,
data_format="channels_first",
kernel_regularizer=None)(model_input)
def add_resnet_unit(path, K, **params):
"""Add a resnet unit to path starting at layer 'K',
adding as many (ReLU + Conv2D) modules as specified by n_skip_K
Returns new path and next layer index, i.e. K + n_skip_K, in a tuple
"""
# loosely based on https://github.com/keunwoochoi/residual_block_keras
# see also # keras docs here:
# http://keras.io/getting-started/functional-api-guide/#all-models-are-callable-just-like-layers
block_input = path
# use n_skip_K if it is there, default to 1
skip_key = "n_skip_%d" % K
n_skip = params.get(skip_key, 1)
for i in range(n_skip):
layer = K + i
# add BatchNorm
path = BatchNormalization()(path)
# add ReLU
path = Activation('relu')(path)
# use filter_width_K if it is there, otherwise use 3
filter_key = "filter_width_%d" % layer
filter_width = params.get(filter_key, 3)
# add Conv2D
path = Conv2D(
filters=params["filters_per_layer"],
kernel_size=(filter_width, filter_width),
kernel_initializer='uniform',
activation='linear',
padding='same',
kernel_constraint=None,
activity_regularizer=None,
trainable=True,
strides=[1, 1],
use_bias=True,
bias_regularizer=None,
bias_constraint=None,
data_format="channels_first",
kernel_regularizer=None)(path)
# Merge 'input layer' with the path
path = add([block_input, path])
return path, K + n_skip
# create all other layers
layer = 1
while layer < params['layers']:
convolution_path, layer = add_resnet_unit(convolution_path, layer, **params)
if layer > params['layers']:
print("Due to skipping, ended with {} layers instead of {}"
.format(layer, params['layers']))
# since each layer's activation was linear, need one more ReLu
convolution_path = Activation('relu')(convolution_path)
# the last layer maps each <filters_per_layer> featuer to a number
convolution_path = Conv2D(
filters=1,
kernel_size=(1, 1),
kernel_initializer='uniform',
name="policy_conv_last",
padding='same',
activation="linear",
kernel_constraint=None,
activity_regularizer=None,
trainable=True,
strides=[1, 1],
use_bias=True,
bias_regularizer=None,
bias_constraint=None,
data_format="channels_first",
kernel_regularizer=None)(convolution_path)
# flatten output
network_output = Flatten()(convolution_path)
# add a bias to each board location
network_output = Bias()(network_output)
# softmax makes it into a probability distribution
network_output = Activation('softmax')(network_output)
return Model(inputs=[model_input], outputs=[network_output])
|
Rochester-NRT/RocAlphaGo
|
AlphaGo/models/policy.py
|
Python
|
mit
| 13,485
|
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Photo'
db.create_table(u'accounts_photo', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('file', self.gf('django.db.models.fields.CharField')(max_length=64)),
('is_primary', self.gf('django.db.models.fields.BooleanField')(default=False)),
('tag', self.gf('django.db.models.fields.CharField')(max_length=16, db_index=True)),
))
db.send_create_signal(u'accounts', ['Photo'])
def backwards(self, orm):
# Deleting model 'Photo'
db.delete_table(u'accounts_photo')
models = {
u'accounts.photo': {
'Meta': {'object_name': 'Photo'},
'file': ('django.db.models.fields.CharField', [], {'max_length': '64'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_primary': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'tag': ('django.db.models.fields.CharField', [], {'max_length': '16', 'db_index': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
},
u'accounts.profile': {
'Meta': {'object_name': 'Profile'},
'age_group': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'chest': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}),
'foot': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}),
'height': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}),
'hipline': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'preferred_style': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': u"orm['auth.User']", 'unique': 'True'}),
'waistline': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'}),
'weight': ('django.db.models.fields.CharField', [], {'max_length': '16', 'blank': 'True'})
},
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
}
}
complete_apps = ['accounts']
|
ygrass/handsome
|
accounts/migrations/0003_auto__add_photo.py
|
Python
|
unlicense
| 5,858
|
# Copyright 2016 - Nokia
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import oslo_messaging
import pecan
from pecan import rest
class RootRestController(rest.RestController):
@pecan.expose()
def _route(self, args, request=None):
"""All requests go through here
We can check the backend status
"""
if not pecan.request.check_backend:
return super(RootRestController, self)._route(args, request)
try:
client = pecan.request.client.prepare(timeout=5)
backend_is_alive = client.call(pecan.request.context, 'is_alive')
if backend_is_alive:
return super(RootRestController, self)._route(args, request)
else:
pecan.abort(503, detail='vitrage-graph is not ready')
except oslo_messaging.MessagingTimeout:
pecan.abort(503, detail='vitrage-graph not available')
|
openstack/vitrage
|
vitrage/api/controllers/rest.py
|
Python
|
apache-2.0
| 1,420
|
#!/usr/bin/env python
import Queue
import threading
class ThreadSafePriorityQueue:
def __init__(self, name):
self.name = None
self.queue = None
self.get_lock = None
self.put_lock = None
self.name = name
self.queue = Queue.PriorityQueue()
self.get_lock = threading.Lock()
self.put_lock = threading.Lock()
def send_to_queue(self, msg, msg_list=False, priority=10):
with self.put_lock:
#print "sending", msg, " to ", self.name, ", size: ", self.queue.qsize(), "id: ", self.queue
if msg_list:
for m in msg:
self.queue.put((priority, m))
else:
self.queue.put((priority, msg))
#print self.name, " q_size: ", self.queue.qsize()
def get_from_queue(self, all_msgs=False, blocking=False):
with self.get_lock:
# if self.name is not "read_queue":
# print "reading from ", self.name, ", size: ", self.queue.qsize(), "id: ", self.queue, " all_msgs: ", \
# all_msgs, " blocking: ", blocking
if all_msgs:
msgs = []
while self.queue.qsize() > 0:
try:
msg = self.queue.get(blocking)
try:
msg = msg[1]
except Exception as e:
pass
print msg
msgs.append(msg)
except Queue.Empty:
msgs = []
return msgs
else:
try:
msg = self.queue.get(blocking)
# if self.name is not "read_queue":
# print self.name, " recv: ", msg
except Exception as e:#Queue.Empty:
# if self.name is not "read_queue":
# print self.name, " read error: ", e
msg = ""
pass
try:
msg = msg[1]
except Exception as e:
# if self.name is not "read_queue":
# print self.name, " read error: ", e
pass
#print self.name, " msg: ", msg
# if self.name is not "read_queue":
# print self.name, ", size: ", self.queue.qsize(), "recv: ", msg
return msg
def filter_queue(self, msg_filter, invert=False):
msgs = self.get_from_queue(all_msgs=True, blocking=True)
if msg_filter is not "":
n = 0
for i, msg in enumerate(msgs):
if filter in msg and not invert:
msgs.pop(i)
n += 1
elif filter not in msg and invert:
msgs.pop(i)
n += 1
if msgs is not []:
self.send_to_queue(msgs, msg_list=True, priority=1)
|
aransena/uarm_metal
|
src/ThreadSafePriorityQueue.py
|
Python
|
mit
| 3,038
|
import factory
class Entry(factory.django.DjangoModelFactory):
title = factory.Faker('sentence')
content = factory.Faker('paragraph')
class Meta:
model = 'faq.Entry'
|
EliotBerriot/mnm
|
mnm/faq/tests/factories.py
|
Python
|
mit
| 190
|
#!/bin/env python
"""
Copyright 2010-2018 University Of Southern California
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This module plots station map and fault trace
"""
from __future__ import division, print_function
# Import Python Modules
import sys
import struct
import numpy as np
import matplotlib as mpl
if mpl.get_backend() != 'agg':
mpl.use('Agg') # Disables use of Tk/X11
import matplotlib.colors as mcolors
import matplotlib.cm as cm
from matplotlib.ticker import FormatStrFormatter
import pylab
# Import plot config file
import plot_config
# GMT "bf" native binary header and format
GMT_HDR_FORMAT = '<3i10d80s80s80s80s320s160s'
GMT_DATA_FORMAT = '<f'
# Note: this script uses the "bf" native C float format
# The existing GMT topo grid in NetCDF format can be
# converted to this format with the following command:
# $ grdreformat calTopo18.grd calTopo18.test=bf -V
def in_region(point, plotregion):
"""
Returns true if point falls within the plotregion
"""
if ((point[0] >= plotregion[0]) and
(point[0] < plotregion[1]) and
(point[1] >= plotregion[2]) and
(point[1] < plotregion[3])):
return True
else:
return False
def read_fault(filename):
"""
Read in fault file
"""
fault_x = []
fault_y = []
fault_file = open(filename)
for segment in fault_file:
x, y = segment.split()
fault_x.append(float(x))
fault_y.append(float(y))
fault_file.close()
return fault_x, fault_y
def read_stations(filename):
"""
Read in station list
"""
sta_x = []
sta_y = []
station_file = open(filename)
for station in station_file:
x, y, _ = station.split()
sta_x.append(float(x))
sta_y.append(float(y))
station_file.close()
return sta_x, sta_y
def read_coastal(filename, plotregion):
"""
Read in coastal geometry as a list of lists of polygon segments
"""
# Initialize all variables
coast_x = []
coast_y = []
poly_x = []
poly_y = []
segnum = 0
segments = 0
# Read in file
polygons = open(filename)
# Parse polygons
for line in polygons:
tokens = line.split()
if (tokens[0] == 'P') or (tokens[0] == 'L'):
if (len(poly_x) > 0):
coast_x.append(poly_x)
coast_y.append(poly_y)
poly_x = []
poly_y = []
segnum = 0
segments = int(tokens[2])
else:
if (segnum >= segments):
print("Invalid number of segments in " +
"polygon from file %s" % (file))
return([], [])
segnum = segnum + 1
x = float(tokens[0])
y = float(tokens[1])
if (in_region([x, y], plotregion)):
poly_x.append(x)
poly_y.append(y)
else:
if (len(poly_x) > 0):
coast_x.append(poly_x)
coast_y.append(poly_y)
poly_x = []
poly_y = []
# Remember to close file
polygons.close()
return coast_x, coast_y
def read_topo(filename, plotregion):
"""
Reads in topo data that is saved in GMT format:
bf GMT native, C-binary format (float)
Header size is 892 bytes
"""
# Open input file
topo_file = open(filename, 'r')
# Parse header
buf = topo_file.read(struct.calcsize(GMT_HDR_FORMAT))
header = struct.unpack(GMT_HDR_FORMAT, buf)
topo_dims = [header[0], header[1]]
topo_region = [header[3], header[4], header[5], header[6]]
# Read elevation values
data = np.arange(topo_dims[0] * topo_dims[1],
dtype=float).reshape(topo_dims[1],
topo_dims[0])
buf = topo_file.read(topo_dims[0] * topo_dims[1] *
struct.calcsize(GMT_DATA_FORMAT))
topo_file.close()
# Data is x-fast
for y in xrange(0, topo_dims[1]):
for x in xrange(0, topo_dims[0]):
offset = ((y * topo_dims[0] + x) *
struct.calcsize(GMT_DATA_FORMAT))
data[y][x] = struct.unpack(GMT_DATA_FORMAT,
buf[offset:offset + 4])[0]
# Pull out sub-matrix for plotregion, and invert y-axis
x0 = int((plotregion[0] - topo_region[0]) / header[9])
y1 = topo_dims[1] - int((plotregion[2] -
topo_region[2]) / header[10])
x1 = int((plotregion[1] - topo_region[0]) / header[9])
y0 = topo_dims[1] - int((plotregion[3] -
topo_region[2]) / header[10])
subdata = np.arange((x1 - x0) * (y1 - y0),
dtype=float).reshape(y1 - y0, x1 - x0)
for y in xrange(y0, y1):
for x in xrange(x0, x1):
if ((y >= 0) and (y < topo_dims[1]) and
(x >= 0) and (x < topo_dims[0])):
subdata[y - y0][x - x0] = data[y][x]
# Mask array to hide NaNs
masked = np.ma.masked_invalid(subdata)
# All done
return masked
def plot_station_map(plottitle, plotregion, topo, coastal, border,
fault, sta, map_prefix, hypocenter_list=None):
"""
Genereate the station map plot
"""
# Read in topo data
topo_points = read_topo(topo, plotregion)
# Read in fault data
fault_x, fault_y = read_fault(fault)
# Read in station data
sta_x, sta_y = read_stations(sta)
# Read coastlines
coast_x, coast_y = read_coastal(coastal, plotregion)
# Read borders
bord_x, bord_y = read_coastal(border, plotregion)
# Set plot dims
pylab.gcf().set_size_inches(6, 6)
pylab.gcf().clf()
# Adjust title y-position
t = pylab.title(plottitle, size=12)
t.set_y(1.06)
# Setup color scale
cmap = cm.gist_earth
norm = mcolors.Normalize(vmin=-1000.0, vmax=3000.0)
# Plot basemap
pylab.imshow(topo_points, cmap=cmap, norm=norm,
extent=plotregion, interpolation='nearest')
# Freeze the axis extents
pylab.gca().set_autoscale_on(False)
# Plot coast lines
for i in xrange(0, len(coast_x)):
pylab.plot(coast_x[i], coast_y[i], linestyle='-', color='0.5')
# Plot borders
for i in xrange(0, len(bord_x)):
pylab.plot(bord_x[i], bord_y[i], linestyle='-', color='0.75')
# Plot fault trace
pylab.plot(fault_x, fault_y, linestyle='-', color='k')
# Plot stations
pylab.plot(sta_x, sta_y, marker='o', color='r', linewidth=0)
# Plot hypocenter if provided
if hypocenter_list is not None:
hypo_lat = []
hypo_lon = []
for hypocenter in hypocenter_list:
hypo_lat.append(hypocenter['lat'])
hypo_lon.append(hypocenter['lon'])
pylab.plot(hypo_lon, hypo_lat, marker='*',
markersize=12, color='y', linewidth=0)
# Set degree formatting of tick values
majorFormatter = FormatStrFormatter(u'%.1f\u00b0')
pylab.gca().xaxis.set_major_formatter(majorFormatter)
pylab.gca().yaxis.set_major_formatter(majorFormatter)
# Turn on ticks for both sides of axis
for tick in pylab.gca().xaxis.get_major_ticks():
tick.label1On = True
tick.label2On = True
for tick in pylab.gca().yaxis.get_major_ticks():
tick.label1On = True
tick.label2On = True
# Set font size
for tick in pylab.gca().get_xticklabels():
tick.set_fontsize(8)
for tick in pylab.gca().get_yticklabels():
tick.set_fontsize(8)
print("==> Creating Plot: %s.png" % (map_prefix))
pylab.savefig('%s.png' % (map_prefix), format="png",
transparent=False, dpi=plot_config.dpi)
pylab.close()
def usage():
"""
Outputs instructions on how to use the program
"""
print("usage: %s <N bound> <S bound> <W bound> <E bound> " %
(sys.argv[0]) +
"<fault file> <station file> <map prefix> <topo> <coastal> <border>")
if __name__ == '__main__':
if (len(sys.argv) != 11):
usage()
sys.exit(1)
PLOTTITLE = 'Fault Trace with Stations'
PLOTREGION = [float(sys.argv[3]), float(sys.argv[4]),
float(sys.argv[2]), float(sys.argv[1])]
FAULT = sys.argv[5]
STA = sys.argv[6]
MAP_PREFIX = sys.argv[7]
TOPO = sys.argv[8]
COASTAL = sys.argv[9]
BORDER = sys.argv[10]
plot_station_map(PLOTTITLE, PLOTREGION, TOPO, COASTAL, BORDER,
FAULT, STA, MAP_PREFIX)
sys.exit(0)
|
SCECcode/BBP
|
bbp/comps/PlotMap.py
|
Python
|
apache-2.0
| 9,038
|
from unittest import TestCase
from unittest import TestSuite
from unittest import main
from unittest import makeSuite
from mwstools.parsers.products import GetMatchingProductForIdResult
class TestGetMatchingProductForIdResult(TestCase):
body = """
<GetMatchingProductForIdResult Id="082676082658" IdType="UPC" status="Success">
<Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01"
xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Product>
<Empty />
</Product>
</Products>
</GetMatchingProductForIdResult>
"""
def setUp(self):
self.parser = GetMatchingProductForIdResult.load(self.body)
def test_id_(self):
self.assertEqual(self.parser.id_, '082676082658')
def test_id_type(self):
self.assertEqual(self.parser.id_type, 'UPC')
def test_status(self):
self.assertEqual(self.parser.status, 'Success')
def test_is_success(self):
self.assertTrue(self.parser.is_success())
def test_products(self):
self.assertEqual(len(self.parser.products()), 1)
__all__ = [
TestGetMatchingProductForIdResult
]
def suite():
s = TestSuite()
for a in __all__:
s.addTest(makeSuite(a))
return s
if __name__ == '__main__':
main(defaultTest='suite')
|
ziplokk1/python-amazon-mws-tools
|
tests/parsers/products/test_GetMatchingProductForIdResult.py
|
Python
|
unlicense
| 1,383
|
"""
MAVProxy rally module
"""
from pymavlink import mavwp
from pymavlink import mavutil
import time, os, platform
from MAVProxy.modules.lib import mp_module
from MAVProxy.modules.lib import mp_util
if mp_util.has_wxpython:
from MAVProxy.modules.lib.mp_menu import *
class RallyModule(mp_module.MPModule):
def __init__(self, mpstate):
super(RallyModule, self).__init__(mpstate, "rally", "rally point control", public = True)
self.rallyloader_by_sysid = {}
self.add_command('rally', self.cmd_rally, "rally point control", ["<add|clear|land|list|move|remove|>",
"<load|save> (FILENAME)"])
self.have_list = False
self.abort_alt = 50
self.abort_first_send_time = 0
self.abort_previous_send_time = 0
self.abort_ack_received = True
self.menu_added_console = False
self.menu_added_map = False
if mp_util.has_wxpython:
self.menu = MPMenuSubMenu('Rally',
items=[MPMenuItem('Clear', 'Clear', '# rally clear'),
MPMenuItem('List', 'List', '# rally list'),
MPMenuItem('Load', 'Load', '# rally load ',
handler=MPMenuCallFileDialog(flags=('open',),
title='Rally Load',
wildcard='RallyPoints(*.txt,*.rally,*.ral)|*.txt;*.rally;*.ral')),
MPMenuItem('Save', 'Save', '# rally save ',
handler=MPMenuCallFileDialog(flags=('save', 'overwrite_prompt'),
title='Rally Save',
wildcard='RallyPoints(*.txt,*.rally,*.ral)|*.txt;*.rally;*.ral')),
MPMenuItem('Add', 'Add', '# rally add ',
handler=MPMenuCallTextDialog(title='Rally Altitude (m)',
default=100))])
@property
def rallyloader(self):
'''rally loader by system ID'''
if not self.target_system in self.rallyloader_by_sysid:
self.rallyloader_by_sysid[self.target_system] = mavwp.MAVRallyLoader(self.settings.target_system,
self.settings.target_component)
return self.rallyloader_by_sysid[self.target_system]
def last_change(self):
'''return time of last changes made to rally points'''
return self.rallyloader.last_change
def rally_count(self):
'''return number of waypoints'''
return self.rallyloader.rally_count()
def rally_point(self, i):
'''return instance of mavutil.mavlink.MAVLink_rally_point_message'''
return self.rallyloader.rally_point(i)
def set_last_change(self, time):
'''can be used to cause map redraws'''
self.rallyloader.last_change = time
def idle_task(self):
'''called on idle'''
if self.module('console') is not None:
if not self.menu_added_console:
self.menu_added_console = True
self.module('console').add_menu(self.menu)
else:
self.menu_added_console = False
if self.module('map') is not None:
if not self.menu_added_map:
self.menu_added_map = True
self.module('map').add_menu(self.menu)
else:
self.menu_added_map = False
'''handle abort command; it is critical that the AP to receive it'''
if self.abort_ack_received is False:
#only send abort every second (be insistent, but don't spam)
if (time.time() - self.abort_previous_send_time > 1):
self.master.mav.command_long_send(self.settings.target_system,
self.settings.target_component,
mavutil.mavlink.MAV_CMD_DO_GO_AROUND,
0, int(self.abort_alt), 0, 0, 0, 0, 0, 0,)
self.abort_previous_send_time = time.time()
#try to get an ACK from the plane:
if self.abort_first_send_time == 0:
self.abort_first_send_time = time.time()
elif time.time() - self.abort_first_send_time > 10: #give up after 10 seconds
print("Unable to send abort command!\n")
self.abort_ack_received = True
def cmd_rally_add(self, args):
'''handle rally add'''
if len(args) < 1:
alt = self.settings.rallyalt
else:
alt = float(args[0])
if len(args) < 2:
break_alt = self.settings.rally_breakalt
else:
break_alt = float(args[1])
if len(args) < 3:
flag = self.settings.rally_flags
else:
flag = int(args[2])
#currently only supporting autoland values:
#True (nonzero) and False (zero)
if (flag != 0):
flag = 2
if not self.have_list:
print("Please list rally points first")
return
if (self.rallyloader.rally_count() > 4):
print("Only 5 rally points possible per flight plan.")
return
latlon = self.mpstate.click_location
if latlon is None:
print("No map click position available")
return
land_hdg = 0.0
self.rallyloader.create_and_append_rally_point(latlon[0] * 1e7, latlon[1] * 1e7, alt, break_alt, land_hdg, flag)
self.send_rally_points()
print("Added Rally point at %s %f %f, autoland: %s" % (str(latlon), alt, break_alt, bool(flag & 2)))
def cmd_rally_alt(self, args):
'''handle rally alt change'''
if (len(args) < 2):
print("Usage: rally alt RALLYNUM newAlt <newBreakAlt>")
return
if not self.have_list:
print("Please list rally points first")
return
idx = int(args[0])
if idx <= 0 or idx > self.rallyloader.rally_count():
print("Invalid rally point number %u" % idx)
return
new_alt = int(args[1])
new_break_alt = None
if (len(args) > 2):
new_break_alt = int(args[2])
self.rallyloader.set_alt(idx, new_alt, new_break_alt)
self.send_rally_point(idx-1)
self.fetch_rally_point(idx-1)
self.rallyloader.reindex()
def cmd_rally_move(self, args):
'''handle rally move'''
if len(args) < 1:
print("Usage: rally move RALLYNUM")
return
if not self.have_list:
print("Please list rally points first")
return
idx = int(args[0])
if idx <= 0 or idx > self.rallyloader.rally_count():
print("Invalid rally point number %u" % idx)
return
rpoint = self.rallyloader.rally_point(idx-1)
latlon = self.mpstate.click_location
if latlon is None:
print("No map click position available")
return
oldpos = (rpoint.lat*1e-7, rpoint.lng*1e-7)
self.rallyloader.move(idx, latlon[0], latlon[1])
self.send_rally_point(idx-1)
p = self.fetch_rally_point(idx-1)
if p.lat != int(latlon[0]*1e7) or p.lng != int(latlon[1]*1e7):
print("Rally move failed")
return
self.rallyloader.reindex()
print("Moved rally point from %s to %s at %fm" % (str(oldpos), str(latlon), rpoint.alt))
def cmd_rally(self, args):
'''rally point commands'''
#TODO: add_land arg
if len(args) < 1:
self.print_usage()
return
elif args[0] == "add":
self.cmd_rally_add(args[1:])
elif args[0] == "move":
self.cmd_rally_move(args[1:])
elif args[0] == "clear":
self.rallyloader.clear()
self.mav_param.mavset(self.master,'RALLY_TOTAL',0,3)
elif args[0] == "remove":
if not self.have_list:
print("Please list rally points first")
return
if (len(args) < 2):
print("Usage: rally remove RALLYNUM")
return
self.rallyloader.remove(int(args[1]))
self.send_rally_points()
elif args[0] == "list":
self.list_rally_points()
self.have_list = True
elif args[0] == "load":
if (len(args) < 2):
print("Usage: rally load filename")
return
try:
self.rallyloader.load(args[1].strip('"'))
except Exception as msg:
print("Unable to load %s - %s" % (args[1], msg))
return
self.send_rally_points()
self.have_list = True
print("Loaded %u rally points from %s" % (self.rallyloader.rally_count(), args[1]))
elif args[0] == "save":
if (len(args) < 2):
print("Usage: rally save filename")
return
self.rallyloader.save(args[1].strip('"'))
print("Saved rally file %s" % args[1])
elif args[0] == "alt":
self.cmd_rally_alt(args[1:])
elif args[0] == "land":
if (len(args) >= 2 and args[1] == "abort"):
self.abort_ack_received = False
self.abort_first_send_time = 0
self.abort_alt = self.settings.rally_breakalt
if (len(args) >= 3):
self.abort_alt = int(args[2])
else:
self.master.mav.command_long_send(self.settings.target_system,
self.settings.target_component,
mavutil.mavlink.MAV_CMD_DO_RALLY_LAND,
0, 0, 0, 0, 0, 0, 0, 0)
else:
self.print_usage()
def mavlink_packet(self, m):
'''handle incoming mavlink packet'''
type = m.get_type()
if type in ['COMMAND_ACK']:
if m.command == mavutil.mavlink.MAV_CMD_DO_GO_AROUND:
if (m.result == 0 and self.abort_ack_received == False):
self.say("Landing Abort Command Successfully Sent.")
self.abort_ack_received = True
elif (m.result != 0 and self.abort_ack_received == False):
self.say("Landing Abort Command Unsuccessful.")
elif m.command == mavutil.mavlink.MAV_CMD_DO_RALLY_LAND:
if (m.result == 0):
self.say("Landing.")
def unload(self):
self.remove_command("rally")
if self.module('console') is not None and self.menu_added_console:
self.menu_added_console = False
self.module('console').remove_menu(self.menu)
if self.module('map') is not None and self.menu_added_map:
self.menu_added_map = False
self.module('map').remove_menu(self.menu)
super(RallyModule, self).unload()
def send_rally_point(self, i):
'''send rally points from fenceloader'''
p = self.rallyloader.rally_point(i)
p.target_system = self.target_system
p.target_component = self.target_component
self.master.mav.send(p)
def send_rally_points(self):
'''send rally points from rallyloader'''
self.mav_param.mavset(self.master,'RALLY_TOTAL',self.rallyloader.rally_count(),3)
for i in range(self.rallyloader.rally_count()):
self.send_rally_point(i)
def fetch_rally_point(self, i):
'''fetch one rally point'''
self.master.mav.rally_fetch_point_send(self.target_system,
self.target_component, i)
tstart = time.time()
p = None
while time.time() - tstart < 1:
p = self.master.recv_match(type='RALLY_POINT', blocking=False)
if p is not None:
break
time.sleep(0.1)
continue
if p is None:
self.console.error("Failed to fetch rally point %u" % i)
return None
return p
def list_rally_points(self):
self.rallyloader.clear()
rally_count = self.mav_param.get('RALLY_TOTAL',0)
if rally_count == 0:
print("No rally points")
return
for i in range(int(rally_count)):
p = self.fetch_rally_point(i)
if p is None:
return
self.rallyloader.append_rally_point(p)
for i in range(self.rallyloader.rally_count()):
p = self.rallyloader.rally_point(i)
self.console.writeln("lat=%f lng=%f alt=%f break_alt=%f land_dir=%f autoland=%f" % (p.lat * 1e-7, p.lng * 1e-7, p.alt, p.break_alt, p.land_dir, int(p.flags & 2!=0) ))
if self.logdir is not None:
fname = 'ral.txt'
if self.target_system > 1:
fname = 'ral_%u.txt' % self.target_system
ral_file_path = os.path.join(self.logdir, fname)
self.rallyloader.save(ral_file_path)
print("Saved rally points to %s" % ral_file_path)
def print_usage(self):
print("Usage: rally <list|load|land|save|add|remove|move|clear|alt>")
def init(mpstate):
'''initialise module'''
return RallyModule(mpstate)
|
tridge/MAVProxy
|
MAVProxy/modules/mavproxy_rally.py
|
Python
|
gpl-3.0
| 13,720
|
# -*- coding: utf-8 -*-
"""
Enumerazione delle tipologie degli oggetti.
"""
from src.element import EnumElement, finalize_enumeration
#-------------------------------------------------------------------------------
name = __name__[__name__.rfind(".")+1 : ]
elements = []
cycle_on_last = False
#-------------------------------------------------------------------------------
class EntitypeElement(EnumElement):
def __init__(self, name, description=""):
super(EntitypeElement, self).__init__(name, description)
self.icon = ""
#- Fine Inizializzazione -
#-------------------------------------------------------------------------------
NONE = EntitypeElement("Nessuna")
CONTAINER = EntitypeElement("Contenitore")
CORPSE = EntitypeElement("Cadavere")
DOOR = EntitypeElement("Porta")
DRINK = EntitypeElement("Bevanda")
FISHING = EntitypeElement("Pesca")
FOOD = EntitypeElement("Cibo")
FLOWER = EntitypeElement("Fiore")
FRUIT = EntitypeElement("Frutto")
GROUND = EntitypeElement("Terreno")
INSTRUMENT = EntitypeElement("Strumento")
KEY = EntitypeElement("Chiave")
KEYRING = EntitypeElement("Portachiavi")
MENHIR = EntitypeElement("Menhir")
MONEY = EntitypeElement("Moneta")
PLANT = EntitypeElement("Pianta")
PORTAL = EntitypeElement("Portale")
READABLE = EntitypeElement("Leggibile")
SEED = EntitypeElement("Seme")
#SHEATH = EntitypeElement("Fodero")
WEAR = EntitypeElement("Abbigliamento")
WEAPON = EntitypeElement("Arma")
#-------------------------------------------------------------------------------
finalize_enumeration(__name__)
|
Onirik79/aaritmud
|
src/enums/ENTITYPE.py
|
Python
|
gpl-2.0
| 1,664
|
# -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2018 Steve Kowalik <steven@wedontsleep.org> #
# #
# This file is part of PyGithub. #
# http://pygithub.readthedocs.io/ #
# #
# PyGithub is free software: you can redistribute it and/or modify it under #
# the terms of the GNU Lesser General Public License as published by the Free #
# Software Foundation, either version 3 of the License, or (at your option) #
# any later version. #
# #
# PyGithub 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 Lesser General Public License for more #
# details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with PyGithub. If not, see <http://www.gnu.org/licenses/>. #
# #
################################################################################
from . import Framework
class BranchProtection(Framework.TestCase):
def setUp(self):
super().setUp()
self.branch_protection = (
self.g.get_user()
.get_repo("PyGithub")
.get_branch("integrations")
.get_protection()
)
def testAttributes(self):
self.assertTrue(self.branch_protection.required_status_checks.strict)
self.assertEqual(
self.branch_protection.required_status_checks.contexts, ["foo/bar"]
)
self.assertEqual(
self.branch_protection.url,
"https://api.github.com/repos/jacquev6/PyGithub/branches/integrations/protection",
)
self.assertEqual(
self.branch_protection.__repr__(),
'BranchProtection(url="https://api.github.com/repos/jacquev6/PyGithub/branches/integrations/protection")',
)
|
mgorny/PyGithub
|
tests/BranchProtection.py
|
Python
|
lgpl-3.0
| 2,619
|
#!python
"""Bootstrap distribute installation
If you want to use setuptools in your package's setup.py, just include this
file in the same directory with it, and add this to the top of your setup.py::
from distribute_setup import use_setuptools
use_setuptools()
If you want to require a specific version of setuptools, set a download
mirror, or use an alternate download directory, you can do so by supplying
the appropriate options to ``use_setuptools()``.
This file can also be run as a script to install or upgrade setuptools.
"""
import os
import sys
import time
import fnmatch
import tempfile
import tarfile
from distutils import log
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
try:
import subprocess
def _python_cmd(*args):
args = (sys.executable,) + args
return subprocess.call(args) == 0
except ImportError:
# will be used for python 2.3
def _python_cmd(*args):
args = (sys.executable,) + args
# quoting arguments if windows
if sys.platform == 'win32':
def quote(arg):
if ' ' in arg:
return '"%s"' % arg
return arg
args = [quote(arg) for arg in args]
return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
DEFAULT_VERSION = "0.6.14"
DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
SETUPTOOLS_FAKED_VERSION = "0.6c11"
SETUPTOOLS_PKG_INFO = """\
Metadata-Version: 1.0
Name: setuptools
Version: %s
Summary: xxxx
Home-page: xxx
Author: xxx
Author-email: xxx
License: xxx
Description: xxx
""" % SETUPTOOLS_FAKED_VERSION
def _install(tarball):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# installing
log.warn('Installing Distribute')
if not _python_cmd('setup.py', 'install'):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
finally:
os.chdir(old_wd)
def _build_egg(egg, tarball, to_dir):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# building an egg
log.warn('Building a Distribute egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
finally:
os.chdir(old_wd)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
tarball = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, tarball, to_dir)
sys.path.insert(0, egg)
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15, no_fake=True):
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
was_imported = 'pkg_resources' in sys.modules or \
'setuptools' in sys.modules
try:
try:
import pkg_resources
if not hasattr(pkg_resources, '_distribute'):
if not no_fake:
_fake_setuptools()
raise ImportError
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("distribute>="+version)
return
except pkg_resources.VersionConflict:
e = sys.exc_info()[1]
if was_imported:
sys.stderr.write(
"The required version of distribute (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first, using\n"
"'easy_install -U distribute'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return _do_download(version, download_base, to_dir,
download_delay)
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir,
download_delay)
finally:
if not no_fake:
_create_fake_setuptools_pkg_info(to_dir)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tgz_name = "distribute-%s.tar.gz" % version
url = download_base + tgz_name
saveto = os.path.join(to_dir, tgz_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
log.warn("Downloading %s", url)
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(saveto, "wb")
dst.write(data)
finally:
if src:
src.close()
if dst:
dst.close()
return os.path.realpath(saveto)
def _no_sandbox(function):
def __no_sandbox(*args, **kw):
try:
from setuptools.sandbox import DirectorySandbox
if not hasattr(DirectorySandbox, '_old'):
def violation(*args):
pass
DirectorySandbox._old = DirectorySandbox._violation
DirectorySandbox._violation = violation
patched = True
else:
patched = False
except ImportError:
patched = False
try:
return function(*args, **kw)
finally:
if patched:
DirectorySandbox._violation = DirectorySandbox._old
del DirectorySandbox._old
return __no_sandbox
def _patch_file(path, content):
"""Will backup the file then patch it"""
existing_content = open(path).read()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
return True
_patch_file = _no_sandbox(_patch_file)
def _same_content(path, content):
return open(path).read() == content
def _rename_path(path):
new_name = path + '.OLD.%s' % time.time()
log.warn('Renaming %s into %s', path, new_name)
os.rename(path, new_name)
return new_name
def _remove_flat_installation(placeholder):
if not os.path.isdir(placeholder):
log.warn('Unkown installation at %s', placeholder)
return False
found = False
for file in os.listdir(placeholder):
if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
found = True
break
if not found:
log.warn('Could not locate setuptools*.egg-info')
return
log.warn('Removing elements out of the way...')
pkg_info = os.path.join(placeholder, file)
if os.path.isdir(pkg_info):
patched = _patch_egg_dir(pkg_info)
else:
patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
if not patched:
log.warn('%s already patched.', pkg_info)
return False
# now let's move the files out of the way
for element in ('setuptools', 'pkg_resources.py', 'site.py'):
element = os.path.join(placeholder, element)
if os.path.exists(element):
_rename_path(element)
else:
log.warn('Could not find the %s element of the '
'Setuptools distribution', element)
return True
_remove_flat_installation = _no_sandbox(_remove_flat_installation)
def _after_install(dist):
log.warn('After install bootstrap.')
placeholder = dist.get_command_obj('install').install_purelib
_create_fake_setuptools_pkg_info(placeholder)
def _create_fake_setuptools_pkg_info(placeholder):
if not placeholder or not os.path.exists(placeholder):
log.warn('Could not find the install location')
return
pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
setuptools_file = 'setuptools-%s-py%s.egg-info' % \
(SETUPTOOLS_FAKED_VERSION, pyver)
pkg_info = os.path.join(placeholder, setuptools_file)
if os.path.exists(pkg_info):
log.warn('%s already exists', pkg_info)
return
log.warn('Creating %s', pkg_info)
f = open(pkg_info, 'w')
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
pth_file = os.path.join(placeholder, 'setuptools.pth')
log.warn('Creating %s', pth_file)
f = open(pth_file, 'w')
try:
f.write(os.path.join(os.curdir, setuptools_file))
finally:
f.close()
_create_fake_setuptools_pkg_info = _no_sandbox(_create_fake_setuptools_pkg_info)
def _patch_egg_dir(path):
# let's check if it's already patched
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
if os.path.exists(pkg_info):
if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
log.warn('%s already patched.', pkg_info)
return False
_rename_path(path)
os.mkdir(path)
os.mkdir(os.path.join(path, 'EGG-INFO'))
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
f = open(pkg_info, 'w')
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
return True
_patch_egg_dir = _no_sandbox(_patch_egg_dir)
def _before_install():
log.warn('Before install bootstrap.')
_fake_setuptools()
def _under_prefix(location):
if 'install' not in sys.argv:
return True
args = sys.argv[sys.argv.index('install')+1:]
for index, arg in enumerate(args):
for option in ('--root', '--prefix'):
if arg.startswith('%s=' % option):
top_dir = arg.split('root=')[-1]
return location.startswith(top_dir)
elif arg == option:
if len(args) > index:
top_dir = args[index+1]
return location.startswith(top_dir)
if arg == '--user' and USER_SITE is not None:
return location.startswith(USER_SITE)
return True
def _fake_setuptools():
log.warn('Scanning installed packages')
try:
import pkg_resources
except ImportError:
# we're cool
log.warn('Setuptools or Distribute does not seem to be installed.')
return
ws = pkg_resources.working_set
try:
setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools',
replacement=False))
except TypeError:
# old distribute API
setuptools_dist = ws.find(pkg_resources.Requirement.parse('setuptools'))
if setuptools_dist is None:
log.warn('No setuptools distribution found')
return
# detecting if it was already faked
setuptools_location = setuptools_dist.location
log.warn('Setuptools installation detected at %s', setuptools_location)
# if --root or --preix was provided, and if
# setuptools is not located in them, we don't patch it
if not _under_prefix(setuptools_location):
log.warn('Not patching, --root or --prefix is installing Distribute'
' in another location')
return
# let's see if its an egg
if not setuptools_location.endswith('.egg'):
log.warn('Non-egg installation')
res = _remove_flat_installation(setuptools_location)
if not res:
return
else:
log.warn('Egg installation')
pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
if (os.path.exists(pkg_info) and
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
log.warn('Already patched.')
return
log.warn('Patching...')
# let's create a fake egg replacing setuptools one
res = _patch_egg_dir(setuptools_location)
if not res:
return
log.warn('Patched done.')
_relaunch()
def _relaunch():
log.warn('Relaunching...')
# we have to relaunch the process
# pip marker to avoid a relaunch bug
if sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']:
sys.argv[0] = 'setup.py'
args = [sys.executable] + sys.argv
sys.exit(subprocess.call(args))
def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
import copy
import operator
from tarfile import ExtractError
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448 # decimal for oct 0700
self.extract(tarinfo, path)
# Reverse sort directories.
if sys.version_info < (2, 4):
def sorter(dir1, dir2):
return cmp(dir1.name, dir2.name)
directories.sort(sorter)
directories.reverse()
else:
directories.sort(key=operator.attrgetter('name'), reverse=True)
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError:
e = sys.exc_info()[1]
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
def main(argv, version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
tarball = download_setuptools()
_install(tarball)
if __name__ == '__main__':
main(sys.argv[1:])
|
victorlin/ez2pay
|
distribute_setup.py
|
Python
|
mit
| 15,758
|
#!/usr/bin/env python
"""alerts.py Classes for sendings alerts
"""
__author__ = "Jean-Martin Archer"
__copyright__ = "Copyright 2013, MIT License."
import smtplib
from twilio.rest import TwilioRestClient
from vendors.pushbullet.pushbullet import PushBullet
import configuration
class Alerts(object):
"""<ac:image ac:thumbnail="true" ac:width="300">for alerts"""
def __init__(self, config_path='./config/'):
self.config = configuration.load(config_path)
self.register()
def register(self):
alerts = self.config['alerts']
alerts_list = []
if alerts['sms']['on']:
alerts_list.append(alerts.sms(alerts['AlertSMS']))
if alerts['pushbullet']['on']:
alerts_list.append(alerts.pushbullet(alerts['AlertPushBullet']))
if alerts['email']['on']:
alerts_list.append(alerts.sms(alerts['AlertPushBullet']))
self.alerts = alerts_list
def send(self, message):
for alert in self.alerts:
alert.send_notification(message)
class BasicAlert(object):
"""<ac:image ac:thumbnail="true" ac:width="300">for BasicAlert class. This is more an interface/contract
than anything else"""
def __init__(self, config):
self.config = config
self.setup()
def setup(self):
raise NotImplementedError
def send_notification(self, message):
raise NotImplementedError
class AlertEmail(BasicAlert):
"""<ac:image ac:thumbnail="true" ac:width="300">for AlertEmail"""
def setup(self):
self.sender = self.config['email_sender']
self.receivers = self.config['email_receivers']
self.server = self.config['server']
def send_notification(self, message):
email_body = """From: Alert <%s>
To: Alert <%s>
Subject: %s
This is a test e-mail message.
""" % (self.sender, self.receivers, message)
try:
smtpObj = smtplib.SMTP(self.server)
smtpObj.sendmail(self.sender, self.receivers, email_body)
print "Successfully sent AlertEmail"
except SMTPException:
print "Error: unable to send AlertEmail"
class AlertPushBullet(BasicAlert):
"""<ac:image ac:thumbnail="true" ac:width="300">for AlertPushBullet. Get you api key from
https://www.PushBullet.com/account
Use the pyPushBullet API to know which deviceID to use.
"""
def setup(self):
self.push = PushBullet(self.config['apikey'])
def send_notification(self, message):
for device in self.config['device']:
self.push.pushNote(device, message, message)
def get_device_id(self):
print self.push.getDevices()
class AlertSMS(BasicAlert):
"""<ac:image ac:thumbnail="true" ac:width="300">for AlertSMS, uses your twilio.com account."""
def setup(self):
# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = self.config['twilio_sid']
auth_token = self.config['twilio_auth_token']
self.client = TwilioRestClient(account_sid, auth_token)
self.create = client.sms.messages.create
def send_notification(self, message):
message = self.create(body=message,
to=self.config['to_number'],
from_=self.config["from_number"])
|
j-martin/raspberry-gpio-zmq
|
raspzmq/alerts.py
|
Python
|
mit
| 3,371
|
import os
import pty
import json
import pytest
from contextlib import contextmanager
from serjax.server import app as app_test
from serjax.server import api, add_api_endpoints
from serjax.client import serial
add_api_endpoints(api)
@contextmanager
@pytest.fixture
def fetch_api_lock():
"""Context manager to setup and gain a lock on the serial port"""
app = app_test.test_client()
app.testing = True
master_pty, slave_pty = pty.openpty()
slave_port = os.ttyname(slave_pty)
master_port = os.ttyname(master_pty)
lock_response = app.get('/open')
# assert lock_response.status_code == 201
print(lock_response)
print(lock_response.get_data())
json_data = json.loads(lock_response.get_data().decode('ascii'))
lock = str(json_data.get('api_lock', ''))
yield (
app,
master_pty,
slave_pty,
master_port,
slave_port,
lock_response,
lock)
os.close(master_pty)
os.close(slave_pty)
app.get('/close')
class testSerial(serial):
"""override the client get and put methods for testing"""
def __init__(self, url='', port=None):
self.app = app_test.test_client()
self.app.testing = True
super(testSerial, self).__init__(url=url, port=port)
def get(self, url):
return json.loads(
self.app.get(
url,
headers=self.headers
).get_data().decode('ascii')
)
def put(self, url, data=None):
return json.loads(
self.app.put(
url,
data=data,
headers=self.headers
).get_data().decode('ascii')
)
def writelines(self, data):
self.post('%s/write' % self.url, data={'data': data.read()})
def post(self, url, data=None):
return json.loads(
self.app.put(
url,
data=data,
headers=self.headers
).get_data().decode('ascii')
)
|
olymk2/serJax
|
tests/helper.py
|
Python
|
gpl-3.0
| 2,018
|
from seahub.base.models import UserEnabledModule, GroupEnabledModule
from seahub.wiki.models import PersonalWiki
MOD_PERSONAL_WIKI = 'personal wiki'
MOD_GROUP_WIKI = 'group wiki'
class BadModNameError(Exception):
pass
def get_available_mods_by_user(username):
"""Returns a list of available modules for user.
"""
mods_available = [MOD_PERSONAL_WIKI, ]
return mods_available
def get_enabled_mods_by_user(username):
"""Returns a list of enabled modules for user.
"""
mod_enabled = []
personal_wiki_enabled = UserEnabledModule.objects.filter(
username=username, module_name=MOD_PERSONAL_WIKI).exists()
if personal_wiki_enabled:
mod_enabled.append(MOD_PERSONAL_WIKI)
return mod_enabled
def enable_mod_for_user(username, mod_name):
if mod_name != MOD_PERSONAL_WIKI:
raise BadModNameError
return UserEnabledModule(username=username, module_name=mod_name).save()
def disable_mod_for_user(username, mod_name):
if mod_name != MOD_PERSONAL_WIKI:
raise BadModNameError
UserEnabledModule.objects.filter(username=username,
module_name=mod_name).delete()
def get_available_mods_by_group(group_id):
"""Returns a list of available modules for group.
"""
mods_available = [MOD_GROUP_WIKI, ]
return mods_available
def get_enabled_mods_by_group(group_id):
"""Returns a list of enabled modules for group.
"""
mod_enabled = []
group_wiki_enabled = GroupEnabledModule.objects.filter(
group_id=group_id, module_name=MOD_GROUP_WIKI).exists()
if group_wiki_enabled:
mod_enabled.append(MOD_GROUP_WIKI)
return mod_enabled
def enable_mod_for_group(group_id, mod_name):
if mod_name != MOD_GROUP_WIKI:
raise BadModNameError
return GroupEnabledModule(group_id=group_id, module_name=mod_name).save()
def disable_mod_for_group(group_id, mod_name):
if mod_name != MOD_GROUP_WIKI:
raise BadModNameError
GroupEnabledModule.objects.filter(group_id=group_id,
module_name=mod_name).delete()
def get_wiki_enabled_group_list(in_group_ids=None):
"""Return all groups that enable wiki module by default.
If ``in_group_ids`` is provided, return groups within that collection.
Arguments:
- `in_group_ids`: A list contains group ids.
"""
qs = GroupEnabledModule.objects.all()
if in_group_ids is not None:
qs = qs.filter(group_id__in=in_group_ids)
return qs
|
cloudcopy/seahub
|
seahub/views/modules.py
|
Python
|
apache-2.0
| 2,544
|
import unittest
import numpy as np
from kona.linalg.memory import KonaMemory
from kona.user import UserSolverIDF
from dummy_solver import DummySolver
class DesignVectorTestCase(unittest.TestCase):
def setUp(self):
solver = DummySolver(10, 10, 0)
self.km = km = KonaMemory(solver)
km.design_lb = 0.
km.primal_factory.request_num_vectors(3)
km.state_factory.request_num_vectors(3)
km.eq_factory.request_num_vectors(1)
km.allocate_memory()
# can't create bear KonaVectors because the memory manager doesn't
# like them, so I'll just use the DesignVector to test the
# KonaVectorMethods
self.pv = km.primal_factory.generate()
self.sv = km.state_factory.generate()
def test_check_type(self):
'''DesignVector type checking'''
try:
self.pv._check_type(self.sv)
except TypeError as err:
self.assertEqual(
str(err),
"Vector type mismatch. " +
"Must be <class 'kona.linalg.vectors.common.DesignVector'>")
else:
self.fail('TypeError expected')
try:
self.pv._check_type(self.pv)
except TypeError:
self.fail('Type error not expected')
# NOTE: If test_inner is not working, none of the other tests will!!!
def test_inner(self):
'''DesignVector inner product'''
# have to manually poke the data here
# so the test doesn't rely on any other methods
self.pv.base.data = 2*np.ones(10)
self.assertEqual(self.pv.inner(self.pv), 40)
# have to manually poke the data here
# so the test doesn't rely on any other methods
self.pv.base.data = -2*np.ones(10)
self.assertEqual(self.pv.inner(self.pv), 40)
def test_norm2(self):
'''DesignVector L2 norm'''
self.pv.equals(3)
self.assertEqual(self.pv.norm2, np.linalg.norm(3*np.ones(10)))
def test_equals(self):
'''DesignVector scalar-value assignment'''
self.pv.equals(3)
self.assertEqual(self.pv.inner(self.pv), 90)
def test_plus(self):
'''DesignVector elementwise summation'''
self.pv.equals(1)
self.pv.plus(self.pv)
self.assertEqual(self.pv.inner(self.pv), 40)
def test_minus(self):
'''DesignVector elementwise subtraction'''
self.pv.equals(1)
self.pv.minus(self.pv) # special case
self.assertEqual(self.pv.inner(self.pv), 0)
self.pv.equals(1)
pv2 = self.km.primal_factory.generate()
pv2.equals(5)
pv2.minus(self.pv)
self.assertEqual(pv2.inner(self.pv), 40)
def test_times(self):
'''DesignVector scalar and elementwise multiplication'''
self.pv.equals(2)
self.pv.times(5)
self.assertEqual(self.pv.inner(self.pv), 1000)
self.pv.equals(2.0)
self.pv.times(5.0)
self.assertEqual(self.pv.inner(self.pv), 1000.0)
self.pv.equals(2.0)
self.pv.times(self.pv)
self.assertEqual(self.pv.inner(self.pv), 160.0)
def test_divide_by(self):
'''DesignVector scalar division'''
self.pv.equals(10)
self.pv.divide_by(5)
self.assertEqual(self.pv.inner(self.pv), 40)
def test_exp(self):
'''DesignVector elementwise exponential'''
self.pv.equals(0.)
self.pv.exp(self.pv)
self.assertEqual(self.pv.inner(self.pv), 10.0)
def test_log(self):
'''DesignVector elementwise natural logarithm'''
self.pv.equals(1.)
self.pv.log(self.pv)
self.assertEqual(self.pv.inner(self.pv), 0.0)
def test_equals_ax_p_by(self):
'''DesignVector linear combination (ax + by)'''
self.pv.equals(1)
pv2 = self.km.primal_factory.generate()
pv2.equals(1)
pv3 = self.km.primal_factory.generate()
pv3.equals(2)
pv3.equals_ax_p_by(2, self.pv, 3, pv3)
self.assertEqual(pv3.inner(self.pv), 80.0)
pv2.equals_ax_p_by(2, self.pv, 3, pv2)
self.assertEqual(pv2.inner(self.pv), 50.0)
def test_init_design(self):
'''DesignVector initial design assignment'''
self.pv.equals_init_design()
self.assertEqual(self.pv.inner(self.pv), 1000.0)
def test_equals_objective_partial(self):
'''DesignVector objective partial derivative'''
at_design = self.km.primal_factory.generate()
at_design.equals(1)
at_state = self.sv
at_state.equals(2)
self.pv.equals_objective_partial(at_design, at_state)
self.assertEqual(self.pv.inner(self.pv), 10.0)
def test_equals_total_gradient(self):
'''DesignVector objective total gradient'''
at_design = self.km.primal_factory.generate()
at_design.equals(1)
at_state = self.km.state_factory.generate()
at_state.equals(2)
primal_work = self.km.primal_factory.generate()
at_adjoint = self.km.state_factory.generate()
at_adjoint.equals(3)
self.pv.equals_total_gradient(at_design, at_state, at_adjoint)
self.assertEqual(self.pv.inner(self.pv), 160.0)
def test_equals_lagrangian_total_gradient(self):
'''DesignVector lagrangian total gradient'''
at_design = self.km.primal_factory.generate()
at_design.equals(1)
at_state = self.km.state_factory.generate()
at_state.equals(2)
primal_work = self.km.primal_factory.generate()
at_adjoint = self.km.state_factory.generate()
at_adjoint.equals(3)
at_dual = self.km.eq_factory.generate()
at_dual.equals(4)
self.pv.equals_lagrangian_total_gradient(at_design, at_state, at_dual,
at_adjoint)
self.assertEqual(self.pv.inner(self.pv), 19360.0)
def test_enforce_bounds(self):
'''DesignVector bound enforcement'''
self.pv.equals(-1.)
self.pv.enforce_bounds()
zero = self.pv.norm2
self.assertEqual(zero, 0.0)
class TestCaseDesignVectorIDF(unittest.TestCase):
def setUp(self):
solver = UserSolverIDF(5, 10, 10)
self.km = km = KonaMemory(solver)
km.primal_factory.request_num_vectors(1)
km.eq_factory.request_num_vectors(1)
km.allocate_memory()
self.pv = km.primal_factory.generate()
self.dv = km.eq_factory.generate()
def test_restrict_to_design(self):
'''DesignVector IDF restriction (1/2)'''
self.pv.equals(5)
self.pv.restrict_to_design()
inner_prod = self.pv.inner(self.pv)
expected_prod = 5.*5.*5
self.assertEqual(inner_prod, expected_prod)
def test_restrict_to_target(self):
'''DesignVector IDF restriction (2/2)'''
self.pv.equals(5)
self.pv.restrict_to_target()
inner_prod = self.pv.inner(self.pv)
expected_prod = 5.*5.*10
self.assertEqual(inner_prod, expected_prod)
def test_convert_to_dual(self):
'''DesignVector IDF conversion'''
self.pv.equals(2)
self.dv.equals(1)
self.pv.convert_to_dual(self.dv)
inner_prod = self.dv.inner(self.dv)
expected_prod = 40.
self.assertEqual(inner_prod, expected_prod)
if __name__ == "__main__":
unittest.main()
|
OptimalDesignLab/Kona
|
src/kona/test/test_design_vector.py
|
Python
|
lgpl-3.0
| 7,369
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 thomasv@gitorious
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import hashlib
import base64
import os
import re
import hmac
import version
from util import print_error, InvalidPassword
import ecdsa
import pyaes
# Bitcoin network constants
TESTNET = False
NOLNET = False
ADDRTYPE_P2PKH = 23
ADDRTYPE_P2SH = 5
ADDRTYPE_P2WPKH = 9999999
XPRV_HEADER = 0x0488ade4
XPUB_HEADER = 0x0488b21e
HEADERS_URL = "https://electrum-arg.org/blockchain_headers"
GENESIS = "88c667bc63167685e4e4da058fffdfe8e007e5abffd6855de52ad59df7bb0bb2"
def set_testnet():
global ADDRTYPE_P2PKH, ADDRTYPE_P2SH, ADDRTYPE_P2WPKH
global XPRV_HEADER, XPUB_HEADER
global TESTNET, HEADERS_URL
global GENESIS
TESTNET = True
ADDRTYPE_P2PKH = 111
ADDRTYPE_P2SH = 196
ADDRTYPE_P2WPKH = 99999999
XPRV_HEADER = 0x04358394
XPUB_HEADER = 0x043587cf
HEADERS_URL = "https://electrum-arg.org/testnet_headers"
GENESIS = "000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"
# def set_nolnet():
# global ADDRTYPE_P2PKH, ADDRTYPE_P2SH, ADDRTYPE_P2WPKH
# global XPRV_HEADER, XPUB_HEADER
# global NOLNET, HEADERS_URL
# global GENESIS
# TESTNET = True
# ADDRTYPE_P2PKH = 0
# ADDRTYPE_P2SH = 5
# ADDRTYPE_P2WPKH = 6
# XPRV_HEADER = 0x0488ade4
# XPUB_HEADER = 0x0488b21e
# HEADERS_URL = "https://headers.electrum.org/nolnet_headers"
# GENESIS = "663c88be18d07c45f87f910b93a1a71ed9ef1946cad50eb6a6f3af4c424625c6"
################################## transactions
MIN_RELAY_TX_FEE = 50000
FEE_STEP = 10000
MAX_FEE_RATE = 500000
FEE_TARGETS = [25, 10, 5, 2]
COINBASE_MATURITY = 100
COIN = 100000000
# supported types of transction outputs
TYPE_ADDRESS = 0
TYPE_PUBKEY = 1
TYPE_SCRIPT = 2
# AES encryption
try:
from Cryptodome.Cipher import AES
except:
AES = None
def aes_encrypt_with_iv(key, iv, data):
if AES:
padlen = 16 - (len(data) % 16)
if padlen == 0:
padlen = 16
data += chr(padlen) * padlen
e = AES.new(key, AES.MODE_CBC, iv).encrypt(data)
return e
else:
aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
aes = pyaes.Encrypter(aes_cbc)
e = aes.feed(data) + aes.feed() # empty aes.feed() appends pkcs padding
return e
def aes_decrypt_with_iv(key, iv, data):
if AES:
cipher = AES.new(key, AES.MODE_CBC, iv)
data = cipher.decrypt(data)
padlen = ord(data[-1])
for i in data[-padlen:]:
if ord(i) != padlen:
raise InvalidPassword()
return data[0:-padlen]
else:
aes_cbc = pyaes.AESModeOfOperationCBC(key, iv=iv)
aes = pyaes.Decrypter(aes_cbc)
s = aes.feed(data) + aes.feed() # empty aes.feed() strips pkcs padding
return s
def EncodeAES(secret, s):
iv = bytes(os.urandom(16))
ct = aes_encrypt_with_iv(secret, iv, s)
e = iv + ct
return base64.b64encode(e)
def DecodeAES(secret, e):
e = bytes(base64.b64decode(e))
iv, e = e[:16], e[16:]
s = aes_decrypt_with_iv(secret, iv, e)
return s
def pw_encode(s, password):
if password:
secret = Hash(password)
return EncodeAES(secret, s.encode("utf8"))
else:
return s
def pw_decode(s, password):
if password is not None:
secret = Hash(password)
try:
d = DecodeAES(secret, s).decode("utf8")
except Exception:
raise InvalidPassword()
return d
else:
return s
def rev_hex(s):
return s.decode('hex')[::-1].encode('hex')
def int_to_hex(i, length=1):
s = hex(i)[2:].rstrip('L')
s = "0"*(2*length - len(s)) + s
return rev_hex(s)
def var_int(i):
# https://en.bitcoin.it/wiki/Protocol_specification#Variable_length_integer
if i<0xfd:
return int_to_hex(i)
elif i<=0xffff:
return "fd"+int_to_hex(i,2)
elif i<=0xffffffff:
return "fe"+int_to_hex(i,4)
else:
return "ff"+int_to_hex(i,8)
def op_push(i):
if i<0x4c:
return int_to_hex(i)
elif i<0xff:
return '4c' + int_to_hex(i)
elif i<0xffff:
return '4d' + int_to_hex(i,2)
else:
return '4e' + int_to_hex(i,4)
def sha256(x):
return hashlib.sha256(x).digest()
def Hash(x):
if type(x) is unicode: x=x.encode('utf-8')
return sha256(sha256(x))
hash_encode = lambda x: x[::-1].encode('hex')
hash_decode = lambda x: x.decode('hex')[::-1]
hmac_sha_512 = lambda x,y: hmac.new(x, y, hashlib.sha512).digest()
def is_new_seed(x, prefix=version.SEED_PREFIX):
import mnemonic
x = mnemonic.normalize_text(x)
s = hmac_sha_512("Seed version", x.encode('utf8')).encode('hex')
return s.startswith(prefix)
def is_old_seed(seed):
import old_mnemonic
words = seed.strip().split()
try:
old_mnemonic.mn_decode(words)
uses_electrum_words = True
except Exception:
uses_electrum_words = False
try:
seed.decode('hex')
is_hex = (len(seed) == 32 or len(seed) == 64)
except Exception:
is_hex = False
return is_hex or (uses_electrum_words and (len(words) == 12 or len(words) == 24))
def seed_type(x):
if is_old_seed(x):
return 'old'
elif is_new_seed(x):
return 'standard'
# elif TESTNET and is_new_seed(x, version.SEED_PREFIX_SW):
# return 'segwit'
elif is_new_seed(x, version.SEED_PREFIX_2FA):
return '2fa'
return ''
is_seed = lambda x: bool(seed_type(x))
# pywallet openssl private key implementation
def i2o_ECPublicKey(pubkey, compressed=False):
# public keys are 65 bytes long (520 bits)
# 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
# 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
# compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
if compressed:
if pubkey.point.y() & 1:
key = '03' + '%064x' % pubkey.point.x()
else:
key = '02' + '%064x' % pubkey.point.x()
else:
key = '04' + \
'%064x' % pubkey.point.x() + \
'%064x' % pubkey.point.y()
return key.decode('hex')
# end pywallet openssl private key implementation
############ functions from pywallet #####################
def hash_160(public_key):
if 'ANDROID_DATA' in os.environ:
from Crypto.Hash import RIPEMD
md = RIPEMD.new()
else:
md = hashlib.new('ripemd')
md.update(sha256(public_key))
return md.digest()
def hash_160_to_bc_address(h160, addrtype, witness_program_version=1):
s = chr(addrtype)
if addrtype == ADDRTYPE_P2WPKH:
s += chr(witness_program_version) + chr(0)
s += h160
return base_encode(s+Hash(s)[0:4], base=58)
def bc_address_to_hash_160(addr):
bytes = base_decode(addr, 25, base=58)
return ord(bytes[0]), bytes[1:21]
def hash160_to_p2pkh(h160):
return hash_160_to_bc_address(h160, ADDRTYPE_P2PKH)
def hash160_to_p2sh(h160):
return hash_160_to_bc_address(h160, ADDRTYPE_P2SH)
def public_key_to_p2pkh(public_key):
return hash160_to_p2pkh(hash_160(public_key))
def public_key_to_p2wpkh(public_key):
return hash160_to_bc_address(hash_160(public_key), ADDRTYPE_P2WPKH)
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
assert len(__b58chars) == 58
__b43chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ$*+-./:'
assert len(__b43chars) == 43
def base_encode(v, base):
""" encode v, which is a string of bytes, to base58."""
if base == 58:
chars = __b58chars
elif base == 43:
chars = __b43chars
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += (256**i) * ord(c)
result = ''
while long_value >= base:
div, mod = divmod(long_value, base)
result = chars[mod] + result
long_value = div
result = chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == '\0': nPad += 1
else: break
return (chars[0]*nPad) + result
def base_decode(v, length, base):
""" decode v into a string of len bytes."""
if base == 58:
chars = __b58chars
elif base == 43:
chars = __b43chars
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += chars.find(c) * (base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == chars[0]: nPad += 1
else: break
result = chr(0)*nPad + result
if length is not None and len(result) != length:
return None
return result
def EncodeBase58Check(vchIn):
hash = Hash(vchIn)
return base_encode(vchIn + hash[0:4], base=58)
def DecodeBase58Check(psz):
vchRet = base_decode(psz, None, base=58)
key = vchRet[0:-4]
csum = vchRet[-4:]
hash = Hash(key)
cs32 = hash[0:4]
if cs32 != csum:
return None
else:
return key
def PrivKeyToSecret(privkey):
return privkey[9:9+32]
def SecretToASecret(secret, compressed=False):
addrtype = ADDRTYPE_P2PKH
vchIn = chr((addrtype+128)&255) + secret
if compressed: vchIn += '\01'
return EncodeBase58Check(vchIn)
def ASecretToSecret(key):
addrtype = ADDRTYPE_P2PKH
vch = DecodeBase58Check(key)
if vch and vch[0] == chr((addrtype+128)&255):
return vch[1:]
elif is_minikey(key):
return minikey_to_private_key(key)
else:
return False
def regenerate_key(sec):
b = ASecretToSecret(sec)
if not b:
return False
b = b[0:32]
return EC_KEY(b)
def GetPubKey(pubkey, compressed=False):
return i2o_ECPublicKey(pubkey, compressed)
def GetSecret(pkey):
return ('%064x' % pkey.secret).decode('hex')
def is_compressed(sec):
b = ASecretToSecret(sec)
return len(b) == 33
def public_key_from_private_key(sec):
# rebuild public key from private key, compressed or uncompressed
pkey = regenerate_key(sec)
assert pkey
compressed = is_compressed(sec)
public_key = GetPubKey(pkey.pubkey, compressed)
return public_key.encode('hex')
def address_from_private_key(sec):
public_key = public_key_from_private_key(sec)
address = public_key_to_p2pkh(public_key.decode('hex'))
return address
def is_valid(addr):
return is_address(addr)
def is_address(addr):
try:
addrtype, h = bc_address_to_hash_160(addr)
except Exception:
return False
if addrtype not in [ADDRTYPE_P2PKH, ADDRTYPE_P2SH]:
return False
return addr == hash_160_to_bc_address(h, addrtype)
def is_p2pkh(addr):
if is_address(addr):
addrtype, h = bc_address_to_hash_160(addr)
return addrtype == ADDRTYPE_P2PKH
def is_p2sh(addr):
if is_address(addr):
addrtype, h = bc_address_to_hash_160(addr)
return addrtype == ADDRTYPE_P2SH
def is_private_key(key):
try:
k = ASecretToSecret(key)
return k is not False
except:
return False
########### end pywallet functions #######################
def is_minikey(text):
# Minikeys are typically 22 or 30 characters, but this routine
# permits any length of 20 or more provided the minikey is valid.
# A valid minikey must begin with an 'S', be in base58, and when
# suffixed with '?' have its SHA256 hash begin with a zero byte.
# They are widely used in Casascius physical bitoins.
return (len(text) >= 20 and text[0] == 'S'
and all(c in __b58chars for c in text)
and ord(sha256(text + '?')[0]) == 0)
def minikey_to_private_key(text):
return sha256(text)
from ecdsa.ecdsa import curve_secp256k1, generator_secp256k1
from ecdsa.curves import SECP256k1
from ecdsa.ellipticcurve import Point
from ecdsa.util import string_to_number, number_to_string
def msg_magic(message):
varint = var_int(len(message))
encoded_varint = "".join([chr(int(varint[i:i+2], 16)) for i in xrange(0, len(varint), 2)])
return "\x19Argentum Signed Message:\n" + encoded_varint + message
def verify_message(address, sig, message):
try:
public_key, compressed = pubkey_from_signature(sig, message)
# check public key using the address
pubkey = point_to_ser(public_key.pubkey.point, compressed)
addr = public_key_to_p2pkh(pubkey)
if address != addr:
raise Exception("Bad signature")
# check message
h = Hash(msg_magic(message))
public_key.verify_digest(sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
return True
except Exception as e:
print_error("Verification error: {0}".format(e))
return False
def encrypt_message(message, pubkey):
return EC_KEY.encrypt_message(message, pubkey.decode('hex'))
def chunks(l, n):
return [l[i:i+n] for i in xrange(0, len(l), n)]
def ECC_YfromX(x,curved=curve_secp256k1, odd=True):
_p = curved.p()
_a = curved.a()
_b = curved.b()
for offset in range(128):
Mx = x + offset
My2 = pow(Mx, 3, _p) + _a * pow(Mx, 2, _p) + _b % _p
My = pow(My2, (_p+1)/4, _p )
if curved.contains_point(Mx,My):
if odd == bool(My&1):
return [My,offset]
return [_p-My,offset]
raise Exception('ECC_YfromX: No Y found')
def negative_point(P):
return Point( P.curve(), P.x(), -P.y(), P.order() )
def point_to_ser(P, comp=True ):
if comp:
return ( ('%02x'%(2+(P.y()&1)))+('%064x'%P.x()) ).decode('hex')
return ( '04'+('%064x'%P.x())+('%064x'%P.y()) ).decode('hex')
def ser_to_point(Aser):
curve = curve_secp256k1
generator = generator_secp256k1
_r = generator.order()
assert Aser[0] in ['\x02','\x03','\x04']
if Aser[0] == '\x04':
return Point( curve, string_to_number(Aser[1:33]), string_to_number(Aser[33:]), _r )
Mx = string_to_number(Aser[1:])
return Point( curve, Mx, ECC_YfromX(Mx, curve, Aser[0]=='\x03')[0], _r )
class MyVerifyingKey(ecdsa.VerifyingKey):
@classmethod
def from_signature(klass, sig, recid, h, curve):
""" See http://www.secg.org/download/aid-780/sec1-v2.pdf, chapter 4.1.6 """
from ecdsa import util, numbertheory
import msqr
curveFp = curve.curve
G = curve.generator
order = G.order()
# extract r,s from signature
r, s = util.sigdecode_string(sig, order)
# 1.1
x = r + (recid/2) * order
# 1.3
alpha = ( x * x * x + curveFp.a() * x + curveFp.b() ) % curveFp.p()
beta = msqr.modular_sqrt(alpha, curveFp.p())
y = beta if (beta - recid) % 2 == 0 else curveFp.p() - beta
# 1.4 the constructor checks that nR is at infinity
R = Point(curveFp, x, y, order)
# 1.5 compute e from message:
e = string_to_number(h)
minus_e = -e % order
# 1.6 compute Q = r^-1 (sR - eG)
inv_r = numbertheory.inverse_mod(r,order)
Q = inv_r * ( s * R + minus_e * G )
return klass.from_public_point( Q, curve )
def pubkey_from_signature(sig, message):
if len(sig) != 65:
raise Exception("Wrong encoding")
nV = ord(sig[0])
if nV < 27 or nV >= 35:
raise Exception("Bad encoding")
if nV >= 31:
compressed = True
nV -= 4
else:
compressed = False
recid = nV - 27
h = Hash(msg_magic(message))
return MyVerifyingKey.from_signature(sig[1:], recid, h, curve = SECP256k1), compressed
class MySigningKey(ecdsa.SigningKey):
"""Enforce low S values in signatures"""
def sign_number(self, number, entropy=None, k=None):
curve = SECP256k1
G = curve.generator
order = G.order()
r, s = ecdsa.SigningKey.sign_number(self, number, entropy, k)
if s > order/2:
s = order - s
return r, s
class EC_KEY(object):
def __init__( self, k ):
secret = string_to_number(k)
self.pubkey = ecdsa.ecdsa.Public_key( generator_secp256k1, generator_secp256k1 * secret )
self.privkey = ecdsa.ecdsa.Private_key( self.pubkey, secret )
self.secret = secret
def get_public_key(self, compressed=True):
return point_to_ser(self.pubkey.point, compressed).encode('hex')
def sign(self, msg_hash):
private_key = MySigningKey.from_secret_exponent(self.secret, curve = SECP256k1)
public_key = private_key.get_verifying_key()
signature = private_key.sign_digest_deterministic(msg_hash, hashfunc=hashlib.sha256, sigencode = ecdsa.util.sigencode_string)
assert public_key.verify_digest(signature, msg_hash, sigdecode = ecdsa.util.sigdecode_string)
return signature
def sign_message(self, message, is_compressed):
signature = self.sign(Hash(msg_magic(message)))
for i in range(4):
sig = chr(27 + i + (4 if is_compressed else 0)) + signature
try:
self.verify_message(sig, message)
return sig
except Exception:
continue
else:
raise Exception("error: cannot sign message")
def verify_message(self, sig, message):
public_key, compressed = pubkey_from_signature(sig, message)
# check public key
if point_to_ser(public_key.pubkey.point, compressed) != point_to_ser(self.pubkey.point, compressed):
raise Exception("Bad signature")
# check message
h = Hash(msg_magic(message))
public_key.verify_digest(sig[1:], h, sigdecode = ecdsa.util.sigdecode_string)
# ECIES encryption/decryption methods; AES-128-CBC with PKCS7 is used as the cipher; hmac-sha256 is used as the mac
@classmethod
def encrypt_message(self, message, pubkey):
pk = ser_to_point(pubkey)
if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, pk.x(), pk.y()):
raise Exception('invalid pubkey')
ephemeral_exponent = number_to_string(ecdsa.util.randrange(pow(2,256)), generator_secp256k1.order())
ephemeral = EC_KEY(ephemeral_exponent)
ecdh_key = point_to_ser(pk * ephemeral.privkey.secret_multiplier)
key = hashlib.sha512(ecdh_key).digest()
iv, key_e, key_m = key[0:16], key[16:32], key[32:]
ciphertext = aes_encrypt_with_iv(key_e, iv, message)
ephemeral_pubkey = ephemeral.get_public_key(compressed=True).decode('hex')
encrypted = 'BIE1' + ephemeral_pubkey + ciphertext
mac = hmac.new(key_m, encrypted, hashlib.sha256).digest()
return base64.b64encode(encrypted + mac)
def decrypt_message(self, encrypted):
encrypted = base64.b64decode(encrypted)
if len(encrypted) < 85:
raise Exception('invalid ciphertext: length')
magic = encrypted[:4]
ephemeral_pubkey = encrypted[4:37]
ciphertext = encrypted[37:-32]
mac = encrypted[-32:]
if magic != 'BIE1':
raise Exception('invalid ciphertext: invalid magic bytes')
try:
ephemeral_pubkey = ser_to_point(ephemeral_pubkey)
except AssertionError, e:
raise Exception('invalid ciphertext: invalid ephemeral pubkey')
if not ecdsa.ecdsa.point_is_valid(generator_secp256k1, ephemeral_pubkey.x(), ephemeral_pubkey.y()):
raise Exception('invalid ciphertext: invalid ephemeral pubkey')
ecdh_key = point_to_ser(ephemeral_pubkey * self.privkey.secret_multiplier)
key = hashlib.sha512(ecdh_key).digest()
iv, key_e, key_m = key[0:16], key[16:32], key[32:]
if mac != hmac.new(key_m, encrypted[:-32], hashlib.sha256).digest():
raise InvalidPassword()
return aes_decrypt_with_iv(key_e, iv, ciphertext)
###################################### BIP32 ##############################
random_seed = lambda n: "%032x"%ecdsa.util.randrange( pow(2,n) )
BIP32_PRIME = 0x80000000
def get_pubkeys_from_secret(secret):
# public key
private_key = ecdsa.SigningKey.from_string( secret, curve = SECP256k1 )
public_key = private_key.get_verifying_key()
K = public_key.to_string()
K_compressed = GetPubKey(public_key.pubkey,True)
return K, K_compressed
# Child private key derivation function (from master private key)
# k = master private key (32 bytes)
# c = master chain code (extra entropy for key derivation) (32 bytes)
# n = the index of the key we want to derive. (only 32 bits will be used)
# If n is negative (i.e. the 32nd bit is set), the resulting private key's
# corresponding public key can NOT be determined without the master private key.
# However, if n is positive, the resulting private key's corresponding
# public key can be determined without the master private key.
def CKD_priv(k, c, n):
is_prime = n & BIP32_PRIME
return _CKD_priv(k, c, rev_hex(int_to_hex(n,4)).decode('hex'), is_prime)
def _CKD_priv(k, c, s, is_prime):
order = generator_secp256k1.order()
keypair = EC_KEY(k)
cK = GetPubKey(keypair.pubkey,True)
data = chr(0) + k + s if is_prime else cK + s
I = hmac.new(c, data, hashlib.sha512).digest()
k_n = number_to_string( (string_to_number(I[0:32]) + string_to_number(k)) % order , order )
c_n = I[32:]
return k_n, c_n
# Child public key derivation function (from public key only)
# K = master public key
# c = master chain code
# n = index of key we want to derive
# This function allows us to find the nth public key, as long as n is
# non-negative. If n is negative, we need the master private key to find it.
def CKD_pub(cK, c, n):
if n & BIP32_PRIME: raise
return _CKD_pub(cK, c, rev_hex(int_to_hex(n,4)).decode('hex'))
# helper function, callable with arbitrary string
def _CKD_pub(cK, c, s):
order = generator_secp256k1.order()
I = hmac.new(c, cK + s, hashlib.sha512).digest()
curve = SECP256k1
pubkey_point = string_to_number(I[0:32])*curve.generator + ser_to_point(cK)
public_key = ecdsa.VerifyingKey.from_public_point( pubkey_point, curve = SECP256k1 )
c_n = I[32:]
cK_n = GetPubKey(public_key.pubkey,True)
return cK_n, c_n
def xprv_header(xtype):
return ("%08x"%(XPRV_HEADER + xtype)).decode('hex')
def xpub_header(xtype):
return ("%08x"%(XPUB_HEADER + xtype)).decode('hex')
def serialize_xprv(xtype, c, k, depth=0, fingerprint=chr(0)*4, child_number=chr(0)*4):
xprv = xprv_header(xtype) + chr(depth) + fingerprint + child_number + c + chr(0) + k
return EncodeBase58Check(xprv)
def serialize_xpub(xtype, c, cK, depth=0, fingerprint=chr(0)*4, child_number=chr(0)*4):
xpub = xpub_header(xtype) + chr(depth) + fingerprint + child_number + c + cK
return EncodeBase58Check(xpub)
def deserialize_xkey(xkey, prv):
xkey = DecodeBase58Check(xkey)
if len(xkey) != 78:
raise BaseException('Invalid length')
depth = ord(xkey[4])
fingerprint = xkey[5:9]
child_number = xkey[9:13]
c = xkey[13:13+32]
header = XPRV_HEADER if prv else XPUB_HEADER
xtype = int('0x' + xkey[0:4].encode('hex'), 16) - header
if xtype not in ([0, 1] if TESTNET else [0]):
raise BaseException('Invalid header')
n = 33 if prv else 32
K_or_k = xkey[13+n:]
return xtype, depth, fingerprint, child_number, c, K_or_k
def deserialize_xpub(xkey):
return deserialize_xkey(xkey, False)
def deserialize_xprv(xkey):
return deserialize_xkey(xkey, True)
def is_xpub(text):
try:
deserialize_xpub(text)
return True
except:
return False
def is_xprv(text):
try:
deserialize_xprv(text)
return True
except:
return False
def xpub_from_xprv(xprv):
xtype, depth, fingerprint, child_number, c, k = deserialize_xprv(xprv)
K, cK = get_pubkeys_from_secret(k)
return serialize_xpub(xtype, c, cK, depth, fingerprint, child_number)
def bip32_root(seed, xtype):
I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest()
master_k = I[0:32]
master_c = I[32:]
K, cK = get_pubkeys_from_secret(master_k)
xprv = serialize_xprv(xtype, master_c, master_k)
xpub = serialize_xpub(xtype, master_c, cK)
return xprv, xpub
def xpub_from_pubkey(xtype, cK):
assert cK[0] in ['\x02','\x03']
return serialize_xpub(xtype, chr(0)*32, cK)
def bip32_private_derivation(xprv, branch, sequence):
assert sequence.startswith(branch)
if branch == sequence:
return xprv, xpub_from_xprv(xprv)
xtype, depth, fingerprint, child_number, c, k = deserialize_xprv(xprv)
sequence = sequence[len(branch):]
for n in sequence.split('/'):
if n == '': continue
i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n)
parent_k = k
k, c = CKD_priv(k, c, i)
depth += 1
_, parent_cK = get_pubkeys_from_secret(parent_k)
fingerprint = hash_160(parent_cK)[0:4]
child_number = ("%08X"%i).decode('hex')
K, cK = get_pubkeys_from_secret(k)
xpub = serialize_xpub(xtype, c, cK, depth, fingerprint, child_number)
xprv = serialize_xprv(xtype, c, k, depth, fingerprint, child_number)
return xprv, xpub
def bip32_public_derivation(xpub, branch, sequence):
xtype, depth, fingerprint, child_number, c, cK = deserialize_xpub(xpub)
assert sequence.startswith(branch)
sequence = sequence[len(branch):]
for n in sequence.split('/'):
if n == '': continue
i = int(n)
parent_cK = cK
cK, c = CKD_pub(cK, c, i)
depth += 1
fingerprint = hash_160(parent_cK)[0:4]
child_number = ("%08X"%i).decode('hex')
return serialize_xpub(xtype, c, cK, depth, fingerprint, child_number)
def bip32_private_key(sequence, k, chain):
for i in sequence:
k, chain = CKD_priv(k, chain, i)
return SecretToASecret(k, True)
def xkeys_from_seed(seed, passphrase, derivation):
from mnemonic import Mnemonic
xprv, xpub = bip32_root(Mnemonic.mnemonic_to_seed(seed, passphrase), 0)
xprv, xpub = bip32_private_derivation(xprv, "m/", derivation)
return xprv, xpub
|
argentumproject/electrum-arg
|
lib/bitcoin.py
|
Python
|
mit
| 27,317
|
# coding=utf-8
"""
Profiler utility for python
Erik de Jonge
erik@a8.nl
license: gpl2
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import cProfile
from pstats import Stats
from cProfile import Profile
def start_profile():
"""
start_profile
@rtype: Profile
"""
pr = Profile()
pr.enable()
return pr
def console(x):
"""
@type x: str, unicode
@return: None
"""
print("\033[33m$", x, "\033[0m")
def end_profile(pr, items=20, printstats=False, returnvalue=False):
"""
@type pr: str, unicode
@type items: int
@type printstats: bool
@type returnvalue: bool
@return: None
"""
p = Stats(pr)
if returnvalue is True:
return p.get_print_list([items])
p.strip_dirs()
console("total time")
p.sort_stats('time')
if items is None:
p.print_stats()
else:
p.print_stats(items)
if printstats:
console("cumulative time")
p.sort_stats('cumtime')
if items is None:
p.print_stats()
else:
p.print_stats(items)
p.sort_stats('calls')
if items is None:
p.print_stats()
else:
p.print_stats(items)
def runsnake_profile_method(method, cglobals, clocals):
"""
@type method: str, unicode
@type cglobals: dict
@type clocals: dict
@return: None
"""
cProfile.runctx(method + "()", globals=cglobals, locals=clocals, filename=method + ".profile")
os.system("python /usr/local/lib/python2.7/site-packages/runsnakerun/runsnake.py " + method + ".profile")
os.system("rm " + method + ".profile")
def graph_profile_program(sourcefile):
"""
@type sourcefile: str, unicode
@return: None
"""
if 0 != os.system("python -m cProfile -o output.pstats ./" + sourcefile):
print("\033[31mprofile error:\033[0m")
print("\033[33m", "pip install graphviz", "\033[0m")
print("\033[33m", "pip install gprof2dot", "\033[0m")
elif 0 != os.system("gprof2dot -f pstats output.pstats | dot -Tpng -o " + sourcefile.replace(".py", ".png")):
print("\033[31mgprof2dot error:\033[0m")
print("\033[33m", "pip install graphviz", "\033[0m")
print("\033[33m", "pip install gprof2dot", "\033[0m")
print("\033[33m", "gprof2dot is in path? (/usr/local/bin/gprof2dot)", "\033[0m")
else:
if not os.path.exists("./" + sourcefile.replace(".py", ".png")):
print("\033[31mcannot find", sourcefile.replace(".py", ".png"), "\033[0m")
else:
os.system("open " + sourcefile.replace(".py", ".png"))
if os.remove("output.pstats"):
os.remove("output.pstats")
|
erikdejonge/pyprofiler
|
pyprofiler/__init__.py
|
Python
|
gpl-2.0
| 2,901
|
class Background:
"""pre-game background image
Attributes:
filename (str): image filename
included (int): is image included ?
Todo:
load() -load image from a file
save() -save image to a file
"""
def __init__(self, filename="", included=0, size=0,
width=0, height=0, include=0, planes=0,
bitCount=0, compression=0, sizeImage=0,
xPels=0, yPels=0, colors=0, iColors=0,
colorTable=[], rawData=[]):
self.filename = filename
self.included = included
self.width = width
self.height = height
self.include = include
self.size = size
self.planes, self.bitCount = planes, bitCount
self.compression, self.sizeImage = compression, sizeImage
self.xPels, self.yPels, self.colors = xPels, yPels, colors
self.iColors, self.colorTable, self.rawData = iColors, colorTable, rawData
def __len__(self):
"""
Todo:
Finish, return size of image in bytes
"""
pass
def __repr__(self):
name = "Background: \n"
fname = "\tfilename: {}\n".format(self.filename)
size = "\tsize: {}\n".format(self.size)
prop = "\twidth: {}\n\theight: {}\n".format(self.width, self.height)
return name + fname + size + prop
def size(self):
"""size of Background
Return:
(tuple): width and height
"""
pass
|
dderevjanik/agescx
|
agescx/controller/background.py
|
Python
|
mit
| 1,505
|
import tarfile
import tempfile
import os
import os.path
import re
from django.core.files import File
from storages.backends.s3boto3 import S3Boto3Storage
from xml.etree import ElementTree
from ..papers.models import SourceFile, SourceFileBulkTarball
def convert_source_file_to_arxiv_id(filename):
"""
Converts a source file name into an ArXiV ID.
"""
# Remove folder and extension
arxiv_id, _ = os.path.splitext(os.path.basename(filename))
# Add a slash to old arxiv ID format
match = re.match(r"([a-z-]+)([0-9]+)", arxiv_id)
if match:
return f"{match.group(1)}/{match.group(2)}"
return arxiv_id
def update_bulk_sources():
"""
Check for new bulk sources in the arXiv bulk data S3 bucket:
https://arxiv.org/help/bulk_data_s3
If there are new sources, download them and put them into our S3 bucket.
"""
print("Downloading manifest...")
manifest = get_manifest()
for f in manifest:
# We've already processed this file, skip.
# TODO: Re-process files which have been updated. (i.e. where md5 has
# changed)
try:
tarball = SourceFileBulkTarball.objects.get(filename=f["filename"])
except SourceFileBulkTarball.DoesNotExist:
# This is a new file
pass
else:
if tarball.has_correct_number_of_files():
print(f"Skipping {f['filename']}")
continue
else:
print(
f"Reprocessing {f['filename']} because it has incorrect number of files"
)
with tempfile.NamedTemporaryFile(suffix="tar") as tarfh:
# Download new sources
print(f"Downloading {f['filename']}...")
download_tarball(f["filename"], tarfh.name)
tarfh.flush()
# Mark database as downloaded
bulk_tarball, _ = SourceFileBulkTarball.objects.get_or_create(
filename=f["filename"], defaults=f
)
print(f"Extracting {f['filename']}...")
for name, f in extract_tarball(tarfh.name):
# Dedupe!
# TODO: At some point, when we need to update papers, this should
# instead update the file.
if SourceFile.objects.filename_exists(name):
print(f"{name} already exists")
continue
print(f"Saving {name}...")
# Pass file handle directory to Django, which will stream the file
# to S3 instead of loading into memory (in theory)
wrapped_f = File(f)
wrapped_f.name = name
arxiv_id = convert_source_file_to_arxiv_id(name)
source_file = SourceFile.objects.create(
arxiv_id=arxiv_id, file=wrapped_f, bulk_tarball=bulk_tarball
)
def get_manifest():
"""
Download and parse manifest from arxiv S3 bucket.
"""
connection = S3Boto3Storage().connection
obj = connection.Object("arxiv", "src/arXiv_src_manifest.xml")
s = obj.get(RequestPayer="requester")["Body"].read()
return parse_manifest(s)
def parse_manifest(s):
"""
Returns a list of files from a bulk source manifest XML string.
"""
root = ElementTree.fromstring(s)
result = []
for f in root.findall("file"):
# Turn it into a sensible dictionary
d = {child.tag: child.text for child in f}
# All the fields are text, apart from these which should be int
for k in ("num_items", "seq_num", "size"):
d[k] = int(d[k])
result.append(d)
return result
def download_tarball(key, local_filename):
connection = S3Boto3Storage().connection
bucket = connection.Bucket("arxiv")
bucket.download_file(key, local_filename, {"RequestPayer": "requester"})
def extract_tarball(path):
"""
Returns an iterator of (filename, file object) tuples given a path to
a tarball.
"""
with tarfile.open(path, "r:") as tar:
for member in tar.getmembers():
if member.isreg():
yield os.path.basename(member.name), tar.extractfile(member.name)
|
arxiv-vanity/arxiv-vanity
|
arxiv_vanity/scraper/bulk_sources.py
|
Python
|
apache-2.0
| 4,230
|
# Copyright (C) 2008 AG Projects
# Author: Ruud Klaver <ruud@ag-projects.com>
#
"""Header encoding and decoding rules for communication between the dispatcher and relay components"""
class EncodingError(Exception):
pass
class DecodingError(Exception):
pass
class MediaProxyHeaders(object):
@classmethod
def encode(cls, name, value):
func_name = "encode_%s" % name
if hasattr(cls, func_name):
return getattr(cls, func_name)(value)
else:
return value
@classmethod
def decode(cls, name, value):
func_name = "decode_%s" % name
if hasattr(cls, func_name):
return getattr(cls, func_name)(value)
else:
return value
@staticmethod
def encode_cseq(value):
return str(value)
@staticmethod
def decode_cseq(value):
try:
return int(value)
except ValueError:
raise DecodingError("Not an integer: %s" % value)
@staticmethod
def encode_type(value):
if value not in ["request", "reply"]:
raise EncodingError('"type" header should be either "request" or "reply"')
return value
@staticmethod
def decode_type(value):
if value not in ["request", "reply"]:
raise DecodingError('"type" header should be either "request" or "reply"')
return value
@staticmethod
def encode_media(value):
try:
return ','.join(':'.join([type, ip, str(port), direction] + ['%s=%s' % param for param in parameters]) for type, ip, port, direction, parameters in value)
except:
raise EncodingError("Ill-formatted media information")
@staticmethod
def decode_media(value):
try:
streams = []
for stream_data in (data for data in value.split(",") if data):
stream_data = stream_data.split(":")
type, ip, port, direction = stream_data[:4]
parameters = dict(param.split("=") for param in stream_data[4:] if param)
streams.append((type, ip, int(port), direction, parameters))
return streams
except:
raise DecodingError("Ill-formatted media header")
return retval
class CodingDict(dict):
def __init__(self, *args, **kwargs):
if not args and not kwargs:
it = []
elif kwargs:
it = kwargs.iteritems()
elif isinstance(args[0], dict):
it = args[0].iteritems()
else:
try:
it = iter(args[0])
except:
dict.__init__(self, *args, **kwargs)
return
dict.__init__(self)
for key, value in it:
self.__setitem__(key, value)
class EncodingDict(CodingDict):
def __setitem__(self, key, value):
encoded_value = MediaProxyHeaders.encode(key, value)
dict.__setitem__(self, key, encoded_value)
class DecodingDict(CodingDict):
def __setitem__(self, key, value):
decoded_value = MediaProxyHeaders.decode(key, value)
dict.__setitem__(self, key, decoded_value)
|
misaksen/umediaproxy
|
mediaproxy/headers.py
|
Python
|
gpl-2.0
| 3,161
|
# This file is part of ranger, the console file manager.
# License: GNU GPL version 3, see the file "AUTHORS" for details.
# Author: Emanuel Guevel, 2013
# Author: Delisa Mason, 2015
"""Interface for drawing images into the console
This module provides functions to draw images in the terminal using supported
implementations, which are currently w3m, iTerm2 and urxvt.
"""
from __future__ import (absolute_import, division, print_function)
import base64
import curses
import errno
import fcntl
import imghdr
import os
import struct
import sys
from subprocess import Popen, PIPE
import termios
from ranger.core.shared import FileManagerAware
W3MIMGDISPLAY_ENV = "W3MIMGDISPLAY_PATH"
W3MIMGDISPLAY_OPTIONS = []
W3MIMGDISPLAY_PATHS = [
'/usr/lib/w3m/w3mimgdisplay',
'/usr/libexec/w3m/w3mimgdisplay',
'/usr/lib64/w3m/w3mimgdisplay',
'/usr/libexec64/w3m/w3mimgdisplay',
'/usr/local/libexec/w3m/w3mimgdisplay',
]
class ImageDisplayError(Exception):
pass
class ImgDisplayUnsupportedException(Exception):
pass
class ImageDisplayer(object):
"""Image display provider functions for drawing images in the terminal"""
def draw(self, path, start_x, start_y, width, height):
"""Draw an image at the given coordinates."""
pass
def clear(self, start_x, start_y, width, height):
"""Clear a part of terminal display."""
pass
def quit(self):
"""Cleanup and close"""
pass
class W3MImageDisplayer(ImageDisplayer, FileManagerAware):
"""Implementation of ImageDisplayer using w3mimgdisplay, an utilitary
program from w3m (a text-based web browser). w3mimgdisplay can display
images either in virtual tty (using linux framebuffer) or in a Xorg session.
Does not work over ssh.
w3m need to be installed for this to work.
"""
is_initialized = False
def __init__(self):
self.binary_path = None
self.process = None
def initialize(self):
"""start w3mimgdisplay"""
self.binary_path = None
self.binary_path = self._find_w3mimgdisplay_executable() # may crash
self.process = Popen([self.binary_path] + W3MIMGDISPLAY_OPTIONS,
stdin=PIPE, stdout=PIPE, universal_newlines=True)
self.is_initialized = True
@staticmethod
def _find_w3mimgdisplay_executable():
paths = [os.environ.get(W3MIMGDISPLAY_ENV, None)] + W3MIMGDISPLAY_PATHS
for path in paths:
if path is not None and os.path.exists(path):
return path
raise ImageDisplayError("No w3mimgdisplay executable found. Please set "
"the path manually by setting the %s environment variable. (see "
"man page)" % W3MIMGDISPLAY_ENV)
def _get_font_dimensions(self):
# Get the height and width of a character displayed in the terminal in
# pixels.
if self.binary_path is None:
self.binary_path = self._find_w3mimgdisplay_executable()
farg = struct.pack("HHHH", 0, 0, 0, 0)
fd_stdout = sys.stdout.fileno()
fretint = fcntl.ioctl(fd_stdout, termios.TIOCGWINSZ, farg)
rows, cols, xpixels, ypixels = struct.unpack("HHHH", fretint)
if xpixels == 0 and ypixels == 0:
process = Popen([self.binary_path, "-test"], stdout=PIPE, universal_newlines=True)
output, _ = process.communicate()
output = output.split()
xpixels, ypixels = int(output[0]), int(output[1])
# adjust for misplacement
xpixels += 2
ypixels += 2
return (xpixels // cols), (ypixels // rows)
def draw(self, path, start_x, start_y, width, height):
if not self.is_initialized or self.process.poll() is not None:
self.initialize()
try:
input_gen = self._generate_w3m_input(path, start_x, start_y, width, height)
except ImageDisplayError:
raise
# Mitigate the issue with the horizontal black bars when
# selecting some images on some systems. 2 milliseconds seems
# enough. Adjust as necessary.
if self.fm.settings.w3m_delay > 0:
from time import sleep
sleep(self.fm.settings.w3m_delay)
self.process.stdin.write(input_gen)
self.process.stdin.flush()
self.process.stdout.readline()
self.quit()
self.is_initialized = False
def clear(self, start_x, start_y, width, height):
if not self.is_initialized or self.process.poll() is not None:
self.initialize()
fontw, fonth = self._get_font_dimensions()
cmd = "6;{x};{y};{w};{h}\n4;\n3;\n".format(
x=int((start_x - 0.2) * fontw),
y=start_y * fonth,
# y = int((start_y + 1) * fonth), # (for tmux top status bar)
w=int((width + 0.4) * fontw),
h=height * fonth + 1,
# h = (height - 1) * fonth + 1, # (for tmux top status bar)
)
try:
self.process.stdin.write(cmd)
except IOError as ex:
if ex.errno == errno.EPIPE:
return
raise
self.process.stdin.flush()
self.process.stdout.readline()
def _generate_w3m_input(self, path, start_x, start_y, max_width, max_height):
"""Prepare the input string for w3mimgpreview
start_x, start_y, max_height and max_width specify the drawing area.
They are expressed in number of characters.
"""
fontw, fonth = self._get_font_dimensions()
if fontw == 0 or fonth == 0:
raise ImgDisplayUnsupportedException
max_width_pixels = max_width * fontw
max_height_pixels = max_height * fonth - 2
# (for tmux top status bar)
# max_height_pixels = (max_height - 1) * fonth - 2
# get image size
cmd = "5;{}\n".format(path)
self.process.stdin.write(cmd)
self.process.stdin.flush()
output = self.process.stdout.readline().split()
if len(output) != 2:
raise ImageDisplayError('Failed to execute w3mimgdisplay', output)
width = int(output[0])
height = int(output[1])
# get the maximum image size preserving ratio
if width > max_width_pixels:
height = (height * max_width_pixels) // width
width = max_width_pixels
if height > max_height_pixels:
width = (width * max_height_pixels) // height
height = max_height_pixels
return "0;1;{x};{y};{w};{h};;;;;{filename}\n4;\n3;\n".format(
x=int((start_x - 0.2) * fontw),
y=start_y * fonth,
# y = (start_y + 1) * fonth, # (for tmux top status bar)
w=width,
h=height,
filename=path,
)
def quit(self):
if self.is_initialized and self.process and self.process.poll() is None:
self.process.kill()
# TODO: remove FileManagerAwareness, as stuff in ranger.ext should be
# ranger-independent libraries.
class ITerm2ImageDisplayer(ImageDisplayer, FileManagerAware):
"""Implementation of ImageDisplayer using iTerm2 image display support
(http://iterm2.com/images.html).
Ranger must be running in iTerm2 for this to work.
"""
def draw(self, path, start_x, start_y, width, height):
curses.putp(curses.tigetstr("sc"))
tparm = curses.tparm(curses.tigetstr("cup"), start_y, start_x)
if sys.version_info[0] < 3:
sys.stdout.write(tparm)
else:
sys.stdout.buffer.write(tparm) # pylint: disable=no-member
sys.stdout.write(self._generate_iterm2_input(path, width, height))
curses.putp(curses.tigetstr("rc"))
sys.stdout.flush()
def clear(self, start_x, start_y, width, height):
self.fm.ui.win.redrawwin()
self.fm.ui.win.refresh()
def _generate_iterm2_input(self, path, max_cols, max_rows):
"""Prepare the image content of path for image display in iTerm2"""
image_width, image_height = self._get_image_dimensions(path)
if max_cols == 0 or max_rows == 0 or image_width == 0 or image_height == 0:
return ""
image_width = self._fit_width(
image_width, image_height, max_cols, max_rows)
content = self._encode_image_content(path)
display_protocol = "\033"
close_protocol = "\a"
if "screen" in os.environ['TERM']:
display_protocol += "Ptmux;\033\033"
close_protocol += "\033\\"
text = "{0}]1337;File=inline=1;preserveAspectRatio=0;size={1};width={2}px:{3}{4}\n".format(
display_protocol,
str(len(content)),
str(int(image_width)),
content,
close_protocol)
return text
def _fit_width(self, width, height, max_cols, max_rows):
max_width = self.fm.settings.iterm2_font_width * max_cols
max_height = self.fm.settings.iterm2_font_height * max_rows
if height > max_height:
if width > max_width:
width_scale = max_width / width
height_scale = max_height / height
min_scale = min(width_scale, height_scale)
max_scale = max(width_scale, height_scale)
if width * max_scale <= max_width and height * max_scale <= max_height:
return width * max_scale
return width * min_scale
scale = max_height / height
return width * scale
elif width > max_width:
scale = max_width / width
return width * scale
return width
@staticmethod
def _encode_image_content(path):
"""Read and encode the contents of path"""
with open(path, 'rb') as fobj:
return base64.b64encode(fobj.read())
@staticmethod
def _get_image_dimensions(path):
"""Determine image size using imghdr"""
file_handle = open(path, 'rb')
file_header = file_handle.read(24)
image_type = imghdr.what(path)
if len(file_header) != 24:
file_handle.close()
return 0, 0
if image_type == 'png':
check = struct.unpack('>i', file_header[4:8])[0]
if check != 0x0d0a1a0a:
file_handle.close()
return 0, 0
width, height = struct.unpack('>ii', file_header[16:24])
elif image_type == 'gif':
width, height = struct.unpack('<HH', file_header[6:10])
elif image_type == 'jpeg':
unreadable = IOError if sys.version_info[0] < 3 else OSError
try:
file_handle.seek(0)
size = 2
ftype = 0
while not 0xc0 <= ftype <= 0xcf:
file_handle.seek(size, 1)
byte = file_handle.read(1)
while ord(byte) == 0xff:
byte = file_handle.read(1)
ftype = ord(byte)
size = struct.unpack('>H', file_handle.read(2))[0] - 2
file_handle.seek(1, 1)
height, width = struct.unpack('>HH', file_handle.read(4))
except unreadable:
height, width = 0, 0
else:
file_handle.close()
return 0, 0
file_handle.close()
return width, height
class TerminologyImageDisplayer(ImageDisplayer, FileManagerAware):
"""Implementation of ImageDisplayer using terminology image display support
(https://github.com/billiob/terminology).
Ranger must be running in terminology for this to work.
Doesn't work with TMUX :/
"""
def __init__(self):
self.display_protocol = "\033"
self.close_protocol = "\000"
def draw(self, path, start_x, start_y, width, height):
# Save cursor
curses.putp(curses.tigetstr("sc"))
y = start_y
# Move to drawing zone
self._move_to(start_x, y)
# Write intent
sys.stdout.write("%s}ic#%d;%d;%s%s" % (
self.display_protocol,
width, height,
path,
self.close_protocol))
# Write Replacement commands ('#')
for _ in range(0, height):
sys.stdout.write("%s}ib%s%s%s}ie%s" % (
self.display_protocol,
self.close_protocol,
"#" * width,
self.display_protocol,
self.close_protocol))
y = y + 1
self._move_to(start_x, y)
# Restore cursor
curses.putp(curses.tigetstr("rc"))
sys.stdout.flush()
@staticmethod
def _move_to(x, y):
# curses.move(y, x)
tparm = curses.tparm(curses.tigetstr("cup"), y, x)
if sys.version_info[0] < 3:
sys.stdout.write(tparm)
else:
sys.stdout.buffer.write(tparm) # pylint: disable=no-member
def clear(self, start_x, start_y, width, height):
self.fm.ui.win.redrawwin()
self.fm.ui.win.refresh()
class URXVTImageDisplayer(ImageDisplayer, FileManagerAware):
"""Implementation of ImageDisplayer working by setting the urxvt
background image "under" the preview pane.
Ranger must be running in urxvt for this to work.
"""
def __init__(self):
self.display_protocol = "\033"
self.close_protocol = "\a"
if "screen" in os.environ['TERM']:
self.display_protocol += "Ptmux;\033\033"
self.close_protocol += "\033\\"
self.display_protocol += "]20;"
@staticmethod
def _get_max_sizes():
"""Use the whole terminal."""
pct_width = 100
pct_height = 100
return pct_width, pct_height
@staticmethod
def _get_centered_offsets():
"""Center the image."""
pct_x = 50
pct_y = 50
return pct_x, pct_y
def _get_sizes(self):
"""Return the width and height of the preview pane in relation to the
whole terminal window.
"""
if self.fm.ui.pager.visible:
return self._get_max_sizes()
total_columns_ratio = sum(self.fm.settings.column_ratios)
preview_column_ratio = self.fm.settings.column_ratios[-1]
pct_width = int((100 * preview_column_ratio) / total_columns_ratio)
pct_height = 100 # As much as possible while preserving the aspect ratio.
return pct_width, pct_height
def _get_offsets(self):
"""Return the offsets of the image center."""
if self.fm.ui.pager.visible:
return self._get_centered_offsets()
pct_x = 100 # Right-aligned.
pct_y = 2 # TODO: Use the font size to calculate this offset.
return pct_x, pct_y
def draw(self, path, start_x, start_y, width, height):
# The coordinates in the arguments are ignored as urxvt takes
# the coordinates in a non-standard way: the position of the
# image center as a percentage of the terminal size. As a
# result all values below are in percents.
pct_x, pct_y = self._get_offsets()
pct_width, pct_height = self._get_sizes()
sys.stdout.write(
self.display_protocol
+ path
+ ";{pct_width}x{pct_height}+{pct_x}+{pct_y}:op=keep-aspect".format(
pct_width=pct_width, pct_height=pct_height, pct_x=pct_x, pct_y=pct_y
)
+ self.close_protocol
)
sys.stdout.flush()
def clear(self, start_x, start_y, width, height):
sys.stdout.write(
self.display_protocol
+ ";100x100+1000+1000"
+ self.close_protocol
)
sys.stdout.flush()
def quit(self):
self.clear(0, 0, 0, 0) # dummy assignments
class URXVTImageFSDisplayer(URXVTImageDisplayer):
"""URXVTImageDisplayer that utilizes the whole terminal."""
def _get_sizes(self):
"""Use the whole terminal."""
return self._get_max_sizes()
def _get_offsets(self):
"""Center the image."""
return self._get_centered_offsets()
|
Vifon/ranger
|
ranger/ext/img_display.py
|
Python
|
gpl-3.0
| 16,218
|
import os
import json
import logging
import random
from django.conf import settings
from backend.kubernetes.k8sclient import KubeClient
from backend.schedule import DockerSchedulerFactory
logger = logging.getLogger('hummer')
def fetch_digest_from_response(response):
"""
Fetch the image digest from response when push image from docker host to
private registry.
"""
# logger.debug(response)
res = json.loads(response.decode())
items = res.get('status').split(' ')
res = [item for item in items if item.startswith('sha256:')]
digest = res[0].split(':')[-1]
return digest
def get_optimal_docker_host():
"""
Returns the optimal docker host to build image.
"""
scheduler = DockerSchedulerFactory.get_scheduler()
docker_host = scheduler.get_optimal_docker_host()
return docker_host
def get_volume_nfs_dir(base_dir, namespace, volume):
"""
Create the volume dir in nfs server.
"""
return os.path.join(base_dir, namespace, volume)
def remove_file_from_disk(filename):
"""
Delete the file from disk.
"""
if os.path.exists(filename):
os.remove(filename)
def get_application_instance_name(application):
"""
Return the name of the application instance.
"""
return "{}-{}".format(application.image.project.name, application.name)
def get_optimal_external_ip(namespace, app_name):
"""
Return the optimal external ip from all host ips of the application.
"""
kubeclient = KubeClient("http://{}:{}{}".format(settings.MASTER_IP,
settings.K8S_PORT, settings.K8S_API_PATH))
label = "app=" + app_name
hosts = kubeclient.list_host_ips(namespace=namespace, label=label)
# logger.debug(hosts)
index = random.randint(0, len(hosts) - 1)
return hosts[index]
|
wangtaoking1/hummer
|
backend/utils.py
|
Python
|
apache-2.0
| 1,817
|
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test mulitple rpc user config option rpcauth
#
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import str_to_b64str, assert_equal
import os
import http.client
import urllib.parse
class HTTPBasicsTest (BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = False
self.num_nodes = 1
def setup_chain(self):
super().setup_chain()
#Append rpcauth to bitcoin.conf before initialization
rpcauth = "rpcauth=rt:93648e835a54c573682c2eb19f882535$7681e9c5b74bdd85e78166031d2058e1069b3ed7ed967c93fc63abba06f31144"
rpcauth2 = "rpcauth=rt2:f8607b1a88861fac29dfccf9b52ff9f$ff36a0c23c8c62b4846112e50fa888416e94c17bfd4c42f88fd8f55ec6a3137e"
with open(os.path.join(self.options.tmpdir+"/node0", "bolsonarocoin.conf"), 'a', encoding='utf8') as f:
f.write(rpcauth+"\n")
f.write(rpcauth2+"\n")
def setup_network(self):
self.nodes = self.setup_nodes()
def run_test(self):
##################################################
# Check correctness of the rpcauth config option #
##################################################
url = urllib.parse.urlparse(self.nodes[0].url)
#Old authpair
authpair = url.username + ':' + url.password
#New authpair generated via share/rpcuser tool
rpcauth = "rpcauth=rt:93648e835a54c573682c2eb19f882535$7681e9c5b74bdd85e78166031d2058e1069b3ed7ed967c93fc63abba06f31144"
password = "cA773lm788buwYe4g4WT+05pKyNruVKjQ25x3n0DQcM="
#Second authpair with different username
rpcauth2 = "rpcauth=rt2:f8607b1a88861fac29dfccf9b52ff9f$ff36a0c23c8c62b4846112e50fa888416e94c17bfd4c42f88fd8f55ec6a3137e"
password2 = "8/F3uMDw4KSEbw96U3CA1C4X05dkHDN2BPFjTgZW4KI="
authpairnew = "rt:"+password
headers = {"Authorization": "Basic " + str_to_b64str(authpair)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, False)
conn.close()
#Use new authpair to confirm both work
headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, False)
conn.close()
#Wrong login name with rt's password
authpairnew = "rtwrong:"+password
headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, True)
conn.close()
#Wrong password for rt
authpairnew = "rt:"+password+"wrong"
headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, True)
conn.close()
#Correct for rt2
authpairnew = "rt2:"+password2
headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, False)
conn.close()
#Wrong password for rt2
authpairnew = "rt2:"+password2+"wrong"
headers = {"Authorization": "Basic " + str_to_b64str(authpairnew)}
conn = http.client.HTTPConnection(url.hostname, url.port)
conn.connect()
conn.request('POST', '/', '{"method": "getbestblockhash"}', headers)
resp = conn.getresponse()
assert_equal(resp.status==401, True)
conn.close()
if __name__ == '__main__':
HTTPBasicsTest ().main ()
|
freemanjackal/bolsonarocoin
|
qa/rpc-tests/multi_rpc.py
|
Python
|
mit
| 4,581
|
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
|
Larvichee/StolenProjects
|
mysite/mysite/urls.py
|
Python
|
mit
| 822
|
import sys
import numpy
import math
from foldyFloatList import foldyFloatList
class OOBError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
from KMCLib.PluginInterfaces.KMCAnalysisPlugin import KMCAnalysisPlugin
from KMCLib.Utilities.CheckUtilities import checkSequenceOfPositiveIntegers
from KMCLib.Utilities.CheckUtilities import checkPositiveFloat
from KMCLib.Utilities.CheckUtilities import checkPositiveInteger
from KMCLib.Exceptions.Error import Error
from KMCLib.Backend.Backend import MPICommons
class DensHist(KMCAnalysisPlugin):
def __init__(self, spec=None, inProc=None, outProc=None):
self.__spec = spec
msg = "The 'inProc' parameter must be given as a list of relevant input processes."
self.__inProc = checkSequenceOfPositiveIntegers(inProc, msg)
msg = "The 'outProc' parameter must be given as a list of relevant output processes."
self.__outProc = checkSequenceOfPositiveIntegers(outProc, msg)
self.__initTime = 0.0
self.__lastTime = 0.0
self.__currentTime = 0.0
def setup(self, step, time, configuration):
self.__initTime = time
typeList = configuration.types()
self.__histSize = len(typeList)
self.__histogram = []
for i in range(0, self.__histSize):
self.__histogram.append(foldyFloatList())
total = 0
for i in typeList:
if i in self.__spec:
total += 1
self.__currTot = total
self.__lastTime = time
self.__currentTime = time
def registerStep(self, step, time, configuration):
self.__currentTime = time
if configuration.latestEventProcess() in self.__inProc:
self.__currTot += 1
if configuration.latestEventProcess() in self.__outProc:
self.__currTot -= 1
if self.__currTot < 0 or self.__currTot > self.__histSize:
raise OOBError(0)
self.__histogram[self.__currTot].addValue(self.__currentTime - self.__lastTime)
self.__lastTime = time
def finalize(self):
self.__lastTime = self.__currentTime
self.__finalHist = []
totalWeight = foldyFloatList()
for data in self.__histogram:
temp = data.extractSum()
totalWeight.addValue(temp)
self.__finalHist.append(temp)
ovTot = totalWeight.extractSum()
for index in range(0, self.__histSize):
self.__finalHist[index] = self.__finalHist[index]/ovTot
def printResults(self, stream=sys.stdout):
if MPICommons.isMaster():
for index in range(0, self.__histSize):
stream.write(str(index)+" "+"{:.6E}".format(self.__finalHist[index])+"\n")
|
joshuahellier/PhDStuff
|
codes/thesisCodes/kmc/customAnalysis/DensHist.py
|
Python
|
mit
| 2,799
|
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function, with_statement
from tornado.escape import utf8, _unicode
from tornado import gen
from tornado.httpclient import HTTPResponse, HTTPError, AsyncHTTPClient, main, _RequestProxy
from tornado import httputil
from tornado.http1connection import HTTP1Connection, HTTP1ConnectionParameters
from tornado.iostream import StreamClosedError
from tornado.netutil import Resolver, OverrideResolver, _client_ssl_defaults
from tornado.log import gen_log
from tornado import stack_context
from tornado.tcpclient import TCPClient
from tornado.util import PY3
import base64
import collections
import copy
import functools
import re
import socket
import sys
from io import BytesIO
if PY3:
import urllib.parse as urlparse
else:
import urlparse
try:
import ssl
except ImportError:
# ssl is not available on Google App Engine.
ssl = None
try:
import certifi
except ImportError:
certifi = None
def _default_ca_certs():
if certifi is None:
raise Exception("The 'certifi' package is required to use https "
"in simple_httpclient")
return certifi.where()
class SimpleAsyncHTTPClient(AsyncHTTPClient):
"""Non-blocking HTTP client with no external dependencies.
This class implements an HTTP 1.1 client on top of Tornado's IOStreams.
Some features found in the curl-based AsyncHTTPClient are not yet
supported. In particular, proxies are not supported, connections
are not reused, and callers cannot select the network interface to be
used.
"""
def initialize(self, io_loop, max_clients=10,
hostname_mapping=None, max_buffer_size=104857600,
resolver=None, defaults=None, max_header_size=None,
max_body_size=None):
"""Creates a AsyncHTTPClient.
Only a single AsyncHTTPClient instance exists per IOLoop
in order to provide limitations on the number of pending connections.
``force_instance=True`` may be used to suppress this behavior.
Note that because of this implicit reuse, unless ``force_instance``
is used, only the first call to the constructor actually uses
its arguments. It is recommended to use the ``configure`` method
instead of the constructor to ensure that arguments take effect.
``max_clients`` is the number of concurrent requests that can be
in progress; when this limit is reached additional requests will be
queued. Note that time spent waiting in this queue still counts
against the ``request_timeout``.
``hostname_mapping`` is a dictionary mapping hostnames to IP addresses.
It can be used to make local DNS changes when modifying system-wide
settings like ``/etc/hosts`` is not possible or desirable (e.g. in
unittests).
``max_buffer_size`` (default 100MB) is the number of bytes
that can be read into memory at once. ``max_body_size``
(defaults to ``max_buffer_size``) is the largest response body
that the client will accept. Without a
``streaming_callback``, the smaller of these two limits
applies; with a ``streaming_callback`` only ``max_body_size``
does.
.. versionchanged:: 4.2
Added the ``max_body_size`` argument.
"""
super(SimpleAsyncHTTPClient, self).initialize(io_loop,
defaults=defaults)
self.max_clients = max_clients
self.queue = collections.deque()
self.active = {}
self.waiting = {}
self.max_buffer_size = max_buffer_size
self.max_header_size = max_header_size
self.max_body_size = max_body_size
# TCPClient could create a Resolver for us, but we have to do it
# ourselves to support hostname_mapping.
if resolver:
self.resolver = resolver
self.own_resolver = False
else:
self.resolver = Resolver(io_loop=io_loop)
self.own_resolver = True
if hostname_mapping is not None:
self.resolver = OverrideResolver(resolver=self.resolver,
mapping=hostname_mapping)
self.tcp_client = TCPClient(resolver=self.resolver, io_loop=io_loop)
def close(self):
super(SimpleAsyncHTTPClient, self).close()
if self.own_resolver:
self.resolver.close()
self.tcp_client.close()
def fetch_impl(self, request, callback):
key = object()
self.queue.append((key, request, callback))
if not len(self.active) < self.max_clients:
timeout_handle = self.io_loop.add_timeout(
self.io_loop.time() + min(request.connect_timeout,
request.request_timeout),
functools.partial(self._on_timeout, key, "in request queue"))
else:
timeout_handle = None
self.waiting[key] = (request, callback, timeout_handle)
self._process_queue()
if self.queue:
gen_log.debug("max_clients limit reached, request queued. "
"%d active, %d queued requests." % (
len(self.active), len(self.queue)))
def _process_queue(self):
with stack_context.NullContext():
while self.queue and len(self.active) < self.max_clients:
key, request, callback = self.queue.popleft()
if key not in self.waiting:
continue
self._remove_timeout(key)
self.active[key] = (request, callback)
release_callback = functools.partial(self._release_fetch, key)
self._handle_request(request, release_callback, callback)
def _connection_class(self):
return _HTTPConnection
def _handle_request(self, request, release_callback, final_callback):
self._connection_class()(
self.io_loop, self, request, release_callback,
final_callback, self.max_buffer_size, self.tcp_client,
self.max_header_size, self.max_body_size)
def _release_fetch(self, key):
del self.active[key]
self._process_queue()
def _remove_timeout(self, key):
if key in self.waiting:
request, callback, timeout_handle = self.waiting[key]
if timeout_handle is not None:
self.io_loop.remove_timeout(timeout_handle)
del self.waiting[key]
def _on_timeout(self, key, info=None):
"""Timeout callback of request.
Construct a timeout HTTPResponse when a timeout occurs.
:arg object key: A simple object to mark the request.
:info string key: More detailed timeout information.
"""
request, callback, timeout_handle = self.waiting[key]
self.queue.remove((key, request, callback))
error_message = "Timeout {0}".format(info) if info else "Timeout"
timeout_response = HTTPResponse(
request, 599, error=HTTPError(599, error_message),
request_time=self.io_loop.time() - request.start_time)
self.io_loop.add_callback(callback, timeout_response)
del self.waiting[key]
class _HTTPConnection(httputil.HTTPMessageDelegate):
_SUPPORTED_METHODS = set(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
def __init__(self, io_loop, client, request, release_callback,
final_callback, max_buffer_size, tcp_client,
max_header_size, max_body_size):
self.start_time = io_loop.time()
self.io_loop = io_loop
self.client = client
self.request = request
self.release_callback = release_callback
self.final_callback = final_callback
self.max_buffer_size = max_buffer_size
self.tcp_client = tcp_client
self.max_header_size = max_header_size
self.max_body_size = max_body_size
self.code = None
self.headers = None
self.chunks = []
self._decompressor = None
# Timeout handle returned by IOLoop.add_timeout
self._timeout = None
self._sockaddr = None
with stack_context.ExceptionStackContext(self._handle_exception):
self.parsed = urlparse.urlsplit(_unicode(self.request.url))
if self.parsed.scheme not in ("http", "https"):
raise ValueError("Unsupported url scheme: %s" %
self.request.url)
# urlsplit results have hostname and port results, but they
# didn't support ipv6 literals until python 2.7.
netloc = self.parsed.netloc
if "@" in netloc:
userpass, _, netloc = netloc.rpartition("@")
host, port = httputil.split_host_and_port(netloc)
if port is None:
port = 443 if self.parsed.scheme == "https" else 80
if re.match(r'^\[.*\]$', host):
# raw ipv6 addresses in urls are enclosed in brackets
host = host[1:-1]
self.parsed_hostname = host # save final host for _on_connect
if request.allow_ipv6 is False:
af = socket.AF_INET
else:
af = socket.AF_UNSPEC
ssl_options = self._get_ssl_options(self.parsed.scheme)
timeout = min(self.request.connect_timeout, self.request.request_timeout)
if timeout:
self._timeout = self.io_loop.add_timeout(
self.start_time + timeout,
stack_context.wrap(functools.partial(self._on_timeout, "while connecting")))
self.tcp_client.connect(host, port, af=af,
ssl_options=ssl_options,
max_buffer_size=self.max_buffer_size,
callback=self._on_connect)
def _get_ssl_options(self, scheme):
if scheme == "https":
if self.request.ssl_options is not None:
return self.request.ssl_options
# If we are using the defaults, don't construct a
# new SSLContext.
if (self.request.validate_cert and
self.request.ca_certs is None and
self.request.client_cert is None and
self.request.client_key is None):
return _client_ssl_defaults
ssl_options = {}
if self.request.validate_cert:
ssl_options["cert_reqs"] = ssl.CERT_REQUIRED
if self.request.ca_certs is not None:
ssl_options["ca_certs"] = self.request.ca_certs
elif not hasattr(ssl, 'create_default_context'):
# When create_default_context is present,
# we can omit the "ca_certs" parameter entirely,
# which avoids the dependency on "certifi" for py34.
ssl_options["ca_certs"] = _default_ca_certs()
if self.request.client_key is not None:
ssl_options["keyfile"] = self.request.client_key
if self.request.client_cert is not None:
ssl_options["certfile"] = self.request.client_cert
# SSL interoperability is tricky. We want to disable
# SSLv2 for security reasons; it wasn't disabled by default
# until openssl 1.0. The best way to do this is to use
# the SSL_OP_NO_SSLv2, but that wasn't exposed to python
# until 3.2. Python 2.7 adds the ciphers argument, which
# can also be used to disable SSLv2. As a last resort
# on python 2.6, we set ssl_version to TLSv1. This is
# more narrow than we'd like since it also breaks
# compatibility with servers configured for SSLv3 only,
# but nearly all servers support both SSLv3 and TLSv1:
# http://blog.ivanristic.com/2011/09/ssl-survey-protocol-support.html
if sys.version_info >= (2, 7):
# In addition to disabling SSLv2, we also exclude certain
# classes of insecure ciphers.
ssl_options["ciphers"] = "DEFAULT:!SSLv2:!EXPORT:!DES"
else:
# This is really only necessary for pre-1.0 versions
# of openssl, but python 2.6 doesn't expose version
# information.
ssl_options["ssl_version"] = ssl.PROTOCOL_TLSv1
return ssl_options
return None
def _on_timeout(self, info=None):
"""Timeout callback of _HTTPConnection instance.
Raise a timeout HTTPError when a timeout occurs.
:info string key: More detailed timeout information.
"""
self._timeout = None
error_message = "Timeout {0}".format(info) if info else "Timeout"
if self.final_callback is not None:
raise HTTPError(599, error_message)
def _remove_timeout(self):
if self._timeout is not None:
self.io_loop.remove_timeout(self._timeout)
self._timeout = None
def _on_connect(self, stream):
if self.final_callback is None:
# final_callback is cleared if we've hit our timeout.
stream.close()
return
self.stream = stream
self.stream.set_close_callback(self.on_connection_close)
self._remove_timeout()
if self.final_callback is None:
return
if self.request.request_timeout:
self._timeout = self.io_loop.add_timeout(
self.start_time + self.request.request_timeout,
stack_context.wrap(functools.partial(self._on_timeout, "during request")))
if (self.request.method not in self._SUPPORTED_METHODS and
not self.request.allow_nonstandard_methods):
raise KeyError("unknown method %s" % self.request.method)
for key in ('network_interface',
'proxy_host', 'proxy_port',
'proxy_username', 'proxy_password',
'proxy_auth_mode'):
if getattr(self.request, key, None):
raise NotImplementedError('%s not supported' % key)
if "Connection" not in self.request.headers:
self.request.headers["Connection"] = "close"
if "Host" not in self.request.headers:
if '@' in self.parsed.netloc:
self.request.headers["Host"] = self.parsed.netloc.rpartition('@')[-1]
else:
self.request.headers["Host"] = self.parsed.netloc
username, password = None, None
if self.parsed.username is not None:
username, password = self.parsed.username, self.parsed.password
elif self.request.auth_username is not None:
username = self.request.auth_username
password = self.request.auth_password or ''
if username is not None:
if self.request.auth_mode not in (None, "basic"):
raise ValueError("unsupported auth_mode %s",
self.request.auth_mode)
auth = utf8(username) + b":" + utf8(password)
self.request.headers["Authorization"] = (b"Basic " +
base64.b64encode(auth))
if self.request.user_agent:
self.request.headers["User-Agent"] = self.request.user_agent
if not self.request.allow_nonstandard_methods:
# Some HTTP methods nearly always have bodies while others
# almost never do. Fail in this case unless the user has
# opted out of sanity checks with allow_nonstandard_methods.
body_expected = self.request.method in ("POST", "PATCH", "PUT")
body_present = (self.request.body is not None or
self.request.body_producer is not None)
if ((body_expected and not body_present) or
(body_present and not body_expected)):
raise ValueError(
'Body must %sbe None for method %s (unless '
'allow_nonstandard_methods is true)' %
('not ' if body_expected else '', self.request.method))
if self.request.expect_100_continue:
self.request.headers["Expect"] = "100-continue"
if self.request.body is not None:
# When body_producer is used the caller is responsible for
# setting Content-Length (or else chunked encoding will be used).
self.request.headers["Content-Length"] = str(len(
self.request.body))
if (self.request.method == "POST" and
"Content-Type" not in self.request.headers):
self.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
if self.request.decompress_response:
self.request.headers["Accept-Encoding"] = "gzip"
req_path = ((self.parsed.path or '/') +
(('?' + self.parsed.query) if self.parsed.query else ''))
self.connection = self._create_connection(stream)
start_line = httputil.RequestStartLine(self.request.method,
req_path, '')
self.connection.write_headers(start_line, self.request.headers)
if self.request.expect_100_continue:
self._read_response()
else:
self._write_body(True)
def _create_connection(self, stream):
stream.set_nodelay(True)
connection = HTTP1Connection(
stream, True,
HTTP1ConnectionParameters(
no_keep_alive=True,
max_header_size=self.max_header_size,
max_body_size=self.max_body_size,
decompress=self.request.decompress_response),
self._sockaddr)
return connection
def _write_body(self, start_read):
if self.request.body is not None:
self.connection.write(self.request.body)
elif self.request.body_producer is not None:
fut = self.request.body_producer(self.connection.write)
if fut is not None:
fut = gen.convert_yielded(fut)
def on_body_written(fut):
fut.result()
self.connection.finish()
if start_read:
self._read_response()
self.io_loop.add_future(fut, on_body_written)
return
self.connection.finish()
if start_read:
self._read_response()
def _read_response(self):
# Ensure that any exception raised in read_response ends up in our
# stack context.
self.io_loop.add_future(
self.connection.read_response(self),
lambda f: f.result())
def _release(self):
if self.release_callback is not None:
release_callback = self.release_callback
self.release_callback = None
release_callback()
def _run_callback(self, response):
self._release()
if self.final_callback is not None:
final_callback = self.final_callback
self.final_callback = None
self.io_loop.add_callback(final_callback, response)
def _handle_exception(self, typ, value, tb):
if self.final_callback:
self._remove_timeout()
if isinstance(value, StreamClosedError):
if value.real_error is None:
value = HTTPError(599, "Stream closed")
else:
value = value.real_error
self._run_callback(HTTPResponse(self.request, 599, error=value,
request_time=self.io_loop.time() - self.start_time,
))
if hasattr(self, "stream"):
# TODO: this may cause a StreamClosedError to be raised
# by the connection's Future. Should we cancel the
# connection more gracefully?
self.stream.close()
return True
else:
# If our callback has already been called, we are probably
# catching an exception that is not caused by us but rather
# some child of our callback. Rather than drop it on the floor,
# pass it along, unless it's just the stream being closed.
return isinstance(value, StreamClosedError)
def on_connection_close(self):
if self.final_callback is not None:
message = "Connection closed"
if self.stream.error:
raise self.stream.error
try:
raise HTTPError(599, message)
except HTTPError:
self._handle_exception(*sys.exc_info())
def headers_received(self, first_line, headers):
if self.request.expect_100_continue and first_line.code == 100:
self._write_body(False)
return
self.code = first_line.code
self.reason = first_line.reason
self.headers = headers
if self._should_follow_redirect():
return
if self.request.header_callback is not None:
# Reassemble the start line.
self.request.header_callback('%s %s %s\r\n' % first_line)
for k, v in self.headers.get_all():
self.request.header_callback("%s: %s\r\n" % (k, v))
self.request.header_callback('\r\n')
def _should_follow_redirect(self):
return (self.request.follow_redirects and
self.request.max_redirects > 0 and
self.code in (301, 302, 303, 307))
def finish(self):
data = b''.join(self.chunks)
self._remove_timeout()
original_request = getattr(self.request, "original_request",
self.request)
if self._should_follow_redirect():
assert isinstance(self.request, _RequestProxy)
new_request = copy.copy(self.request.request)
new_request.url = urlparse.urljoin(self.request.url,
self.headers["Location"])
new_request.max_redirects = self.request.max_redirects - 1
del new_request.headers["Host"]
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
# Client SHOULD make a GET request after a 303.
# According to the spec, 302 should be followed by the same
# method as the original request, but in practice browsers
# treat 302 the same as 303, and many servers use 302 for
# compatibility with pre-HTTP/1.1 user agents which don't
# understand the 303 status.
if self.code in (302, 303):
new_request.method = "GET"
new_request.body = None
for h in ["Content-Length", "Content-Type",
"Content-Encoding", "Transfer-Encoding"]:
try:
del self.request.headers[h]
except KeyError:
pass
new_request.original_request = original_request
final_callback = self.final_callback
self.final_callback = None
self._release()
self.client.fetch(new_request, final_callback)
self._on_end_request()
return
if self.request.streaming_callback:
buffer = BytesIO()
else:
buffer = BytesIO(data) # TODO: don't require one big string?
response = HTTPResponse(original_request,
self.code, reason=getattr(self, 'reason', None),
headers=self.headers,
request_time=self.io_loop.time() - self.start_time,
buffer=buffer,
effective_url=self.request.url)
self._run_callback(response)
self._on_end_request()
def _on_end_request(self):
self.stream.close()
def data_received(self, chunk):
if self._should_follow_redirect():
# We're going to follow a redirect so just discard the body.
return
if self.request.streaming_callback is not None:
self.request.streaming_callback(chunk)
else:
self.chunks.append(chunk)
if __name__ == "__main__":
AsyncHTTPClient.configure(SimpleAsyncHTTPClient)
main()
|
mr-ping/tornado
|
tornado/simple_httpclient.py
|
Python
|
apache-2.0
| 24,731
|
# -*- coding: utf-8 -*-
""" Models for the base application.
All apps should use the BaseModel as parent for all models
"""
# standard library
import json
# django
from django.contrib.sites.models import Site
from django.db import models
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
# base
from base import utils
from base.managers import BaseManager
from base.serializers import ModelEncoder
# public methods
def file_path(self, name):
"""
Generic method to give to a FileField or ImageField in it's upload_to
parameter.
This returns the name of the class, concatenated with the id of the
object and the name of the file.
"""
base_path = "{}/{}/{}"
return base_path.format(
self.__class__.__name__,
utils.random_string(30),
name
)
class BaseModel(models.Model):
""" An abstract class that every model should inherit from """
BOOLEAN_CHOICES = ((False, _('No')), (True, _('Yes')))
created_at = models.DateTimeField(
auto_now_add=True,
help_text=_("creation date"),
)
updated_at = models.DateTimeField(
auto_now=True, null=True,
help_text=_("edition date"),
)
# using BaseManager
objects = BaseManager()
class Meta:
""" set to abstract """
abstract = True
# public methods
def update(self, **kwargs):
""" proxy method for the QuerySet: update method
highly recommended when you need to save just one field
"""
kwargs['updated_at'] = timezone.now()
for kw in kwargs:
self.__setattr__(kw, kwargs[kw])
self.__class__.objects.filter(pk=self.pk).update(**kwargs)
def to_dict(instance, fields=None, exclude=None):
"""
Returns a dict containing the data in ``instance``
``fields`` is an optional list of field names. If provided, only the
named fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed
in the ``fields`` argument.
"""
opts = instance._meta
data = {}
for f in opts.fields + opts.many_to_many:
if fields and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
if isinstance(f, models.fields.related.ManyToManyField):
# If the object doesn't have a primary key yet, just use an
# emptylist for its m2m fields. Calling f.value_from_object
# will raise an exception.
if instance.pk is None:
data[f.name] = []
else:
# MultipleChoiceWidget needs a list of pks, not objects.
data[f.name] = list(
f.value_from_object(instance).values_list('pk',
flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data
def to_json(self, fields=None, exclude=None, **kargs):
"""
Returns a string containing the data in of the instance in json format
``fields`` is an optional list of field names. If provided, only the
named fields will be included in the returned dict.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned dict, even if they are listed
in the ``fields`` argument.
kwargs are optional named parameters for the json.dumps method
"""
# obtain a dict of the instance data
data = self.to_dict(fields=fields, exclude=exclude)
# turn the dict to json
return json.dumps(data, cls=ModelEncoder, **kargs)
def get_full_url(self):
absolute_url = self.get_absolute_url()
site = Site.objects.get_current().domain
return 'http://{site}{path}'.format(site=site, path=absolute_url)
|
Angoreher/xcero
|
base/models.py
|
Python
|
mit
| 4,142
|
# -*- coding: utf-8 -*-
__all__ = ('QLearning',
)
import numpy as np
import matplotlib.pyplot as plt
from .NeuralNetwork import *
class Cost:
cost_history = []
def append(self, value):
self.cost_history.append(value)
return
def show(self):
print('cost: ', self.cost_history)
plt.plot(np.arange(len(self.cost_history)), self.cost_history)
plt.ylabel('Cost')
plt.xlabel('training steps')
plt.show()
return
class QLearning:
learning_rate = 0
def __init__(self, learning_rate=0.01):
self.learning_rate = learning_rate
self.NN = NeuralNetwork()
self.cost = Cost()
def build_net(self, input_size, hidden, cname=None, folder=None):
"""
build a base network.
:param input_size: the size of input layer
:param hidden: [the number of hidden layer,
the node of each hidden layer]
hidden_layer < 1, return input layer
:param cname: name for collections
:param folder: folder name contain network
:return: output layer index
"""
def layer_name(nr):
if folder is None:
return
return folder + '/l' + str(nr)
[hidden_layer, hidden_size] = hidden
input_node = self.NN.add_placeholder('input')
if hidden_layer < 1:
return None, input_node
l_in = self.NN.add_fc(
input_size, relu=True,
cname=cname, name=layer_name(0))
self.NN.connect_node(input_node, l_in)
for i in range(1, hidden_layer):
# hidden_layer times, start with 1
l_out = self.NN.add_fc(
hidden_size, relu=True,
cname=cname, name=layer_name(i))
self.NN.connect_node(l_in, l_out)
l_in = l_out
output_node = self.NN.add_fc(
hidden_size, relu=False,
cname=cname, name=layer_name(hidden_layer))
self.NN.connect_node(l_in, output_node)
return input_node, output_node
def build_regress(self, output_layer=0, output_size=None,
target_layer=None, name=None):
"""
build a graph with regress.
:param output_layer: output layer
:param output_size: output layer size
:param target_layer: target layer
:param name: regress layer name
:return: regress layer
"""
if target_layer is None:
print('without target layer, nothing to do')
return
regress = self.NN.add_regress(output_size,
self.learning_rate, name)
self.NN.connect_node(target_layer, regress)
self.NN.connect_node(output_layer, regress)
self.NN.build_graph(end_node=regress)
return regress
def build_graph(self, output_layer=0, output_size=None):
"""
build a graph about generate output layer.
:param output_layer: output layer
:param output_size: output layer size
:return: None
"""
self.NN.build_graph(end_node=output_layer,
end_size=output_size)
def init_graph(self, collections=None):
"""
when all graph built, run this
:param collections: collections name list if have collection.
:return: collections can be eval.
"""
c = None
self.NN.init_graph() # will not display collection part
if collections is not None:
c = self.NN.add_collection(collections)
return c
def eval_graph(self, raw_node, raw_feed=None):
"""
eval node in graph.
:param raw_node: {node: [node content key]}
:param raw_feed: {feed node: {feed node content: feed value}}
:return: node result
"""
return self.NN.eval(raw_node, raw_feed)
def regress_graph(self, regress_node, raw_feed=None):
"""
calculate regress in graph.
:param regress_node: regress node
:param raw_feed: {feed node: {feed node content: feed value}}
:return: None
"""
_, cost_value = self.NN.eval(
{regress_node: [None, 'loss']}, raw_feed)
self.cost.append(cost_value)
return
def show_regress(self):
self.cost.show()
return
|
kelifrisk/justforfun
|
python/QLearning/DQN/QLearning.py
|
Python
|
mit
| 5,343
|
#!/usr/bin/env python3
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: Sajjad "JJ" Arshad (sajjadium)
from os.path import join
import json
import os
import random
import shlex
import string
import subprocess
import sys
import time
import base64
ADB_PORT = int(random.random() * 60000 + 5000)
EMULATOR_PORT = ADB_PORT + 1
EXPLOIT_TIME_SECS = 30
APK_FILE = "/challenge/app.apk"
FLAG_FILE = "/challenge/flag"
HOME = "/home/user"
ENV = {}
ENV.update(os.environ)
ENV.update({
"ANDROID_ADB_SERVER_PORT": "{}".format(ADB_PORT),
"ANDROID_SERIAL": "emulator-{}".format(EMULATOR_PORT),
"ANDROID_SDK_ROOT": "/opt/android/sdk",
"ANDROID_SDK_HOME": HOME,
"ANDROID_PREFS_ROOT": HOME,
"ANDROID_EMULATOR_HOME": HOME + "/.android",
"ANDROID_AVD_HOME": HOME + "/.android/avd",
"JAVA_HOME": "/usr/lib/jvm/java-11-openjdk-amd64",
"PATH": "/opt/android/sdk/cmdline-tools/latest/bin:/opt/android/sdk/emulator:/opt/android/sdk/platform-tools:/bin:/usr/bin:" + os.environ.get("PATH", "")
})
def print_to_user(message):
print(message)
sys.stdout.flush()
def setup_emulator():
subprocess.call(
"avdmanager" +
" create avd" +
" --name 'pixel_4_xl_api_30'" +
" --abi 'google_apis/x86_64'" +
" --package 'system-images;android-30;google_apis;x86_64'" +
" --device pixel_4_xl" +
" --force" +
" > /dev/null 2> /dev/null",
env=ENV,
close_fds=True,
shell=True)
return subprocess.Popen(
"emulator" +
" -avd pixel_4_xl_api_30" +
" -no-cache" +
" -no-snapstorage" +
" -no-snapshot-save" +
" -no-snapshot-load" +
" -no-audio" +
" -no-window" +
" -no-snapshot" +
" -no-boot-anim" +
" -wipe-data" +
" -accel on" +
" -netdelay none" +
" -no-sim" +
" -netspeed full" +
" -delay-adb" +
" -port {}".format(EMULATOR_PORT) +
" > /dev/null 2> /dev/null ",
env=ENV,
close_fds=True,
shell=True)
def adb(args, capture_output=True):
return subprocess.run(
"adb {} 2> /dev/null".format(" ".join(args)),
env=ENV,
shell=True,
close_fds=True,
capture_output=capture_output).stdout
def adb_install(apk):
adb(["install", "-r", apk])
def adb_activity(activity):
adb(["shell", "am", "start", "-W", "-n", activity])
def adb_logs():
logs = adb(["logcat", "-d", "-s", "TriDroid"], True)
for log in logs.decode("utf-8").strip().split("\n"):
print_to_user(log)
def adb_broadcast(action, extras=None):
args = ["shell", "am", "broadcast", "-a", action]
if extras:
for key in extras:
args += ["-e", key, extras[key]]
adb(args)
print_to_user("""
Welcome to TriDroid, the Triangle of Android:
/\\
DEX / \\ Web
(Java & Kotlin) / \\ (HTML & JS)
/ \\
/________\\
Native (C & C++)
""")
print_to_user("Preparing TriDroid. This may take a while ...\n")
emulator = setup_emulator()
adb(["wait-for-device"])
adb_install(APK_FILE)
adb_activity("com.google.ctf.pwn.tridroid/.MainActivity")
with open(FLAG_FILE, "r") as f:
adb_broadcast("com.google.ctf.pwn.tridroid.SET_FLAG", extras = {
"data": base64.b64encode(f.read().encode()).decode()
})
print_to_user("Please enter your name encoded in base64:")
name = sys.stdin.readline().strip()
adb_broadcast("com.google.ctf.pwn.tridroid.SET_NAME", extras = {
"data": name
})
print_to_user("Thank you! Check out the logs. This may take a while ...\n")
time.sleep(EXPLOIT_TIME_SECS)
adb_logs()
emulator.kill()
|
google/google-ctf
|
2021/quals/pwn-tridroid/attachments/server.py
|
Python
|
apache-2.0
| 4,265
|
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
def get_absolute_url(self):
return '/views/authors/%s/' % self.id
@python_2_unicode_compatible
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
author = models.ForeignKey(Author)
date_created = models.DateTimeField()
def __str__(self):
return self.title
|
atruberg/django-custom
|
tests/contenttypes_tests/models.py
|
Python
|
bsd-3-clause
| 644
|
"""Extension to execute code outside the Python shell window.
This adds the following commands:
- Check module does a full syntax check of the current module.
It also runs the tabnanny to catch any inconsistent tabs.
- Run module executes the module's code in the __main__ namespace. The window
must have been saved previously. The module is added to sys.modules, and is
also added to the __main__ namespace.
XXX GvR Redesign this interface (yet again) as follows:
- Present a dialog box for ``Run Module''
- Allow specify command line arguments in the dialog box
"""
import os
import tabnanny
import tokenize
import tkinter.messagebox as tkMessageBox
from idlelib import PyShell
from idlelib.configHandler import idleConf
from idlelib import macosxSupport
indent_message = """Error: Inconsistent indentation detected!
1) Your indentation is outright incorrect (easy to fix), OR
2) Your indentation mixes tabs and spaces.
To fix case 2, change all tabs to spaces by using Edit->Select All followed \
by Format->Untabify Region and specify the number of columns used by each tab.
"""
class ScriptBinding:
menudefs = [
('run', [None,
('Check Module', '<<check-module>>'),
('Run Module', '<<run-module>>'), ]), ]
def __init__(self, editwin):
self.editwin = editwin
# Provide instance variables referenced by Debugger
# XXX This should be done differently
self.flist = self.editwin.flist
self.root = self.editwin.root
if macosxSupport.isCocoaTk():
self.editwin.text_frame.bind('<<run-module-event-2>>', self._run_module_event)
def check_module_event(self, event):
filename = self.getfilename()
if not filename:
return 'break'
if not self.checksyntax(filename):
return 'break'
if not self.tabnanny(filename):
return 'break'
def tabnanny(self, filename):
# XXX: tabnanny should work on binary files as well
with tokenize.open(filename) as f:
try:
tabnanny.process_tokens(tokenize.generate_tokens(f.readline))
except tokenize.TokenError as msg:
msgtxt, (lineno, start) = msg.args
self.editwin.gotoline(lineno)
self.errorbox("Tabnanny Tokenizing Error",
"Token Error: %s" % msgtxt)
return False
except tabnanny.NannyNag as nag:
# The error messages from tabnanny are too confusing...
self.editwin.gotoline(nag.get_lineno())
self.errorbox("Tab/space error", indent_message)
return False
return True
def checksyntax(self, filename):
self.shell = shell = self.flist.open_shell()
saved_stream = shell.get_warning_stream()
shell.set_warning_stream(shell.stderr)
with open(filename, 'rb') as f:
source = f.read()
if b'\r' in source:
source = source.replace(b'\r\n', b'\n')
source = source.replace(b'\r', b'\n')
if source and source[-1] != ord(b'\n'):
source = source + b'\n'
editwin = self.editwin
text = editwin.text
text.tag_remove("ERROR", "1.0", "end")
try:
# If successful, return the compiled code
return compile(source, filename, "exec")
except (SyntaxError, OverflowError, ValueError) as value:
msg = getattr(value, 'msg', '') or value or "<no detail available>"
lineno = getattr(value, 'lineno', '') or 1
offset = getattr(value, 'offset', '') or 0
if offset == 0:
lineno += 1 #mark end of offending line
pos = "0.0 + %d lines + %d chars" % (lineno-1, offset-1)
editwin.colorize_syntax_error(text, pos)
self.errorbox("SyntaxError", "%-20s" % msg)
return False
finally:
shell.set_warning_stream(saved_stream)
def run_module_event(self, event):
if macosxSupport.isCocoaTk():
# Tk-Cocoa in MacOSX is broken until at least
# Tk 8.5.9, and without this rather
# crude workaround IDLE would hang when a user
# tries to run a module using the keyboard shortcut
# (the menu item works fine).
self.editwin.text_frame.after(200,
lambda: self.editwin.text_frame.event_generate('<<run-module-event-2>>'))
return 'break'
else:
return self._run_module_event(event)
def _run_module_event(self, event):
"""Run the module after setting up the environment.
First check the syntax. If OK, make sure the shell is active and
then transfer the arguments, set the run environment's working
directory to the directory of the module being executed and also
add that directory to its sys.path if not already included.
"""
filename = self.getfilename()
if not filename:
return 'break'
code = self.checksyntax(filename)
if not code:
return 'break'
if not self.tabnanny(filename):
return 'break'
interp = self.shell.interp
if PyShell.use_subprocess:
interp.restart_subprocess(with_cwd=False, filename=
self.editwin._filename_to_unicode(filename))
dirname = os.path.dirname(filename)
# XXX Too often this discards arguments the user just set...
interp.runcommand("""if 1:
__file__ = {filename!r}
import sys as _sys
from os.path import basename as _basename
if (not _sys.argv or
_basename(_sys.argv[0]) != _basename(__file__)):
_sys.argv = [__file__]
import os as _os
_os.chdir({dirname!r})
del _sys, _basename, _os
\n""".format(filename=filename, dirname=dirname))
interp.prepend_syspath(filename)
# XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
# go to __stderr__. With subprocess, they go to the shell.
# Need to change streams in PyShell.ModifiedInterpreter.
interp.runcode(code)
return 'break'
def getfilename(self):
"""Get source filename. If not saved, offer to save (or create) file
The debugger requires a source file. Make sure there is one, and that
the current version of the source buffer has been saved. If the user
declines to save or cancels the Save As dialog, return None.
If the user has configured IDLE for Autosave, the file will be
silently saved if it already exists and is dirty.
"""
filename = self.editwin.io.filename
if not self.editwin.get_saved():
autosave = idleConf.GetOption('main', 'General',
'autosave', type='bool')
if autosave and filename:
self.editwin.io.save(None)
else:
confirm = self.ask_save_dialog()
self.editwin.text.focus_set()
if confirm:
self.editwin.io.save(None)
filename = self.editwin.io.filename
else:
filename = None
return filename
def ask_save_dialog(self):
msg = "Source Must Be Saved\n" + 5*' ' + "OK to Save?"
confirm = tkMessageBox.askokcancel(title="Save Before Run or Check",
message=msg,
default=tkMessageBox.OK,
parent=self.editwin.text)
return confirm
def errorbox(self, title, message):
# XXX This should really be a function of EditorWindow...
tkMessageBox.showerror(title, message, parent=self.editwin.text)
self.editwin.text.focus_set()
|
Microvellum/Fluid-Designer
|
win64-vc/2.78/python/lib/idlelib/ScriptBinding.py
|
Python
|
gpl-3.0
| 8,061
|
"""Implements generic utilities for monitoring classes.
"""
import sys
import re
import subprocess
import urllib, urllib2
import socket
import telnetlib
__author__ = "Ali Onur Uyar"
__copyright__ = "Copyright 2011, Ali Onur Uyar"
__credits__ = []
__license__ = "GPL"
__version__ = "0.9.12"
__maintainer__ = "Ali Onur Uyar"
__email__ = "aouyar at gmail.com"
__status__ = "Development"
buffSize = 4096
timeoutHTTP = 10
def parse_value(val, parsebool=False):
"""Parse input string and return int, float or str depending on format.
@param val: Input string.
@param parsebool: If True parse yes / no, on / off as boolean.
@return: Value of type int, float or str.
"""
try:
return int(val)
except ValueError:
pass
try:
return float(val)
except:
pass
if parsebool:
if re.match('yes|on', str(val), re.IGNORECASE):
return True
elif re.match('no|off', str(val), re.IGNORECASE):
return False
return val
def safe_sum(seq):
"""Returns the sum of a sequence of numbers. Returns 0 for empty sequence
and None if any item is None.
@param seq: Sequence of numbers or None.
"""
if None in seq:
return None
else:
return sum(seq)
def socket_read(fp):
"""Buffered read from socket. Reads all data available from socket.
@fp: File pointer for socket.
@return: String of characters read from buffer.
"""
response = ''
oldlen = 0
newlen = 0
while True:
response += fp.read(buffSize)
newlen = len(response)
if newlen - oldlen == 0:
break
else:
oldlen = newlen
return response
def exec_command(args, env=None):
"""Convenience function that executes command and returns result.
@param args: Tuple of command and arguments.
@param env: Dictionary of environment variables.
(Environment is not modified if None.)
@return: Command output.
"""
try:
cmd = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=buffSize,
env=env)
except OSError, e:
raise Exception("Execution of command failed.\n",
" Command: %s\n Error: %s" % (' '.join(args), str(e)))
out, err = cmd.communicate(None)
if cmd.returncode != 0:
raise Exception("Execution of command failed with error code: %s\n%s\n"
% (cmd.returncode, err))
return out
def get_url(url, user=None, password=None, params=None, use_post=False):
if user is not None and password is not None:
pwdmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwdmgr.add_password(None, url, user, password)
auth_handler = urllib2.HTTPBasicAuthHandler(pwdmgr)
opener = urllib2.build_opener(auth_handler)
else:
opener = urllib2.build_opener()
if params is not None:
req_params = urllib.urlencode(params)
if use_post:
req_url = url
data = req_params
else:
req_url = "%s?%s" % (url, req_params)
data = None
else:
req_url = url
data = None
try:
if sys.version_info[:2] < (2,6):
resp = opener.open(req_url, data)
else:
resp = opener.open(req_url, data, timeoutHTTP)
except urllib2.URLError, e:
raise Exception("Retrieval of URL failed.\n"
" url: %s\n Error: %s" % (url, str(e)))
return socket_read(resp)
class NestedDict(dict):
"""Dictionary class facilitates creation of nested dictionaries.
This works:
NestedDict d
d[k1][k2][k3] ... = v
"""
def __getitem__(self, key):
"""x.__getitem__(y) <==> x[y]"""
try:
return dict.__getitem__(self, key)
except KeyError:
value = self[key] = type(self)()
return value
def set_nested(self, klist, value):
"""D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v"""
keys = list(klist)
if len(keys) > 0:
curr_dict = self
last_key = keys.pop()
for key in keys:
if not curr_dict.has_key(key) or not isinstance(curr_dict[key],
NestedDict):
curr_dict[key] = type(self)()
curr_dict = curr_dict[key]
curr_dict[last_key] = value
class SoftwareVersion(tuple):
"""Class for parsing, storing and comparing versions.
All standard operations for tuple class are supported.
"""
def __init__(self, version):
"""Initialize the new instance of class.
@param version: Version must either be a string or a tuple of integers
or strings representing integers.
Version strings must begin with integer numbers separated by dots and
may end with any string.
"""
self._versionstr = '.'.join([str(v) for v in self])
def __new__(cls, version):
"""Static method for creating a new instance which is a subclass of
immutable tuple type. Versions are parsed and stored as a tuple of
integers internally.
@param cls: Class
@param version: Version must either be a string or a tuple of integers
or strings representing integers.
Version strings must begin with integer numbers separated by dots and
may end with any string.
"""
if isinstance(version, basestring):
mobj = re.match('(?P<version>\d+(\.\d+)*)(?P<suffix>.*)$', version)
if mobj:
version = [int(i) for i in mobj.groupdict()['version'].split('.')]
return tuple.__new__(cls, version)
else:
raise ValueError('Invalid version string format.')
else:
try:
return tuple.__new__(cls, [int(v) for v in version])
except:
raise TypeError("Version must either be a string or an iterable"
" of integers.")
def __str__(self):
"""Returns string representation of version.
"""
return self._versionstr
class TableFilter:
"""Class for filtering rows of tables based on filters on values of columns.
The tables are represented as nested lists (list of lists of columns.)
"""
def __init__(self):
"""Initialize Filter."""
self._filters = {}
def registerFilter(self, column, patterns, is_regex=False,
ignore_case=False):
"""Register filter on a column of table.
@param column: The column name.
@param patterns: A single pattern or a list of patterns used for
matching column values.
@param is_regex: The patterns will be treated as regex if True, the
column values will be tested for equality with the
patterns otherwise.
@param ignore_case: Case insensitive matching will be used if True.
"""
if isinstance(patterns, basestring):
patt_list = (patterns,)
elif isinstance(patterns, (tuple, list)):
patt_list = list(patterns)
else:
raise ValueError("The patterns parameter must either be as string "
"or a tuple / list of strings.")
if is_regex:
if ignore_case:
flags = re.IGNORECASE
else:
flags = 0
patt_exprs = [re.compile(pattern, flags) for pattern in patt_list]
else:
if ignore_case:
patt_exprs = [pattern.lower() for pattern in patt_list]
else:
patt_exprs = patt_list
self._filters[column] = (patt_exprs, is_regex, ignore_case)
def unregisterFilter(self, column):
"""Unregister filter on a column of the table.
@param column: The column header.
"""
if self._filters.has_key(column):
del self._filters[column]
def registerFilters(self, **kwargs):
"""Register multiple filters at once.
@param **kwargs: Multiple filters are registered using keyword
variables. Each keyword must correspond to a field name
with an optional suffix:
field: Field equal to value or in list of
values.
field_ic: Field equal to value or in list of
values, using case insensitive
comparison.
field_regex: Field matches regex value or matches
with any regex in list of values.
field_ic_regex: Field matches regex value or matches
with any regex in list of values
using case insensitive match.
"""
for (key, patterns) in kwargs.items():
if key.endswith('_regex'):
col = key[:-len('_regex')]
is_regex = True
else:
col = key
is_regex = False
if col.endswith('_ic'):
col = col[:-len('_ic')]
ignore_case = True
else:
ignore_case = False
self.registerFilter(col, patterns, is_regex, ignore_case)
def applyFilters(self, headers, table):
"""Apply filter on ps command result.
@param headers: List of column headers.
@param table: Nested list of rows and columns.
@return: Nested list of rows and columns filtered using
registered filters.
"""
result = []
column_idxs = {}
for column in self._filters.keys():
try:
column_idxs[column] = headers.index(column)
except ValueError:
raise ValueError('Invalid column name %s in filter.' % column)
for row in table:
for (column, (patterns,
is_regex,
ignore_case)) in self._filters.items():
col_idx = column_idxs[column]
col_val = row[col_idx]
if is_regex:
for pattern in patterns:
if pattern.search(col_val):
break
else:
break
else:
if ignore_case:
col_val = col_val.lower()
if col_val in patterns:
pass
else:
break
else:
result.append(row)
return result
class Telnet(telnetlib.Telnet):
__doc__ = telnetlib.Telnet.__doc__
def __init__(self, host=None, port=0, socket_file=None,
timeout=socket.getdefaulttimeout()):
"""Constructor.
When called without arguments, create an unconnected instance.
With a host argument, it connects the instance using TCP; port number
and timeout are optional, socket_file must be None.
With a socket_file argument, it connects the instance using
named socket; timeout is optional and host must be None.
"""
telnetlib.Telnet.__init__(self, timeout=timeout)
if host is not None or socket_file is not None:
self.open(host, port, socket_file, timeout=timeout)
def open(self, host=None, port=0, socket_file=None,
timeout=socket.getdefaulttimeout()):
"""Connect to a host.
With a host argument, it connects the instance using TCP; port number
and timeout are optional, socket_file must be None. The port number
defaults to the standard telnet port (23).
With a socket_file argument, it connects the instance using
named socket; timeout is optional and host must be None.
Don't try to reopen an already connected instance.
"""
self.socket_file = socket_file
if host is not None:
if sys.version_info[:2] >= (2,6):
telnetlib.Telnet.open(self, host, port, timeout)
else:
telnetlib.Telnet.open(self, host, port)
elif socket_file is not None:
self.eof = 0
self.host = host
self.port = port
self.timeout = timeout
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(timeout)
self.sock.connect(socket_file)
else:
raise TypeError("Either host or socket_file argument is required.")
|
aouyar/PyMunin
|
pysysinfo/util.py
|
Python
|
gpl-3.0
| 13,551
|
import base64
import glob
import os
import re
import threading
import urllib
import execjs
from concurrent.futures import ThreadPoolExecutor
from queue import Queue, Empty
from core.login import Login
from util.utils import HttpUtils
class Crawler(Login):
task_pool = Queue()
process_thread = None
book_id = 0
comic_id = "0"
comic_name = ""
root_url = "http://www.js518.net/"
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zh-TW;q=0.6,ja;q=0.5",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"DNT": "1",
"Host": "www.js518.net",
"If-Modified-Since": "Sun, 30 Aug 2020 07:32:53 GMT",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36"
}
@classmethod
def start(cls, book_id):
cls.book_id = book_id
cls.comic_id = re.match("(\d+)", book_id).group(1)
cls.parse_lvl_one()
@classmethod
def init_thread(cls):
if cls.process_thread is None:
cls.process_thread = threading.Thread(target=cls.process)
cls.process_thread.start()
@classmethod
def parse_lvl_one(cls):
if cls.book_id is None:
return
url = "http://www.js518.net/mohuanmanhua/%s/" % cls.book_id
retry = 0
while True:
resp = HttpUtils.get(url)
if resp is not None:
break
else:
retry += 1
assert retry < 5, "fail to query %s" % url
cls.comic_name = HttpUtils.get_content(resp, "title").strip()
links = HttpUtils.get_attrs(resp, "#mh-chapter-list-ol-0 a", "href")
titles = HttpUtils.get_contents(resp, "#mh-chapter-list-ol-0 a")
assert len(titles) == len(links)
cls.init_thread()
for index in range(len(titles)):
link = links[index]
title = titles[index].strip()
cls.parse_lvl_two((link, title))
cls.process_thread.join()
# code below should be useless if everything goes well
while not cls.task_pool.empty():
print("pool size = " + str(cls.task_pool.qsize()))
cls.init_thread()
cls.process_thread.join()
@classmethod
def parse_lvl_two(cls, info):
link = info[0]
title = info[1]
# create folder once
folder_name = "output/" + cls.comic_name + "/" + title
if not os.path.exists(folder_name):
os.makedirs(folder_name, exist_ok=True)
# path_file_number = len(glob.glob(pathname=folder_name + '/*'))
# if path_file_number == image_number:
# print("下载完毕:" + title)
# # already downloaded all
# return
print("开始下载: " + title)
index = 0
query_url = cls.root_url + link
retry = 0
while True:
content = HttpUtils.get(query_url)
if content is not None:
break
else:
retry += 1
assert retry < 5, "fail to query %s" % query_url
if content.text.strip() == "":
print("url: " + query_url)
print("get wrong data: \"" + content.text.strip() + "\"")
print("fail to parse image key, %s-%d" % (title, index))
else:
url_encoded = re.search("qTcms_S_m_murl_e.*=.*(\".*?\");", content.text).group(1)
image_url_list = base64.b64decode(url_encoded).decode("utf-8").split("$qingtiandy$")
assert len(image_url_list) > 0
index = 1
for image_url in image_url_list:
file_name = image_url.split("/")[-1]
file_path = "%s/%03d_%s" % (folder_name, index, file_name)
if "http" not in image_url:
image_url = "http://j.aiwenwo.net" + image_url
cls.task_pool.put([file_path, image_url, 0])
index += 1
@classmethod
def process(cls):
print("#### process thread started")
with ThreadPoolExecutor(max_workers=50) as executor:
while True:
try:
# queue timeout should be greater than the download timeout
item = cls.task_pool.get(timeout=60)
executor.submit(cls.do_process, item)
except Empty as e:
print("#### queue timeout")
break
cls.process_thread = None
print("#### process thread stopped")
@classmethod
def do_process(cls, item):
path = item[0]
url = item[1]
retry = item[2]
if retry <= 5:
if not HttpUtils.download_file(url=url, dest_path=path):
item[2] += 1
cls.task_pool.put(item)
cls.init_thread()
else:
print("Exceed max retry time: " + path)
if __name__ == "__main__":
Crawler.start("10082")
|
AaronGeist/Llama
|
biz/js518.py
|
Python
|
gpl-3.0
| 5,174
|
###############################################################################
##
## Copyright (C) 2014-2015, New York University.
## Copyright (C) 2011-2014, NYU-Poly.
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "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 the New York University nor the names of its
## contributors 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 HOLDER 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."
##
###############################################################################
""" This file contains classes related to loading and saving a set of
connection objects to an XML file.
It defines the following
classes:
- ExtConnection
- DBConnection
- ExtConnectionList
"""
from __future__ import division
import os
import tempfile
import unittest
from vistrails.core.utils import VistrailsInternalError, abstract
from vistrails.core.utils.enum import enum
from vistrails.core.utils.uxml import named_elements, XMLWrapper
################################################################################
ConnectionType = enum('ConnectionType',
['DB', 'HTTP', 'Unknown'],
"Enumeration of Connection Types")
class ExtConnection(object):
"""Stores Information for an External Connection"""
parseDispatch = {}
def __init__(self, id=-1, name='', host='', type=ConnectionType.Unknown):
"""__init__(id: int, name: str, host: str, type: ConnectionType)
-> ExtConnection
It creates an external connection. Ignoring the connection type, every
connection should have at least a name, a hostname and an id """
self.id = id
self.name = name
self.host = host
self.type = type
def serialize(self, dom, element):
abstract()
@staticmethod
def parse(element):
type = str(element.getAttribute('type'))
return ExtConnection.parseDispatch[type](element)
class DBConnection(ExtConnection):
"""Stores Information for Database Connection """
def __init__(self, id=-1, name='', host='', port=0, user='', passwd='',
database='', dbtype=''):
"""__init__(id: int, name: str, host: str, port: int, username: str,
passwd: str, database: str, type:ConnectionType)->DBConnection
It creates a DBConnection Object
"""
ExtConnection.__init__(self, id, name, host, ConnectionType.DB)
self.port = port
self.user = user
self.passwd = passwd
self.database = database
self.dbtype = dbtype
def serialize(self, dom, element):
"""serialize(dom, element) -> None
Convert this object to an XML representation.
"""
conn = dom.createElement('connection')
conn.setAttribute('id', str(self.id))
conn.setAttribute('name', str(self.name))
conn.setAttribute('host', str(self.host))
conn.setAttribute('port',str(self.port))
conn.setAttribute('user', str(self.user))
conn.setAttribute('passwd', str(self.passwd))
conn.setAttribute('database', str(self.database))
conn.setAttribute('type', str(self.type))
conn.setAttribute('dbtype', str(self.dbtype))
element.appendChild(conn)
def __str__(self):
""" __str__() -> str - Writes itself as a string """
return """<<id= '%s' name='%s' type='%s' host='%s'
user='%s' database='%s' dbtype='%s'>>""" % (
self.id,
self.name,
self.type,
self.host,
self.user,
self.database,
self.dbtype)
@staticmethod
def parse(element):
""" parse(element) -> DBConnection
Parse an XML object representing a DBConnection and returns a
DBConnection object.
"""
conn = DBConnection()
conn.type = ConnectionType.DB
conn.id = int(element.getAttribute('id'))
conn.name = str(element.getAttribute('name'))
conn.host = str(element.getAttribute('host'))
conn.port = int(element.getAttribute('port'))
conn.user = str(element.getAttribute('user'))
conn.passwd = str(element.getAttribute('passwd'))
conn.database = str(element.getAttribute('database'))
conn.dbtype = str(element.getAttribute('dbtype'))
return conn
def __eq__(self, other):
""" __eq__(other: DBConnection) -> boolean
Returns True if self and other have the same attributes. Used by ==
operator.
"""
if other is None:
return False
if self.type != other.type:
return False
if self.id != other.id:
return False
if self.name != other.name:
return False
if self.host != other.host:
return False
if self.port != other.port:
return False
if self.user != other.user:
return False
if self.passwd != other.passwd:
return False
if self.database != other.database:
return False
if self.dbtype != other.dbtype:
return False
return True
def __ne__(self, other):
return not (self == other)
ExtConnection.parseDispatch[str(ConnectionType.DB)] = DBConnection.parse
class ExtConnectionList(XMLWrapper):
"""Class to store and manage a list of connections.
"""
_instance = None
@staticmethod
def getInstance(*args, **kwargs):
if ExtConnectionList._instance is None:
obj = ExtConnectionList(*args, **kwargs)
ExtConnectionList._instance = obj
return ExtConnectionList._instance
def __init__(self, filename=''):
""" __init__() -> ExtConnectionList """
if not ExtConnectionList._instance:
self.__connections = {}
self.changed = False
self.current_id = 1
self.filename = filename
self.load_connections()
ExtConnectionList._instance = self
else:
raise RuntimeError, 'Only one instance of ExtConnectionList is \
allowed!'
def load_connections(self):
"""load_connections()-> None
Load connections from its internal filename
"""
if os.path.exists(self.filename):
self.parse(self.filename)
def add_connection(self, conn):
"""add_connection(conn: ExtConnection) -> None
Adds a connection to the list
"""
if self.__connections.has_key(conn.id):
msg = "External Connection '%s' with repeated id" % conn.name
raise VistrailsInternalError(msg)
self.__connections[conn.id] = conn
self.current_id = max(self.current_id, conn.id+1)
self.serialize()
def get_connection(self, id):
"""get_connection(id: int) -> ExtConnection
Returns connection object associated with id
"""
if self.__connections.has_key(id):
return self.__connections[id]
else:
return None
def has_connection(self, id):
"""has_connection(id: int) -> Boolean
Returns True if connection with id exists """
return self.__connections.has_key(id)
def find_db_connection(self, host, port, db):
"""find_db_connection(host: str, port: int, db: str) -> id
Returns the id of the first connection that matches the provided
parameters. It will return -1 if not found
"""
for conn in self.__connections.itervalues():
if conn.host == host and conn.port == port and conn.database == db:
return conn.id
return -1
def set_connection(self, id, conn):
"""set_connection(id: int, conn: ExtConnection)- > None
Updates the connection with id to be conn
"""
if self.__connections.has_key(id):
self.__connections[id] = conn
self.serialize()
def remove_connection(self, id):
"""remove_connection(id: int) -> None
Remove connection with id 'id'
"""
if self.__connections.has_key(id):
del self.__connections[id]
self.serialize()
def clear(self):
""" clear() -> None
Remove current connections """
self.__connections.clear()
self.current_id = 1
def count(self):
"""count() -> int - Returns the number of connections """
return len(self.__connections)
def items(self):
""" items() -> - Returns the connections """
return self.__connections.items()
def parse(self, filename):
"""parse(filename: str) -> None
Loads a list of connections from a XML file, appending it to
self.__connections.
"""
self.open_file(filename)
root = self.dom.documentElement
for element in named_elements(root, 'connection'):
self.add_connection(ExtConnection.parse(element))
self.refresh_current_id()
def serialize(self):
"""serialize(filename:str) -> None
Writes connection list to given filename.
"""
dom = self.create_document('connections')
root = dom.documentElement
for conn in self.__connections.values():
conn.serialize(dom, root)
self.write_document(root, self.filename)
def refresh_current_id(self):
"""refresh_current_id() -> None
Recomputes the next unused id from scratch
"""
self.current_id = max([0] + self.__connections.keys()) + 1
def get_fresh_id(self):
"""get_fresh_id() -> int - Returns an unused id. """
return self.current_id
###############################################################################
class TestConnectionList(unittest.TestCase):
def test1(self):
""" Exercising writing and reading a file """
fd, filename = tempfile.mkstemp(prefix='vt_', suffix='_connections.xml')
os.close(fd)
try:
conns = ExtConnectionList.getInstance()
conns.filename = filename
conns.clear()
conn = DBConnection()
conn.id = 1
conn.name = 'test'
conn.host = 'somehost.com'
conn.port = 1234
conn.user = 'nobody'
conn.passwd = '123'
conn.database = 'anydatabase'
conn.dbtype = 'MySQL'
conns.add_connection(conn)
#reading it again
conns.clear()
self.assertEquals(conns.count(),0)
conns.load_connections()
self.assertEquals(conns.count(),1)
newconn = conns.get_connection(1)
self.assertEqual(conn, newconn)
finally:
#remove created file
os.unlink(filename)
if __name__ == '__main__':
unittest.main()
|
hjanime/VisTrails
|
vistrails/core/external_connection.py
|
Python
|
bsd-3-clause
| 12,398
|
from jsonrpc import ServiceProxy
access = ServiceProxy("http://127.0.0.1:13144")
pwd = raw_input("Enter old wallet passphrase: ")
pwd2 = raw_input("Enter new wallet passphrase: ")
access.walletpassphrasechange(pwd, pwd2)
|
LiveChains/Live-Coin
|
contrib/wallettools/walletchangepass.py
|
Python
|
mit
| 220
|
#!/usr/bin/env python
import os
import sys
from setuptools import find_packages, setup
EXCLUDE_FROM_PACKAGES = ['nucleo.migrations', 'nucleo.fixtures']
version = __import__('nucleo').__version__
def get_required():
required_txt = os.path.join(os.path.dirname(__file__), 'requirements.txt')
return open(required_txt).readlines()
extras = {
'develop': [
'nose',
]
}
setup(
name='nucleo',
version=version,
url='https://github.com/Naible/django-nucleo/',
author='Naible',
author_email='admin@naible.com',
description=('A django app for building social networks.'),
license='GPLv3+',
packages=find_packages(exclude=EXCLUDE_FROM_PACKAGES),
include_package_data=True,
install_requires=get_required(),
extras_require=extras,
zip_safe=False,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
# 'Programming Language :: Python :: 3',
# 'Programming Language :: Python :: 3.3',
# 'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Internet :: WWW/HTTP :: WSGI',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Naible/django-nucleo
|
setup.py
|
Python
|
gpl-3.0
| 1,725
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# --- BEGIN_HEADER ---
#
# ssh - remote command wrappers using ssh/scp
# Copyright (C) 2003-2014 The MiG Project lead by Brian Vinter
#
# This file is part of MiG.
#
# MiG 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 2 of the License, or
# (at your option) any later version.
#
# MiG 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# -- END_HEADER ---
#
"""SSH based remote operations"""
import base64
import os
import paramiko
import tempfile
import StringIO
from shared.conf import get_resource_exe, get_configuration_object
def parse_pub_key(public_key):
"""Parse public_key string to paramiko key.
Throws exception if key is broken.
"""
public_key_elms = public_key.split(' ')
# Either we have 'from' or 'ssh-' as first element
if len(public_key_elms) > 0 and \
public_key_elms[0].startswith('ssh-'):
ssh_type_idx = 0
elif len(public_key_elms) > 1 and \
public_key_elms[1].startwith('ssh-'):
ssh_type_idx = 1
else:
msg = 'Invalid ssh public key: (%s)' % public_key
raise ValueError(msg)
head, tail = public_key.split(' ')[ssh_type_idx:2+ssh_type_idx]
bits = base64.decodestring(tail)
msg = paramiko.Message(bits)
if head == 'ssh-rsa':
parse_key = paramiko.RSAKey
elif head == 'ssh-dss':
parse_key = paramiko.DSSKey
else:
# Try RSA for unknown key types
parse_key = paramiko.RSAKey
return parse_key(msg)
def default_ssh_options():
"""Default list of options for ssh connections"""
options = []
options.append('-o BatchMode=yes')
# We need fault tolerance but can't block e.g. grid_script for long
options.append('-o ConnectionAttempts=2')
options.append('-o ConnectTimeout=10')
return options
def copy_file_to_resource(
filename,
dest_path,
resource_config,
logger,
):
"""Copy filename to dest_path relative to resource home on resource
using scp.
"""
configuration = get_configuration_object()
multiplex = '0'
if resource_config.has_key('SSHMULTIPLEX'):
multiplex = str(resource_config['SSHMULTIPLEX'])
hostkey = resource_config['HOSTKEY']
host = resource_config['HOSTURL']
identifier = resource_config['HOSTIDENTIFIER']
unique_id = '%s.%s' % (host, identifier)
res_dir = os.path.join(configuration.resource_home, unique_id)
port = resource_config['SSHPORT']
user = resource_config['MIGUSER']
if dest_path.startswith(os.sep):
logger.warning('copy_file_to_resource: force relative dest path!'
)
dest_path = dest_path.lstrip(os.sep)
# create known-hosts file with only the resources hostkey (could
# this be avoided and just passed as an argument?)
try:
# Securely open a temporary file in resource dir
# Please note that mkstemp uses os.open() style rather
# than open()
(filehandle, key_path) = tempfile.mkstemp(dir=res_dir,
text=True)
os.write(filehandle, hostkey)
os.close(filehandle)
logger.debug('single_known_hosts for %s written in %s' % (host,
key_path))
logger.debug('value %s' % hostkey)
except Exception, err:
logger.error('could not write single_known_hosts %s (%s)'
% (host, err))
options = default_ssh_options()
if '0' != multiplex:
options.append('-o ControlPath=%s/ssh-multiplexing' % res_dir)
options.append('-o Port=%s' % port)
options.append('-o StrictHostKeyChecking=yes')
options.append('-o CheckHostIP=yes')
if hostkey:
options.append('-o UserKnownHostsFile=' + key_path)
command = 'scp %s %s %s@%s:%s >> /dev/null 2>> %s/scp.err' % (
' '.join(options),
filename,
user,
host,
os.path.join(resource_config['RESOURCEHOME'], dest_path),
configuration.log_dir,
)
logger.debug(command)
status = os.system(command) >> 8
# Remove temp file no matter what command returned
try:
os.remove(key_path)
except Exception, err:
logger.error('could not remove %s (%s)' % (key_path, err))
if status != 0:
# File was not sent!! Take action
logger.error(command)
logger.error('scp return code: %s %s' % (status, host))
return False
logger.info('scp ok %s' % host)
return True
def copy_file_to_exe(
local_filename,
dest_path,
resource_config,
exe_name,
logger,
):
"""Copy local_filename to dest_path relative to execution_dir on
exe_name. This needs to go through the resource front end using scp
and the copy method to the exe depends on the shared fs setting.
"""
msg = ''
unique_resource_name = resource_config['HOSTURL'] + '.'\
+ resource_config['HOSTIDENTIFIER']
(status, exe) = get_resource_exe(resource_config, exe_name, logger)
if not status:
msg = "No EXE config for: '" + unique_resource_name + "' EXE: '"\
+ exe_name + "'"
return (False, msg)
if dest_path.startswith(os.sep):
logger.warning('copy_file_to_exe: force relative dest path!')
dest_path = dest_path.lstrip(os.sep)
# copy file to frontend
copy_attempts = 3
for attempt in range(copy_attempts):
copy_status = copy_file_to_resource(local_filename, dest_path,
resource_config, logger)
if not copy_status:
logger.warning('scp of file failed in attempt %d of %d'
% (attempt, copy_attempts))
else:
break
# Remove temporary file no matter what scp returned
try:
os.remove(local_filename)
except Exception, err:
logger.error('Could not remove %s (%s)' % (local_filename, err))
if copy_status:
msg += 'scp of file was successful!\n'
logger.info('scp of file was successful!')
else:
msg += 'scp of file was NOT successful!\n'
logger.error('scp of file was NOT successful!')
return (False, msg)
# copy file to exe
if exe.has_key('shared_fs') and exe['shared_fs']:
ssh_command = 'cp '\
+ os.path.join(resource_config['RESOURCEHOME'], dest_path)\
+ ' ' + exe['execution_dir']
else:
# We do not have exe host keys and don't really care about auth there
ssh_command = 'scp %s %s %s@%s:%s'\
% (' '.join(default_ssh_options()),
os.path.join(resource_config['RESOURCEHOME'],
dest_path), exe['execution_user'], exe['execution_node'
], exe['execution_dir'])
copy_attempts = 3
for attempt in range(copy_attempts):
(status, executed_command) = execute_on_resource(ssh_command,
False, resource_config, logger)
if status != 0:
logger.warning('copy of file to exe failed (%d) in attempt %d of %d'
% (status, attempt, copy_attempts))
else:
break
msg += executed_command + '\n'
if 0 != status:
logger.error('file not copied to exe!')
msg += 'file not copied to exe!\n'
return (False, msg)
else:
logger.info('file copied to exe')
msg += 'file copied to exe\n'
return (True, '')
def execute_on_resource(
command,
background,
resource_config,
logger,
):
"""Execute command on resource"""
configuration = get_configuration_object()
hostkey = resource_config['HOSTKEY']
host = resource_config['HOSTURL']
port = resource_config['SSHPORT']
user = resource_config['MIGUSER']
job_type = 'batch'
if resource_config.has_key('JOBTYPE'):
job_type = resource_config['JOBTYPE']
multiplex = '0'
if resource_config.has_key('SSHMULTIPLEX'):
multiplex = str(resource_config['SSHMULTIPLEX'])
# Use manually added SSHMULTIPLEXMASTER variable to only run master
# from sessions initiated by grid_sshmux.py: There's a race in the
# handling of ControlMaster=auto in openssh-4.3 resulting in error:
# ControlSocket $SOCKET already exists
# (see http://article.gmane.org/gmane.network.openssh.devel/13839)
multiplex_master = False
if resource_config.has_key('SSHMULTIPLEXMASTER'):
multiplex_master = bool(resource_config['SSHMULTIPLEXMASTER'])
identifier = resource_config['HOSTIDENTIFIER']
unique_id = '%s.%s' % (host, identifier)
res_dir = os.path.join(configuration.resource_home, unique_id)
# fname should be unique to avoid race conditions, since several
# cgi-scripts may run at the same time due to a multi process
# or multi thread web server
try:
# Securely open a temporary file in resource dir
# Please note that mkstemp uses os.open() style rather
# than open()
(filehandle, key_path) = tempfile.mkstemp(dir=res_dir,
text=True)
os.write(filehandle, hostkey)
os.close(filehandle)
logger.debug('wrote hostkey %s to %s' % (hostkey, key_path))
except Exception, err:
logger.error('could not write tmp host key file (%s)' % err)
return (-1, '')
options = default_ssh_options()
# Only enable X forwarding for interactive resources (i.e. job_type
# 'interactive' or 'all')
if 'batch' != job_type.lower():
options.append('-X')
options.append('-o Port=%s' % port)
options.append('-o CheckHostIP=yes')
options.append('-o StrictHostKeyChecking=yes')
if hostkey:
options.append('-o UserKnownHostsFile=%s' % key_path)
if '0' != multiplex:
options.append('-o ControlPath=%s/ssh-multiplexing' % res_dir)
# Only open a new control socket if explicitly told so:
# All other invocations will reuse it if possible.
if multiplex_master:
options.append('-o ControlMaster=yes')
batch = []
batch.append('1> /dev/null')
batch.append('2> /dev/null')
if background:
batch.append('&')
# IMPORTANT: careful with the ssh_command line!
# removing explicit bash or changing quotes breaks resource management
ssh_command = 'ssh %s %s@%s "bash -c \'%s %s\'"'\
% (' '.join(options), user, host, command, ' '.join(batch))
logger.debug('running command: %s' % ssh_command)
status = os.system(ssh_command) >> 8
logger.debug('cleaning up after command')
# Remove temp file no matter what ssh command returned
try:
os.remove(key_path)
except Exception, err:
logger.error('Could not remove hostkey file %s: %s'
% (key_path, err))
if 0 != status:
# Command was not executed with return code 0!! Take action
logger.error('%s EXITED WITH STATUS: %s' % (ssh_command,
status))
return (status, ssh_command)
logger.debug('Remote execution ok: %s' % ssh_command)
return (status, ssh_command)
def execute_on_exe(
command,
background,
resource_config,
exe_config,
logger,
):
"""Execute command (through resource) on exe"""
node = exe_config['execution_node']
user = exe_config['execution_user']
options = default_ssh_options()
options.append('-X')
# This command should already be properly escaped by the apostrophes
# in the execute_on_resource call
ssh_command = "ssh %s %s@%s %s" % (' '.join(options), user,
node, command)
logger.debug(ssh_command)
return execute_on_resource(ssh_command, background,
resource_config, logger)
def execute_on_store(
command,
background,
resource_config,
store_config,
logger,
):
"""Execute command (through resource) on store"""
node = store_config['storage_node']
user = store_config['storage_user']
options = default_ssh_options()
options.append('-X')
# This command should already be properly escaped by the apostrophes
# in the execute_on_resource call
ssh_command = "ssh %s %s@%s %s" % (' '.join(options), user,
node, command)
logger.debug(ssh_command)
return execute_on_resource(ssh_command, background,
resource_config, logger)
def execute_remote_ssh(
remote_port,
remote_hostkey,
remote_username,
remote_hostname,
ssh_command,
logger,
ssh_background,
resource_dir='/tmp',
):
"""Wrap old style ssh calls to use new version"""
resource_config = {
'SSHPORT': remote_port,
'HOSTKEY': remote_hostkey,
'MIGUSER': remote_username,
'HOSTURL': remote_hostname,
}
return execute_on_resource(ssh_command, ssh_background,
resource_config, logger)
def generate_ssh_rsa_key_pair(size=2048, public_key_prefix='', public_key_postfix=''):
"""Generates ssh rsa key pair"""
rsa_key = paramiko.RSAKey.generate(size)
string_io_obj = StringIO.StringIO()
rsa_key.write_private_key(string_io_obj)
private_key = string_io_obj.getvalue()
public_key = ("%s ssh-rsa %s %s" % (public_key_prefix, rsa_key.get_base64(), public_key_postfix)).strip()
return (private_key, public_key)
|
heromod/migrid
|
mig/shared/ssh.py
|
Python
|
gpl-2.0
| 13,910
|
# -*- coding: utf-8 -*-
#
# hl_api_types.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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 2 of the License, or
# (at your option) any later version.
#
# NEST 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with NEST. If not, see <http://www.gnu.org/licenses/>.
"""
Classes defining the different PyNEST types
"""
from ..ll_api import *
from .. import pynestkernel as kernel
from .hl_api_helper import *
from .hl_api_simulation import GetKernelStatus
import numpy
import json
try:
import pandas
HAVE_PANDAS = True
except ImportError:
HAVE_PANDAS = False
__all__ = [
'CreateParameter',
'Mask',
'NodeCollection',
'Parameter',
'serializable',
'SynapseCollection',
'to_json',
]
def CreateParameter(parametertype, specs):
"""
Create a parameter.
Parameters
----------
parametertype : string
Parameter type with or without distance dependency.
Can be one of the following: 'constant', 'linear', 'exponential', 'gaussian', 'gaussian2D',
'uniform', 'normal', 'lognormal', 'distance', 'position'
specs : dict
Dictionary specifying the parameters of the provided
`parametertype`, see **Parameter types**.
Returns
-------
``Parameter``:
Object representing the parameter
Notes
-----
- Instead of using `CreateParameter` you can also use the various parametrizations embedded in NEST. See for
instance :py:func:`.uniform`.
**Parameter types**
Some available parameter types (`parametertype` parameter), their function and
acceptable keys for their corresponding specification dictionaries
* Constant
::
'constant' :
{'value' : float} # constant value
* Randomization
::
# random parameter with uniform distribution in [min,max)
'uniform' :
{'min' : float, # minimum value, default: 0.0
'max' : float} # maximum value, default: 1.0
# random parameter with normal distribution, optionally truncated
# to [min,max)
'normal':
{'mean' : float, # mean value, default: 0.0
'sigma': float, # standard deviation, default: 1.0
'min' : float, # minimum value, default: -inf
'max' : float} # maximum value, default: +inf
# random parameter with lognormal distribution,
# optionally truncated to [min,max)
'lognormal' :
{'mu' : float, # mean value of logarithm, default: 0.0
'sigma': float, # standard deviation of log, default: 1.0
'min' : float, # minimum value, default: -inf
'max' : float} # maximum value, default: +inf
"""
return sli_func('CreateParameter', {parametertype: specs})
class NodeCollectionIterator(object):
"""
Iterator class for `NodeCollection`.
Returns
-------
`NodeCollection`:
Single node ID `NodeCollection` of respective iteration.
"""
def __init__(self, nc):
self._nc = nc
self._increment = 0
def __iter__(self):
return self
def __next__(self):
if self._increment > len(self._nc) - 1:
raise StopIteration
val = sli_func('Take', self._nc._datum, [self._increment + (self._increment >= 0)])
self._increment += 1
return val
next = __next__ # Python2.x
class NodeCollection(object):
"""
Class for `NodeCollection`.
`NodeCollection` represents the nodes of a network. The class supports
iteration, concatenation, indexing, slicing, membership, length, conversion to and
from lists, test for membership, and test for equality. By using the
membership functions :py:func:`get()` and :py:func:`set()`, you can get and set desired
parameters.
A `NodeCollection` is created by the :py:func:`.Create` function, or by converting a
list of nodes to a `NodeCollection` with ``nest.NodeCollection(list)``.
If your nodes have spatial extent, use the member parameter ``spatial`` to get the spatial information.
Example
-------
::
import nest
nest.ResetKernel()
# Create NodeCollection representing nodes
nc = nest.Create('iaf_psc_alpha', 10)
# Convert from list
node_ids_in = [2, 4, 6, 8]
new_nc = nest.NodeCollection(node_ids_in)
# Convert to list
nc_list = nc.tolist()
# Concatenation
Enrns = nest.Create('aeif_cond_alpha', 600)
Inrns = nest.Create('iaf_psc_alpha', 400)
nrns = Enrns + Inrns
# Slicing and membership
print(new_nc[2])
print(new_nc[1:2])
6 in new_nc
"""
_datum = None
def __init__(self, data):
if isinstance(data, kernel.SLIDatum):
if data.dtype != "nodecollectiontype":
raise TypeError("Need NodeCollection Datum.")
self._datum = data
else:
# Data from user, must be converted to datum
# Data can be anything that can be converted to a NodeCollection,
# such as list, tuple, etc.
nc = sli_func('cvnodecollection', data)
self._datum = nc._datum
def __iter__(self):
return NodeCollectionIterator(self)
def __add__(self, other):
if not isinstance(other, NodeCollection):
raise NotImplementedError()
return sli_func('join', self._datum, other._datum)
def __getitem__(self, key):
if isinstance(key, slice):
if key.start is None:
start = 1
else:
start = key.start + 1 if key.start >= 0 else max(key.start, -1 * self.__len__())
if start > self.__len__():
raise IndexError('slice start value outside of the NodeCollection')
if key.stop is None:
stop = self.__len__()
else:
stop = min(key.stop, self.__len__()) if key.stop >= 0 else key.stop - 1
if abs(stop) > self.__len__():
raise IndexError('slice stop value outside of the NodeCollection')
step = 1 if key.step is None else key.step
if step < 1:
raise IndexError('slicing step for NodeCollection must be strictly positive')
return sli_func('Take', self._datum, [start, stop, step])
elif isinstance(key, (int, numpy.integer)):
if abs(key + (key >= 0)) > self.__len__():
raise IndexError('index value outside of the NodeCollection')
return sli_func('Take', self._datum, [key + (key >= 0)])
elif isinstance(key, (list, tuple)):
if len(key) == 0:
return NodeCollection([])
# Must check if elements are bool first, because bool inherits from int
if all(isinstance(x, bool) for x in key):
if len(key) != len(self):
raise IndexError('Bool index array must be the same length as NodeCollection')
np_key = numpy.array(key, dtype=numpy.bool)
# Checking that elements are not instances of bool too, because bool inherits from int
elif all(isinstance(x, int) and not isinstance(x, bool) for x in key):
np_key = numpy.array(key, dtype=numpy.uint64)
if len(numpy.unique(np_key)) != len(np_key):
raise ValueError('All node IDs in a NodeCollection have to be unique')
else:
raise TypeError('Indices must be integers or bools')
return take_array_index(self._datum, np_key)
elif isinstance(key, numpy.ndarray):
if len(key) == 0:
return NodeCollection([])
if len(key.shape) != 1:
raise TypeError('NumPy indices must one-dimensional')
is_booltype = numpy.issubdtype(key.dtype, numpy.dtype(bool).type)
if not (is_booltype or numpy.issubdtype(key.dtype, numpy.integer)):
raise TypeError('NumPy indices must be an array of integers or bools')
if is_booltype and len(key) != len(self):
raise IndexError('Bool index array must be the same length as NodeCollection')
if not is_booltype and len(numpy.unique(key)) != len(key):
raise ValueError('All node IDs in a NodeCollection have to be unique')
return take_array_index(self._datum, key)
else:
raise IndexError('only integers, slices, lists, tuples, and numpy arrays are valid indices')
def __contains__(self, node_id):
return sli_func('MemberQ', self._datum, node_id)
def __eq__(self, other):
if not isinstance(other, NodeCollection):
raise NotImplementedError('Cannot compare NodeCollection to {}'.format(type(other).__name__))
if self.__len__() != other.__len__():
return False
return sli_func('eq', self, other)
def __neq__(self, other):
if not isinstance(other, NodeCollection):
raise NotImplementedError()
return not self == other
def __len__(self):
return sli_func('size', self._datum)
def __str__(self):
return sli_func('pcvs', self._datum)
def __repr__(self):
return sli_func('pcvs', self._datum)
def get(self, *params, **kwargs):
"""
Get parameters from nodes.
Parameters
----------
params : str or list, optional
Parameters to get from the nodes. It must be one of the following:
- A single string.
- A list of strings.
- One or more strings, followed by a string or list of strings.
This is for hierarchical addressing.
output : str, ['pandas','json'], optional
If the returned data should be in a Pandas DataFrame or in a
JSON serializable format.
Returns
-------
int or float:
If there is a single node in the `NodeCollection`, and a single
parameter in params.
array_like:
If there are multiple nodes in the `NodeCollection`, and a single
parameter in params.
dict:
If there are multiple parameters in params. Or, if no parameters
are specified, a dictionary containing aggregated parameter-values
for all nodes is returned.
DataFrame:
Pandas Data frame if output should be in pandas format.
Raises
------
TypeError
If the input params are of the wrong form.
KeyError
If the specified parameter does not exist for the nodes.
See Also
--------
set
"""
# ------------------------- #
# Checks of input #
# ------------------------- #
if not kwargs:
output = ''
elif 'output' in kwargs:
output = kwargs['output']
if output == 'pandas' and not HAVE_PANDAS:
raise ImportError('Pandas could not be imported')
else:
raise TypeError('Got unexpected keyword argument')
pandas_output = output == 'pandas'
if len(params) == 0:
# get() is called without arguments
result = sli_func('get', self._datum)
elif len(params) == 1:
# params is a tuple with a string or list of strings
result = get_parameters(self, params[0])
else:
# Hierarchical addressing
result = get_parameters_hierarchical_addressing(self, params)
if pandas_output:
index = self.get('global_id')
if len(params) == 1 and is_literal(params[0]):
# params is a string
result = {params[0]: result}
elif len(params) > 1 and is_literal(params[1]):
# hierarchical, single string
result = {params[1]: result}
if len(self) == 1:
index = [index]
result = {key: [val] for key, val in result.items()}
result = pandas.DataFrame(result, index=index)
elif output == 'json':
result = to_json(result)
return result
def set(self, params=None, **kwargs):
"""
Set the parameters of nodes to params.
NB! This is almost the same implementation as `SetStatus`.
If `kwargs` is given, it has to be names and values of an attribute as keyword argument pairs. The values
can be single values or list of the same size as the `NodeCollection`.
Parameters
----------
params : str or dict or list
Dictionary of parameters or list of dictionaries of parameters of
same length as the `NodeCollection`.
kwargs : keyword argument pairs
Named arguments of parameters of the elements in the `NodeCollection`.
Raises
------
TypeError
If the input params are of the wrong form.
KeyError
If the specified parameter does not exist for the nodes.
"""
if kwargs and params is None:
params = kwargs
elif kwargs and params:
raise TypeError("must either provide params or kwargs, but not both.")
if isinstance(params, dict) and self[0].get('local'):
contains_list = [is_iterable(vals) and not is_iterable(self[0].get(key)) for key, vals in params.items()]
if any(contains_list):
temp_param = [{} for _ in range(self.__len__())]
for key, vals in params.items():
if not is_iterable(vals):
for temp_dict in temp_param:
temp_dict[key] = vals
else:
for i, temp_dict in enumerate(temp_param):
temp_dict[key] = vals[i]
params = temp_param
if (isinstance(params, (list, tuple)) and self.__len__() != len(params)):
raise TypeError(
"status dict must be a dict, or a list of dicts of length len(nodes)")
sli_func('SetStatus', self._datum, params)
def tolist(self):
"""
Convert `NodeCollection` to list.
"""
if self.__len__() == 0:
return []
return list(self.get('global_id')) if self.__len__() > 1 else [self.get('global_id')]
def index(self, node_id):
"""
Find the index of a node ID in the `NodeCollection`.
Parameters
----------
node_id : int
Global ID to be found.
Raises
------
ValueError
If the node ID is not in the `NodeCollection`.
"""
index = sli_func('Find', self._datum, node_id)
if index == -1:
raise ValueError('{} is not in NodeCollection'.format(node_id))
return index
def __getattr__(self, attr):
if attr == 'spatial':
metadata = sli_func('GetMetadata', self._datum)
val = metadata if metadata else None
super().__setattr__(attr, val)
return self.spatial
return self.get(attr)
def __setattr__(self, attr, value):
# `_datum` is the only property of NodeCollection that should not be
# interpreted as a property of the model
if attr == '_datum':
super().__setattr__(attr, value)
else:
self.set({attr: value})
class SynapseCollectionIterator(object):
"""
Iterator class for SynapseCollection.
"""
def __init__(self, synapse_collection):
self._iter = iter(synapse_collection._datum)
def __iter__(self):
return self
def __next__(self):
return SynapseCollection(next(self._iter))
next = __next__ # Python2.x
class SynapseCollection(object):
"""
Class for Connections.
`SynapseCollection` represents the connections of a network. The class supports indexing, iteration, length and
equality. You can get and set connection parameters by using the membership functions :py:func:`get()` and
:py:func:`set()`. By using the membership function :py:func:`sources()` you get an iterator over
source nodes, while :py:func:`targets()` returns an interator over the target nodes of the connections.
A SynapseCollection is created by the :py:func:`.GetConnections` function.
"""
_datum = None
def __init__(self, data):
if isinstance(data, list):
for datum in data:
if (not isinstance(datum, kernel.SLIDatum) or
datum.dtype != "connectiontype"):
raise TypeError("Expected Connection Datum.")
self._datum = data
elif data is None:
# We can have an empty SynapseCollection if there are no connections.
self._datum = data
else:
if (not isinstance(data, kernel.SLIDatum) or
data.dtype != "connectiontype"):
raise TypeError("Expected Connection Datum.")
# self._datum needs to be a list of Connection datums.
self._datum = [data]
def __iter__(self):
return SynapseCollectionIterator(self)
def __len__(self):
if self._datum is None:
return 0
return len(self._datum)
def __eq__(self, other):
if not isinstance(other, SynapseCollection):
raise NotImplementedError()
if self.__len__() != other.__len__():
return False
self_get = self.get(['source', 'target', 'target_thread',
'synapse_id', 'port'])
other_get = other.get(['source', 'target', 'target_thread',
'synapse_id', 'port'])
if self_get != other_get:
return False
return True
def __neq__(self, other):
if not isinstance(other, SynapseCollection):
raise NotImplementedError()
return not self == other
def __getitem__(self, key):
if isinstance(key, slice):
return SynapseCollection(self._datum[key])
else:
return SynapseCollection([self._datum[key]])
def __str__(self):
"""
Printing a `SynapseCollection` returns something of the form:
*--------*-------------*
| source | 1, 1, 2, 2, |
*--------*-------------*
| target | 1, 2, 1, 2, |
*--------*-------------*
"""
srcs = self.get('source')
trgt = self.get('target')
if isinstance(srcs, int):
srcs = [srcs]
if isinstance(trgt, int):
trgt = [trgt]
# 35 is arbitrarily chosen.
if len(srcs) < 35:
source = '| source | ' + ''.join(str(e)+', ' for e in srcs) + '|'
target = '| target | ' + ''.join(str(e)+', ' for e in trgt) + '|'
else:
source = ('| source | ' + ''.join(str(e)+', ' for e in srcs[:15]) +
'... ' + ''.join(str(e)+', ' for e in srcs[-15:]) + '|')
target = ('| target | ' + ''.join(str(e)+', ' for e in trgt[:15]) +
'... ' + ''.join(str(e)+', ' for e in trgt[-15:]) + '|')
borderline_s = '*--------*' + '-'*(len(source) - 12) + '-*'
borderline_t = '*--------*' + '-'*(len(target) - 12) + '-*'
borderline_m = max(borderline_s, borderline_t)
result = (borderline_s + '\n' + source + '\n' + borderline_m + '\n' +
target + '\n' + borderline_t)
return result
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, attr, value):
# `_datum` is the only property of SynapseCollection that should not be
# interpreted as a property of the model
if attr == '_datum':
super().__setattr__(attr, value)
else:
self.set({attr: value})
def sources(self):
"""Returns iterator containing the source node IDs of the `SynapseCollection`."""
sources = self.get('source')
if not isinstance(sources, (list, tuple)):
sources = (sources,)
return iter(sources)
def targets(self):
"""Returns iterator containing the target node IDs of the `SynapseCollection`."""
targets = self.get('target')
if not isinstance(targets, (list, tuple)):
targets = (targets,)
return iter(targets)
def get(self, keys=None, output=''):
"""
Return a parameter dictionary of the connections.
If `keys` is a string, a list of values is returned, unless we have a
single connection, in which case the single value is returned.
`keys` may also be a list, in which case a dictionary with a list of
values is returned.
Parameters
----------
keys : str or list, optional
String or a list of strings naming model properties. get
then returns a single value or a dictionary with lists of values
belonging to the given `keys`.
output : str, ['pandas','json'], optional
If the returned data should be in a Pandas DataFrame or in a
JSON serializable format.
Returns
-------
dict:
All parameters, or, if keys is a list of strings, a dictionary with
lists of corresponding parameters
type:
If keys is a string, the corrsponding parameter(s) is returned
Raises
------
TypeError
If input params are of the wrong form.
KeyError
If the specified parameter does not exist for the connections.
"""
pandas_output = output == 'pandas'
if pandas_output and not HAVE_PANDAS:
raise ImportError('Pandas could not be imported')
# Return empty tuple if we have no connections or if we have done a
# nest.ResetKernel()
num_conn = GetKernelStatus('num_connections')
if self.__len__() == 0 or num_conn == 0:
return ()
if keys is None:
cmd = 'GetStatus'
elif is_literal(keys):
cmd = 'GetStatus {{ /{0} get }} Map'.format(keys)
elif is_iterable(keys):
keys_str = " ".join("/{0}".format(x) for x in keys)
cmd = 'GetStatus {{ [ [ {0} ] ] get }} Map'.format(keys_str)
else:
raise TypeError("keys should be either a string or an iterable")
sps(self._datum)
sr(cmd)
result = spp()
# Need to restructure the data.
final_result = restructure_data(result, keys)
if pandas_output:
index = (self.get('source') if self.__len__() > 1 else
(self.get('source'),))
if is_literal(keys):
final_result = {keys: final_result}
final_result = pandas.DataFrame(final_result, index=index)
elif output == 'json':
final_result = to_json(final_result)
return final_result
def set(self, params=None, **kwargs):
"""
Set the parameters of the connections to `params`.
NB! This is almost the same implementation as SetStatus
If `kwargs` is given, it has to be names and values of an attribute as keyword argument pairs. The values
can be single values or list of the same size as the `SynapseCollection`.
Parameters
----------
params : str or dict or list
Dictionary of parameters or list of dictionaries of parameters of
same length as the `SynapseCollection`.
kwargs : keyword argument pairs
Named arguments of parameters of the elements in the `SynapseCollection`.
Raises
------
TypeError
If input params are of the wrong form.
KeyError
If the specified parameter does not exist for the connections.
"""
# This was added to ensure that the function is a nop (instead of,
# for instance, raising an exception) when applied to an empty
# SynapseCollection, or after having done a nest.ResetKernel().
if self.__len__() == 0 or GetKernelStatus()['network_size'] == 0:
return
if (isinstance(params, (list, tuple)) and
self.__len__() != len(params)):
raise TypeError(
"status dict must be a dict, or a list of dicts of length "
"len(nodes)")
if kwargs and params is None:
params = kwargs
elif kwargs and params:
raise TypeError("must either provide params or kwargs, but not both.")
if isinstance(params, dict):
contains_list = [is_iterable(vals) and not is_iterable(self[0].get(key)) for key, vals in params.items()]
if any(contains_list):
temp_param = [{} for _ in range(self.__len__())]
for key, vals in params.items():
if not is_iterable(vals):
for temp_dict in temp_param:
temp_dict[key] = vals
else:
for i, temp_dict in enumerate(temp_param):
temp_dict[key] = vals[i]
params = temp_param
params = broadcast(params, self.__len__(), (dict,), "params")
sps(self._datum)
sps(params)
sr('2 arraystore')
sr('Transpose { arrayload pop SetStatus } forall')
class Mask(object):
"""
Class for spatial masks.
Masks are used when creating connections when nodes have spatial extent. A mask
describes the area of the pool population that shall be searched to find nodes to
connect to for any given node in the driver population. Masks are created using
the :py:func:`.CreateMask` command.
"""
_datum = None
# The constructor should not be called by the user
def __init__(self, datum):
"""Masks must be created using the CreateMask command."""
if not isinstance(datum, kernel.SLIDatum) or datum.dtype != "masktype":
raise TypeError("expected mask Datum")
self._datum = datum
# Generic binary operation
def _binop(self, op, other):
if not isinstance(other, Mask):
raise NotImplementedError()
return sli_func(op, self._datum, other._datum)
def __or__(self, other):
return self._binop("or", other)
def __and__(self, other):
return self._binop("and", other)
def __sub__(self, other):
return self._binop("sub", other)
def Inside(self, point):
"""
Test if a point is inside a mask.
Parameters
----------
point : tuple/list of float values
Coordinate of point
Returns
-------
out : bool
True if the point is inside the mask, False otherwise
"""
return sli_func("Inside", point, self._datum)
class Parameter(object):
"""
Class for parameters
A parameter may be used as a probability kernel when creating
connections and nodes or as synaptic parameters (such as weight and delay).
Parameters are created using the :py:func:`.CreateParameter` command.
"""
_datum = None
# The constructor should not be called by the user
def __init__(self, datum):
"""Parameters must be created using the CreateParameter command."""
if not isinstance(datum,
kernel.SLIDatum) or datum.dtype != "parametertype":
raise TypeError("expected parameter datum")
self._datum = datum
# Generic binary operation
def _binop(self, op, other, params=None):
if isinstance(other, (int, float)):
other = CreateParameter('constant', {'value': float(other)})
if not isinstance(other, Parameter):
raise NotImplementedError()
if params is None:
return sli_func(op, self._datum, other._datum)
else:
return sli_func(op, self._datum, other._datum, params)
def __add__(self, other):
return self._binop("add", other)
def __radd__(self, other):
return self + other
def __sub__(self, other):
return self._binop("sub", other)
def __rsub__(self, other):
return self * (-1) + other
def __neg__(self):
return self * (-1)
def __mul__(self, other):
return self._binop("mul", other)
def __rmul__(self, other):
return self * other
def __div__(self, other):
return self._binop("div", other)
def __truediv__(self, other):
return self._binop("div", other)
def __pow__(self, exponent):
return sli_func("pow", self._datum, float(exponent))
def __lt__(self, other):
return self._binop("compare", other, {'comparator': 0})
def __le__(self, other):
return self._binop("compare", other, {'comparator': 1})
def __eq__(self, other):
return self._binop("compare", other, {'comparator': 2})
def __ne__(self, other):
return self._binop("compare", other, {'comparator': 3})
def __ge__(self, other):
return self._binop("compare", other, {'comparator': 4})
def __gt__(self, other):
return self._binop("compare", other, {'comparator': 5})
def GetValue(self):
"""
Compute value of parameter.
Returns
-------
out : value
The value of the parameter
See also
--------
CreateParameter
Example
-------
::
import nest
# normal distribution parameter
P = nest.CreateParameter('normal', {'mean': 0.0, 'sigma': 1.0})
# get out value
P.GetValue()
"""
return sli_func("GetValue", self._datum)
def is_spatial(self):
return sli_func('ParameterIsSpatial', self._datum)
def apply(self, spatial_nc, positions=None):
if positions is None:
return sli_func('Apply', self._datum, spatial_nc)
else:
if len(spatial_nc) != 1:
raise ValueError('The NodeCollection must contain a single node ID only')
if not isinstance(positions, (list, tuple)):
raise TypeError('Positions must be a list or tuple of positions')
for pos in positions:
if not isinstance(pos, (list, tuple, numpy.ndarray)):
raise TypeError('Each position must be a list or tuple')
if len(pos) != len(positions[0]):
raise ValueError('All positions must have the same number of dimensions')
return sli_func('Apply', self._datum, {'source': spatial_nc, 'targets': positions})
def serializable(data):
"""Make data serializable for JSON.
Parameters
----------
data : any
Returns
-------
data_serialized : str, int, float, list, dict
Data can be encoded to JSON
"""
if isinstance(data, (numpy.ndarray, NodeCollection)):
return data.tolist()
if isinstance(data, SynapseCollection):
# Get full information from SynapseCollection
return serializable(data.get())
if isinstance(data, kernel.SLILiteral):
# Get name of SLILiteral.
return data.name
if isinstance(data, (list, tuple)):
return [serializable(d) for d in data]
if isinstance(data, dict):
return dict([(key, serializable(value)) for key, value in data.items()])
return data
def to_json(data, **kwargs):
"""Serialize data to JSON.
Parameters
----------
data : any
kwargs : keyword argument pairs
Named arguments of parameters for `json.dumps` function.
Returns
-------
data_json : str
JSON format of the data
"""
data_serialized = serializable(data)
data_json = json.dumps(data_serialized, **kwargs)
return data_json
|
alberto-antonietti/nest-simulator
|
pynest/nest/lib/hl_api_types.py
|
Python
|
gpl-2.0
| 32,884
|
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Backup manager manages volume backups.
Volume Backups are full copies of persistent volumes stored in a backup
store e.g. an object store or any other backup store if and when support is
added. They are usable without the original object being available. A
volume backup can be restored to the original volume it was created from or
any other available volume with a minimum size of the original volume.
Volume backups can be created, restored, deleted and listed.
**Related Flags**
:backup_topic: What :mod:`rpc` topic to listen to (default:
`cinder-backup`).
:backup_manager: The module name of a class derived from
:class:`manager.Manager` (default:
:class:`cinder.backup.manager.Manager`).
"""
from oslo_config import cfg
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_utils import excutils
from oslo_utils import importutils
import six
from cinder.backup import driver
from cinder.backup import rpcapi as backup_rpcapi
from cinder import context
from cinder import exception
from cinder.i18n import _, _LE, _LI, _LW
from cinder import manager
from cinder import objects
from cinder import quota
from cinder import rpc
from cinder import utils
from cinder.volume import utils as volume_utils
LOG = logging.getLogger(__name__)
backup_manager_opts = [
cfg.StrOpt('backup_driver',
default='cinder.backup.drivers.swift',
help='Driver to use for backups.',)
]
# This map doesn't need to be extended in the future since it's only
# for old backup services
mapper = {'cinder.backup.services.swift': 'cinder.backup.drivers.swift',
'cinder.backup.services.ceph': 'cinder.backup.drivers.ceph'}
CONF = cfg.CONF
CONF.register_opts(backup_manager_opts)
QUOTAS = quota.QUOTAS
class BackupManager(manager.SchedulerDependentManager):
"""Manages backup of block storage devices."""
RPC_API_VERSION = '1.2'
target = messaging.Target(version=RPC_API_VERSION)
def __init__(self, service_name=None, *args, **kwargs):
self.service = importutils.import_module(self.driver_name)
self.az = CONF.storage_availability_zone
self.volume_managers = {}
self._setup_volume_drivers()
self.backup_rpcapi = backup_rpcapi.BackupAPI()
super(BackupManager, self).__init__(service_name='backup',
*args, **kwargs)
@property
def driver_name(self):
"""This function maps old backup services to backup drivers."""
return self._map_service_to_driver(CONF.backup_driver)
def _map_service_to_driver(self, service):
"""Maps services to drivers."""
if service in mapper:
return mapper[service]
return service
@property
def driver(self):
return self._get_driver()
def _get_volume_backend(self, host=None, allow_null_host=False):
if host is None:
if not allow_null_host:
msg = _("NULL host not allowed for volume backend lookup.")
raise exception.BackupFailedToGetVolumeBackend(msg)
else:
LOG.debug("Checking hostname '%s' for backend info.", host)
part = host.partition('@')
if (part[1] == '@') and (part[2] != ''):
backend = part[2]
LOG.debug("Got backend '%s'.", backend)
return backend
LOG.info(_LI("Backend not found in hostname (%s) so using default."),
host)
if 'default' not in self.volume_managers:
# For multi-backend we just pick the top of the list.
return self.volume_managers.keys()[0]
return 'default'
def _get_manager(self, backend):
LOG.debug("Manager requested for volume_backend '%s'.",
backend)
if backend is None:
LOG.debug("Fetching default backend.")
backend = self._get_volume_backend(allow_null_host=True)
if backend not in self.volume_managers:
msg = (_("Volume manager for backend '%s' does not exist.") %
(backend))
raise exception.BackupFailedToGetVolumeBackend(msg)
return self.volume_managers[backend]
def _get_driver(self, backend=None):
LOG.debug("Driver requested for volume_backend '%s'.",
backend)
if backend is None:
LOG.debug("Fetching default backend.")
backend = self._get_volume_backend(allow_null_host=True)
mgr = self._get_manager(backend)
mgr.driver.db = self.db
return mgr.driver
def _setup_volume_drivers(self):
if CONF.enabled_backends:
for backend in CONF.enabled_backends:
host = "%s@%s" % (CONF.host, backend)
mgr = importutils.import_object(CONF.volume_manager,
host=host,
service_name=backend)
config = mgr.configuration
backend_name = config.safe_get('volume_backend_name')
LOG.debug("Registering backend %(backend)s (host=%(host)s "
"backend_name=%(backend_name)s).",
{'backend': backend, 'host': host,
'backend_name': backend_name})
self.volume_managers[backend] = mgr
else:
default = importutils.import_object(CONF.volume_manager)
LOG.debug("Registering default backend %s.", default)
self.volume_managers['default'] = default
def _init_volume_driver(self, ctxt, driver):
LOG.info(_LI("Starting volume driver %(driver_name)s (%(version)s)."),
{'driver_name': driver.__class__.__name__,
'version': driver.get_version()})
try:
driver.do_setup(ctxt)
driver.check_for_setup_error()
except Exception:
LOG.exception(_LE("Error encountered during initialization of "
"driver: %(name)s."),
{'name': driver.__class__.__name__})
# we don't want to continue since we failed
# to initialize the driver correctly.
return
driver.set_initialized()
def _update_backup_error(self, backup, context, err):
backup.status = 'error'
backup.fail_reason = err
backup.save()
def init_host(self):
"""Run initialization needed for a standalone service."""
ctxt = context.get_admin_context()
for mgr in self.volume_managers.values():
self._init_volume_driver(ctxt, mgr.driver)
LOG.info(_LI("Cleaning up incomplete backup operations."))
volumes = self.db.volume_get_all_by_host(ctxt, self.host)
for volume in volumes:
volume_host = volume_utils.extract_host(volume['host'], 'backend')
backend = self._get_volume_backend(host=volume_host)
attachments = volume['volume_attachment']
if attachments:
if (volume['status'] == 'backing-up' and
volume['previous_status'] == 'available'):
LOG.info(_LI('Resetting volume %(vol_id)s to previous '
'status %(status)s (was backing-up).'),
{'vol_id': volume['id'],
'status': volume['previous_status']})
mgr = self._get_manager(backend)
for attachment in attachments:
if (attachment['attached_host'] == self.host and
attachment['instance_uuid'] is None):
mgr.detach_volume(ctxt, volume['id'],
attachment['id'])
elif (volume['status'] == 'backing-up' and
volume['previous_status'] == 'in-use'):
LOG.info(_LI('Resetting volume %(vol_id)s to previous '
'status %(status)s (was backing-up).'),
{'vol_id': volume['id'],
'status': volume['previous_status']})
self.db.volume_update(ctxt, volume['id'],
volume['previous_status'])
elif volume['status'] == 'restoring-backup':
LOG.info(_LI('setting volume %s to error_restoring '
'(was restoring-backup).'), volume['id'])
mgr = self._get_manager(backend)
for attachment in attachments:
if (attachment['attached_host'] == self.host and
attachment['instance_uuid'] is None):
mgr.detach_volume(ctxt, volume['id'],
attachment['id'])
self.db.volume_update(ctxt, volume['id'],
{'status': 'error_restoring'})
# TODO(smulcahy) implement full resume of backup and restore
# operations on restart (rather than simply resetting)
backups = objects.BackupList.get_all_by_host(ctxt, self.host)
for backup in backups:
if backup['status'] == 'creating':
LOG.info(_LI('Resetting backup %s to error (was creating).'),
backup['id'])
err = 'incomplete backup reset on manager restart'
self._update_backup_error(backup, ctxt, err)
if backup['status'] == 'restoring':
LOG.info(_LI('Resetting backup %s to '
'available (was restoring).'),
backup['id'])
backup.status = 'available'
backup.save()
if backup['status'] == 'deleting':
LOG.info(_LI('Resuming delete on backup: %s.'), backup['id'])
self.delete_backup(ctxt, backup)
self._cleanup_temp_volumes_snapshots(backups)
def _cleanup_temp_volumes_snapshots(self, backups):
# NOTE(xyang): If the service crashes or gets restarted during the
# backup operation, there could be temporary volumes or snapshots
# that are not deleted. Make sure any temporary volumes or snapshots
# create by the backup job are deleted when service is started.
ctxt = context.get_admin_context()
for backup in backups:
try:
volume = self.db.volume_get(ctxt, backup.volume_id)
volume_host = volume_utils.extract_host(volume['host'],
'backend')
backend = self._get_volume_backend(host=volume_host)
mgr = self._get_manager(backend)
except (KeyError, exception.VolumeNotFound):
LOG.debug("Could not find a volume to clean up for "
"backup %s.", backup.id)
continue
if backup.temp_volume_id and backup.status == 'error':
temp_volume = self.db.volume_get(ctxt,
backup.temp_volume_id)
# The temp volume should be deleted directly thru the
# the volume driver, not thru the volume manager.
mgr.driver.delete_volume(temp_volume)
self.db.volume_destroy(ctxt, temp_volume['id'])
if backup.temp_snapshot_id and backup.status == 'error':
temp_snapshot = objects.Snapshot.get_by_id(
ctxt, backup.temp_snapshot_id)
# The temp snapshot should be deleted directly thru the
# volume driver, not thru the volume manager.
mgr.driver.delete_snapshot(temp_snapshot)
with temp_snapshot.obj_as_admin():
self.db.volume_glance_metadata_delete_by_snapshot(
ctxt, temp_snapshot.id)
temp_snapshot.destroy()
def create_backup(self, context, backup):
"""Create volume backups using configured backup service."""
volume_id = backup.volume_id
volume = self.db.volume_get(context, volume_id)
previous_status = volume.get('previous_status', None)
LOG.info(_LI('Create backup started, backup: %(backup_id)s '
'volume: %(volume_id)s.'),
{'backup_id': backup.id, 'volume_id': volume_id})
self._notify_about_backup_usage(context, backup, "create.start")
volume_host = volume_utils.extract_host(volume['host'], 'backend')
backend = self._get_volume_backend(host=volume_host)
backup.host = self.host
backup.service = self.driver_name
backup.save()
expected_status = 'backing-up'
actual_status = volume['status']
if actual_status != expected_status:
err = _('Create backup aborted, expected volume status '
'%(expected_status)s but got %(actual_status)s.') % {
'expected_status': expected_status,
'actual_status': actual_status,
}
self._update_backup_error(backup, context, err)
raise exception.InvalidVolume(reason=err)
expected_status = 'creating'
actual_status = backup.status
if actual_status != expected_status:
err = _('Create backup aborted, expected backup status '
'%(expected_status)s but got %(actual_status)s.') % {
'expected_status': expected_status,
'actual_status': actual_status,
}
self._update_backup_error(backup, context, err)
backup.save()
raise exception.InvalidBackup(reason=err)
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught,
# the volume status will be set back to available and
# the backup status to 'error'
utils.require_driver_initialized(self.driver)
backup_service = self.service.get_backup_driver(context)
self._get_driver(backend).backup_volume(context, backup,
backup_service)
except Exception as err:
with excutils.save_and_reraise_exception():
self.db.volume_update(context, volume_id,
{'status': previous_status,
'previous_status': 'error_backing-up'})
self._update_backup_error(backup, context, six.text_type(err))
# Restore the original status.
self.db.volume_update(context, volume_id,
{'status': previous_status,
'previous_status': 'backing-up'})
backup.status = 'available'
backup.size = volume['size']
backup.availability_zone = self.az
backup.save()
LOG.info(_LI('Create backup finished. backup: %s.'), backup.id)
self._notify_about_backup_usage(context, backup, "create.end")
def restore_backup(self, context, backup, volume_id):
"""Restore volume backups from configured backup service."""
LOG.info(_LI('Restore backup started, backup: %(backup_id)s '
'volume: %(volume_id)s.'),
{'backup_id': backup.id, 'volume_id': volume_id})
volume = self.db.volume_get(context, volume_id)
volume_host = volume_utils.extract_host(volume['host'], 'backend')
backend = self._get_volume_backend(host=volume_host)
self._notify_about_backup_usage(context, backup, "restore.start")
backup.host = self.host
backup.save()
expected_status = 'restoring-backup'
actual_status = volume['status']
if actual_status != expected_status:
err = (_('Restore backup aborted, expected volume status '
'%(expected_status)s but got %(actual_status)s.') %
{'expected_status': expected_status,
'actual_status': actual_status})
backup.status = 'available'
backup.save()
raise exception.InvalidVolume(reason=err)
expected_status = 'restoring'
actual_status = backup['status']
if actual_status != expected_status:
err = (_('Restore backup aborted: expected backup status '
'%(expected_status)s but got %(actual_status)s.') %
{'expected_status': expected_status,
'actual_status': actual_status})
self._update_backup_error(backup, context, err)
self.db.volume_update(context, volume_id, {'status': 'error'})
raise exception.InvalidBackup(reason=err)
if volume['size'] > backup['size']:
LOG.info(_LI('Volume: %(vol_id)s, size: %(vol_size)d is '
'larger than backup: %(backup_id)s, '
'size: %(backup_size)d, continuing with restore.'),
{'vol_id': volume['id'],
'vol_size': volume['size'],
'backup_id': backup['id'],
'backup_size': backup['size']})
backup_service = self._map_service_to_driver(backup['service'])
configured_service = self.driver_name
if backup_service != configured_service:
err = _('Restore backup aborted, the backup service currently'
' configured [%(configured_service)s] is not the'
' backup service that was used to create this'
' backup [%(backup_service)s].') % {
'configured_service': configured_service,
'backup_service': backup_service,
}
backup.status = 'available'
backup.save()
self.db.volume_update(context, volume_id, {'status': 'error'})
raise exception.InvalidBackup(reason=err)
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught,
# the volume status will be set back to available and
# the backup status to 'error'
utils.require_driver_initialized(self.driver)
backup_service = self.service.get_backup_driver(context)
self._get_driver(backend).restore_backup(context, backup,
volume,
backup_service)
except Exception:
with excutils.save_and_reraise_exception():
self.db.volume_update(context, volume_id,
{'status': 'error_restoring'})
backup.status = 'available'
backup.save()
self.db.volume_update(context, volume_id, {'status': 'available'})
backup.status = 'available'
backup.save()
LOG.info(_LI('Restore backup finished, backup %(backup_id)s restored'
' to volume %(volume_id)s.'),
{'backup_id': backup.id, 'volume_id': volume_id})
self._notify_about_backup_usage(context, backup, "restore.end")
def delete_backup(self, context, backup):
"""Delete volume backup from configured backup service."""
LOG.info(_LI('Delete backup started, backup: %s.'), backup.id)
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the backup status updated. Fail early since there
# are no other status to change but backup's
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized as err:
with excutils.save_and_reraise_exception():
self._update_backup_error(backup, context, six.text_type(err))
self._notify_about_backup_usage(context, backup, "delete.start")
backup.host = self.host
backup.save()
expected_status = 'deleting'
actual_status = backup.status
if actual_status != expected_status:
err = _('Delete_backup aborted, expected backup status '
'%(expected_status)s but got %(actual_status)s.') \
% {'expected_status': expected_status,
'actual_status': actual_status}
self._update_backup_error(backup, context, err)
raise exception.InvalidBackup(reason=err)
backup_service = self._map_service_to_driver(backup['service'])
if backup_service is not None:
configured_service = self.driver_name
if backup_service != configured_service:
err = _('Delete backup aborted, the backup service currently'
' configured [%(configured_service)s] is not the'
' backup service that was used to create this'
' backup [%(backup_service)s].')\
% {'configured_service': configured_service,
'backup_service': backup_service}
self._update_backup_error(backup, context, err)
raise exception.InvalidBackup(reason=err)
try:
backup_service = self.service.get_backup_driver(context)
backup_service.delete(backup)
except Exception as err:
with excutils.save_and_reraise_exception():
self._update_backup_error(backup, context,
six.text_type(err))
# Get reservations
try:
reserve_opts = {
'backups': -1,
'backup_gigabytes': -backup.size,
}
reservations = QUOTAS.reserve(context,
project_id=backup.project_id,
**reserve_opts)
except Exception:
reservations = None
LOG.exception(_LE("Failed to update usages deleting backup"))
backup.destroy()
# Commit the reservations
if reservations:
QUOTAS.commit(context, reservations,
project_id=backup.project_id)
LOG.info(_LI('Delete backup finished, backup %s deleted.'), backup.id)
self._notify_about_backup_usage(context, backup, "delete.end")
def _notify_about_backup_usage(self,
context,
backup,
event_suffix,
extra_usage_info=None):
volume_utils.notify_about_backup_usage(
context, backup, event_suffix,
extra_usage_info=extra_usage_info,
host=self.host)
def export_record(self, context, backup):
"""Export all volume backup metadata details to allow clean import.
Export backup metadata so it could be re-imported into the database
without any prerequisite in the backup database.
:param context: running context
:param backup: backup object to export
:returns: backup_record - a description of how to import the backup
:returns: contains 'backup_url' - how to import the backup, and
:returns: 'backup_service' describing the needed driver.
:raises: InvalidBackup
"""
LOG.info(_LI('Export record started, backup: %s.'), backup.id)
expected_status = 'available'
actual_status = backup.status
if actual_status != expected_status:
err = (_('Export backup aborted, expected backup status '
'%(expected_status)s but got %(actual_status)s.') %
{'expected_status': expected_status,
'actual_status': actual_status})
raise exception.InvalidBackup(reason=err)
backup_record = {}
backup_record['backup_service'] = backup.service
backup_service = self._map_service_to_driver(backup.service)
configured_service = self.driver_name
if backup_service != configured_service:
err = (_('Export record aborted, the backup service currently'
' configured [%(configured_service)s] is not the'
' backup service that was used to create this'
' backup [%(backup_service)s].') %
{'configured_service': configured_service,
'backup_service': backup_service})
raise exception.InvalidBackup(reason=err)
# Call driver to create backup description string
try:
utils.require_driver_initialized(self.driver)
backup_service = self.service.get_backup_driver(context)
backup_url = backup_service.export_record(backup)
backup_record['backup_url'] = backup_url
except Exception as err:
msg = six.text_type(err)
raise exception.InvalidBackup(reason=msg)
LOG.info(_LI('Export record finished, backup %s exported.'), backup.id)
return backup_record
def import_record(self,
context,
backup,
backup_service,
backup_url,
backup_hosts):
"""Import all volume backup metadata details to the backup db.
:param context: running context
:param backup: The new backup object for the import
:param backup_service: The needed backup driver for import
:param backup_url: An identifier string to locate the backup
:param backup_hosts: Potential hosts to execute the import
:raises: InvalidBackup
:raises: ServiceNotFound
"""
LOG.info(_LI('Import record started, backup_url: %s.'), backup_url)
# Can we import this backup?
if (backup_service != self.driver_name):
# No, are there additional potential backup hosts in the list?
if len(backup_hosts) > 0:
# try the next host on the list, maybe he can import
first_host = backup_hosts.pop()
self.backup_rpcapi.import_record(context,
first_host,
backup,
backup_service,
backup_url,
backup_hosts)
else:
# empty list - we are the last host on the list, fail
err = _('Import record failed, cannot find backup '
'service to perform the import. Request service '
'%(service)s') % {'service': backup_service}
self._update_backup_error(backup, context, err)
raise exception.ServiceNotFound(service_id=backup_service)
else:
# Yes...
try:
utils.require_driver_initialized(self.driver)
backup_service = self.service.get_backup_driver(context)
backup_options = backup_service.import_record(backup_url)
except Exception as err:
msg = six.text_type(err)
self._update_backup_error(backup, context, msg)
raise exception.InvalidBackup(reason=msg)
required_import_options = ['display_name',
'display_description',
'container',
'size',
'service_metadata',
'service',
'object_count']
backup_update = {}
backup_update['status'] = 'available'
backup_update['service'] = self.driver_name
backup_update['availability_zone'] = self.az
backup_update['host'] = self.host
for entry in required_import_options:
if entry not in backup_options:
msg = (_('Backup metadata received from driver for '
'import is missing %s.'), entry)
self._update_backup_error(backup, context, msg)
raise exception.InvalidBackup(reason=msg)
backup_update[entry] = backup_options[entry]
# Update the database
backup.update(backup_update)
backup.save()
# Verify backup
try:
if isinstance(backup_service, driver.BackupDriverWithVerify):
backup_service.verify(backup.id)
else:
LOG.warning(_LW('Backup service %(service)s does not '
'support verify. Backup id %(id)s is '
'not verified. Skipping verify.'),
{'service': self.driver_name,
'id': backup.id})
except exception.InvalidBackup as err:
with excutils.save_and_reraise_exception():
self._update_backup_error(backup, context,
six.text_type(err))
LOG.info(_LI('Import record id %s metadata from driver '
'finished.'), backup.id)
def reset_status(self, context, backup, status):
"""Reset volume backup status.
:param context: running context
:param backup: The backup object for reset status operation
:param status: The status to be set
:raises: InvalidBackup
:raises: BackupVerifyUnsupportedDriver
:raises: AttributeError
"""
LOG.info(_LI('Reset backup status started, backup_id: '
'%(backup_id)s, status: %(status)s.'),
{'backup_id': backup.id,
'status': status})
try:
# NOTE(flaper87): Verify the driver is enabled
# before going forward. The exception will be caught
# and the backup status updated. Fail early since there
# are no other status to change but backup's
utils.require_driver_initialized(self.driver)
except exception.DriverNotInitialized:
with excutils.save_and_reraise_exception():
LOG.exception(_LE("Backup driver has not been initialized"))
backup_service = self._map_service_to_driver(backup.service)
LOG.info(_LI('Backup service: %s.'), backup_service)
if backup_service is not None:
configured_service = self.driver_name
if backup_service != configured_service:
err = _('Reset backup status aborted, the backup service'
' currently configured [%(configured_service)s] '
'is not the backup service that was used to create'
' this backup [%(backup_service)s].') % \
{'configured_service': configured_service,
'backup_service': backup_service}
raise exception.InvalidBackup(reason=err)
# Verify backup
try:
# check whether the backup is ok or not
if status == 'available' and backup['status'] != 'restoring':
# check whether we could verify the backup is ok or not
if isinstance(backup_service,
driver.BackupDriverWithVerify):
backup_service.verify(backup.id)
backup.status = status
backup.save()
# driver does not support verify function
else:
msg = (_('Backup service %(configured_service)s '
'does not support verify. Backup id'
' %(id)s is not verified. '
'Skipping verify.') %
{'configured_service': self.driver_name,
'id': backup.id})
raise exception.BackupVerifyUnsupportedDriver(
reason=msg)
# reset status to error or from restoring to available
else:
if (status == 'error' or
(status == 'available' and
backup.status == 'restoring')):
backup.status = status
backup.save()
except exception.InvalidBackup:
with excutils.save_and_reraise_exception():
LOG.error(_LE("Backup id %s is not invalid. "
"Skipping reset."), backup.id)
except exception.BackupVerifyUnsupportedDriver:
with excutils.save_and_reraise_exception():
LOG.error(_LE('Backup service %(configured_service)s '
'does not support verify. Backup id '
'%(id)s is not verified. '
'Skipping verify.'),
{'configured_service': self.driver_name,
'id': backup.id})
except AttributeError:
msg = (_('Backup service %(service)s does not support '
'verify. Backup id %(id)s is not verified. '
'Skipping reset.') %
{'service': self.driver_name,
'id': backup.id})
LOG.error(msg)
raise exception.BackupVerifyUnsupportedDriver(
reason=msg)
# send notification to ceilometer
notifier_info = {'id': backup.id, 'update': {'status': status}}
notifier = rpc.get_notifier('backupStatusUpdate')
notifier.info(context, "backups.reset_status.end",
notifier_info)
def check_support_to_force_delete(self, context):
"""Check if the backup driver supports force delete operation.
:param context: running context
"""
backup_service = self.service.get_backup_driver(context)
return backup_service.support_force_delete
|
JioCloud/cinder
|
cinder/backup/manager.py
|
Python
|
apache-2.0
| 35,514
|
import yaml
import unittest
from bipy.toolbox import piranha
from bcbio.utils import safe_makedir, file_exists
import os
from bipy.toolbox import reporting
from bipy.utils import in2out
STAGENAME = "piranha"
class TestPiranha(unittest.TestCase):
def setUp(self):
self.config_file = os.path.join("test", STAGENAME, "test_" +
STAGENAME + ".yaml")
with open(self.config_file) as in_handle:
self.config = yaml.load(in_handle)
self.in_file = self.config["input"]
self.stage_config = self.config["stage"][STAGENAME]
self.bin_size = self.stage_config.get("bin_size", 30)
self.covariate = self.stage_config.get("covariate", None)
self.out_dir = os.path.join("results", "test", STAGENAME)
def test_run(self):
exp_out = in2out(self.in_file, "piranha.bed", transform=True,
out_dir = self.out_dir)
print exp_out
out_file = piranha.run(self.in_file, bin_size=self.bin_size,
covariate=self.covariate, out_file=exp_out)
print out_file
self.assertTrue(file_exists(out_file))
self.assertTrue(exp_out == out_file)
os.remove(out_file)
def test_stage_wrapper(self):
exp_out = in2out(self.in_file, "piranha.bed", transform=True,
out_dir = self.out_dir)
pstage = piranha.PiranhaStage(self.config)
out_file = pstage(self.in_file)
self.assertTrue(file_exists(out_file))
self.assertTrue(exp_out == out_file)
os.remove(out_file)
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(TestPiranha)
unittest.TextTestRunner(verbosity=2).run(suite)
|
roryk/bipy
|
test/piranha/test_piranha.py
|
Python
|
mit
| 1,767
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from .__init__ import *
from .object import Object
from .control import Control
from gi.repository import Gtk
from gi.repository import Pango
from gi.repository import PangoCairo
class Table(Object):
"""This class represents a table"""
__name__ = "Table"
def __init__(self, rows=5, columns="0", titles=_("Column 1")):
Object.__init__(self)
self.vertical_spacing = 5
self.horizontal_spacing = 5
self.control = MANUAL
self.rows = rows
self.columns = columns
self.titles = titles
self.font = "Verdana"
self.size = 16
def get_properties(self):
return Object.get_properties(self) + ["rows", "columns", "titles", "font", "size"]
def post(self):
controls = len(self.handler.control)
while controls > ANONIMOUS:
controls -= 1
del self.handler.control[controls]
columns = self.get_property("columns").split(':')
offset = 0
for i, column in enumerate(columns):
offset += int(column)
if i:
offset += self.horizontal_spacing
control = Control()
self.handler.control.append(control)
control.x = self.x + offset
control.y = self.y + self.height / 2
control.limbus = True
def draw(self, context):
###context.save()
rows = int(self.rows)
columns = self.columns.split(':')
n_columns = len(columns)
titles = self.titles.split(':')
self.width = 0
self.height = 0
#_context = PangoCairo.create_context(context) # XXX
total_width = 0
for column in range(n_columns):
for row in range(rows):
#layout = PangoCairo.create_layout(_context)
layout = PangoCairo.create_layout(context)
fontname = self.font
if fontname.endswith(("0", "1", "2", "3", "4", "5", "6", "7", "8", "9")): # XXX
description = fontname
else:
size = int(self.size)
description = "%s %d" % (fontname, size)
font = Pango.FontDescription(description)
layout.set_font_description(font)
title = titles[column]
layout.set_markup(title)
if row == 0:
context.set_source_rgb(0.0, 0.0, 0.0)
else:
context.set_source_rgb(0.75, 0.75, 0.75)
width, height = layout.get_size()
if columns[column] == '0':
width /= Pango.SCALE
columns[column] = str(width)
else:
width = int(columns[column])
height /= Pango.SCALE
x = self.x + total_width + self.horizontal_spacing * column
y = self.y + (self.vertical_spacing + height) * row
context.move_to(x, y)
PangoCairo.show_layout(context, layout)
self.height = (self.vertical_spacing + height) * rows
total_width += width
self.columns = ':'.join(columns)
self.width = n_columns * self.horizontal_spacing - self.horizontal_spacing + total_width
Object.draw(self, context)
def get_cursor(self, direction):
return Gdk.Cursor.new(Gdk.FLEUR)
def transform(self, x, y):
direction = self.direction - ANONIMOUS
columns = self.columns.split(':')
n_columns = len(columns)
offset = self.x
if direction < n_columns:
for column in range(direction):
offset += int(columns[column]) + self.horizontal_spacing
columns[direction] = str(int(x - offset))
self.columns = ':'.join(columns)
|
jmouriz/sanaviron
|
sanaviron/objects/table.py
|
Python
|
apache-2.0
| 4,006
|
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright (C) 2016 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program 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 for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import snapcraft.internal
from snapcraft import tests
class BuildStateTestCase(tests.TestCase):
def setUp(self):
super().setUp()
self.schema_properties = ['foo']
class Options:
def __init__(self):
self.foo = ['bar']
self.options = Options()
class Project:
def __init__(self):
self.deb_arch = 'amd64'
self.project = Project()
self.state = snapcraft.internal.states.BuildState(
self.schema_properties, self.options, self.project)
def test_representation(self):
expected = ('BuildState(project_options: {}, properties: {}, '
'schema_properties: {})').format(
self.project.__dict__, self.options.__dict__,
self.schema_properties)
self.assertEqual(expected, repr(self.state))
def test_comparison(self):
other = snapcraft.internal.states.BuildState(
self.schema_properties, self.options, self.project)
self.assertTrue(self.state == other, 'Expected states to be identical')
def test_comparison_not_equal(self):
others = [
snapcraft.internal.states.BuildState(
[], self.options, self.project),
snapcraft.internal.states.BuildState(
self.schema_properties, None, self.project),
snapcraft.internal.states.BuildState(
self.schema_properties, self.options, None)
]
for index, other in enumerate(others):
with self.subTest('other #{}'.format(index+1)):
self.assertFalse(self.state == other,
'Expected states to be different')
|
jocave/snapcraft
|
snapcraft/tests/test_states_build.py
|
Python
|
gpl-3.0
| 2,391
|
#!/usr/bin/env python
#
# Copyright (C) 2007 SIOS Technology, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for xmldsig"""
__author__ = 'tmatsuo@example.com (Takashi MATSUO)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import ds_data
import xmldsig as ds
class TestObject:
def setup_class(self):
self.object = ds.Object()
def testAccessors(self):
"""Test for Object accessors"""
self.object.id = "object_id"
self.object.mime_type = "test/plain; charset=UTF-8"
self.object.encoding = ds.ENCODING_BASE64
new_object = ds.object_from_string(self.object.to_string())
assert new_object.id == "object_id"
assert new_object.mime_type == "test/plain; charset=UTF-8"
assert new_object.encoding == ds.ENCODING_BASE64
def testUsingTestData(self):
"""Test for object_from_string() using test data"""
new_object = ds.object_from_string(ds_data.TEST_OBJECT)
assert new_object.id == "object_id"
assert new_object.encoding == ds.ENCODING_BASE64
assert new_object.text.strip() == \
"V2VkIEp1biAgNCAxMjoxMTowMyBFRFQgMjAwMwo"
class TestMgmtData:
def setup_class(self):
self.mgmt_data = ds.MgmtData()
def testAccessors(self):
"""Test for MgmtData accessors"""
self.mgmt_data.text = "mgmt data"
new_mgmt_data = ds.mgmt_data_from_string(self.mgmt_data.to_string())
assert new_mgmt_data.text.strip() == "mgmt data"
def testUsingTestData(self):
"""Test for mgmt_data_from_string() using test data"""
new_mgmt_data = ds.mgmt_data_from_string(ds_data.TEST_MGMT_DATA)
assert new_mgmt_data.text.strip() == "mgmt data"
class TestSPKISexp:
def setup_class(self):
self.spki_sexp = ds.SPKISexp()
def testAccessors(self):
"""Test for SPKISexp accessors"""
self.spki_sexp.text = "spki sexp"
new_spki_sexp = ds.spki_sexp_from_string(self.spki_sexp.to_string())
assert new_spki_sexp.text.strip() == "spki sexp"
def testUsingTestData(self):
"""Test for spki_sexp_from_string() using test data"""
new_spki_sexp = ds.spki_sexp_from_string(ds_data.TEST_SPKI_SEXP)
assert new_spki_sexp.text.strip() == "spki sexp"
class TestSPKIData:
def setup_class(self):
self.spki_data = ds.SPKIData()
def testAccessors(self):
"""Test for SPKIData accessors"""
self.spki_data.spki_sexp.append(
ds.spki_sexp_from_string(ds_data.TEST_SPKI_SEXP))
new_spki_data = ds.spki_data_from_string(self.spki_data.to_string())
assert new_spki_data.spki_sexp[0].text.strip() == "spki sexp"
def testUsingTestData(self):
"""Test for spki_data_from_string() using test data"""
new_spki_data = ds.spki_data_from_string(ds_data.TEST_SPKI_DATA)
print new_spki_data
assert new_spki_data.spki_sexp[0].text.strip() == "spki sexp"
assert new_spki_data.spki_sexp[1].text.strip() == "spki sexp2"
class TestPGPData:
def setup_class(self):
self.pgp_data = ds.PGPData()
def testAccessors(self):
"""Test for PGPData accessors"""
self.pgp_data.pgp_key_id = ds.PGPKeyID(text="pgp key id")
self.pgp_data.pgp_key_packet = ds.PGPKeyPacket(text="pgp key packet")
new_pgp_data = ds.pgp_data_from_string(self.pgp_data.to_string())
assert isinstance(new_pgp_data.pgp_key_id, ds.PGPKeyID)
assert isinstance(new_pgp_data.pgp_key_packet, ds.PGPKeyPacket)
assert new_pgp_data.pgp_key_id.text.strip() == "pgp key id"
assert new_pgp_data.pgp_key_packet.text.strip() == "pgp key packet"
def testUsingTestData(self):
"""Test for pgp_data_from_string() using test data"""
new_pgp_data = ds.pgp_data_from_string(ds_data.TEST_PGP_DATA)
assert isinstance(new_pgp_data.pgp_key_id, ds.PGPKeyID)
assert isinstance(new_pgp_data.pgp_key_packet, ds.PGPKeyPacket)
assert new_pgp_data.pgp_key_id.text.strip() == "pgp key id"
assert new_pgp_data.pgp_key_packet.text.strip() == "pgp key packet"
class TestX509IssuerSerial:
def setup_class(self):
self.x509_issuer_serial = ds.X509IssuerSerialType_()
def testAccessors(self):
"""Test for X509SerialNumber accessors"""
self.x509_issuer_serial.x509_issuer_name = ds.X509IssuerName(
text="issuer name")
self.x509_issuer_serial.x509_serial_number = ds.X509SerialNumber(text="1")
new_x509_issuer_serial = ds.x509_issuer_serial_type__from_string(
self.x509_issuer_serial.to_string())
assert new_x509_issuer_serial.x509_issuer_name.text.strip() == \
"issuer name"
assert new_x509_issuer_serial.x509_serial_number.text.strip() == "1"
def testUsingTestData(self):
"""Test for x509_issuer_serial_from_string() using test data"""
new_x509_issuer_serial = ds.x509_issuer_serial_from_string(
ds_data.TEST_X509_ISSUER_SERIAL)
assert new_x509_issuer_serial.x509_issuer_name.text.strip() == \
"issuer name"
assert new_x509_issuer_serial.x509_serial_number.text.strip() == "1"
class TestX509Data:
def setup_class(self):
self.x509_data = ds.X509Data()
def testAccessors(self):
"""Test for X509Data accessors"""
st = ds.x509_issuer_serial_from_string(ds_data.TEST_X509_ISSUER_SERIAL)
print st
self.x509_data.x509_issuer_serial= st
self.x509_data.x509_ski = ds.X509SKI(text="x509 ski")
self.x509_data.x509_subject_name = ds.X509SubjectName(
text="x509 subject name")
self.x509_data.x509_certificate = ds.X509Certificate(
text="x509 certificate")
self.x509_data.x509_crl = ds.X509CRL(text="x509 crl")
new_x509_data = ds.x509_data_from_string(self.x509_data.to_string())
print new_x509_data.keyswv()
print new_x509_data.__dict__.keys()
assert new_x509_data.x509_issuer_serial
assert isinstance(new_x509_data.x509_issuer_serial, ds.X509IssuerSerial)
assert new_x509_data.x509_ski.text.strip() == "x509 ski"
assert isinstance(new_x509_data.x509_ski, ds.X509SKI)
assert new_x509_data.x509_subject_name.text.strip() == \
"x509 subject name"
assert isinstance(new_x509_data.x509_subject_name, ds.X509SubjectName)
assert new_x509_data.x509_certificate.text.strip() == \
"x509 certificate"
assert isinstance(new_x509_data.x509_certificate, ds.X509Certificate)
assert new_x509_data.x509_crl.text.strip() == "x509 crl"
assert isinstance(new_x509_data.x509_crl,ds.X509CRL)
def testUsingTestData(self):
"""Test for x509_data_from_string() using test data"""
new_x509_data = ds.x509_data_from_string(ds_data.TEST_X509_DATA)
assert isinstance(new_x509_data.x509_issuer_serial, ds.X509IssuerSerial)
assert new_x509_data.x509_ski.text.strip() == "x509 ski"
assert isinstance(new_x509_data.x509_ski, ds.X509SKI)
assert new_x509_data.x509_subject_name.text.strip() == \
"x509 subject name"
assert isinstance(new_x509_data.x509_subject_name, ds.X509SubjectName)
assert new_x509_data.x509_certificate.text.strip() == \
"x509 certificate"
assert isinstance(new_x509_data.x509_certificate, ds.X509Certificate)
assert new_x509_data.x509_crl.text.strip() == "x509 crl"
assert isinstance(new_x509_data.x509_crl,ds.X509CRL)
class TestTransform:
def setup_class(self):
self.transform = ds.Transform()
def testAccessors(self):
"""Test for Transform accessors"""
self.transform.x_path.append(ds.TransformType_XPath(text="xpath"))
self.transform.algorithm = ds.TRANSFORM_ENVELOPED
new_transform = ds.transform_from_string(self.transform.to_string())
assert isinstance(new_transform.x_path[0], ds.TransformType_XPath)
assert new_transform.x_path[0].text.strip() == "xpath"
assert new_transform.algorithm == ds.TRANSFORM_ENVELOPED
def testUsingTestData(self):
"""Test for transform_from_string() using test data"""
new_transform = ds.transform_from_string(ds_data.TEST_TRANSFORM)
assert isinstance(new_transform.x_path[0], ds.TransformType_XPath)
assert new_transform.x_path[0].text.strip() == "xpath"
assert new_transform.algorithm == ds.TRANSFORM_ENVELOPED
class TestTransforms:
def setup_class(self):
self.transforms = ds.Transforms()
def testAccessors(self):
"""Test for Transforms accessors"""
self.transforms.transform.append(
ds.transform_from_string(ds_data.TEST_TRANSFORM))
self.transforms.transform.append(
ds.transform_from_string(ds_data.TEST_TRANSFORM))
new_transforms = ds.transforms_from_string(self.transforms.to_string())
assert isinstance(new_transforms.transform[0], ds.Transform)
assert isinstance(new_transforms.transform[1], ds.Transform)
assert new_transforms.transform[0].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[1].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[0].x_path[0].text.strip() == "xpath"
assert new_transforms.transform[1].x_path[0].text.strip() == "xpath"
def testUsingTestData(self):
"""Test for transform_from_string() using test data"""
new_transforms = ds.transforms_from_string(ds_data.TEST_TRANSFORMS)
assert isinstance(new_transforms.transform[0], ds.Transform)
assert isinstance(new_transforms.transform[1], ds.Transform)
assert new_transforms.transform[0].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[1].algorithm == \
ds.TRANSFORM_ENVELOPED
assert new_transforms.transform[0].x_path[0].text.strip() == "xpath"
assert new_transforms.transform[1].x_path[0].text.strip() == "xpath"
class TestRetrievalMethod:
def setup_class(self):
self.retrieval_method = ds.RetrievalMethod()
def testAccessors(self):
"""Test for RetrievalMethod accessors"""
self.retrieval_method.uri = "http://www.example.com/URI"
self.retrieval_method.type = "http://www.example.com/Type"
self.retrieval_method.transforms = ds.transforms_from_string(
ds_data.TEST_TRANSFORMS)
new_retrieval_method = ds.retrieval_method_from_string(
self.retrieval_method.to_string())
assert new_retrieval_method.uri == "http://www.example.com/URI"
assert new_retrieval_method.type == "http://www.example.com/Type"
assert isinstance(new_retrieval_method.transforms, ds.Transforms)
def testUsingTestData(self):
"""Test for retrieval_method_from_string() using test data"""
new_retrieval_method = ds.retrieval_method_from_string(
ds_data.TEST_RETRIEVAL_METHOD)
assert new_retrieval_method.uri == "http://www.example.com/URI"
assert new_retrieval_method.type == "http://www.example.com/Type"
assert isinstance(new_retrieval_method.transforms, ds.Transforms)
class TestRSAKeyValue:
def setup_class(self):
self.rsa_key_value = ds.RSAKeyValue()
def testAccessors(self):
"""Test for RSAKeyValue accessors"""
self.rsa_key_value.modulus = ds.Modulus(text="modulus")
self.rsa_key_value.exponent = ds.Exponent(text="exponent")
new_rsa_key_value = ds.rsa_key_value_from_string(self.rsa_key_value.to_string())
assert isinstance(new_rsa_key_value.modulus, ds.Modulus)
assert isinstance(new_rsa_key_value.exponent, ds.Exponent)
assert new_rsa_key_value.modulus.text.strip() == "modulus"
assert new_rsa_key_value.exponent.text.strip() == "exponent"
def testUsingTestData(self):
"""Test for rsa_key_value_from_string() using test data"""
new_rsa_key_value = ds.rsa_key_value_from_string(
ds_data.TEST_RSA_KEY_VALUE)
assert isinstance(new_rsa_key_value.modulus, ds.Modulus)
assert isinstance(new_rsa_key_value.exponent, ds.Exponent)
assert new_rsa_key_value.modulus.text.strip() == "modulus"
assert new_rsa_key_value.exponent.text.strip() == "exponent"
class TestDSAKeyValue:
def setup_class(self):
self.dsa_key_value = ds.DSAKeyValue()
def testAccessors(self):
"""Test for DSAKeyValue accessors"""
self.dsa_key_value.p = ds.P(text="p")
self.dsa_key_value.q = ds.Q(text="q")
self.dsa_key_value.g = ds.G(text="g")
self.dsa_key_value.y = ds.Y(text="y")
self.dsa_key_value.j = ds.J(text="j")
self.dsa_key_value.seed = ds.Seed(text="seed")
self.dsa_key_value.pgen_counter = ds.PgenCounter(text="pgen counter")
new_dsa_key_value = ds.dsa_key_value_from_string(self.dsa_key_value.to_string())
assert isinstance(new_dsa_key_value.p, ds.P)
assert isinstance(new_dsa_key_value.q, ds.Q)
assert isinstance(new_dsa_key_value.g, ds.G)
assert isinstance(new_dsa_key_value.y, ds.Y)
assert isinstance(new_dsa_key_value.j, ds.J)
assert isinstance(new_dsa_key_value.seed, ds.Seed)
assert isinstance(new_dsa_key_value.pgen_counter, ds.PgenCounter)
assert new_dsa_key_value.p.text.strip() == "p"
assert new_dsa_key_value.q.text.strip() == "q"
assert new_dsa_key_value.g.text.strip() == "g"
assert new_dsa_key_value.y.text.strip() == "y"
assert new_dsa_key_value.j.text.strip() == "j"
assert new_dsa_key_value.seed.text.strip() == "seed"
assert new_dsa_key_value.pgen_counter.text.strip() == "pgen counter"
def testUsingTestData(self):
"""Test for dsa_key_value_from_string() using test data"""
new_dsa_key_value = ds.dsa_key_value_from_string(
ds_data.TEST_DSA_KEY_VALUE)
assert isinstance(new_dsa_key_value.p, ds.P)
assert isinstance(new_dsa_key_value.q, ds.Q)
assert isinstance(new_dsa_key_value.g, ds.G)
assert isinstance(new_dsa_key_value.y, ds.Y)
assert isinstance(new_dsa_key_value.j, ds.J)
assert isinstance(new_dsa_key_value.seed, ds.Seed)
assert isinstance(new_dsa_key_value.pgen_counter, ds.PgenCounter)
assert new_dsa_key_value.p.text.strip() == "p"
assert new_dsa_key_value.q.text.strip() == "q"
assert new_dsa_key_value.g.text.strip() == "g"
assert new_dsa_key_value.y.text.strip() == "y"
assert new_dsa_key_value.j.text.strip() == "j"
assert new_dsa_key_value.seed.text.strip() == "seed"
assert new_dsa_key_value.pgen_counter.text.strip() == "pgen counter"
class TestKeyValue:
def setup_class(self):
self.key_value = ds.KeyValue()
def testAccessors(self):
"""Test for KeyValue accessors"""
self.key_value.dsa_key_value = ds.dsa_key_value_from_string(
ds_data.TEST_DSA_KEY_VALUE)
new_key_value = ds.key_value_from_string(self.key_value.to_string())
assert isinstance(new_key_value.dsa_key_value, ds.DSAKeyValue)
self.key_value.dsa_key_value = None
self.key_value.rsa_key_value = ds.rsa_key_value_from_string(
ds_data.TEST_RSA_KEY_VALUE)
new_key_value = ds.key_value_from_string(self.key_value.to_string())
assert isinstance(new_key_value.rsa_key_value, ds.RSAKeyValue)
def testUsingTestData(self):
"""Test for key_value_from_string() using test data"""
new_key_value = ds.key_value_from_string(ds_data.TEST_KEY_VALUE1)
assert isinstance(new_key_value.dsa_key_value, ds.DSAKeyValue)
self.key_value.dsa_key_value = None
self.key_value.rsa_key_value = ds.rsa_key_value_from_string(
ds_data.TEST_RSA_KEY_VALUE)
new_key_value = ds.key_value_from_string(ds_data.TEST_KEY_VALUE2)
assert isinstance(new_key_value.rsa_key_value, ds.RSAKeyValue)
class TestKeyName:
def setup_class(self):
self.key_name = ds.KeyName()
def testAccessors(self):
"""Test for KeyName accessors"""
self.key_name.text = "key name"
new_key_name = ds.key_name_from_string(self.key_name.to_string())
assert new_key_name.text.strip() == "key name"
def testUsingTestData(self):
"""Test for key_name_from_string() using test data"""
new_key_name = ds.key_name_from_string(ds_data.TEST_KEY_NAME)
assert new_key_name.text.strip() == "key name"
class TestKeyInfo:
def setup_class(self):
self.key_info = ds.KeyInfo()
def testAccessors(self):
"""Test for KeyInfo accessors"""
self.key_info.key_name.append(
ds.key_name_from_string(ds_data.TEST_KEY_NAME))
self.key_info.key_value.append(
ds.key_value_from_string(ds_data.TEST_KEY_VALUE1))
self.key_info.retrieval_method.append(
ds.retrieval_method_from_string(ds_data.TEST_RETRIEVAL_METHOD))
self.key_info.x509_data.append(
ds.x509_data_from_string(ds_data.TEST_X509_DATA))
self.key_info.pgp_data.append(
ds.pgp_data_from_string(ds_data.TEST_PGP_DATA))
self.key_info.spki_data.append(
ds.spki_data_from_string(ds_data.TEST_SPKI_DATA))
self.key_info.mgmt_data.append(
ds.mgmt_data_from_string(ds_data.TEST_MGMT_DATA))
self.key_info.id = "id"
new_key_info = ds.key_info_from_string(self.key_info.to_string())
assert isinstance(new_key_info.key_name[0], ds.KeyName)
assert isinstance(new_key_info.key_value[0], ds.KeyValue)
assert isinstance(new_key_info.retrieval_method[0],
ds.RetrievalMethod)
assert isinstance(new_key_info.x509_data[0], ds.X509Data)
assert isinstance(new_key_info.pgp_data[0], ds.PGPData)
assert isinstance(new_key_info.spki_data[0], ds.SPKIData)
assert isinstance(new_key_info.mgmt_data[0], ds.MgmtData)
assert new_key_info.id == "id"
def testUsingTestData(self):
"""Test for key_info_from_string() using test data"""
new_key_info = ds.key_info_from_string(ds_data.TEST_KEY_INFO)
assert isinstance(new_key_info.key_name[0], ds.KeyName)
assert isinstance(new_key_info.key_value[0], ds.KeyValue)
assert isinstance(new_key_info.retrieval_method[0],
ds.RetrievalMethod)
assert isinstance(new_key_info.x509_data[0], ds.X509Data)
assert isinstance(new_key_info.pgp_data[0], ds.PGPData)
assert isinstance(new_key_info.spki_data[0], ds.SPKIData)
assert isinstance(new_key_info.mgmt_data[0], ds.MgmtData)
assert new_key_info.id == "id"
class TestDigestValue:
def setup_class(self):
self.digest_value = ds.DigestValue()
def testAccessors(self):
"""Test for DigestValue accessors"""
self.digest_value.text = "digest value"
new_digest_value = ds.digest_value_from_string(self.digest_value.to_string())
assert new_digest_value.text.strip() == "digest value"
def testUsingTestData(self):
"""Test for digest_value_from_string() using test data"""
new_digest_value = ds.digest_value_from_string(ds_data.TEST_DIGEST_VALUE)
assert new_digest_value.text.strip() == "digest value"
class TestDigestMethod:
def setup_class(self):
self.digest_method = ds.DigestMethod()
def testAccessors(self):
"""Test for DigestMethod accessors"""
self.digest_method.algorithm = ds.DIGEST_SHA1
new_digest_method = ds.digest_method_from_string(
self.digest_method.to_string())
assert new_digest_method.algorithm == ds.DIGEST_SHA1
def testUsingTestData(self):
"""Test for digest_method_from_string() using test data"""
new_digest_method = ds.digest_method_from_string(
ds_data.TEST_DIGEST_METHOD)
assert new_digest_method.algorithm == ds.DIGEST_SHA1
class TestReference:
def setup_class(self):
self.reference = ds.Reference()
def testAccessors(self):
"""Test for Reference accessors"""
self.reference.transforms = ds.transforms_from_string(
ds_data.TEST_TRANSFORMS)
self.reference.digest_method = ds.digest_method_from_string(
ds_data.TEST_DIGEST_METHOD)
self.reference.digest_value = ds.digest_value_from_string(
ds_data.TEST_DIGEST_VALUE)
self.reference.id = "id"
self.reference.uri = "http://www.example.com/URI"
self.reference.type = "http://www.example.com/Type"
new_reference = ds.reference_from_string(self.reference.to_string())
assert isinstance(new_reference.transforms, ds.Transforms)
assert isinstance(new_reference.digest_method, ds.DigestMethod)
assert isinstance(new_reference.digest_value, ds.DigestValue)
assert new_reference.id == "id"
assert new_reference.uri == "http://www.example.com/URI"
assert new_reference.type == "http://www.example.com/Type"
def testUsingTestData(self):
"""Test for reference_from_string() using test data"""
new_reference = ds.reference_from_string(ds_data.TEST_REFERENCE)
assert isinstance(new_reference.transforms, ds.Transforms)
assert isinstance(new_reference.digest_method, ds.DigestMethod)
assert isinstance(new_reference.digest_value, ds.DigestValue)
assert new_reference.id == "id"
assert new_reference.uri == "http://www.example.com/URI"
assert new_reference.type == "http://www.example.com/Type"
class TestSignatureMethod:
def setup_class(self):
self.signature_method = ds.SignatureMethod()
def testAccessors(self):
"""Test for SignatureMethod accessors"""
self.signature_method.algorithm = ds.SIG_RSA_SHA1
self.signature_method.hmac_output_length = ds.HMACOutputLength(text="8")
new_signature_method = ds.signature_method_from_string(
self.signature_method.to_string())
assert isinstance(new_signature_method.hmac_output_length,
ds.HMACOutputLength)
assert new_signature_method.hmac_output_length.text.strip() == "8"
assert new_signature_method.algorithm == ds.SIG_RSA_SHA1
def testUsingTestData(self):
"""Test for signature_method_from_string() using test data"""
new_signature_method = ds.signature_method_from_string(
ds_data.TEST_SIGNATURE_METHOD)
assert isinstance(new_signature_method.hmac_output_length,
ds.HMACOutputLength)
assert new_signature_method.hmac_output_length.text.strip() == "8"
assert new_signature_method.algorithm == ds.SIG_RSA_SHA1
class TestCanonicalizationMethod:
def setup_class(self):
self.canonicalization_method = ds.CanonicalizationMethod()
def testAccessors(self):
"""Test for CanonicalizationMethod accessors"""
self.canonicalization_method.algorithm = ds.C14N_WITH_C
new_canonicalization_method = ds.canonicalization_method_from_string(
self.canonicalization_method.to_string())
assert new_canonicalization_method.algorithm == ds.C14N_WITH_C
def testUsingTestData(self):
"""Test for canonicalization_method_from_string() using test data"""
new_canonicalization_method = ds.canonicalization_method_from_string(
ds_data.TEST_CANONICALIZATION_METHOD)
assert new_canonicalization_method.algorithm == ds.C14N_WITH_C
class TestSignedInfo:
def setup_class(self):
self.si = ds.SignedInfo()
def testAccessors(self):
"""Test for SignedInfo accessors"""
self.si.id = "id"
self.si.canonicalization_method = ds.canonicalization_method_from_string(
ds_data.TEST_CANONICALIZATION_METHOD)
self.si.signature_method = ds.signature_method_from_string(
ds_data.TEST_SIGNATURE_METHOD)
self.si.reference.append(ds.reference_from_string(
ds_data.TEST_REFERENCE))
new_si = ds.signed_info_from_string(self.si.to_string())
assert new_si.id == "id"
assert isinstance(new_si.canonicalization_method,
ds.CanonicalizationMethod)
assert isinstance(new_si.signature_method, ds.SignatureMethod)
assert isinstance(new_si.reference[0], ds.Reference)
def testUsingTestData(self):
"""Test for signed_info_from_string() using test data"""
new_si = ds.signed_info_from_string(ds_data.TEST_SIGNED_INFO)
assert new_si.id == "id"
assert isinstance(new_si.canonicalization_method,
ds.CanonicalizationMethod)
assert isinstance(new_si.signature_method, ds.SignatureMethod)
assert isinstance(new_si.reference[0], ds.Reference)
class TestSignatureValue:
def setup_class(self):
self.signature_value = ds.SignatureValue()
def testAccessors(self):
"""Test for SignatureValue accessors"""
self.signature_value.id = "id"
self.signature_value.text = "signature value"
new_signature_value = ds.signature_value_from_string(
self.signature_value.to_string())
assert new_signature_value.id == "id"
assert new_signature_value.text.strip() == "signature value"
def testUsingTestData(self):
"""Test for signature_value_from_string() using test data"""
new_signature_value = ds.signature_value_from_string(
ds_data.TEST_SIGNATURE_VALUE)
assert new_signature_value.id == "id"
assert new_signature_value.text.strip() == "signature value"
class TestSignature:
def setup_class(self):
self.signature = ds.Signature()
def testAccessors(self):
"""Test for Signature accessors"""
self.signature.id = "id"
self.signature.signed_info = ds.signed_info_from_string(
ds_data.TEST_SIGNED_INFO)
self.signature.signature_value = ds.signature_value_from_string(
ds_data.TEST_SIGNATURE_VALUE)
self.signature.key_info = ds.key_info_from_string(ds_data.TEST_KEY_INFO)
self.signature.object.append(ds.object_from_string(ds_data.TEST_OBJECT))
new_signature = ds.signature_from_string(self.signature.to_string())
assert new_signature.id == "id"
assert isinstance(new_signature.signed_info, ds.SignedInfo)
assert isinstance(new_signature.signature_value, ds.SignatureValue)
assert isinstance(new_signature.key_info, ds.KeyInfo)
assert isinstance(new_signature.object[0], ds.Object)
def testUsingTestData(self):
"""Test for signature_value_from_string() using test data"""
new_signature = ds.signature_from_string(ds_data.TEST_SIGNATURE)
assert new_signature.id == "id"
assert isinstance(new_signature.signed_info, ds.SignedInfo)
assert isinstance(new_signature.signature_value, ds.SignatureValue)
assert isinstance(new_signature.key_info, ds.KeyInfo)
assert isinstance(new_signature.object[0], ds.Object)
if __name__ == '__main__':
unittest.main()
|
arbn/pysaml2
|
tests/test_00_xmldsig.py
|
Python
|
bsd-2-clause
| 26,402
|
import time
import socket
from client import Client
import util
class SimpleClient(Client):
def __init__(self, ip):
Client.__init__(self)
self.ip = ip
def send_request(self,hostname):
for whitelist_ip_port in self.whitelist:
request = {"client_ip": self.ip, "hostname":hostname,"timestamp": str(time.time())}
ip, port = whitelist_ip_port.split(':')
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print(ip)
s.connect((ip, 8888))
try:
s.sendall(util.json_to_bytes(request))
response = self.listen(3333)
return response
except socket.error as msg:
s = None
continue
finally:
s.close()
return {}
if __name__ == '__main__':
SimpleClient("127.0.0.1:3333").run()
|
xniccum/P2P-DNS
|
src/Client/SimpleClient.py
|
Python
|
gpl-3.0
| 745
|
# -*- coding: utf-8 -*-
# @Author : Huangcc
import requests
import urllib
from lxml import etree
import re
import datetime
import codecs
import time
import random
SLEEP = [0.5, 1, 1.5, 2, 2.5, 3]
class BaiduZhidao():
search_url = 'https://zhidao.baidu.com/search?word={keyword}&ie=gbk&site=-1&sites=0&date=0&pn=PAGE'
my_headers = {
'Host': 'zhidao.baidu.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
}
comment_url = 'https://zhidao.baidu.com/question/{question_id}.html?sort=9&rn=5&pn=PAGE#wgt-answers'
def __init__(self, keyword):
self.session = requests.Session()
self.keyword = keyword
self.search_url = self.search_url.format(keyword=urllib.quote(keyword.decode('utf-8').encode('gbk')))
self.question_ids = []
self.filename = 'baidu_zhidao-comments-%s.csv' % (datetime.datetime.now().strftime('%Y%m%d-%H%M'))
def set_keyword(self, keyword):
self.keyword = keyword
def reset_filename(self):
self.filename = 'baidu_zhidao-comments-%s.csv' % (datetime.datetime.now().strftime('%Y%m%d-%H%M'))
@staticmethod
def extract_question_id(url):
pattern = '/question/(\d+?)\.'
result = re.findall(pattern, url)
if result:
return result[0]
else:
return None
@staticmethod
def html_filter(html_text):
html_text = html_text.replace('\n', '').replace('\t', ' ')
pattern = re.compile(r'<[^>]+>', re.S)
no_html_text = pattern.sub('', html_text)
return no_html_text
def search(self, page=0):
print '-*- start search with page %d -*-' % (page / 10 + 1)
time.sleep(SLEEP[random.randint(0, len(SLEEP) - 1)])
resp = self.session.get(url=self.search_url.replace('PAGE', str(page)), headers=self.my_headers)
if resp.status_code == 200:
response = etree.HTML(resp.text)
urls = response.xpath('//a[@class="ti"]/@href')
self.question_ids.extend(filter(lambda x: True if x else False, map(self.extract_question_id, urls)))
next_page = response.xpath('//a[@class="pager-next"]/@href')
if next_page:
next_page_number = re.findall('&pn=(\d+)$', next_page[0])
if next_page_number:
next_page_number = int(next_page_number[0])
else:
next_page_number = 0
self.search(page=next_page_number) # 递归调用直到没有下一页
else:
print '=*= end search with page %d =*=' % (page / 10 + 1)
else:
print 'Error status code %d in getting search result with page %d' % (resp.status_code, (page / 10 + 1))
print resp.content
def print_question_ids(self):
print self.question_ids
def find_comments(self):
total = len(self.question_ids)
for i, question_id in enumerate(self.question_ids):
print '|*| start get content from question id %s - %d/%d |*|' % (question_id, i + 1, total)
url = self.comment_url.format(question_id=question_id)
self.comment(url)
print '_*_ end get content from question id %s - %d/%d _*_' % (question_id, i + 1, total)
def comment(self, url, page=0):
print ' * start get comments with page %d *' % (page / 5 + 1)
time.sleep(SLEEP[random.randint(0, len(SLEEP) - 1)])
resp = self.session.get(url.replace('PAGE', str(page)), headers=self.my_headers, allow_redirects=False)
if resp.status_code != 200:
print 'Error status code %d in getting comment result with page %d' % (resp.status_code, (page / 5 + 1))
print resp.content
else:
response = etree.HTML(resp.content)
comment_nodes = response.xpath('//span[@class="con"]')
comments = []
for node in comment_nodes:
print node.xpath('string(.)')
comments.append(node.xpath('string(.)').strip())
print ' | get %d comments | ' % len(comments)
# 获取问题
ask_title = response.xpath('//title/text()')
if ask_title:
ask_title = ask_title[0]
else:
ask_title = ""
if comments:
comments = map(self.html_filter, comments)
with codecs.open(self.filename, 'a', encoding='utf-8') as f:
for data in comments:
f.write(ask_title + '|' + data + '\n')
next_page = response.xpath('//a[@class="pager-next"]/@href')
if next_page:
next_page_number = re.findall('&pn=(\d+)#', next_page[0])
if next_page_number:
next_page_number = int(next_page_number[0])
else:
next_page_number = 0
self.comment(url, next_page_number) # 递归调用直到没有下一页
else:
print ' - end get comments with page %d -' % (page / 5 + 1)
if __name__ == '__main__':
baidu_zhidao = BaiduZhidao('美年大健康')
baidu_zhidao.search()
baidu_zhidao.find_comments()
|
huangchuchuan/Spider
|
BaiduZhidaoCommentSpider/baidu_zhidao_comment_spider.py
|
Python
|
apache-2.0
| 5,584
|
request = {
"method": "GET",
"uri": uri("/silly"),
"version": (1, 1),
"headers": [
("AAAAAAAAAAAAA", "++++++++++")
],
"body": ""
}
|
pschanely/gunicorn
|
tests/requests/valid/004.py
|
Python
|
mit
| 162
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-05-17 19:20
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('core', '0013_auto_20180516_1559'),
]
operations = [
migrations.CreateModel(
name='Evento',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('inicio', models.DateTimeField(verbose_name='Início')),
('fim', models.DateTimeField(verbose_name='Fim')),
('titulo', models.CharField(max_length=255, verbose_name='Título')),
('descricao', models.TextField(verbose_name='Descrição')),
('workspace', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='evento_set', to='core.AreaTrabalho', verbose_name='Área de Trabalho')),
],
options={
'verbose_name_plural': 'Eventos',
'verbose_name': 'Evento',
},
),
migrations.CreateModel(
name='Programacao',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('inicio', models.DateTimeField(verbose_name='Início')),
('fim', models.DateTimeField(verbose_name='Fim')),
('titulo', models.CharField(max_length=255, verbose_name='Título')),
('descricao', models.TextField(verbose_name='Descrição')),
('evento', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='programacao_set', to='agenda.Evento', verbose_name='Programacao do Evento')),
],
),
]
|
cmjatai/cmj
|
cmj/agenda/migrations/0001_initial.py
|
Python
|
gpl-3.0
| 1,895
|
"""Truncated SVD for sparse matrices, aka latent semantic analysis (LSA).
"""
# Author: Lars Buitinck <L.J.Buitinck@uva.nl>
# Olivier Grisel <olivier.grisel@ensta.org>
# Michael Becker <mike@beckerfuffle.com>
# License: 3-clause BSD.
import numpy as np
import scipy.sparse as sp
try:
from scipy.sparse.linalg import svds
except ImportError:
from ..utils.arpack import svds
from ..base import BaseEstimator, TransformerMixin
from ..utils import check_array, as_float_array, check_random_state
from ..utils.extmath import randomized_svd, safe_sparse_dot, svd_flip
from ..utils.sparsefuncs import mean_variance_axis
__all__ = ["TruncatedSVD"]
class TruncatedSVD(BaseEstimator, TransformerMixin):
"""Dimensionality reduction using truncated SVD (aka LSA).
This transformer performs linear dimensionality reduction by means of
truncated singular value decomposition (SVD). It is very similar to PCA,
but operates on sample vectors directly, instead of on a covariance matrix.
This means it can work with scipy.sparse matrices efficiently.
In particular, truncated SVD works on term count/tf-idf matrices as
returned by the vectorizers in sklearn.feature_extraction.text. In that
context, it is known as latent semantic analysis (LSA).
This estimator supports two algorithm: a fast randomized SVD solver, and
a "naive" algorithm that uses ARPACK as an eigensolver on (X * X.T) or
(X.T * X), whichever is more efficient.
Read more in the :ref:`User Guide <LSA>`.
Parameters
----------
n_components : int, default = 2
Desired dimensionality of output data.
Must be strictly less than the number of features.
The default value is useful for visualisation. For LSA, a value of
100 is recommended.
algorithm : string, default = "randomized"
SVD solver to use. Either "arpack" for the ARPACK wrapper in SciPy
(scipy.sparse.linalg.svds), or "randomized" for the randomized
algorithm due to Halko (2009).
n_iter : int, optional (default 5)
Number of iterations for randomized SVD solver. Not used by ARPACK.
The default is larger than the default in `randomized_svd` to handle
sparse matrices that may have large slowly decaying spectrum.
random_state : int or RandomState, optional
(Seed for) pseudo-random number generator. If not given, the
numpy.random singleton is used.
tol : float, optional
Tolerance for ARPACK. 0 means machine precision. Ignored by randomized
SVD solver.
Attributes
----------
components_ : array, shape (n_components, n_features)
explained_variance_ratio_ : array, [n_components]
Percentage of variance explained by each of the selected components.
explained_variance_ : array, [n_components]
The variance of the training samples transformed by a projection to
each component.
Examples
--------
>>> from sklearn.decomposition import TruncatedSVD
>>> from sklearn.random_projection import sparse_random_matrix
>>> X = sparse_random_matrix(100, 100, density=0.01, random_state=42)
>>> svd = TruncatedSVD(n_components=5, random_state=42)
>>> svd.fit(X) # doctest: +NORMALIZE_WHITESPACE
TruncatedSVD(algorithm='randomized', n_components=5, n_iter=5,
random_state=42, tol=0.0)
>>> print(svd.explained_variance_ratio_) # doctest: +ELLIPSIS
[ 0.0782... 0.0552... 0.0544... 0.0499... 0.0413...]
>>> print(svd.explained_variance_ratio_.sum()) # doctest: +ELLIPSIS
0.279...
See also
--------
PCA
RandomizedPCA
References
----------
Finding structure with randomness: Stochastic algorithms for constructing
approximate matrix decompositions
Halko, et al., 2009 (arXiv:909) http://arxiv.org/pdf/0909.4061
Notes
-----
SVD suffers from a problem called "sign indeterminancy", which means the
sign of the ``components_`` and the output from transform depend on the
algorithm and random state. To work around this, fit instances of this
class to data once, then keep the instance around to do transformations.
"""
def __init__(self, n_components=2, algorithm="randomized", n_iter=5,
random_state=None, tol=0.):
self.algorithm = algorithm
self.n_components = n_components
self.n_iter = n_iter
self.random_state = random_state
self.tol = tol
def fit(self, X, y=None):
"""Fit LSI model on training data X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Returns
-------
self : object
Returns the transformer object.
"""
self.fit_transform(X)
return self
def fit_transform(self, X, y=None):
"""Fit LSI model to X and perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data.
Returns
-------
X_new : array, shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
"""
X = as_float_array(X, copy=False)
random_state = check_random_state(self.random_state)
# If sparse and not csr or csc, convert to csr
if sp.issparse(X) and X.getformat() not in ["csr", "csc"]:
X = X.tocsr()
if self.algorithm == "arpack":
U, Sigma, VT = svds(X, k=self.n_components, tol=self.tol)
# svds doesn't abide by scipy.linalg.svd/randomized_svd
# conventions, so reverse its outputs.
Sigma = Sigma[::-1]
U, VT = svd_flip(U[:, ::-1], VT[::-1])
elif self.algorithm == "randomized":
k = self.n_components
n_features = X.shape[1]
if k >= n_features:
raise ValueError("n_components must be < n_features;"
" got %d >= %d" % (k, n_features))
U, Sigma, VT = randomized_svd(X, self.n_components,
n_iter=self.n_iter,
random_state=random_state)
else:
raise ValueError("unknown algorithm %r" % self.algorithm)
self.components_ = VT
# Calculate explained variance & explained variance ratio
X_transformed = np.dot(U, np.diag(Sigma))
self.explained_variance_ = exp_var = np.var(X_transformed, axis=0)
if sp.issparse(X):
_, full_var = mean_variance_axis(X, axis=0)
full_var = full_var.sum()
else:
full_var = np.var(X, axis=0).sum()
self.explained_variance_ratio_ = exp_var / full_var
return X_transformed
def transform(self, X):
"""Perform dimensionality reduction on X.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
New data.
Returns
-------
X_new : array, shape (n_samples, n_components)
Reduced version of X. This will always be a dense array.
"""
X = check_array(X, accept_sparse='csr')
return safe_sparse_dot(X, self.components_.T)
def inverse_transform(self, X):
"""Transform X back to its original space.
Returns an array X_original whose transform would be X.
Parameters
----------
X : array-like, shape (n_samples, n_components)
New data.
Returns
-------
X_original : array, shape (n_samples, n_features)
Note that this is always a dense array.
"""
X = check_array(X)
return np.dot(X, self.components_)
|
DailyActie/Surrogate-Model
|
01-codes/scikit-learn-master/sklearn/decomposition/truncated_svd.py
|
Python
|
mit
| 7,897
|
# Copyright 2021 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# WikiGraphs is licensed under the terms of the Creative Commons
# Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
#
# WikiText-103 data (unchanged) is licensed by Salesforce.com, Inc. under the
# terms of the Creative Commons Attribution-ShareAlike 4.0 International
# (CC BY-SA 4.0) license. You can find details about CC BY-SA 4.0 at:
#
# https://creativecommons.org/licenses/by-sa/4.0/legalcode
#
# Freebase data is licensed by Google LLC under the terms of the Creative
# Commons CC BY 4.0 license. You may obtain a copy of the License at:
#
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# ==============================================================================
r"""Tool to visualize graphs.
You need to have the command line tool `dot` installed locally, for example by
`sudo apt-get install graphviz`.
Example usage:
python visualize_graph.py \
--logtostderr --graph_ids=0:48 --truncate_limit=500 --layout=fdp
"""
import html
import os
import textwrap
from absl import app
from absl import flags
from absl import logging
from wikigraphs.data import io_tools
from wikigraphs.data import paired_dataset as pd
FLAGS = flags.FLAGS
flags.DEFINE_string('subset', 'valid', 'Which subset to choose graphs from.')
flags.DEFINE_string('graph_ids', '', 'A comma-separated string of graph IDs'
' (0-based), for example `1,2,3`. Or alternatively a'
' range, e.g. `0:10` which is equivalent to'
' `0,1,2,3,...,9`.')
flags.DEFINE_string('version', 'max256', 'Which version of data to load.')
flags.DEFINE_string('data_dir', '', 'Path to a directory that contains the raw'
' paired data, if provided.')
flags.DEFINE_string('output_dir', '/tmp/graph_vis', 'Output directory to save'
' the visualized graphs.')
flags.DEFINE_integer('truncate_limit', -1, 'Maximum length for graph nodes in'
' visualization.')
flags.DEFINE_string('layout', 'fdp', 'Which one of the dot layout to use.')
def truncate(s: str) -> str:
if FLAGS.truncate_limit > 0 and len(s) > FLAGS.truncate_limit:
s = s[:FLAGS.truncate_limit] + '...'
return s
def format_label(s: str, width: int = 40) -> str:
"""Format a node / edge label."""
s = io_tools.normalize_freebase_string(s)
s = truncate(s)
lines = s.split('\\n')
output_lines = []
for line in lines:
line = html.escape(line)
if width > 0:
output_lines += textwrap.wrap(line, width)
else:
output_lines.append(line)
return '<' + '<br/>'.join(output_lines) + '>'
def graph_to_dot(graph_text_pair: io_tools.GraphTextPair) -> str:
"""Convert a graph to a dot file."""
dot = ['digraph {', 'node [shape=rect];']
graph = pd.Graph.from_edges(graph_text_pair.edges)
center_node_id = graph.node2id(graph_text_pair.center_node)
for i, n in enumerate(graph.nodes()):
color = '#f5dc98' if i == center_node_id else (
'#b0ffad' if not(n[0] == '"' and n[-1] == '"') else '#ffffff')
label = format_label(n)
dot.append(f'{i} [ label = {label}, fillcolor="{color}", style="filled"];')
for i, j, e in graph.edges():
dot.append(f'{i} -> {j} [ label = {format_label(e, width=0)} ];')
dot.append('}')
return '\n'.join(dot)
def visualize_graph(graph_text_pair: io_tools.GraphTextPair,
graph_id: int,
output_dir: str):
"""Visualize a graph and save the visualization to the specified directory."""
dot = graph_to_dot(graph_text_pair)
output_file = os.path.join(output_dir, f'{graph_id}.dot')
logging.info('Writing output to %s', output_file)
with open(output_file, 'w') as f:
f.write(dot)
pdf_output = os.path.join(output_dir, f'{graph_id}.pdf')
os.system(f'dot -K{FLAGS.layout} -Tpdf -o {pdf_output} {output_file}')
def main(_):
logging.info('Loading the %s set of data.', FLAGS.subset)
pairs = list(pd.RawDataset(subset=FLAGS.subset,
data_dir=FLAGS.data_dir or None,
shuffle_data=False,
version=FLAGS.version))
logging.info('Loaded %d graph-text pairs.')
if ':' in FLAGS.graph_ids:
start, end = [int(i) for i in FLAGS.graph_ids.split(':')]
graph_ids = list(range(start, end))
else:
graph_ids = [int(i) for i in FLAGS.graph_ids.split(',')]
logging.info('Visualizing graphs with ID %r', graph_ids)
if not os.path.exists(FLAGS.output_dir):
os.makedirs(FLAGS.output_dir)
for gid in graph_ids:
visualize_graph(pairs[gid], gid, FLAGS.output_dir)
if __name__ == '__main__':
app.run(main)
|
deepmind/deepmind-research
|
wikigraphs/scripts/visualize_graph.py
|
Python
|
apache-2.0
| 5,249
|
"""Models for the builds app."""
from __future__ import absolute_import
import logging
import os.path
import re
from shutil import rmtree
from builtins import object
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _, ugettext
from guardian.shortcuts import assign
from taggit.managers import TaggableManager
from .constants import (BUILD_STATE, BUILD_TYPES, VERSION_TYPES,
LATEST, NON_REPOSITORY_VERSIONS, STABLE,
BUILD_STATE_FINISHED, BRANCH, TAG)
from .managers import VersionManager
from .querysets import BuildQuerySet, RelatedBuildQuerySet, VersionQuerySet
from .version_slug import VersionSlugField
from readthedocs.core.utils import broadcast
from readthedocs.projects.constants import (PRIVACY_CHOICES, GITHUB_URL,
GITHUB_REGEXS, BITBUCKET_URL,
BITBUCKET_REGEXS, PRIVATE)
from readthedocs.projects.models import Project, APIProject
DEFAULT_VERSION_PRIVACY_LEVEL = getattr(settings, 'DEFAULT_VERSION_PRIVACY_LEVEL', 'public')
log = logging.getLogger(__name__)
@python_2_unicode_compatible
class Version(models.Model):
"""Version of a ``Project``."""
project = models.ForeignKey(Project, verbose_name=_('Project'),
related_name='versions')
type = models.CharField(
_('Type'), max_length=20,
choices=VERSION_TYPES, default='unknown',
)
# used by the vcs backend
#: The identifier is the ID for the revision this is version is for. This
#: might be the revision number (e.g. in SVN), or the commit hash (e.g. in
#: Git). If the this version is pointing to a branch, then ``identifier``
#: will contain the branch name.
identifier = models.CharField(_('Identifier'), max_length=255)
#: This is the actual name that we got for the commit stored in
#: ``identifier``. This might be the tag or branch name like ``"v1.0.4"``.
#: However this might also hold special version names like ``"latest"``
#: and ``"stable"``.
verbose_name = models.CharField(_('Verbose Name'), max_length=255)
#: The slug is the slugified version of ``verbose_name`` that can be used
#: in the URL to identify this version in a project. It's also used in the
#: filesystem to determine how the paths for this version are called. It
#: must not be used for any other identifying purposes.
slug = VersionSlugField(_('Slug'), max_length=255,
populate_from='verbose_name')
supported = models.BooleanField(_('Supported'), default=True)
active = models.BooleanField(_('Active'), default=False)
built = models.BooleanField(_('Built'), default=False)
uploaded = models.BooleanField(_('Uploaded'), default=False)
privacy_level = models.CharField(
_('Privacy Level'), max_length=20, choices=PRIVACY_CHOICES,
default=DEFAULT_VERSION_PRIVACY_LEVEL, help_text=_("Level of privacy for this Version.")
)
tags = TaggableManager(blank=True)
machine = models.BooleanField(_('Machine Created'), default=False)
objects = VersionManager.from_queryset(VersionQuerySet)()
class Meta(object):
unique_together = [('project', 'slug')]
ordering = ['-verbose_name']
permissions = (
# Translators: Permission around whether a user can view the
# version
('view_version', _('View Version')),
)
def __str__(self):
return ugettext(u"Version %(version)s of %(project)s (%(pk)s)" % {
'version': self.verbose_name,
'project': self.project,
'pk': self.pk
})
@property
def commit_name(self):
"""
Return the branch name, the tag name or the revision identifier.
The result could be used as ref in a git repo, e.g. for linking to
GitHub or Bitbucket.
"""
# LATEST is special as it is usually a branch but does not contain the
# name in verbose_name.
if self.slug == LATEST:
if self.project.default_branch:
return self.project.default_branch
return self.project.vcs_repo().fallback_branch
if self.slug == STABLE:
if self.type == BRANCH:
# Special case, as we do not store the original branch name
# that the stable version works on. We can only interpolate the
# name from the commit identifier, but it's hacky.
# TODO: Refactor ``Version`` to store more actual info about
# the underlying commits.
if self.identifier.startswith('origin/'):
return self.identifier[len('origin/'):]
return self.identifier
# By now we must have handled all special versions.
assert self.slug not in NON_REPOSITORY_VERSIONS
if self.type in (BRANCH, TAG):
# If this version is a branch or a tag, the verbose_name will
# contain the actual name. We cannot use identifier as this might
# include the "origin/..." part in the case of a branch. A tag
# would contain the hash in identifier, which is not as pretty as
# the actual tag name.
return self.verbose_name
# If we came that far it's not a special version nor a branch or tag.
# Therefore just return the identifier to make a safe guess.
return self.identifier
def get_absolute_url(self):
if not self.built and not self.uploaded:
return reverse('project_version_detail', kwargs={
'project_slug': self.project.slug,
'version_slug': self.slug,
})
private = self.privacy_level == PRIVATE
return self.project.get_docs_url(version_slug=self.slug, private=private)
def save(self, *args, **kwargs): # pylint: disable=arguments-differ
"""Add permissions to the Version for all owners on save."""
from readthedocs.projects import tasks
obj = super(Version, self).save(*args, **kwargs)
for owner in self.project.users.all():
assign('view_version', owner, self)
try:
self.project.sync_supported_versions()
except Exception:
log.exception('failed to sync supported versions')
broadcast(type='app', task=tasks.symlink_project, args=[self.project.pk])
return obj
def delete(self, *args, **kwargs): # pylint: disable=arguments-differ
from readthedocs.projects import tasks
log.info('Removing files for version %s', self.slug)
broadcast(type='app', task=tasks.clear_artifacts, args=[self.pk])
broadcast(type='app', task=tasks.symlink_project, args=[self.project.pk])
super(Version, self).delete(*args, **kwargs)
@property
def identifier_friendly(self):
"""Return display friendly identifier"""
if re.match(r'^[0-9a-f]{40}$', self.identifier, re.I):
return self.identifier[:8]
return self.identifier
def get_subdomain_url(self):
private = self.privacy_level == PRIVATE
return self.project.get_docs_url(version_slug=self.slug,
lang_slug=self.project.language,
private=private)
def get_downloads(self, pretty=False):
project = self.project
data = {}
if pretty:
if project.has_pdf(self.slug):
data['PDF'] = project.get_production_media_url('pdf', self.slug)
if project.has_htmlzip(self.slug):
data['HTML'] = project.get_production_media_url('htmlzip', self.slug)
if project.has_epub(self.slug):
data['Epub'] = project.get_production_media_url('epub', self.slug)
else:
if project.has_pdf(self.slug):
data['pdf'] = project.get_production_media_url('pdf', self.slug)
if project.has_htmlzip(self.slug):
data['htmlzip'] = project.get_production_media_url('htmlzip', self.slug)
if project.has_epub(self.slug):
data['epub'] = project.get_production_media_url('epub', self.slug)
return data
def get_conf_py_path(self):
conf_py_path = self.project.conf_dir(self.slug)
checkout_prefix = self.project.checkout_path(self.slug)
conf_py_path = os.path.relpath(conf_py_path, checkout_prefix)
return conf_py_path
def get_build_path(self):
"""Return version build path if path exists, otherwise `None`"""
path = self.project.checkout_path(version=self.slug)
if os.path.exists(path):
return path
return None
def clean_build_path(self):
"""Clean build path for project version
Ensure build path is clean for project version. Used to ensure stale
build checkouts for each project version are removed.
"""
try:
path = self.get_build_path()
if path is not None:
log.debug('Removing build path {0} for {1}'.format(
path, self))
rmtree(path)
except OSError:
log.exception('Build path cleanup failed')
def get_github_url(self, docroot, filename, source_suffix='.rst', action='view'):
"""
Return a GitHub URL for a given filename.
`docroot`
Location of documentation in repository
`filename`
Name of file
`source_suffix`
File suffix of documentation format
`action`
`view` (default) or `edit`
"""
repo_url = self.project.repo
if 'github' not in repo_url:
return ''
if not docroot:
return ''
else:
if docroot[0] != '/':
docroot = "/%s" % docroot
if docroot[-1] != '/':
docroot = "%s/" % docroot
if action == 'view':
action_string = 'blob'
elif action == 'edit':
action_string = 'edit'
for regex in GITHUB_REGEXS:
match = regex.search(repo_url)
if match:
user, repo = match.groups()
break
else:
return ''
repo = repo.rstrip('/')
return GITHUB_URL.format(
user=user,
repo=repo,
version=self.commit_name,
docroot=docroot,
path=filename,
source_suffix=source_suffix,
action=action_string,
)
def get_bitbucket_url(self, docroot, filename, source_suffix='.rst'):
repo_url = self.project.repo
if 'bitbucket' not in repo_url:
return ''
if not docroot:
return ''
for regex in BITBUCKET_REGEXS:
match = regex.search(repo_url)
if match:
user, repo = match.groups()
break
else:
return ''
repo = repo.rstrip('/')
return BITBUCKET_URL.format(
user=user,
repo=repo,
version=self.commit_name,
docroot=docroot,
path=filename,
source_suffix=source_suffix,
)
class APIVersion(Version):
"""Version proxy model for API data deserialization
This replaces the pattern where API data was deserialized into a mocked
:py:cls:`Version` object. This pattern was confusing, as it was not explicit
as to what form of object you were working with -- API backed or database
backed.
This model preserves the Version model methods, allowing for overrides on
model field differences. This model pattern will generally only be used on
builder instances, where we are interacting solely with API data.
"""
project = None
class Meta:
proxy = True
def __init__(self, *args, **kwargs):
self.project = APIProject(**kwargs.pop('project', {}))
# These fields only exist on the API return, not on the model, so we'll
# remove them to avoid throwing exceptions due to unexpected fields
for key in ['resource_uri', 'absolute_url', 'downloads']:
try:
del kwargs[key]
except KeyError:
pass
super(APIVersion, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
return 0
@python_2_unicode_compatible
class VersionAlias(models.Model):
"""Alias for a ``Version``."""
project = models.ForeignKey(Project, verbose_name=_('Project'),
related_name='aliases')
from_slug = models.CharField(_('From slug'), max_length=255, default='')
to_slug = models.CharField(_('To slug'), max_length=255, default='',
blank=True)
largest = models.BooleanField(_('Largest'), default=False)
def __str__(self):
return ugettext(u"Alias for %(project)s: %(from)s -> %(to)s" % {
'project': self.project,
'from': self.from_slug,
'to': self.to_slug,
})
@python_2_unicode_compatible
class Build(models.Model):
"""Build data."""
project = models.ForeignKey(Project, verbose_name=_('Project'),
related_name='builds')
version = models.ForeignKey(Version, verbose_name=_('Version'), null=True,
related_name='builds')
type = models.CharField(_('Type'), max_length=55, choices=BUILD_TYPES,
default='html')
state = models.CharField(_('State'), max_length=55, choices=BUILD_STATE,
default='finished')
date = models.DateTimeField(_('Date'), auto_now_add=True)
success = models.BooleanField(_('Success'), default=True)
setup = models.TextField(_('Setup'), null=True, blank=True)
setup_error = models.TextField(_('Setup error'), null=True, blank=True)
output = models.TextField(_('Output'), default='', blank=True)
error = models.TextField(_('Error'), default='', blank=True)
exit_code = models.IntegerField(_('Exit code'), null=True, blank=True)
commit = models.CharField(_('Commit'), max_length=255, null=True, blank=True)
length = models.IntegerField(_('Build Length'), null=True, blank=True)
builder = models.CharField(_('Builder'), max_length=255, null=True, blank=True)
cold_storage = models.NullBooleanField(_('Cold Storage'),
help_text='Build steps stored outside the database.')
# Manager
objects = BuildQuerySet.as_manager()
class Meta(object):
ordering = ['-date']
get_latest_by = 'date'
index_together = [
['version', 'state', 'type']
]
def __str__(self):
return ugettext(u"Build %(project)s for %(usernames)s (%(pk)s)" % {
'project': self.project,
'usernames': ' '.join(self.project.users.all()
.values_list('username', flat=True)),
'pk': self.pk,
})
@models.permalink
def get_absolute_url(self):
return ('builds_detail', [self.project.slug, self.pk])
@property
def finished(self):
"""Return if build has a finished state"""
return self.state == BUILD_STATE_FINISHED
class BuildCommandResultMixin(object):
"""Mixin for common command result methods/properties
Shared methods between the database model :py:class:`BuildCommandResult` and
non-model respresentations of build command results from the API
"""
@property
def successful(self):
"""Did the command exit with a successful exit code"""
return self.exit_code == 0
@property
def failed(self):
"""Did the command exit with a failing exit code
Helper for inverse of :py:meth:`successful`
"""
return not self.successful
@python_2_unicode_compatible
class BuildCommandResult(BuildCommandResultMixin, models.Model):
"""Build command for a ``Build``."""
build = models.ForeignKey(Build, verbose_name=_('Build'),
related_name='commands')
command = models.TextField(_('Command'))
description = models.TextField(_('Description'), blank=True)
output = models.TextField(_('Command output'), blank=True)
exit_code = models.IntegerField(_('Command exit code'))
start_time = models.DateTimeField(_('Start time'))
end_time = models.DateTimeField(_('End time'))
class Meta(object):
ordering = ['start_time']
get_latest_by = 'start_time'
objects = RelatedBuildQuerySet.as_manager()
def __str__(self):
return (ugettext(u'Build command {pk} for build {build}')
.format(pk=self.pk, build=self.build))
@property
def run_time(self):
"""Total command runtime in seconds"""
if self.start_time is not None and self.end_time is not None:
diff = self.end_time - self.start_time
return diff.seconds
|
pombredanne/readthedocs.org
|
readthedocs/builds/models.py
|
Python
|
mit
| 17,368
|
# coding: utf8
# intente algo como
from gluon import reserved_sql_keywords
keywords = reserved_sql_keywords.POSTGRESQL
def index(): return dict(message="hello from pgtest.py")
@auth.requires_membership("manager")
def test_keywords():
response.generic_patterns = ["*",]
report = UL()
fields = UL()
for table in db:
if str(table).upper() in keywords:
report.append(LI("Table %s is a pg keyword" % table))
for field in table:
print "field", str(field)
if str(field).split(".")[1].upper() in keywords:
report.append(LI("Field %s is a pg keyword" % field))
fields.append(LI(str(field)))
return dict(report=report, fields=fields)
|
bkahlerventer/web2congress
|
controllers/pgtest.py
|
Python
|
bsd-3-clause
| 726
|
#!/usr/bin/python
# -*- coding:UTF-8 -*-
# Copyright (c) Stephen Smally <stephen.smally@gmail.com>
#
# This program 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 2 of the License, or
# (at your option) any later version.
# This program 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 for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
from gi.repository import Gtk
from gi.repository import Pango
from gi.repository import GdkPixbuf
from ConfigParser import RawConfigParser
from notify import notify
import control
import os
from aptdaemon import client, gtk3widgets
from . import LOG
import gettext
_ = gettext.gettext
client = client.AptClient()
dialog = gtk3widgets.AptProgressDialog(debconf=True)
control.__init__()
import sqlite3
db_path = os.path.join(control.controller.db_path, "lsc_packages.db")
try:
db = sqlite3.Connection(db_path)
cursor = db.cursor()
except sqlite3.OperationalError:
result = os.system('gksu -m %s lubuntu-software-center-build-db %s %s \
/usr/share/LSC/categories.ini' % (_(
'"The database for Lubuntu Software Center needs to be (re-)created"'),
db_path, control.controller.app_install_directory))
if result == 0:
db = sqlite3.Connection(db_path)
cursor = db.cursor()
else:
pass
#Error message should appear. There is no db and it couldn't be created
try:
cursor.execute("SELECT * FROM packages")
except sqlite3.OperationalError:
result = os.system('gksu -m %s lubuntu-software-center-build-db %s %s \
/usr/share/LSC/categories.ini' % (_(
'"The database for Lubuntu Software Center needs to be (re-)created"'),
db_path, control.controller.app_install_directory))
if result == 0:
db = sqlite3.Connection(db_path)
cursor = db.cursor()
else:
pass
# Error message: Table exists, but seems empty and couldn't be filled.
class append_packages:
def __init__(self, app, category, status, model, showboth):
control.__init__()
self.app = app
self.category = category
self.status = status
self.model = model
self.sortkey = 0
self.showboth = showboth
def run(self):
'''Append the packages to the given Gtk.ListStore'''
self.status_dict = {
0: "",
1: "",
2: "",
4: "",
5: "",
6: Gtk.STOCK_YES
}
LOG.debug("sensitive!")
if control.controller.expert_mode:
id = 1
else:
id = 0
if self.showboth:
for items in cursor.execute(
"SELECT * FROM %s ORDER BY name" % (self.category)):
self.app.append_packages_appending(
items, self.status, self.status_dict, self.model, (1, 1))
else:
for items in cursor.execute(
"SELECT * FROM %s WHERE ID=%s ORDER BY name" %
(self.category, id)):
self.app.append_packages_appending(
items, self.status, self.status_dict, self.model, (1, 1))
self.app.ui.pkgs_count.set_text("%s " % len(self.model) +
_("packages listed"))
if self.app.ui.search_pkg.search_entry.get_text() != \
self.app.ui.search_pkg.search_string:
self.app.ui.search_pkg.search_function(
self.app.ui.search_pkg.search_entry.get_text(), 20)
def get_categories():
categories = {}
cat_parser = RawConfigParser()
if os.path.isfile(os.path.join("data", "categories.ini")):
cat = open(os.path.join("data", "categories.ini"))
else:
cat = open(os.path.join(
control.controller.data_system_path, "categories.ini"))
cat_parser.readfp(cat)
for section in cat_parser.sections():
name = cat_parser.get(section, "name")
icon = cat_parser.get(section, "icon")
#tags = cat_parser.get(section, "contains")
showboth = cat_parser.getboolean(section, "showboth")
categories[section] = [icon, _(name), showboth]
return categories
def getdesc(pkg):
for items in cursor.execute(
"SELECT desc FROM packages WHERE pkg_name='%s'" % pkg):
return items[0]
def getshortdesc(pkg):
for items in cursor.execute(
"SELECT comment FROM packages WHERE pkg_name='%s'" % pkg):
return items[0]
def getdeps(pkg):
tmp = ""
for item in cursor.execute(
"SELECT deps FROM packages WHERE pkg_name='%s'" % pkg):
tmp = item[0]
if tmp == "":
return []
else:
return tmp.split(";")
def getrecs(pkg):
tmp = ""
for item in cursor.execute(
"SELECT recs FROM packages WHERE pkg_name='%s'" % pkg):
tmp = item[0]
if tmp == "":
return []
else:
return tmp.split(";")
def download_screenshot(pkg, path, image, button):
path_screenshot = os.path.join("/usr/share/pyshared/",
"lubuntu-software-center/",
"lubuntu-software-center-download-scrot")
if os.path.isfile(path_screenshot):
response = os.popen(" ".join(["python",
path_screenshot,
pkg, path])).read()
else:
response = os.popen(" ".join(["python",
"scripts/lubuntu-software-center-download-scrot",
pkg, path])).read()
button.set_visible(True)
if os.path.exists("/".join([path, pkg])):
try:
scrot_buf = GdkPixbuf.Pixbuf.new_from_file_at_size(
"/".join([path, pkg]), 250, 250)
image.set_from_pixbuf(scrot_buf)
except:
pass
def download_review(pkg, path):
path_review = os.path.join("/usr/share/pyshared/",
"lubuntu-software-center/",
"lubuntu-software-center-download-review")
if os.path.isfile(path_review):
response = os.popen(" ".join(["python",
path_review,
pkg, path])).read()
else:
response = os.popen(" ".join(["python",
"scripts/lubuntu-software-center-download-review",
pkg, path])).read()
return path + pkg
def parse_review(pkg, path, box):
if os.path.exists(path + pkg + ".ini"):
review_parser = RawConfigParser()
review = open(path + pkg + ".ini", "r")
review_parser.readfp(review)
for reviews in review_parser.sections():
summary = Gtk.Label("<b>" + review_parser.get(
reviews, "summary").capitalize() + "</b>")
summary.set_use_markup(True)
summary.props.xalign = 0.0
summary.props.xpad = 5
text = Gtk.Label(review_parser.get(reviews, "review_text"))
text.props.xalign = 0.0
text.props.xpad = 10
text.set_line_wrap_mode(Pango.WrapMode.WORD)
text.set_line_wrap(True)
box.pack_start(summary, False, False, 0)
box.pack_start(text, False, False, 0)
if len(box.get_children()) == 1: # If only the Reviews title is in the box
summary = Gtk.Label("<b>" + _("No reviews available") + "</b>")
summary.set_use_markup(True)
box.pack_start(summary, False, False, 0)
def install_package(pkgs, app):
transaction = client.install_packages(pkgs)
transaction.connect("finished", finish_trans, app, True)
dialog.set_transaction(transaction)
LOG.debug("running dialog")
dialog.run()
def remove_package(pkgs, app):
transaction = client.remove_packages(pkgs)
transaction.connect("finished", finish_trans, app, False)
dialog.set_transaction(transaction)
LOG.debug("running dialog")
dialog.run()
def get_if_apt_lies(pkg):
'''test if the apt cache lies'''
result = os.system("apt-get -s install %s" % pkg)
if result == 0:
# Apt Cache lies, we can install it!
return True
else:
# It's true, damaged packages
return False
def finish_trans(transaction, exit_status, root, inst):
if exit_status == "exit-success":
dialog.hide()
LOG.debug("success")
if inst:
notify("installed")
else:
notify("removed")
root.choosed_page = 1
root.refresh_system_call()
else:
dialog.hide()
finishdialog = gtk3widgets.AptErrorDialog(error=transaction.error)
finishdialog.run()
LOG.warn("failed")
|
hyperdriveguy/mint-software-center
|
src/threadingops.py
|
Python
|
gpl-2.0
| 9,535
|
#!/usr/bin/env python3
def say_hi():
print('Hi, this is mymodule speaking')
__version__ = '0.1'
|
pam-phy/python-notes
|
byte-of-python/mymodule.py
|
Python
|
gpl-2.0
| 99
|
#!/usr/bin/env python
import pika
import os
cloud_broker_host = os.environ.get('CLOUD_BROKER_HOST')
cloud_broker_port = os.environ.get('CLOUD_BROKER_PORT')
cloud_broker_auth = os.environ.get('CLOUD_BROKER_AUTH')
cloud_username = cloud_broker_auth.split(':')[0]
cloud_password = cloud_broker_auth.split(':')[1]
# Connect to fog broker service
credentials = pika.PlainCredentials(cloud_username, cloud_password)
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=cloud_broker_host, port=int(cloud_broker_port), credentials=credentials))
channel = connection.channel()
channel.exchange_declare(exchange='sensor_collector',
exchange_type='fanout')
#
result = channel.queue_declare(durable=True, exclusive=False)
queue_name = result.method.queue
channel.queue_bind(exchange='sensor_collector',
queue=queue_name)
print(' [*] Waiting for data. To exit press CTRL+C')
def callback(ch, method, properties, body):
print(" [x] %r" % body)
channel.basic_consume(callback,
queue=queue_name,
no_ack=True)
channel.start_consuming()
|
cloudcomputinghust/IoT
|
test-component/receive_data_only.py
|
Python
|
mit
| 1,140
|
#!/usr/bin/env python
'''
006.py: https://projecteuler.net/problem=6
Sum Square Difference
The sum of the squares of the first ten natural numbers is,
1^2 + 2^2 + ... + 10^2 = 385
The square of the sum of the first ten natural numbers is,
(1 + 2 + ... + 10)^2 = 55^2 = 3025
Hence the difference between the sum of the squares of the first ten natural
numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred
natural numbers and the square of the sum.
'''
import os
import pytest
def sum_square_diff(n):
return _square_of_sums(n) - _sum_of_squares(n)
def _sum_of_squares(n):
'''Returns the sum of the squares of integers from 1 to n.'''
if n == 1:
return n
elif n > 1:
return (n * n) + _sum_of_squares(n-1)
def _square_of_sums(n):
'''Returns the square of the sum of integers from 1 to n.'''
sum = 0
for i in range(1, n+1):
sum += i
return sum * sum
def test_sum_square_diff():
'''Test'''
assert 2640 == sum_square_diff(10)
def main():
'''Main runner, delegates to solution.'''
print(sum_square_diff(100))
if __name__ == '__main__':
main()
|
ikumen/project-euler
|
solutions/006.py
|
Python
|
mit
| 1,157
|
import re
import ephem
from datetime import datetime, timedelta
def valid_grid(grid):
mo = re.match(r'^[A-R]{2}([0-9]{2}([a-x]{2})?)?$', grid, re.IGNORECASE)
return mo is not None
def grid_to_latlon(grid):
if not valid_grid(grid):
raise Exception('invalid grid locator %s' % grid)
grid = grid.lower()
lat, lon = -90.0, -180.0
lon += 20*(ord(grid[0]) - ord('a'))
lat += 10*(ord(grid[1]) - ord('a'))
if len(grid) == 2:
return lat, lon
lon += 2*int(grid[2])
lat += 1*int(grid[3])
if len(grid) == 4:
return lat, lon
lon += (2/24) * (ord(grid[4]) - ord('a'))
lat += (1/24) * (ord(grid[5]) - ord('a'))
return lat, lon
def latlon_to_grid(lat, lon, precision=2):
grid = ''
grid += chr(int((lon + 180.0)/20) + ord('A'))
grid += chr(int((lat + 90.0)/10) + ord('A'))
if precision == 0:
return grid
grid += str(int(lon % 20 / 2))
grid += str(int(lat % 10))
if precision == 1:
return grid
grid += chr(int(lon % 2 * 12) + ord('a'))
grid += chr(int(lat % 1 * 24) + ord('a'))
return grid
def ephem_time_to_datetime(et):
fmt = '%Y/%m/%d %H:%M:%S'
return datetime.strptime(str(et), fmt)
def datetime_to_ephem_time(dt):
return ephem.Date((dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second))
def timestamp(et, fmt='%Y-%m-%d %H:%M:%S'):
return ephem_time_to_datetime(et).strftime(fmt)
def delta_t(t0, t1):
return ephem_time_to_datetime(t1) - ephem_time_to_datetime(t0)
|
lofaldli/satellite-tracker
|
tracker/utils.py
|
Python
|
mit
| 1,532
|
# coding:utf-8
"""
Utility Tools for Jieba
=======================
https://github.com/fxsjy/jieba
"Jieba" (Chinese for "to stutter") Chinese text segmentation
"""
__author__ = "GE Ning <https://github.com/gening/>"
__copyright__ = "Copyright (C) 2017 GE Ning"
__license__ = "LGPL-3.0"
__version__ = "1.0"
from jieba import posseg
def tag(text):
# return: [(word, pos), ...]
word_pos_list = [(word, pos) for word, pos in posseg.cut(text)]
return word_pos_list
from contextlib import contextmanager
@contextmanager
def enable_parallel(processnum=4):
from jieba import enable_parallel
from jieba import disable_parallel
# __enter__
print('enable jieba parallel')
enable_parallel(processnum)
# yield only one object
yield
# __exit__
disable_parallel()
print('disable jieba parallel')
|
gening/nlp_util
|
nlp_util/jieba_nlp.py
|
Python
|
lgpl-3.0
| 842
|
# -*- coding: utf-8 -*-
# This file is part of Shuup.
#
# Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import unicode_literals
from django.http import JsonResponse
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
from shuup.admin.utils.picotable import ChoicesFilter, Column, TextFilter
from shuup.admin.utils.views import PicotableListView
from shuup.core.models import Product, StockBehavior, Supplier
from shuup.simple_supplier.forms import AlertLimitForm, StockAdjustmentForm
from shuup.simple_supplier.models import StockCount
from shuup.simple_supplier.utils import (
get_stock_adjustment_div, get_stock_information_div_id,
get_stock_information_html
)
class StocksListView(PicotableListView):
template_name = "shuup/simple_supplier/admin/base_picotable.jinja"
model = Product
default_columns = [
Column(
"sku", _("SKU"), sort_field="product__sku", display="product__sku", linked=True,
filter_config=TextFilter(filter_field="product__sku", placeholder=_("Filter by SKU..."))
),
Column(
"name", _("Name"), sort_field="product__translations__name", display="product__name", linked=True,
filter_config=TextFilter(filter_field="product__translations__name", placeholder=_("Filter by name..."))
),
Column(
"supplier", _("Supplier"), display="supplier", linked=False,
filter_config=ChoicesFilter(Supplier.objects.filter(module_identifier="simple_supplier"))
),
Column(
"stock_information", _("Stock information"), display="get_stock_information",
linked=False, sortable=False, raw=True
),
Column(
"adjust_stock", _("Adjust stock"), display="get_stock_adjustment_form",
sortable=False, linked=False, raw=True
)
]
def __init__(self):
super(StocksListView, self).__init__()
self.columns = self.default_columns
def get_object_abstract(self, instance, item):
item.update({"_linked_in_mobile": False, "_url": self.get_object_url(instance.product)})
return [
{"text": item.get("name"), "class": "header"},
{"title": "", "text": item.get("sku")},
{"title": "", "text": " ", "raw": item.get("stock_information")},
{"title": "", "text": " ", "raw": item.get("adjust_stock")},
]
def get_queryset(self):
return StockCount.objects.filter(
supplier__module_identifier="simple_supplier",
product__stock_behavior=StockBehavior.STOCKED,
product__deleted=False
).order_by("product__id")
def get_context_data(self, **kwargs):
context = super(PicotableListView, self).get_context_data(**kwargs)
context["toolbar"] = None
context["title"] = _("Stock management")
return context
def get_stock_information(self, instance):
return get_stock_information_html(instance.supplier, instance.product)
def get_stock_adjustment_form(self, instance):
return get_stock_adjustment_div(self.request, instance.supplier, instance.product)
def get_adjustment_success_message(stock_adjustment):
arguments = {
"delta": stock_adjustment.delta,
"unit_short_name": stock_adjustment.product.sales_unit.short_name,
"product_name": stock_adjustment.product.name,
"supplier_name": stock_adjustment.supplier.name
}
if stock_adjustment.delta > 0:
return _(
"Added %(delta)s %(unit_short_name)s for product %(product_name)s stock (%(supplier_name)s)"
) % arguments
else:
return _(
"Removed %(delta)s %(unit_short_name)s from product %(product_name)s stock (%(supplier_name)s)"
) % arguments
def _process_stock_adjustment(form, request, supplier_id, product_id):
data = form.cleaned_data
supplier = Supplier.objects.get(id=supplier_id)
stock_adjustment = supplier.module.adjust_stock(
product_id,
delta=data.get("delta"),
purchase_price=data.get("purchase_price"),
created_by=request.user
)
success_message = {
"stockInformationDiv": "#%s" % get_stock_information_div_id(
stock_adjustment.supplier, stock_adjustment.product),
"updatedStockInformation": get_stock_information_html(
stock_adjustment.supplier, stock_adjustment.product),
"message": get_adjustment_success_message(stock_adjustment)
}
return JsonResponse(success_message, status=200)
def process_stock_adjustment(request, supplier_id, product_id):
return _process_and_catch_errors(
_process_stock_adjustment, StockAdjustmentForm, request, supplier_id, product_id)
def _process_alert_limit(form, request, supplier_id, product_id):
supplier = Supplier.objects.get(id=supplier_id)
product = Product.objects.get(id=product_id)
sc = StockCount.objects.get(supplier=supplier, product=product)
data = form.cleaned_data
sc.alert_limit = data.get("alert_limit")
sc.save()
supplier = Supplier.objects.get(id=supplier_id)
success_message = {
"stockInformationDiv": "#%s" % get_stock_information_div_id(supplier, product),
"updatedStockInformation": get_stock_information_html(supplier, product),
"message": _("Alert limit for product %(product_name)s set to %(value)s.") % {
"product_name": product.name, "value": sc.alert_limit},
}
return JsonResponse(success_message, status=200)
def process_alert_limit(request, supplier_id, product_id):
return _process_and_catch_errors(
_process_alert_limit, AlertLimitForm, request, supplier_id, product_id)
def _process_and_catch_errors(process, form_class, request, supplier_id, product_id):
try:
if request.method != "POST":
raise Exception(_("Not allowed"))
form = form_class(request.POST)
if form.is_valid():
return process(form, request, supplier_id, product_id)
error_message = ugettext("Error, please check submitted values and try again.")
return JsonResponse({"message": error_message}, status=400)
except Exception as exc:
error_message = ugettext(
"Error, please check submitted values and try again (%(error)s).") % {"error": exc}
return JsonResponse({"message": error_message}, status=400)
|
suutari/shoop
|
shuup/simple_supplier/admin_module/views.py
|
Python
|
agpl-3.0
| 6,635
|
# -*- coding: utf-8 -*-
"""
Base Library (:mod:`refmanage`)
===============================
.. currentmodule:: refmanage
"""
from version import __version__
from refmanage import *
from reffile import RefFile, BibFile, NonbibFile
import utils
|
jrsmith3/refmanage
|
refmanage/__init__.py
|
Python
|
mit
| 245
|
import TestData
import TestGetItemDescriptionRequest
import TestItemDatabase
import TestBountyHunter
import TestLogin
import TestLogout
from kol.util import Report
import sys
import unittest
def main(argv=sys.argv):
TestData.data["userName"] = argv[1]
TestData.data["password"] = argv[2]
Report.activeSections = []
# Add the tests.
suite = unittest.TestSuite()
suite.addTest(TestItemDatabase.Main())
suite.addTest(TestLogin.Main())
suite.addTest(TestGetItemDescriptionRequest.Main())
suite.addTest(TestBountyHunter.Main())
suite.addTest(TestLogout.Main())
# Run the test suite.
unittest.TextTestRunner(verbosity=2).run(suite)
if __name__ == '__main__':
main()
|
ijzer/cwbot-ndy
|
kol/test/TestAll.py
|
Python
|
bsd-3-clause
| 725
|
# coding: utf-8
from __future__ import unicode_literals
from datetime import datetime
import io
import logging
import os
from jinja2.exceptions import TemplateNotFound
import jinja2
import json
from mkdocs import nav, search, utils
from mkdocs.relative_path_ext import RelativePathExtension
import mkdocs
log = logging.getLogger(__name__)
def convert_markdown(markdown_source, config, site_navigation=None):
"""
Convert the Markdown source file to HTML as per the config and
site_navigation. Return a tuple of the HTML as a string, the parsed table
of contents, and a dictionary of any metadata that was specified in the
Markdown file.
"""
extensions = [
RelativePathExtension(site_navigation, config['strict'])
] + config['markdown_extensions']
return utils.convert_markdown(
markdown_source=markdown_source,
extensions=extensions,
extension_configs=config['mdx_configs']
)
def get_global_context(nav, config):
"""
Given the SiteNavigation and config, generate the context which is relevant
to app pages.
"""
site_name = config['site_name']
if config['site_favicon']:
site_favicon = nav.url_context.make_relative('/' + config['site_favicon'])
else:
site_favicon = None
page_description = config['site_description']
extra_javascript = utils.create_media_urls(nav, config['extra_javascript'])
extra_css = utils.create_media_urls(nav, config['extra_css'])
return {
'site_name': site_name,
'site_author': config['site_author'],
'favicon': site_favicon,
'page_description': page_description,
# Note that there's intentionally repetition here. Rather than simply
# provide the config dictionary we instead pass everything explicitly.
#
# This helps ensure that we can throughly document the context that
# gets passed to themes.
'repo_url': config['repo_url'],
'repo_name': config['repo_name'],
'nav': nav,
'base_url': nav.url_context.make_relative('/'),
'homepage_url': nav.homepage.url,
'site_url': config['site_url'],
'extra_css': extra_css,
'extra_javascript': extra_javascript,
'include_nav': config['include_nav'],
'include_next_prev': config['include_next_prev'],
'copyright': config['copyright'],
'google_analytics': config['google_analytics'],
'mkdocs_version': mkdocs.__version__,
'build_date_utc': datetime.utcnow(),
'config': config
}
def get_page_context(page, content, toc, meta, config):
"""
Generate the page context by extending the global context and adding page
specific variables.
"""
if page.is_homepage or page.title is None:
page_title = None
else:
page_title = page.title
if page.is_homepage:
page_description = config['site_description']
else:
page_description = None
if config['site_url']:
base = config['site_url']
if not base.endswith('/'):
base += '/'
canonical_url = utils.urljoin(
base, page.abs_url.lstrip('/'))
else:
canonical_url = None
return {
'page_title': page_title,
'page_description': page_description,
'content': content,
'toc': toc,
'meta': meta,
'canonical_url': canonical_url,
'current_page': page,
'previous_page': page.previous_page,
'next_page': page.next_page
}
def build_template(template_name, env, config, site_navigation=None):
log.debug("Building template: %s", template_name)
try:
template = env.get_template(template_name)
except TemplateNotFound:
return False
if site_navigation is not None:
context = get_global_context(site_navigation, config)
else:
context = {}
output_content = template.render(context)
output_path = os.path.join(config['site_dir'], template_name)
utils.write_file(output_content.encode('utf-8'), output_path)
return True
def _build_page(page, config, site_navigation, env, dump_json):
# Read the input file
input_path = os.path.join(config['docs_dir'], page.input_path)
try:
input_content = io.open(input_path, 'r', encoding='utf-8').read()
except IOError:
log.error('file not found: %s', input_path)
raise
# Process the markdown text
html_content, table_of_contents, meta = convert_markdown(
markdown_source=input_content,
config=config,
site_navigation=site_navigation
)
context = get_global_context(site_navigation, config)
context.update(get_page_context(
page, html_content, table_of_contents, meta, config
))
# Allow 'template:' override in md source files.
if 'template' in meta:
template = env.get_template(meta['template'][0])
else:
template = env.get_template('base.html')
# Render the template.
output_content = template.render(context)
# Write the output file.
output_path = os.path.join(config['site_dir'], page.output_path)
if dump_json:
json_context = {
'content': context['content'],
'title': context['current_page'].title,
'url': context['current_page'].abs_url,
'language': 'en',
}
json_output = json.dumps(json_context, indent=4).encode('utf-8')
utils.write_file(json_output, output_path.replace('.html', '.json'))
else:
utils.write_file(output_content.encode('utf-8'), output_path)
return html_content, table_of_contents, meta
def build_extra_templates(extra_templates, config, site_navigation=None):
log.debug("Building extra_templates page")
for extra_template in extra_templates:
input_path = os.path.join(config['docs_dir'], extra_template)
with io.open(input_path, 'r', encoding='utf-8') as template_file:
template = jinja2.Template(template_file.read())
if site_navigation is not None:
context = get_global_context(site_navigation, config)
else:
context = {}
output_content = template.render(context)
output_path = os.path.join(config['site_dir'], extra_template)
utils.write_file(output_content.encode('utf-8'), output_path)
def build_pages(config, dump_json=False):
"""
Builds all the pages and writes them into the build directory.
"""
site_navigation = nav.SiteNavigation(config['pages'], config['use_directory_urls'])
loader = jinja2.FileSystemLoader(config['theme_dir'] + [config['mkdocs_templates'], ])
env = jinja2.Environment(loader=loader)
search_index = search.SearchIndex()
build_template('404.html', env, config, site_navigation)
if not build_template('search.html', env, config, site_navigation):
log.debug("Search is enabled but the theme doesn't contain a "
"search.html file. Assuming the theme implements search "
"within a modal.")
build_template('sitemap.xml', env, config, site_navigation)
build_extra_templates(config['extra_templates'], config, site_navigation)
for page in site_navigation.walk_pages():
try:
log.debug("Building page %s", page.input_path)
build_result = _build_page(page, config, site_navigation, env,
dump_json)
html_content, table_of_contents, _ = build_result
search_index.add_entry_from_context(
page, html_content, table_of_contents)
except Exception:
log.error("Error building page %s", page.input_path)
raise
search_index = search_index.generate_search_index()
json_output_path = os.path.join(config['site_dir'], 'mkdocs', 'search_index.json')
utils.write_file(search_index.encode('utf-8'), json_output_path)
def build(config, live_server=False, dump_json=False, clean_site_dir=False):
"""
Perform a full site build.
"""
if clean_site_dir:
log.info("Cleaning site directory")
utils.clean_directory(config['site_dir'])
if not live_server:
log.info("Building documentation to directory: %s", config['site_dir'])
if not clean_site_dir and site_directory_contains_stale_files(config['site_dir']):
log.info("The directory contains stale files. Use --clean to remove them.")
if dump_json:
build_pages(config, dump_json=True)
return
# Reversed as we want to take the media files from the builtin theme
# and then from the custom theme_dir so the custom versions take take
# precedence.
for theme_dir in reversed(config['theme_dir']):
log.debug("Copying static assets from theme: %s", theme_dir)
utils.copy_media_files(theme_dir, config['site_dir'])
log.debug("Copying static assets from the docs dir.")
utils.copy_media_files(config['docs_dir'], config['site_dir'])
log.debug("Building markdown pages.")
build_pages(config)
def site_directory_contains_stale_files(site_directory):
"""
Check if the site directory contains stale files from a previous build.
Right now the check returns true if the directory is not empty.
A more sophisticated approach should be found to trigger only if there are
files that won't be overwritten anyway.
"""
if os.path.exists(site_directory):
if os.listdir(site_directory):
return True
return False
|
jpush/mkdocs
|
mkdocs/commands/build.py
|
Python
|
bsd-2-clause
| 9,619
|
import nengo
import numpy as np
model = nengo.Network()
model.config[nengo.Ensemble].neuron_type=nengo.Direct()
with model:
x = nengo.Ensemble(100, 1, neuron_type=nengo.LIF())
y = nengo.Ensemble(100, 1, neuron_type=nengo.LIF())
nengo.Connection(x, y,
function=lambda x: 1-4*(x-0.5)**2)
scale_y = 20
dy = nengo.Ensemble(100, 1)
nengo.Connection(y, dy, synapse=0.001, transform=scale_y)
nengo.Connection(y, dy, synapse=0.02, transform=-scale_y)
scale_x = 5
dx = nengo.Ensemble(100, 1)
nengo.Connection(x, dx, synapse=0.01, transform=scale_x)
nengo.Connection(x, dx, synapse=0.02, transform=-scale_x)
prod = nengo.networks.Product(100, 1)
nengo.Connection(dx, prod.A)
nengo.Connection(dy, prod.B)
nengo.Connection(prod.output, x, synapse=0.01, transform=0.5)
#for ens in prod.all_ensembles:
# ens.neuron_type = nengo.Direct()
stim_x = nengo.Node(0)
nengo.Connection(stim_x, x)
nengo.Connection(x, x, synapse=0.01)
|
tcstewar/nengo_learning_examples
|
rl/find_best.py
|
Python
|
gpl-3.0
| 1,066
|
"""
:mod:`neo.io` provides classes for reading and/or writing
electrophysiological data files.
Note that if the package dependency is not satisfied for one io, it does not
raise an error but a warning.
:attr:`neo.io.iolist` provides a list of successfully imported io classes.
Functions:
.. autofunction:: neo.io.get_io
Classes:
* :attr:`AlphaOmegaIO`
* :attr:`AsciiImageIO`
* :attr:`AsciiSignalIO`
* :attr:`AsciiSpikeTrainIO`
* :attr:`AxographIO`
* :attr:`AxonIO`
* :attr:`BCI2000IO`
* :attr:`BlackrockIO`
* :attr:`BlkIO`
* :attr:`BrainVisionIO`
* :attr:`BrainwareDamIO`
* :attr:`BrainwareF32IO`
* :attr:`BrainwareSrcIO`
* :attr:`ElanIO`
* :attr:`IgorIO`
* :attr:`IntanIO`
* :attr:`KlustaKwikIO`
* :attr:`KwikIO`
* :attr:`MicromedIO`
* :attr:`NeoHdf5IO`
* :attr:`NeoMatlabIO`
* :attr:`NestIO`
* :attr:`NeuralynxIO`
* :attr:`NeuroExplorerIO`
* :attr:`NeuroScopeIO`
* :attr:`NeuroshareIO`
* :attr:`NixIO`
* :attr:`NSDFIO`
* :attr:`OpenEphysIO`
* :attr:`PickleIO`
* :attr:`PlexonIO`
* :attr:`RawBinarySignalIO`
* :attr:`RawMCSIO`
* :attr:`Spike2IO`
* :attr:`StimfitIO`
* :attr:`TdtIO`
* :attr:`TiffIO`
* :attr:`WinEdrIO`
* :attr:`WinWcpIO`
.. autoclass:: neo.io.AlphaOmegaIO
.. autoattribute:: extensions
.. autoclass:: neo.io.AsciiImageIO
.. autoattribute:: extensions
.. autoclass:: neo.io.AsciiSignalIO
.. autoattribute:: extensions
.. autoclass:: neo.io.AsciiSpikeTrainIO
.. autoattribute:: extensions
.. autoclass:: neo.io.AxographIO
.. autoattribute:: extensions
.. autoclass:: neo.io.AxonIO
.. autoattribute:: extensions
.. autoclass:: neo.io.BCI2000IO
.. autoattribute:: extensions
.. autoclass:: neo.io.BlackrockIO
.. autoattribute:: extensions
.. autoclass:: neo.io.BlkIO
.. autoattribute:: extensions
.. autoclass:: neo.io.BrainVisionIO
.. autoattribute:: extensions
.. autoclass:: neo.io.BrainwareDamIO
.. autoattribute:: extensions
.. autoclass:: neo.io.BrainwareF32IO
.. autoattribute:: extensions
.. autoclass:: neo.io.BrainwareSrcIO
.. autoattribute:: extensions
.. autoclass:: neo.io.ElanIO
.. autoattribute:: extensions
.. .. autoclass:: neo.io.ElphyIO
.. autoattribute:: extensions
.. autoclass:: neo.io.IgorIO
.. autoattribute:: extensions
.. autoclass:: neo.io.IntanIO
.. autoattribute:: extensions
.. autoclass:: neo.io.KlustaKwikIO
.. autoattribute:: extensions
.. autoclass:: neo.io.KwikIO
.. autoattribute:: extensions
.. autoclass:: neo.io.MicromedIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NeoHdf5IO
.. autoattribute:: extensions
.. autoclass:: neo.io.NeoMatlabIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NestIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NeuralynxIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NeuroExplorerIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NeuroScopeIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NeuroshareIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NixIO
.. autoattribute:: extensions
.. autoclass:: neo.io.NSDFIO
.. autoattribute:: extensions
.. autoclass:: neo.io.OpenEphysIO
.. autoattribute:: extensions
.. autoclass:: neo.io.PickleIO
.. autoattribute:: extensions
.. autoclass:: neo.io.PlexonIO
.. autoattribute:: extensions
.. autoclass:: neo.io.RawBinarySignalIO
.. autoattribute:: extensions
.. autoclass:: neo.io.RawMCSIO
.. autoattribute:: extensions
.. autoclass:: Spike2IO
.. autoattribute:: extensions
.. autoclass:: neo.io.StimfitIO
.. autoattribute:: extensions
.. autoclass:: neo.io.TdtIO
.. autoattribute:: extensions
.. autoclass:: neo.io.TiffIO
.. autoattribute:: extensions
.. autoclass:: neo.io.WinEdrIO
.. autoattribute:: extensions
.. autoclass:: neo.io.WinWcpIO
.. autoattribute:: extensions
"""
import os.path
# try to import the neuroshare library.
# if it is present, use the neuroshareapiio to load neuroshare files
# if it is not present, use the neurosharectypesio to load files
try:
import neuroshare as ns
except ImportError as err:
from neo.io.neurosharectypesio import NeurosharectypesIO as NeuroshareIO
# print("\n neuroshare library not found, loading data with ctypes" )
# print("\n to use the API be sure to install the library found at:")
# print("\n www.http://pythonhosted.org/neuroshare/")
else:
from neo.io.neuroshareapiio import NeuroshareapiIO as NeuroshareIO
# print("neuroshare library successfully imported")
# print("\n loading with API...")
from neo.io.alphaomegaio import AlphaOmegaIO
from neo.io.asciiimageio import AsciiImageIO
from neo.io.asciisignalio import AsciiSignalIO
from neo.io.asciispiketrainio import AsciiSpikeTrainIO
from neo.io.axographio import AxographIO
from neo.io.axonio import AxonIO
from neo.io.blackrockio import BlackrockIO
from neo.io.blackrockio_v4 import BlackrockIO as OldBlackrockIO
from neo.io.blkio import BlkIO
from neo.io.bci2000io import BCI2000IO
from neo.io.brainvisionio import BrainVisionIO
from neo.io.brainwaredamio import BrainwareDamIO
from neo.io.brainwaref32io import BrainwareF32IO
from neo.io.brainwaresrcio import BrainwareSrcIO
from neo.io.elanio import ElanIO
# from neo.io.elphyio import ElphyIO
from neo.io.exampleio import ExampleIO
from neo.io.igorproio import IgorIO
from neo.io.intanio import IntanIO
from neo.io.klustakwikio import KlustaKwikIO
from neo.io.kwikio import KwikIO
from neo.io.micromedio import MicromedIO
from neo.io.hdf5io import NeoHdf5IO
from neo.io.neomatlabio import NeoMatlabIO
from neo.io.nestio import NestIO
from neo.io.neuralynxio import NeuralynxIO
from neo.io.neuralynxio_v1 import NeuralynxIO as OldNeuralynxIO
from neo.io.neuroexplorerio import NeuroExplorerIO
from neo.io.neuroscopeio import NeuroScopeIO
from neo.io.nixio import NixIO
from neo.io.nixio_fr import NixIO as NixIOFr
from neo.io.nsdfio import NSDFIO
from neo.io.openephysio import OpenEphysIO
from neo.io.pickleio import PickleIO
from neo.io.plexonio import PlexonIO
from neo.io.rawbinarysignalio import RawBinarySignalIO
from neo.io.rawmcsio import RawMCSIO
from neo.io.spike2io import Spike2IO
from neo.io.stimfitio import StimfitIO
from neo.io.tdtio import TdtIO
from neo.io.tiffio import TiffIO
from neo.io.winedrio import WinEdrIO
from neo.io.winwcpio import WinWcpIO
iolist = [
AlphaOmegaIO,
AsciiImageIO,
AsciiSignalIO,
AsciiSpikeTrainIO,
AxographIO,
AxonIO,
BCI2000IO,
BlackrockIO,
BlkIO,
BrainVisionIO,
BrainwareDamIO,
BrainwareF32IO,
BrainwareSrcIO,
ElanIO,
# ElphyIO,
ExampleIO,
IgorIO,
IntanIO,
KlustaKwikIO,
KwikIO,
MicromedIO,
NixIO, # place NixIO before NeoHdf5IO to make it the default for .h5 files
NeoHdf5IO,
NeoMatlabIO,
NestIO,
NeuralynxIO,
NeuroExplorerIO,
NeuroScopeIO,
NeuroshareIO,
NSDFIO,
OpenEphysIO,
PickleIO,
PlexonIO,
RawBinarySignalIO,
RawMCSIO,
Spike2IO,
StimfitIO,
TdtIO,
TiffIO,
WinEdrIO,
WinWcpIO
]
def get_io(filename, *args, **kwargs):
"""
Return a Neo IO instance, guessing the type based on the filename suffix.
"""
extension = os.path.splitext(filename)[1][1:]
for io in iolist:
if extension in io.extensions:
return io(filename, *args, **kwargs)
raise IOError("File extension %s not registered" % extension)
|
JuliaSprenger/python-neo
|
neo/io/__init__.py
|
Python
|
bsd-3-clause
| 7,472
|
#!/usr/bin/env python
#
# Copyright 2015 British Broadcasting Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Unit-tests for code that maps timings from arduino to synchronisation timeline
and also code that does the pulse detection.
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../src")
from detect import ConvertAtoB
from detect import ErrorBoundInterpolator
from detect import calcAcWcCorrelationAndDispersion
from detect import TimelineReconstructor
from detect import calcFlashThresholds
from detect import calcBeepThresholds
from detect import detectPulses
from detect import minMaxDataToEnvelopeData
from detect import timesForSamples
from detect import ArduinoToSyncTimelineTime
from detect import BeepFlashDetector
import unittest
class Test_ConvertAtoB(unittest.TestCase):
def test_a2b(self):
a2b = ConvertAtoB( (100,10), (200, 20) )
self.assertEquals(a2b(150), 15.0)
self.assertEquals(a2b(100), 10.0)
self.assertEquals(a2b(200), 20.0)
self.assertEquals(a2b(133), 13.3)
class Test_ErrorBoundInterpolator(unittest.TestCase):
def testInterpolate(self):
err = ErrorBoundInterpolator( (100, 0.5), (200, 0.7) )
self.assertEquals(err(100), 0.5)
self.assertEquals(err(150), 0.6)
self.assertEquals(err(200), 0.7)
def testOutOfBounds(self):
err = ErrorBoundInterpolator( (100, 0.5), (200, 0.7) )
self.assertRaises(ValueError, err, 99)
self.assertRaises(ValueError, err, 201)
class Test_calcAcWcCorrelationAndDispersion(unittest.TestCase):
def testSimple(self):
wcT1 = 100
acT2 = 1000
acT3 = 1002
wcT4 = 140
wcPrecision=5
acPrecision=2
c,d = calcAcWcCorrelationAndDispersion( wcT1, acT2, acT3, wcT4, wcPrecision, acPrecision )
self.assertEquals(c, (1001, 120))
self.assertEquals(d, 38/2 + 5 + 2)
class Test_TimelineReconstructor(unittest.TestCase):
def testSimple(self):
history = [
(100, (100, 1000, 1.0)), # when time was 100, we observed that time 100 maps to timeline position 1000, and that the speed of timeline for 1
(200, (100, 1000, 1.0)), # when time was 200, we observed that the same relationship was true
(300, (100, 1005, 1.0)), # by time 300, we observed that the relationship had changed slightly
]
parentTickRate = 100
childTickRate = 1000
interpolate = True
reconstructor = TimelineReconstructor(history, parentTickRate, childTickRate, interpolate)
# do tests, pretending we wind the clock back to when time was 120
self.assertEquals(reconstructor(150, at=120), 1500)
self.assertEquals(reconstructor(200, at=120), 2000)
# now pretend we're after the 3rd observations - the relationship should have shifted
self.assertEquals(reconstructor(110, at=300), 1105)
# now pretend we're midway between 2nd and 3rd. Expect it to interpolate
self.assertEquals(reconstructor(110, at=250), 1102.5)
# cant reconstruct at a time before the first control timestamp was logged
self.assertRaises(ValueError, reconstructor, 110, at=99)
class Test_calcThresholds(unittest.TestCase):
def testFlashThresholds(self):
hiSampleData = [ 1, 8, 8, 0, 0, 0, 3, 8, 8, 7, 4, 1, 0, 1, 0, 7, 9, 1, 7, 9, 8, 3, 0, 0, 0, 8, 9 ]
loSampleData = [ 0, 7, 3, 0, 0, 0, 1, 6, 8, 7, 2, 0, 0, 0, 0, 5, 8, 0, 4, 9, 7, 1, 0, 0, 0, 1, 9 ]
rising, falling = calcFlashThresholds(loSampleData, hiSampleData)
self.assertEquals(rising, 6.0)
self.assertEquals(falling, 3.0)
def testBeepThresholds(self):
sampleEnvelope = [12, 16, 16, 11, 1, 2, 2, 3, 1, 8, 12, 17, 5, 1, 1, 2, 6, 14, 9, 13, 14, 3, 2, 1, 2, 11, 12, 14, 17]
rising, falling = calcBeepThresholds(sampleEnvelope)
self.assertAlmostEqual(rising, 11.667, places=3)
self.assertAlmostEqual(falling, 6.333, places=3)
class Test_detectPulses(unittest.TestCase):
def testSimpleFlashScenario(self):
risingThreshold = 7
fallingThreshold = 4
minPulseDuration = 0
holdCount = 1
# IGNORE- FIRST--- SECOND---------- IGNORE
sampleData = [ 1, 8, 8, 0, 0, 0, 3, 8, 8, 7, 4, 1, 0, 1, 0, 7, 9, 1, 7, 9, 8, 3, 0, 0, 0, 8, 9 ]
result = detectPulses(sampleData, risingThreshold, fallingThreshold, minPulseDuration, holdCount)
self.assertEquals(result, [8.0, 17.5])
def testSimpleBeepScenario(self):
# IGNORE------- FIRST---------
hiSampleData = [ 7, 9, 8, 2, 0, 1, 0, 2, 1, 0, 3, 8, 4, 1, 0, 1 ]
loSampleData = [ -5, -7, -8, -9, -1, -1, -2, -1, 0, -8, -9, -9, -1, 0, -1, -1 ]
# SECOND----------- IGNORE----
hiSampleData.extend([ 2, 6, 0, 9, 8, 2, 2, 0, 1, 8, 6, 9, 9 ])
loSampleData.extend([-4, -8, -9, -4, -6, -1, 0, -1, -1, -3, -6, -5, -8 ])
# offset it so it is not about 0
loSampleData = map(lambda x:x+100, loSampleData)
hiSampleData = map(lambda x:x+100, hiSampleData)
envelope = minMaxDataToEnvelopeData(loSampleData, hiSampleData)
self.assertEquals(envelope, [12, 16, 16, 11, 1, 2, 2, 3, 1, 8, 12, 17, 5, 1, 1, 2, 6, 14, 9, 13, 14, 3, 2, 1, 2, 11, 12, 14, 17])
risingThreshold = 6
fallingThreshold = 3
minPulseDuration = 0
holdCount = 0
result = detectPulses(envelope, risingThreshold, fallingThreshold, minPulseDuration, holdCount)
self.assertEquals(result, [10.5, 18.0])
holdCount = 1
result = detectPulses(envelope, risingThreshold, fallingThreshold, minPulseDuration, holdCount)
self.assertEquals(result, [10.5, 18.0])
def testNoisySamplesScenario(self):
risingThreshold = 7
fallingThreshold = 4
minPulseDuration = 2
holdCount = 1
# IGNORE- FIRST--- |noise| SECOND---------- IGNORE
sampleData = [ 1, 8, 8, 0, 0, 0, 3, 8, 8, 7, 4, 1, 10, 1, 0, 7, 9, 1, 7, 9, 8, 3, 0, 0, 0, 8, 9 ]
result = detectPulses(sampleData, risingThreshold, fallingThreshold, minPulseDuration, holdCount)
self.assertEquals(result, [8.0, 17.5])
class Test_timesForSamples(unittest.TestCase):
def test_timesForSamples(self):
numSamples = 10
acToStFunc= lambda x: (x*10 + 1000, 7)
acFirstSampleStart=58
acLastSampleEnd=78
timesAndErrors=timesForSamples(numSamples, acToStFunc, acFirstSampleStart, acLastSampleEnd)
self.assertEquals(timesAndErrors, [
(1580, 7),
(1600, 7),
(1620, 7),
(1640, 7),
(1660, 7),
(1680, 7),
(1700, 7),
(1720, 7),
(1740, 7),
(1760, 7),
(1780, 7),
])
class Test_ArduinoToSyncTimelineTime(unittest.TestCase):
"""\
scenario:
sync.timeline wall clock arduino time
(90kHz) (nanos) (nanos)
| | |
50,000 + - - - 200,000,000 + - - - 100,000,000 + sync point between clocks/timelines
| | |
| | |
50,090 + - - - 201,002,000 + - - - 101,000,000 + start of first sample
| | |
| | |
/\/ /\/ /\/
... sampling happens during this period ...
/\/ /\/ /\/
| | |
| | |
50,990 + - - - 211,022,000 + - - - 111,000,000 + end of last sample
| | |
| | |
51,080 + - - - 212,024,000 + - - - 112,000,000 + sync point between clocks/timelines
error for arduino clock estimation is constant 144us
error for wall clock estimation is constant 0.5ms
"""
def test_simple(self):
convAcWc = lambda aNanos : (aNanos - 100000000) * 1.002 + 200000000
calcAcErr = lambda aNanos : 144000 # 144 us
convWcSt = lambda wcNanos : (wcNanos - 200000000) * 90000 / 1002000000 + 50000
wcDispCalc = lambda wcNanos : 0.5*1000000 # 0.5 ms
stTickRate = 90000.0
ac2st = ArduinoToSyncTimelineTime(convAcWc, calcAcErr, convWcSt, wcDispCalc, stTickRate)
stTime, stErr = ac2st(111000000)
self.assertEquals(stTime, 50990)
self.assertEquals(stErr, 90000*(144/1000000.0 + 0.5/1000.0) + 1)
stTime, stErr = ac2st(101000000)
self.assertEquals(stTime, 50090)
self.assertEquals(stErr, 90000*(144/1000000.0 + 0.5/1000.0) + 1)
def testValuesUsedWithinRangeOnly(self):
convAcWc = lambda aNanos : (aNanos - 100000000) * 1.002 + 200000000
def calcAcErr(aNanos):
self.assertTrue(aNanos >= 100000000 and aNanos <= 112000000)
return 144000
convWcSt = lambda wcNanos : (wcNanos - 200000000) * 90000 / 1002000000 + 50000
def wcDispCalc(wcNanos):
self.assertTrue(wcNanos >= 200000000 and wcNanos <= 212024000)
return 0.5*1000000
stTickRate = 90000.0
ac2st = ArduinoToSyncTimelineTime(convAcWc, calcAcErr, convWcSt, wcDispCalc, stTickRate)
stTime, stErr = ac2st(111000000)
class Test_BeepFlashTimingDetector(unittest.TestCase):
"""\
scenario:
sync.timeline wall clock arduino time
(90kHz) (nanos) (nanos)
| | |
50,000 + - - - 200,000,000 + - - - 100,000,000 + sync point between clocks/timelines (pre sampling)
| | |
| | |
50,090 + - - - 201,002,000 + - - - 101,000,000 + start of first sample
| | |
| | |
/\/ /\/ /\/
... 10 x 1 millisecond samples taken during this period ...
/\/ /\/ /\/
| | |
| | |
50,990 + - - - 211,022,000 + - - - 111,000,000 + end of last sample
| | |
| | |
51,080 + - - - 212,024,000 + - - - 112,000,000 + sync point between clocks/timelines (post sampling)
We assume trip time each direction for arduino to PC clock sync is 144 us.
We assume wall clock sync was measured with dispersions always of 0.5 ms.
We assume wall clock precision of 1 us
We assume arduino clock precision of 4 us
"""
def test_beeps(self):
US = 1000 # number of nanoseconds in one microsecond
# ----pulse----
loSamples = [ 130, 128, 116, 83, 76, 72, 124, 129, 125, 128 ]
hiSamples = [ 130, 135, 146, 175, 176, 170, 134, 129, 130, 128 ]
# | | |
# index 0 4.5 10
# stTime 50090 50495 50990
wcAcReqResp = {
"pre" : (
200000000 - 144*US, # t1 <wcNanos>,
100000000, # t2 <acNanos>,
100000000, # t3 <acNanos>,
200000000 + 144*US, # t4 <wcNanos>,
),
"post" : (
212024000 - 144*US, # t1 <wcNanos>,
112000000, # t2 <acNanos>,
112000000, # t3 <acNanos>,
212024000 + 144*US, # t4 <wcNanos>,
),
}
syncTimelineTickRate = 90000.0
wcSyncTimeCorrelations = [
(200000000, (200000000, 50000, 1.0)), # (<wcWhen>, (<wcNanos>, <syncTimelineTicks>, <speed>)),
(212024000, (212024000, 51080, 1.0)), # (<wcWhen>, (<wcNanos>, <syncTimelineTicks>, <speed>)),
]
wcDispersions = ErrorBoundInterpolator(
(199000000, 0.5*1000000), # pre (<wcNanos>, <dispersionNanos>),
(213024000, 0.5*1000000) # post (<wcNanos>, <dispersionNanos>),
)
wcPrecisionNanos = 1 * US
acPrecisionNanos = 4 * US
detector = BeepFlashDetector(wcAcReqResp, syncTimelineTickRate, wcSyncTimeCorrelations, wcDispersions, wcPrecisionNanos, acPrecisionNanos)
acStartNanos = 101000000
acEndNanos = 111000000
beepDurationSeconds = 3 / 1000 # one sample = 1 millisecond
beepTimings = detector.samplesToBeepTimings(loSamples, hiSamples, acStartNanos, acEndNanos, beepDurationSeconds)
self.assertEquals(len(beepTimings), 1)
ptsTime = beepTimings[0][0]
error = beepTimings[0][1]
self.assertEquals(ptsTime, 50495)
# check if error is equal to 1 pts tick + wcPrecision + acPrecision + acWcHalfRoundTrip + wcDispersion
self.assertEquals(error, 1+(wcPrecisionNanos+acPrecisionNanos+144*US+0.5*1000000+0.5*1000000)*90000/1000000000)
if __name__ == "__main__":
unittest.main()
|
tjenkinson/dvbcss-synctiming
|
tests/test_detect.py
|
Python
|
apache-2.0
| 14,628
|
import logging
class Logger(object):
"""
@summary: A common logger for this library
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
logging.basicConfig(filename='master.log',
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level='INFO')
def get_logger(self):
return self.logger
|
wzin/interactivespaces-python-api
|
interactivespaces/misc.py
|
Python
|
apache-2.0
| 483
|
from utils import parse_date_string
from . import app, configure, request, instance_method
from . import get_or_create, commit
from . import Resource, QueryResource, BaseIngestResource, RangeQuery
from ..models.vms import Instance
class IngestResource(BaseIngestResource):
def ingest(self):
"""Ingest instances."""
messages = [message for message in request.get_json(force=True)
if message["schema"] == "cloud.tango"]
for message in messages:
for instance in message["data"]["instances"]:
# need to convert month from a sting like 2017-12-01 to timestamp
# to be consistant with other usage data
instance['month'] = parse_date_string(instance['month'], fmt='%Y-%m-%d')
get_or_create(Instance, **instance)
commit()
return "", 204
class InstanceResource(RangeQuery):
"""Instance Endpoint"""
def _get(self, **kwargs):
return Instance.list(start_ts=kwargs['start'], end_ts=kwargs['end'])
def setup():
resources = {
"/instance": InstanceResource,
"/ingest": IngestResource
}
configure(resources)
setup()
|
eResearchSA/reporting-unified
|
unified/apis/vms.py
|
Python
|
apache-2.0
| 1,198
|
#!/usr/bin/env python3
# This file is part of the Finna Pomodoro Project
# Copyright (C) 2014 Vinícius dos Santos Oliveira <vini.ipsmaker@gmail.com>
#
# This software is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any
# later version.
#
# This software 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this library. If not, see <http://www.gnu.org/licenses/>.
import dbus
bus = dbus.SessionBus()
bus_name = 'io.github.finna_pomodoro_project' #< The service name
object_path = '/io/github/finna_pomodoro_project/Pomodoro'
dbus_interface = 'io.github.finna_pomodoro_project.Pomodoro'
try:
bus.call_blocking(bus_name, object_path, dbus_interface, 'toggle', '', [],
timeout=0.5)
except dbus.exceptions.DBusException:
# Method doesn't have return, then it'll timeout
pass
|
finna-pomodoro-project/finna-pomodoro-pyclient
|
pypomodoro-toggle.py
|
Python
|
gpl-3.0
| 1,257
|
# BEGIN_COPYRIGHT
#
# Copyright (C) 2009-2013 CRS4.
#
# This file is part of biodoop-blast.
#
# biodoop-blast 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.
#
# biodoop-blast 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 for
# more details.
#
# You should have received a copy of the GNU General Public License along with
# biodoop-blast. If not, see <http://www.gnu.org/licenses/>.
#
# END_COPYRIGHT
"""Biodoop BLAST
A wrapper-based MapReduce implementation of BLAST for Hadoop.
"""
import os, datetime
from distutils.core import setup
from distutils.errors import DistutilsSetupError
from distutils.command.build_py import build_py as du_build_py
from distutils.command.sdist import sdist as du_sdist
CURRENT_YEAR = datetime.datetime.now().year
DESCRIPTION, LONG_DESCRIPTION = __doc__.split("\n", 1)
LONG_DESCRIPTION = LONG_DESCRIPTION.strip()
URL = "http://biodoop.sourceforge.net"
# DOWNLOAD_URL = ""
LICENSE = 'GPL'
CLASSIFIERS = [
"Programming Language :: Python",
"License :: OSI Approved :: GNU General Public License (GPL)",
"Operating System :: POSIX :: Linux",
"Topic :: Scientific/Engineering :: Bio-Informatics",
"Intended Audience :: Science/Research",
]
PLATFORMS = ["Linux"]
try:
with open("NAME") as f:
NAME = f.read().strip()
with open("VERSION") as f:
VERSION = f.read().strip()
except IOError:
raise DistutilsSetupError("failed to read name/version info")
AUTHOR_INFO = [
("Simone Leo", "simone.leo@crs4.it"),
]
MAINTAINER_INFO = [
("Simone Leo", "simone.leo@crs4.it"),
]
AUTHOR = ", ".join(t[0] for t in AUTHOR_INFO)
AUTHOR_EMAIL = ", ".join("<%s>" % t[1] for t in AUTHOR_INFO)
MAINTAINER = ", ".join(t[0] for t in MAINTAINER_INFO)
MAINTAINER_EMAIL = ", ".join("<%s>" % t[1] for t in MAINTAINER_INFO)
mtime = lambda fn: os.stat(fn).st_mtime
def write_authors(filename="AUTHORS"):
if os.path.exists(filename) and mtime(__file__) <= mtime(filename):
return
with open(filename, "w") as f:
f.write("%s is developed by:\n" % NAME)
for name, email in AUTHOR_INFO:
f.write(" * %s <%s>\n" % (name, email))
f.write("and maintained by:\n")
for name, email in MAINTAINER_INFO:
f.write(" * %s <%s>\n" % (name, email))
def write_version(filename="bl/blast/version.py"):
if os.path.exists(filename) and mtime("VERSION") <= mtime(filename):
return
with open(filename, "w") as f:
f.write("# GENERATED BY setup.py\n")
f.write("version='%s'\n" % VERSION)
class build_py(du_build_py):
def run(self):
write_version()
du_build_py.run(self)
class sdist(du_sdist):
def run(self):
write_authors()
du_sdist.run(self)
setup(
name=NAME,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
url=URL,
## download_url=DOWNLOAD_URL,
license=LICENSE,
classifiers=CLASSIFIERS,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
maintainer=MAINTAINER,
maintainer_email=MAINTAINER_EMAIL,
platforms=PLATFORMS,
version=VERSION,
packages=[
'bl',
'bl.blast',
'bl.blast.mr',
'bl.blast.mr.blastall',
],
scripts=["scripts/biodoop_blast"],
cmdclass={"sdist": sdist, "build_py": build_py},
)
|
crs4/biodoop-blast
|
setup.py
|
Python
|
gpl-3.0
| 3,496
|
#!/usr/bin/python
# coding=utf-8
import time
for x in range(0, 10):
tempFile = open('/sys/class/thermal/thermal_zone0/temp')
temp = float(tempFile.read())
tempC = temp / 1000
print("Raspberry Pi Temperature: %.2fC" % tempC)
time.sleep(2)
|
kizniche/Mycodo
|
mycodo/tests/manual_tests/test_RPi_temperature.py
|
Python
|
gpl-3.0
| 260
|
import re
########################################
# GlslInt ##############################
########################################
class GlslInt:
"""GLSL integer."""
def __init__(self, source):
"""Constructor."""
if source[0] in ("-", "+"):
self.__sign = source[0]
self.__string = source[1:]
# Plus sign does not need preservation.
if self.__sign == "+":
self.__sign = ""
else:
self.__sign = ""
self.__string = source
self.__number = int(source)
def format(self, force):
"""Return formatted output."""
return str(self.__number)
def getFloat(self):
"""Floating point representation."""
return float(self.__number)
def getInt(self):
"""Integer representation."""
return self.__number
def getPrecision(self):
"""Get precision - number of numbers to express."""
return len(self.__string.strip("+-0"))
def getSign(self):
"""Access sign, only minus sign is preserved."""
return self.__sign
def getStr(self):
"""Access actual string."""
return self.__sign + self.__string
def truncatePrecision(self, op):
"""Truncate numeric precision to some value of expressed numbers."""
# If the number is 0, it has no precision.
if self.__number == 0:
return 0
# Preserve zeroes in front. They are not counted.
zeroes_front = ""
rest = self.__string
for ii in range(len(rest)):
if self.__string[ii] != "0":
if ii > 0:
zeroes_front = rest[:ii]
rest = rest[ii:]
break
# Preserve zeroes in back. Also not counted.
zeroes_back = ""
for ii in reversed(range(len(rest))):
if rest[ii] != "0":
if ii < (len(rest) - 1):
zeroes_back = rest[ii + 1:]
rest = rest[:ii + 1]
break
# If length of rest is smaller than truncation, just return it.
if len(rest) <= op:
return len(rest)
# Round the result.
divisor = pow(10, len(rest) - op)
rest = str(int(round(float(rest) / float(divisor))) * divisor)
self.__string = zeroes_front + rest + zeroes_back
self.__number = int(self.__sign + self.__string)
return op
def __str__(self):
"""String representation."""
return "GlslInt('%s')" % (self.__string)
########################################
# Functions ############################
########################################
def interpret_int(source):
"""Try to interpret integer."""
if re.match(r'^\-?\d+f?$', source):
# Suffixing number with 'f' is not allowd according to the spec, but NVidia accepts it.
if source[-1] == "f":
print("WARNING: GLSL: discarding number literal suffix for '%s'" % (source))
return GlslInt(source[:-1])
return GlslInt(source)
return None
def is_glsl_int(op):
"""Tell if token is integer."""
return isinstance(op, GlslInt)
def is_glsl_int_unsigned(op):
"""Tell if token is integer."""
return isinstance(op, GlslInt) and (op.getInt() >= 0)
|
trilkk/dnload
|
dnload/glsl_int.py
|
Python
|
bsd-3-clause
| 3,332
|
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
ZMQ example using python3's asyncio
Bitcoin should be started with the command line arguments:
GuldenD -testnet -daemon \
-zmqpubhashblock=tcp://127.0.0.1:28332 \
-zmqpubrawtx=tcp://127.0.0.1:28332 \
-zmqpubhashtx=tcp://127.0.0.1:28332 \
-zmqpubhashblock=tcp://127.0.0.1:28332
We use the asyncio library here. `self.handle()` installs itself as a
future at the end of the function. Since it never returns with the event
loop having an empty stack of futures, this creates an infinite loop. An
alternative is to wrap the contents of `handle` inside `while True`.
The `@asyncio.coroutine` decorator and the `yield from` syntax found here
was introduced in python 3.4 and has been deprecated in favor of the `async`
and `await` keywords respectively.
A blocking example using python 2.7 can be obtained from the git history:
https://github.com/bitcoin/bitcoin/blob/37a7fe9e440b83e2364d5498931253937abe9294/contrib/zmq/zmq_sub.py
"""
import binascii
import asyncio
import zmq
import zmq.asyncio
import signal
import struct
import sys
if not (sys.version_info.major >= 3 and sys.version_info.minor >= 4):
print("This example only works with Python 3.4 and greater")
exit(1)
port = 28332
class ZMQHandler():
def __init__(self):
self.loop = zmq.asyncio.install()
self.zmqContext = zmq.asyncio.Context()
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashtx")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawblock")
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "rawtx")
self.zmqSubSocket.connect("tcp://127.0.0.1:%i" % port)
@asyncio.coroutine
def handle(self) :
msg = yield from self.zmqSubSocket.recv_multipart()
topic = msg[0]
body = msg[1]
sequence = "Unknown"
if len(msg[-1]) == 4:
msgSequence = struct.unpack('<I', msg[-1])[-1]
sequence = str(msgSequence)
if topic == b"hashblock":
print('- HASH BLOCK ('+sequence+') -')
print(binascii.hexlify(body))
elif topic == b"hashtx":
print('- HASH TX ('+sequence+') -')
print(binascii.hexlify(body))
elif topic == b"rawblock":
print('- RAW BLOCK HEADER ('+sequence+') -')
print(binascii.hexlify(body[:80]))
elif topic == b"rawtx":
print('- RAW TX ('+sequence+') -')
print(binascii.hexlify(body))
# schedule ourselves to receive the next message
asyncio.ensure_future(self.handle())
def start(self):
self.loop.add_signal_handler(signal.SIGINT, self.stop)
self.loop.create_task(self.handle())
self.loop.run_forever()
def stop(self):
self.loop.stop()
self.zmqContext.destroy()
daemon = ZMQHandler()
daemon.start()
|
nlgcoin/guldencoin-official
|
contrib/zmq/zmq_sub3.4.py
|
Python
|
mit
| 3,273
|
#!/usr/bin/env python
"""Interactive context using the PyGame API (provides navigation support)"""
import string
from OpenGLContext.pygamecontext import *
from OpenGLContext import interactivecontext
from OpenGLContext.move import viewplatformmixin
class PygameInteractiveContext(
viewplatformmixin.ViewPlatformMixin,
interactivecontext.InteractiveContext,
PygameContext,
):
'''PyGame context providing mouse and keyboard interaction '''
def PygameVideoResize(self, event):
sizex, sizey = event.size
PygameContext.PygameVideoResize(self, event)
self.CallVirtual('OnResize', sizex, sizey)
return 1
def PygameActivateEvent(self, event):
return 1
def OnIdle(self):
pass
if __name__ == '__main__':
from drawcube import drawCube
class TestContext(PygameInteractiveContext):
def Render(self, mode):
glTranslated(0, 0, -3)
glRotated(30, 1, 0, 0)
glRotated(30, 0, 1, 0)
drawCube()
TestContext.ContextMainLoop(
title='Interactive Pygame Context', size=(400,300)
)
|
stack-of-tasks/rbdlpy
|
tutorial/lib/python2.7/site-packages/OpenGLContext/pygameinteractivecontext.py
|
Python
|
lgpl-3.0
| 1,126
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.