text
stringlengths
29
850k
from numpy.testing import assert_array_equal, assert_equal, assert_raises, \ assert_almost_equal import numpy as np from skimage._shared.testing import test_parallel from skimage.draw import (set_color, line, line_aa, polygon, polygon_perimeter, circle, circle_perimeter, circle_perimeter_aa, ellipse, ellipse_perimeter, _bezier_segment, bezier_curve) from skimage.measure import regionprops def test_set_color(): img = np.zeros((10, 10)) rr, cc = line(0, 0, 0, 30) set_color(img, (rr, cc), 1) img_ = np.zeros((10, 10)) img_[0, :] = 1 assert_array_equal(img, img_) def test_set_color_with_alpha(): img = np.zeros((10, 10)) rr, cc, alpha = line_aa(0, 0, 0, 30) set_color(img, (rr, cc), 1, alpha=alpha) # Wrong dimensionality color assert_raises(ValueError, set_color, img, (rr, cc), (255, 0, 0), alpha=alpha) img = np.zeros((10, 10, 3)) rr, cc, alpha = line_aa(0, 0, 0, 30) set_color(img, (rr, cc), (1, 0, 0), alpha=alpha) @test_parallel() def test_line_horizontal(): img = np.zeros((10, 10)) rr, cc = line(0, 0, 0, 9) img[rr, cc] = 1 img_ = np.zeros((10, 10)) img_[0, :] = 1 assert_array_equal(img, img_) def test_line_vertical(): img = np.zeros((10, 10)) rr, cc = line(0, 0, 9, 0) img[rr, cc] = 1 img_ = np.zeros((10, 10)) img_[:, 0] = 1 assert_array_equal(img, img_) def test_line_reverse(): img = np.zeros((10, 10)) rr, cc = line(0, 9, 0, 0) img[rr, cc] = 1 img_ = np.zeros((10, 10)) img_[0, :] = 1 assert_array_equal(img, img_) def test_line_diag(): img = np.zeros((5, 5)) rr, cc = line(0, 0, 4, 4) img[rr, cc] = 1 img_ = np.eye(5) assert_array_equal(img, img_) def test_line_aa_horizontal(): img = np.zeros((10, 10)) rr, cc, val = line_aa(0, 0, 0, 9) set_color(img, (rr, cc), 1, alpha=val) img_ = np.zeros((10, 10)) img_[0, :] = 1 assert_array_equal(img, img_) def test_line_aa_vertical(): img = np.zeros((10, 10)) rr, cc, val = line_aa(0, 0, 9, 0) img[rr, cc] = val img_ = np.zeros((10, 10)) img_[:, 0] = 1 assert_array_equal(img, img_) def test_line_aa_diagonal(): img = np.zeros((10, 10)) rr, cc, val = line_aa(0, 0, 9, 6) img[rr, cc] = 1 # Check that each pixel belonging to line, # also belongs to line_aa r, c = line(0, 0, 9, 6) for r_i, c_i in zip(r, c): assert_equal(img[r_i, c_i], 1) def test_line_equal_aliasing_horizontally_vertically(): img0 = np.zeros((25, 25)) img1 = np.zeros((25, 25)) # Near-horizontal line rr, cc, val = line_aa(10, 2, 12, 20) img0[rr, cc] = val # Near-vertical (transpose of prior) rr, cc, val = line_aa(2, 10, 20, 12) img1[rr, cc] = val # Difference - should be zero assert_array_equal(img0, img1.T) def test_polygon_rectangle(): img = np.zeros((10, 10), 'uint8') rr, cc = polygon((1, 4, 4, 1, 1), (1, 1, 4, 4, 1)) img[rr, cc] = 1 img_ = np.zeros((10, 10)) img_[1:4, 1:4] = 1 assert_array_equal(img, img_) def test_polygon_rectangle_angular(): img = np.zeros((10, 10), 'uint8') poly = np.array(((0, 3), (4, 7), (7, 4), (3, 0), (0, 3))) rr, cc = polygon(poly[:, 0], poly[:, 1]) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_polygon_parallelogram(): img = np.zeros((10, 10), 'uint8') poly = np.array(((1, 1), (5, 1), (7, 6), (3, 6), (1, 1))) rr, cc = polygon(poly[:, 0], poly[:, 1]) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_polygon_exceed(): img = np.zeros((10, 10), 'uint8') poly = np.array(((1, -1), (100, -1), (100, 100), (1, 100), (1, 1))) rr, cc = polygon(poly[:, 0], poly[:, 1], img.shape) img[rr, cc] = 1 img_ = np.zeros((10, 10)) img_[1:, :] = 1 assert_array_equal(img, img_) def test_circle(): img = np.zeros((15, 15), 'uint8') rr, cc = circle(7, 7, 6) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_circle_perimeter_bresenham(): img = np.zeros((15, 15), 'uint8') rr, cc = circle_perimeter(7, 7, 0, method='bresenham') img[rr, cc] = 1 assert(np.sum(img) == 1) assert(img[7][7] == 1) img = np.zeros((17, 15), 'uint8') rr, cc = circle_perimeter(7, 7, 7, method='bresenham') img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_circle_perimeter_bresenham_shape(): img = np.zeros((15, 20), 'uint8') rr, cc = circle_perimeter(7, 10, 9, method='bresenham', shape=(15, 20)) img[rr, cc] = 1 shift = 5 img_ = np.zeros((15 + 2 * shift, 20), 'uint8') rr, cc = circle_perimeter(7 + shift, 10, 9, method='bresenham', shape=None) img_[rr, cc] = 1 assert_array_equal(img, img_[shift:-shift, :]) def test_circle_perimeter_andres(): img = np.zeros((15, 15), 'uint8') rr, cc = circle_perimeter(7, 7, 0, method='andres') img[rr, cc] = 1 assert(np.sum(img) == 1) assert(img[7][7] == 1) img = np.zeros((17, 15), 'uint8') rr, cc = circle_perimeter(7, 7, 7, method='andres') img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_circle_perimeter_aa(): img = np.zeros((15, 15), 'uint8') rr, cc, val = circle_perimeter_aa(7, 7, 0) img[rr, cc] = 1 assert(np.sum(img) == 1) assert(img[7][7] == 1) img = np.zeros((17, 17), 'uint8') rr, cc, val = circle_perimeter_aa(8, 8, 7) img[rr, cc] = val * 255 img_ = np.array( [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 82, 180, 236, 255, 236, 180, 82, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 189, 172, 74, 18, 0, 18, 74, 172, 189, 0, 0, 0, 0], [ 0, 0, 0, 229, 25, 0, 0, 0, 0, 0, 0, 0, 25, 229, 0, 0, 0], [ 0, 0, 189, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 189, 0, 0], [ 0, 82, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 172, 82, 0], [ 0, 180, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 180, 0], [ 0, 236, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 236, 0], [ 0, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 255, 0], [ 0, 236, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 236, 0], [ 0, 180, 74, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 180, 0], [ 0, 82, 172, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 172, 82, 0], [ 0, 0, 189, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 25, 189, 0, 0], [ 0, 0, 0, 229, 25, 0, 0, 0, 0, 0, 0, 0, 25, 229, 0, 0, 0], [ 0, 0, 0, 0, 189, 172, 74, 18, 0, 18, 74, 172, 189, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 82, 180, 236, 255, 236, 180, 82, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_circle_perimeter_aa_shape(): img = np.zeros((15, 20), 'uint8') rr, cc, val = circle_perimeter_aa(7, 10, 9, shape=(15, 20)) img[rr, cc] = val * 255 shift = 5 img_ = np.zeros((15 + 2 * shift, 20), 'uint8') rr, cc, val = circle_perimeter_aa(7 + shift, 10, 9, shape=None) img_[rr, cc] = val * 255 assert_array_equal(img, img_[shift:-shift, :]) def test_ellipse_trivial(): img = np.zeros((2, 2), 'uint8') rr, cc = ellipse(0.5, 0.5, 0.5, 0.5) img[rr, cc] = 1 img_correct = np.array([ [0, 0], [0, 0] ]) assert_array_equal(img, img_correct) img = np.zeros((2, 2), 'uint8') rr, cc = ellipse(0.5, 0.5, 1.1, 1.1) img[rr, cc] = 1 img_correct = np.array([ [1, 1], [1, 1], ]) assert_array_equal(img, img_correct) img = np.zeros((3, 3), 'uint8') rr, cc = ellipse(1, 1, 0.9, 0.9) img[rr, cc] = 1 img_correct = np.array([ [0, 0, 0], [0, 1, 0], [0, 0, 0], ]) assert_array_equal(img, img_correct) img = np.zeros((3, 3), 'uint8') rr, cc = ellipse(1, 1, 1.1, 1.1) img[rr, cc] = 1 img_correct = np.array([ [0, 1, 0], [1, 1, 1], [0, 1, 0], ]) assert_array_equal(img, img_correct) img = np.zeros((3, 3), 'uint8') rr, cc = ellipse(1, 1, 1.5, 1.5) img[rr, cc] = 1 img_correct = np.array([ [1, 1, 1], [1, 1, 1], [1, 1, 1], ]) assert_array_equal(img, img_correct) def test_ellipse_generic(): img = np.zeros((4, 4), 'uint8') rr, cc = ellipse(1.5, 1.5, 1.1, 1.7) img[rr, cc] = 1 img_ = np.array([ [0, 0, 0, 0], [1, 1, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0], ]) assert_array_equal(img, img_) img = np.zeros((5, 5), 'uint8') rr, cc = ellipse(2, 2, 1.7, 1.7) img[rr, cc] = 1 img_ = np.array([ [0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0], ]) assert_array_equal(img, img_) img = np.zeros((10, 10), 'uint8') rr, cc = ellipse(5, 5, 3, 4) img[rr, cc] = 1 img_ = np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]) assert_array_equal(img, img_) img = np.zeros((10, 10), 'uint8') rr, cc = ellipse(4.5, 5, 3.5, 4) img[rr, cc] = 1 img_ = np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]) assert_array_equal(img, img_) img = np.zeros((15, 15), 'uint8') rr, cc = ellipse(7, 7, 3, 7) img[rr, cc] = 1 img_ = np.array([ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ]) assert_array_equal(img, img_) def test_ellipse_with_shape(): img = np.zeros((15, 15), 'uint8') rr, cc = ellipse(7, 7, 3, 10, shape=img.shape) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_ellipse_negative(): rr, cc = ellipse(-3, -3, 1.7, 1.7) rr_, cc_ = np.nonzero(np.array([ [0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0], ])) assert_array_equal(rr, rr_ - 5) assert_array_equal(cc, cc_ - 5) def test_ellipse_rotation_symmetry(): img1 = np.zeros((150, 150), dtype=np.uint8) img2 = np.zeros((150, 150), dtype=np.uint8) for angle in range(0, 180, 15): img1.fill(0) rr, cc = ellipse(80, 70, 60, 40, rotation=np.deg2rad(angle)) img1[rr, cc] = 1 img2.fill(0) rr, cc = ellipse(80, 70, 60, 40, rotation=np.deg2rad(angle + 180)) img2[rr, cc] = 1 assert_array_equal(img1, img2) def test_ellipse_rotated(): img = np.zeros((1000, 1200), dtype=np.uint8) for rot in range(0, 180, 10): img.fill(0) angle = np.deg2rad(rot) rr, cc = ellipse(500, 600, 200, 400, rotation=angle) img[rr, cc] = 1 # estimate orientation of ellipse angle_estim = np.round(regionprops(img)[0].orientation, 3) % (np.pi / 2) assert_almost_equal(angle_estim, angle % (np.pi / 2), 2) def test_ellipse_perimeter_dot_zeroangle(): # dot, angle == 0 img = np.zeros((30, 15), 'uint8') rr, cc = ellipse_perimeter(15, 7, 0, 0, 0) img[rr, cc] = 1 assert(np.sum(img) == 1) assert(img[15][7] == 1) def test_ellipse_perimeter_dot_nzeroangle(): # dot, angle != 0 img = np.zeros((30, 15), 'uint8') rr, cc = ellipse_perimeter(15, 7, 0, 0, 1) img[rr, cc] = 1 assert(np.sum(img) == 1) assert(img[15][7] == 1) def test_ellipse_perimeter_flat_zeroangle(): # flat ellipse img = np.zeros((20, 18), 'uint8') img_ = np.zeros((20, 18), 'uint8') rr, cc = ellipse_perimeter(6, 7, 0, 5, 0) img[rr, cc] = 1 rr, cc = line(6, 2, 6, 12) img_[rr, cc] = 1 assert_array_equal(img, img_) def test_ellipse_perimeter_zeroangle(): # angle == 0 img = np.zeros((30, 15), 'uint8') rr, cc = ellipse_perimeter(15, 7, 14, 6, 0) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_ellipse_perimeter_nzeroangle(): # angle != 0 img = np.zeros((30, 25), 'uint8') rr, cc = ellipse_perimeter(15, 11, 12, 6, 1.1) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_array_equal(img, img_) def test_ellipse_perimeter_shape(): img = np.zeros((15, 20), 'uint8') rr, cc = ellipse_perimeter(7, 10, 9, 9, 0, shape=(15, 20)) img[rr, cc] = 1 shift = 5 img_ = np.zeros((15 + 2 * shift, 20), 'uint8') rr, cc = ellipse_perimeter(7 + shift, 10, 9, 9, 0, shape=None) img_[rr, cc] = 1 assert_array_equal(img, img_[shift:-shift, :]) def test_bezier_segment_straight(): image = np.zeros((200, 200), dtype=int) r0, r1, r2 = 50, 150, 150 c0, c1, c2 = 50, 50, 150 rr, cc = _bezier_segment(r0, c0, r1, c1, r2, c2, 0) image[rr, cc] = 1 image2 = np.zeros((200, 200), dtype=int) rr, cc = line(r0, c0, r2, c2) image2[rr, cc] = 1 assert_array_equal(image, image2) def test_bezier_segment_curved(): img = np.zeros((25, 25), 'uint8') r0, c0 = 20, 20 r1, c1 = 20, 2 r2, c2 = 2, 2 rr, cc = _bezier_segment(r0, c0, r1, c1, r2, c2, 1) img[rr, cc] = 1 img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_equal(img[r0, c0], 1) assert_equal(img[r2, c2], 1) assert_array_equal(img, img_) def test_bezier_curve_straight(): image = np.zeros((200, 200), dtype=int) r0, c0 = 50, 50 r1, c1 = 150, 50 r2, c2 = 150, 150 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 0) image[rr, cc] = 1 image2 = np.zeros((200, 200), dtype=int) rr, cc = line(r0, c0, r2, c2) image2[rr, cc] = 1 assert_array_equal(image, image2) def test_bezier_curved_weight_eq_1(): img = np.zeros((23, 8), 'uint8') r0, c0 = 1, 1 r1, c1 = 11, 11 r2, c2 = 21, 1 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 1) img[rr, cc] = 1 assert_equal(img[r0, c0], 1) assert_equal(img[r2, c2], 1) img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] ) assert_equal(img, img_) def test_bezier_curved_weight_neq_1(): img = np.zeros((23, 10), 'uint8') r0, c0 = 1, 1 r1, c1 = 11, 11 r2, c2 = 21, 1 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2) img[rr, cc] = 1 assert_equal(img[r0, c0], 1) assert_equal(img[r2, c2], 1) img_ = np.array( [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] ) assert_equal(img, img_) def test_bezier_curve_shape(): img = np.zeros((15, 20), 'uint8') r0, c0 = 1, 5 r1, c1 = 6, 11 r2, c2 = 1, 14 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2, shape=(15, 20)) img[rr, cc] = 1 shift = 5 img_ = np.zeros((15 + 2 * shift, 20), 'uint8') r0, c0 = 1 + shift, 5 r1, c1 = 6 + shift, 11 r2, c2 = 1 + shift, 14 rr, cc = bezier_curve(r0, c0, r1, c1, r2, c2, 2, shape=None) img_[rr, cc] = 1 assert_array_equal(img, img_[shift:-shift, :]) def test_polygon_perimeter(): expected = np.array( [[1, 1, 1, 1], [1, 0, 0, 1], [1, 1, 1, 1]] ) out = np.zeros_like(expected) rr, cc = polygon_perimeter([0, 2, 2, 0], [0, 0, 3, 3]) out[rr, cc] = 1 assert_array_equal(out, expected) out = np.zeros_like(expected) rr, cc = polygon_perimeter([-1, -1, 3, 3], [-1, 4, 4, -1], shape=out.shape, clip=True) out[rr, cc] = 1 assert_array_equal(out, expected) assert_raises(ValueError, polygon_perimeter, [0], [1], clip=True) def test_polygon_perimeter_outside_image(): rr, cc = polygon_perimeter([-1, -1, 3, 3], [-1, 4, 4, -1], shape=(3, 4)) assert_equal(len(rr), 0) assert_equal(len(cc), 0) if __name__ == "__main__": from numpy.testing import run_module_suite run_module_suite()
It’s a big day for fans of multi award winning group, The McClymonts who today announce details of a new studio album as well as the release of a brand new single and dates to their first leg of a national tour. Brooke reflects on the songwriting inspiration, “We got to connect with so many fans and friends on the ’10 Years of Hits’ tour and as you hear their stories we realised that there are a lot of people that have grown up with our music and they are going through the same feelings, whether positive or negative as we do and in a way ‘Endless’ is a diary of our lives right now which can be just as relevant to someone else’s life as it is to ours”. Sam commented on what fans can expect from the new show, “It’s always fun when you add new songs to the setlist and in addition to the new songs fans will get the ones they know like “Wrapped Up Good” and “Kick It Up” and “Forever Begins Tonight”. The McClymonts are acknowledged as Australia’s #1 Country Group and throughout their ten-year career they have released four studio albums which have achieved 2 x Gold Sales Accreditations, 10 x Golden Guitar Awards, 2 x ARIA Awards, an APRA Award and a CMA (Country Music Association U.S) Award for Global Artist of the Year. They have released twenty hit singles and toured extensively throughout Australia and the U.S. They are Ambassadors of Toyota Australia and charity organisations the McGrath Foundation and Legacy Australia.
"""CIFAR example with static subgraph optimizations. This is a version of the Chainer CIFAR example that has been modified to support the static subgraph optimizations feature. Note that the code is mostly unchanged except for the addition of the `@static_graph` decorator to the model chain's `__call__()` method. This code is a custom loop version of train_cifar.py. That is, we train models without using the Trainer class in chainer and instead write a training loop that manually computes the loss of minibatches and applies an optimizer to update the model. """ import argparse import chainer from chainer import configuration from chainer.dataset import convert import chainer.links as L from chainer import serializers from chainer.datasets import get_cifar10 from chainer.datasets import get_cifar100 import models.VGG def main(): parser = argparse.ArgumentParser(description='Chainer CIFAR example:') parser.add_argument('--dataset', '-d', default='cifar10', help='The dataset to use: cifar10 or cifar100') parser.add_argument('--batchsize', '-b', type=int, default=64, help='Number of images in each mini-batch') parser.add_argument('--learnrate', '-l', type=float, default=0.05, help='Learning rate for SGD') parser.add_argument('--epoch', '-e', type=int, default=300, help='Number of sweeps over the dataset to train') parser.add_argument('--gpu', '-g', type=int, default=0, help='GPU ID (negative value indicates CPU)') parser.add_argument('--out', '-o', default='result', help='Directory to output the result') parser.add_argument('--test', action='store_true', help='Use tiny datasets for quick tests') parser.add_argument('--resume', '-r', default='', help='Resume the training from snapshot') args = parser.parse_args() print('GPU: {}'.format(args.gpu)) print('# Minibatch-size: {}'.format(args.batchsize)) print('# epoch: {}'.format(args.epoch)) print('') # Set up a neural network to train. # Classifier reports softmax cross entropy loss and accuracy at every # iteration, which will be used by the PrintReport extension below. if args.dataset == 'cifar10': print('Using CIFAR10 dataset.') class_labels = 10 train, test = get_cifar10() elif args.dataset == 'cifar100': print('Using CIFAR100 dataset.') class_labels = 100 train, test = get_cifar100() else: raise RuntimeError('Invalid dataset choice.') if args.test: train = train[:200] test = test[:200] train_count = len(train) test_count = len(test) model = L.Classifier(models.VGG.VGG(class_labels)) if args.gpu >= 0: # Make a specified GPU current chainer.backends.cuda.get_device_from_id(args.gpu).use() model.to_gpu() # Copy the model to the GPU optimizer = chainer.optimizers.MomentumSGD(args.learnrate) optimizer.setup(model) optimizer.add_hook(chainer.optimizer.WeightDecay(5e-4)) train_iter = chainer.iterators.SerialIterator(train, args.batchsize) test_iter = chainer.iterators.SerialIterator(test, args.batchsize, repeat=False, shuffle=False) sum_accuracy = 0 sum_loss = 0 while train_iter.epoch < args.epoch: batch = train_iter.next() # Reduce learning rate by 0.5 every 25 epochs. if train_iter.epoch % 25 == 0 and train_iter.is_new_epoch: optimizer.lr *= 0.5 print('Reducing learning rate to: {}'.format(optimizer.lr)) x_array, t_array = convert.concat_examples(batch, args.gpu) x = chainer.Variable(x_array) t = chainer.Variable(t_array) optimizer.update(model, x, t) sum_loss += float(model.loss.data) * len(t.data) sum_accuracy += float(model.accuracy.data) * len(t.data) if train_iter.is_new_epoch: print('epoch: {}'.format(train_iter.epoch)) print('train mean loss: {}, accuracy: {}'.format( sum_loss / train_count, sum_accuracy / train_count)) # evaluation sum_accuracy = 0 sum_loss = 0 model.predictor.train = False # It is good practice to turn off train mode during evaluation. with configuration.using_config('train', False): for batch in test_iter: x_array, t_array = convert.concat_examples(batch, args.gpu) x = chainer.Variable(x_array) t = chainer.Variable(t_array) loss = model(x, t) sum_loss += float(loss.data) * len(t.data) sum_accuracy += float(model.accuracy.data) * len(t.data) test_iter.reset() model.predictor.train = True print('test mean loss: {}, accuracy: {}'.format( sum_loss / test_count, sum_accuracy / test_count)) sum_accuracy = 0 sum_loss = 0 # Save the model and the optimizer print('save the model') serializers.save_npz('mlp.model', model) print('save the optimizer') serializers.save_npz('mlp.state', optimizer) if __name__ == '__main__': main()
I have been missin you and your humor and your insights. nice new photo! shame i can only see the small thumbnail! my dear i know you know how to listen just by your gift to write. talk to your God ask for His wisdom and He will show you the path and even light it for you. There's no way your hospital bills are gonna be free! I'll make it sure it's doubled when I'm on you. Look out darkorange!!!! I so wish I could have a very long real conversation with the boy jorj inside that you try to make us all believe you are. When I read the words that come from your soul I want to just hug you to pieces. You can bring to light a warmth that we forget sometimes is in us. Never stop writing and thinking and imagining. Your words are like heavenly colors that are a prelude of things we have to look forward to. I could write here for a long time but just know I am very serious. YOU ARE VERY OVERWHELMINGLY SPECIAL !
# 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. """ The baseclass module is part of the nmeta suite and provides an inheritable class methods for logging """ #*** logging imports: import logging import logging.handlers import coloredlogs class BaseClass(object): """ This class provides the common methods for inheritance by other classes """ def __init__(self): """ Initialise the BaseClass class """ pass def configure_logging(self, name, s_name, c_name): """ Configure logging for the class that has inherited this method """ #*** Set up Logging: self.logger = logging.getLogger(name) #*** Get logging config values from config class: _logging_level_s = self.config.get_value(s_name) _logging_level_c = self.config.get_value(c_name) _syslog_enabled = self.config.get_value('syslog_enabled') _loghost = self.config.get_value('loghost') _logport = self.config.get_value('logport') _logfacility = self.config.get_value('logfacility') _syslog_format = self.config.get_value('syslog_format') _console_log_enabled = self.config.get_value('console_log_enabled') _coloredlogs_enabled = self.config.get_value('coloredlogs_enabled') _console_format = self.config.get_value('console_format') self.logger.propagate = False #*** Syslog: if _syslog_enabled: #*** Log to syslog on host specified in config.yaml: self.syslog_handler = logging.handlers.SysLogHandler(address=( _loghost, _logport), facility=_logfacility) syslog_formatter = logging.Formatter(_syslog_format) self.syslog_handler.setFormatter(syslog_formatter) self.syslog_handler.setLevel(_logging_level_s) #*** Add syslog log handler to logger: self.logger.addHandler(self.syslog_handler) #*** Console logging: if _console_log_enabled: #*** Log to the console: if _coloredlogs_enabled: #*** Colourise the logs to make them easier to understand: coloredlogs.install(level=_logging_level_c, logger=self.logger, fmt=_console_format, datefmt='%H:%M:%S') else: #*** Add console log handler to logger: self.console_handler = logging.StreamHandler() console_formatter = logging.Formatter(_console_format) self.console_handler.setFormatter(console_formatter) self.console_handler.setLevel(_logging_level_c) self.logger.addHandler(self.console_handler)
A collision in Paynesville caused five children to be sent to the hospital on Wednesday. The Stearns County Sheriff’s Office says 78-year-old Kathryn Huselid of Paynesville was driving south on County Road 20 when she attempted to make a left turn on Breezewood Road. Huselid’s car turned in front of a car driven by 32-year-old Sarah Hight of Lake Lillian, and the cars collided. Hight had her five children, ranging from six months old to six years old, in the car with her at the time. The sheriff’s office received a call about the crash at 10:39 a.m., with the caller telling them that a child was injured. One of the children received a minor cut on their face. All five children were taken to Paynesville Hospital to be examined.
# -*- coding: utf-8 -*- # # twoneurons.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/>. """Two neuron example ---------------------------- This script simulates two connected pre- and postsynaptic neurons. The presynaptic neuron receives a constant external current, and the membrane potential of both neurons are recorded. See Also ~~~~~~~~ :doc:`one_neuron` """ ############################################################################### # First, we import all necessary modules for simulation, analysis and plotting. # Additionally, we set the verbosity to suppress info messages and reset # the kernel. import nest import nest.voltage_trace import matplotlib.pyplot as plt nest.set_verbosity("M_WARNING") nest.ResetKernel() ############################################################################### # Second, we create the two neurons and the recording device. neuron_1 = nest.Create("iaf_psc_alpha") neuron_2 = nest.Create("iaf_psc_alpha") voltmeter = nest.Create("voltmeter") ############################################################################### # Third, we set the external current of neuron 1. neuron_1.I_e = 376.0 ############################################################################### # Fourth, we connect neuron 1 to neuron 2. # Then, we connect a voltmeter to the two neurons. # To learn more about the previous steps, please check out the # :doc:`one neuron example <one_neuron>`. weight = 20.0 delay = 1.0 nest.Connect(neuron_1, neuron_2, syn_spec={"weight": weight, "delay": delay}) nest.Connect(voltmeter, neuron_1) nest.Connect(voltmeter, neuron_2) ############################################################################### # Now we simulate the network using ``Simulate``, which takes the # desired simulation time in milliseconds. nest.Simulate(1000.0) ############################################################################### # Finally, we plot the neurons' membrane potential as a function of # time. nest.voltage_trace.from_device(voltmeter) plt.show()
Vedhasoft Technologies is a Enterprise Applications consulting & implementation services providers for emerging small & medium business entities. We have partnered with SAP for implementing SAP Business One ERP solution. Vedhasoft Technologies was conceptualized during the year 2009 and brought to operational by Mr. Babu, one of the founder member of this young & vibrant organization. Our Mission is to provide highly reliable and Value adding Enterprise Solutions for Organizations to realize their KPI's. Vedhasoft, with the utmost quality and consistency, we make technology an asset for our clients through unique, individualized solutions. A young & vibrant Startup – with SAP recognition as Partner. Team Expertise – Experience of executing 100+ successful implementation project. Industry specific solution extensions ready availability. Expert advisory from Vedhasoft GST Team – Qualified Chartered Accountants. Enable your business to meets the dynamics of Market with SAP Business One ERP.
import os SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) ALLOWED_HOSTS = ['localhost'] # change this to your servers domain FEEDS_SERVER = 'https://example.com/' # change this to where you are running - it's in the user agent string used when polling sites FEEDS_CLOUDFLARE_WORKER = None # You will need a cloudflare account with the django-feed-reader cloudflare worker installed to use this setting # this is where collectstatic will gather its files STATIC_ROOT = os.path.join(SITE_ROOT, "..", "static") DEBUG = False # or true if you are running locally DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'feedthing', # Or path to database file if using sqlite3. 'USER': 'auser', # Not used with sqlite3. 'PASSWORD': 'apassword', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. 'OPTIONS': { 'init_command': 'SET default_storage_engine=INNODB', } } } # Make this unique, and don't share it with anybody. SECRET_KEY = 'BigLongStringOfCharactersHere'
@Sasha - did you get this? Hi Alyssa, thank you for all of your hard work! I love this community.
# 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 unittest import models.base as modb import models.defconfig as moddf class TestDefconfModel(unittest.TestCase): def test_defconfig_document_valid_instance(self): defconf_doc = moddf.DefconfigDocument('job', 'kernel', 'defconfig') self.assertIsInstance(defconf_doc, modb.BaseDocument) self.assertIsInstance(defconf_doc, moddf.DefconfigDocument) def test_defconfig_document_collection(self): defconfig_doc = moddf.DefconfigDocument('job', 'kernel', 'defconfig') self.assertEqual(defconfig_doc.collection, 'defconfig') def test_defconfig_document_to_dict(self): defconf_doc = moddf.DefconfigDocument( 'job', 'kernel', 'defconfig', 'defconfig_full') defconf_doc.id = "defconfig_id" defconf_doc.job_id = "job_id" defconf_doc.created_on = "now" defconf_doc.metadata = {} defconf_doc.status = "FAIL" defconf_doc.dirname = "defconfig" defconf_doc.boot_resul_description = [] defconf_doc.errors = 1 defconf_doc.warnings = 1 defconf_doc.build_time = 1 defconf_doc.arch = "foo" defconf_doc.git_url = "git_url" defconf_doc.git_commit = "git_commit" defconf_doc.git_branch = "git_branch" defconf_doc.git_describe = "git_describe" defconf_doc.version = "1.0" defconf_doc.modules = "modules-file" defconf_doc.dtb_dir = "dtb-dir" defconf_doc.kernel_config = "kernel-config" defconf_doc.system_map = "system-map" defconf_doc.text_offset = "offset" defconf_doc.kernel_image = "kernel-image" defconf_doc.modules_dir = "modules-dir" defconf_doc.build_log = "build.log" defconf_doc.kconfig_fragments = "config-frag" defconf_doc.file_server_resource = "file-resource" defconf_doc.file_server_url = "server-url" expected = { "name": "job-kernel-defconfig_full", "_id": "defconfig_id", "job": "job", "kernel": "kernel", "defconfig": "defconfig", "job_id": "job_id", "created_on": "now", "metadata": {}, "status": "FAIL", "defconfig": "defconfig", "errors": 1, "warnings": 1, "build_time": 1, "arch": "foo", "dirname": "defconfig", "git_url": "git_url", "git_describe": "git_describe", "git_branch": "git_branch", "git_commit": "git_commit", "build_platform": [], "version": "1.0", "dtb_dir": "dtb-dir", "kernel_config": "kernel-config", "kernel_image": "kernel-image", "system_map": "system-map", "text_offset": "offset", "modules": "modules-file", "modules_dir": "modules-dir", "build_log": "build.log", "kconfig_fragments": "config-frag", "defconfig_full": "defconfig_full", "file_server_resource": "file-resource", "file_server_url": "server-url", } self.assertDictEqual(expected, defconf_doc.to_dict()) def test_deconfig_set_status_wrong_and_right(self): defconf_doc = moddf.DefconfigDocument("job", "kernel", "defconfig") self.assertRaises(ValueError, setattr, defconf_doc, "status", "foo") self.assertRaises(ValueError, setattr, defconf_doc, "status", []) self.assertRaises(ValueError, setattr, defconf_doc, "status", {}) self.assertRaises(ValueError, setattr, defconf_doc, "status", ()) defconf_doc.status = "FAIL" self.assertEqual(defconf_doc.status, "FAIL") defconf_doc.status = "PASS" self.assertEqual(defconf_doc.status, "PASS") defconf_doc.status = "UNKNOWN" self.assertEqual(defconf_doc.status, "UNKNOWN") defconf_doc.status = "BUILD" self.assertEqual(defconf_doc.status, "BUILD") def test_defconfig_set_build_platform_wrong(self): defconf_doc = moddf.DefconfigDocument("job", "kernel", "defconfig") self.assertRaises( TypeError, setattr, defconf_doc, "build_platform", ()) self.assertRaises( TypeError, setattr, defconf_doc, "build_platform", {}) self.assertRaises( TypeError, setattr, defconf_doc, "build_platform", "") def test_defconfig_set_build_platform(self): defconf_doc = moddf.DefconfigDocument("job", "kernel", "defconfig") defconf_doc.build_platform = ["a", "b"] self.assertListEqual(defconf_doc.build_platform, ["a", "b"]) def test_defconfig_set_metadata_wrong(self): defconf_doc = moddf.DefconfigDocument("job", "kernel", "defconfig") self.assertRaises(TypeError, setattr, defconf_doc, "metadata", ()) self.assertRaises(TypeError, setattr, defconf_doc, "metadata", []) self.assertRaises(TypeError, setattr, defconf_doc, "metadata", "") def test_defconfig_from_json_is_none(self): self.assertIsNone(moddf.DefconfigDocument.from_json({})) self.assertIsNone(moddf.DefconfigDocument.from_json("")) self.assertIsNone(moddf.DefconfigDocument.from_json([])) self.assertIsNone(moddf.DefconfigDocument.from_json(()))
The Beauty Products We Couldn't Live Without in 2017 – Yow Yow! 2017 felt like the year that I was not only collecting products, but educating myself on them more than average. I was constantly talking with my friends about what they were using and getting feedback via Instagram and Instagram Stories on what was working and what wasn’t. In 2018, my hope is that I do the opposite. I learn to live with less! How can I become more creative and resourceful with what I already have to avoid spending more money – another New Year’s resolution that we’ll get to soon. One thing that I learned about myself this year is that I no longer need to have a facial once a season. I used to convince myself that this was what I needed because seasons in the Bay Area were so harsh on my skin and so different that I needed to restart and refresh my routine with a facial. Turns out, I was lying to myself and didn’t need it and making excuses. You can create your own facials at home and you can moisturize and exfoliate your skin without breaking the bank. My favorite products in 2017 did JUST that. They looked like they could’ve been more high-end, but were actually affordable and did the job and more. 2017 was the year that I discovered that I could do something with my eyebrows! I don’t know what took us so long, but just like everyone says, Boy Brow really is a game changer. A few swipes of these across my brows keeps everything together and more importantly, natural looking. I also learned how to fill in my own eyebrows this year as well, but it’s not something that I feel like I can pull off as an everyday look rather than more of a day to night. Boy Brow gives me that everyday feel, but also cuts down on my getting ready time. For $16, you’ll be happy with this purchase, I promise. For the last year, I’ve been trying out a number of different facial masks – all with varying ingredients, durations, effects, etc. The one that stuck with me is the Detox by Malin + Goetz. Sometimes my biggest gripe with masks is the waiting around. I get impatient letting it sit on my face or some part of it starts to itch. With this one, all you need is five minutes and the best part is that you can feel it working as it instantly begins to foam up the second it hits your skin. Then, you can actually feel the payoff once you wash it all off. I know I should be moisturizing even afterwards, but the mask is so good that sometimes I’d rather just let my face breathe after I’ve done one of these. If you’ve never been a fan of foundation or are wanting a foundation that has the same texture as your moisturizer with a little bit of color, I would recommend the tinted hydrating gel cream by Bare Minerals. I’ve been using this product for a couple of years now and because of how light it is, I can sometimes eliminate both my moisturizer and foundation by using this one product. You only need a pea-sized amount to use for your whole face and this product often lasts me months. My issue with concealers is that when you’re applying them, it looks like they’re doing its job…until you get home and you realized that sometime during the day, things went awry. Concealers can appear cakey, can dry out your skin, and often times have a hard time blending in with your foundation and powder. I bought this product on a whim one day not even thinking about shopping for a concealer, but it is my favorite thing for hiding blemishes and using as an under eye cover. The concealer itself is surrounded by a hydra-smoothing formula with Vitamin E so when you use it, you’re hiding the blemish or affected area while keeping it moisturized. Because the worst thing that can happen is that you’re going about your day and finding that it’s flaking off by the end of it. Even while using this on blemishes, I often times don’t need to use foundation or powder over it and can blend it on its own and call it good – something that can be said for all concealers. When using mascara, I used to always have to bust out my eyelash curler first. This mascara eliminates that step because it has two sides one that lengthens and thickens. The curved wand also allows it to curl on its own naturally without having to use a real eyelash curler. I love how this never clumps up, but is dramatic enough for any day or evening look and lasts all day. I’m using this for as long as I can and hopefully won’t ever have to search for a new brand after this.
import os import redis import requests import json from werkzeug.wrappers import Request, Response from src.utils import (fetch_apps, contact_nodes, was_applied, exist_application, add_app_to_webserver_routing, remove_app_from_webserver_routing, add_container_to_webserver_routing, pick_up_node) @Request.application def application(request): """ Set up the infrastructure required for Heroku-ish app deployment. This setting uses Hipache/Redis as webserver and load balancer, and Docker as app container. Please be aware that the docker configuration is done in the different nodes (node.py). The standard configuration chooses one node of the list defined above, and provides him with the required information for a success deployment (user & repo params). """ DOMAIN = os.environ.get('DOOKIO_DOMAIN', 'localhost') redis_cli = redis.StrictRedis(host='localhost', port=6379, db=0) # Dookio-cli: apps command if request.path == '/apps': apps = fetch_apps(redis_cli) return Response( [('--> {} (replicated in {} containers)\n'.format( app[app.find(":") + 1:], len(apps[app]))) for app in apps]) # Pick up the proper params conf = { 'action': request.args.get('action'), 'multiplicator': int(request.args.get('multiplicator', 1)), 'user': request.args.get('user'), 'repo': request.args.get('repo'), 'application_address': '{}.{}.{}'.format( request.args.get('repo'), request.args.get('user'), DOMAIN) } if not all([conf.get('user'), conf.get('repo')]): return Response( 'There was a problem. Please be sure you are ' 'providing both "user", "repo"\n') # Dookio-cli: containers command action = conf.get('action') if request.path == '/containers': response_nodes = contact_nodes(conf) if action == 'stop': if was_applied(response_nodes): remove_app_from_webserver_routing(redis_cli, conf) elif action == 'start': if (was_applied(response_nodes) and not exist_application(redis_cli, conf)): add_app_to_webserver_routing(redis_cli, conf) for node_ip, response in response_nodes.iteritems(): # We only want to iterate over the valid responses. status_code = response[1] body = response[0][0] if status_code == 200: port = body.get('Ports')[0].get('PublicPort') add_container_to_webserver_routing(redis_cli, node_ip, port, conf) resp = [{ 'node': node_ip, 'containers': content[0] } for node_ip, content in response_nodes.iteritems()] return Response(json.dumps(resp)) # Dookio-cli: scale command if request.path == '/scale': if not exist_application(redis_cli, conf): return Response( 'The app can not scale unless is running!\n') if request.path == '/scale' or request.path == '/': user = conf.get('user') repo = conf.get('repo') # Stop all existing containers conf['action'] = 'stop' contact_nodes(conf) conf['action'] = None remove_app_from_webserver_routing(redis_cli, conf) for i in range(conf.get('multiplicator')): node = pick_up_node() response = requests.get('{}:5000'.format(node), params={'user': user, 'repo': repo}) if response.status_code == 200: # Set up hipache webserver for the specified branch container = json.loads(response.content) if not exist_application(redis_cli, conf): add_app_to_webserver_routing(redis_cli, conf) add_container_to_webserver_routing(redis_cli, node, container.get('port'), conf) else: return Response(response.content, status=response.status_code) return Response( 'App successfully deployed! Go to http://{}\n'.format( conf.get('application_address'))) else: return Response( 'Something went wrong! Are you using the proper parameters?. \n')
Summary: Business Intelligence has to look good & deliver exactly what each individual user needs… quickly. In this webinar you will learn about the top 10 features of a BI solution and the 10 key security features. See working apps, plus see the whole build-process with m-Power from mrc. With all of the available options, how do you know which one is best for your company? How do you separate the good from the bad?
import re import ckan.plugins as p import ckan.plugins.toolkit as tk import ckan.logic.auth as auth from ckan.common import _ class Article(p.SingletonPlugin, tk.DefaultDatasetForm): ''' Dataset type handling articles ''' p.implements(p.ITemplateHelpers) # Helpers for templates _PACKAGE_TYPE = 'article' def get_helpers(self): return { 'dp_recent_articles': self.h_recent_articles, 'dp_shorten_article': self.h_shorten_article } def h_recent_articles(self, count=4): search = tk.get_action('package_search')(data_dict={ 'rows': count, 'sort': 'metadata_created desc', 'fq': '+type:' + Article._PACKAGE_TYPE, 'facet': 'false' }) if search['count'] == 0: return [] return search['results'] def h_shorten_article(self, markdown, length=140, trail='...'): # Try to return first paragraph (two consecutive \n disregarding white characters) paragraph = markdown m = re.search('([ \t\r\f\v]*\n){2}', markdown) if m: paragraph = paragraph[0:m.regs[0][0]] if len(paragraph) > length: paragraph = paragraph[0:(length - len(trail))] + trail return paragraph p.implements(p.IDatasetForm) def package_types(self): return [Article._PACKAGE_TYPE] def is_fallback(self): return False def _modify_package_schema(self, schema): to_extras = tk.get_converter('convert_to_extras') to_tags = tk.get_converter('convert_to_tags') optional = tk.get_validator('ignore_missing') boolean_validator = tk.get_validator('boolean_validator') not_empty = tk.get_validator('not_empty') checkboxes = [optional, tk.get_validator('boolean_validator'), to_extras] def fixed_type(value, context): return Article._PACKAGE_TYPE schema = { 'id': schema['id'], 'name': schema['name'], 'title': [not_empty, unicode], 'author': schema['author'], 'notes': [not_empty, unicode], # notes [content] is obligatory 'type': [fixed_type], 'private': [optional, boolean_validator], 'license_id': [not_empty, unicode], 'tag_string': schema['tag_string'], 'resources': schema['resources'] } return schema def show_package_schema(self): not_empty = tk.get_validator('not_empty') schema = super(Article, self).show_package_schema() schema.update({ 'notes': [not_empty, unicode], # notes [content] is obligatory }) return schema def create_package_schema(self): schema = super(Article, self).create_package_schema() schema = self._modify_package_schema(schema) return schema def update_package_schema(self): schema = super(Article, self).update_package_schema() schema = self._modify_package_schema(schema) return schema def new_template(self): return 'article/new.html' def read_template(self): return 'article/read.html' def edit_template(self): return 'article/edit.html' def search_template(self): return 'article/search.html' # # def history_template(self): # return 'article/history.html' # def package_form(self): return 'article/new_package_form.html' p.implements(p.IAuthFunctions) def get_auth_functions(self): return { 'package_create': _package_create, # new = context.get('package') == None 'package_delete': _package_delete, # data_dict['id] 'package_update': _package_update, # context['package'].type } def _package_create(context, data_dict=None): user = context['user'] package = context.get('package') # None for new if package and package['type'] == 'article': return {'success': False, 'msg': _('User %s not authorized to create articles') % user} return auth.create.package_create(context, data_dict) def _package_delete(context, data_dict=None): user = context['user'] package = auth.get_package_object(context, data_dict) if package and package.type == 'article': return {'success': False, 'msg': _('User %s not authorized to delete articles') % user} return auth.delete.package_delete(context, data_dict) def _package_update(context, data_dict=None): user = context['user'] package = auth.get_package_object(context, data_dict) if package and (package.type == 'article' or package.type == 'application'): return {'success': False, 'msg': _('User %s not authorized to update articles') % user} return auth.update.package_update(context, data_dict)
But First, have you ever had a friend that you could sit down and dream with or someone that you could put your money together and it felt like magic when it grew. Everything you both touched together just made money. Well, I once had a friend like that in high school and his name was Brian Todd Willett. But tragically, Brian Willett died in a car wreck when I was in college. It was one of the saddest days of my life. Brian will be missed but never forgotten. With this being said you may be wondering when my little guy arrives and how in the world I would know the exact date. Well Brian is breech so we are doing a c-section on Sept. 4th. With that being said, I’ve only shared with a few people the next news. I have decided after the arrival of my son, I’m taking a huge step back from the teaching thing. I’m going to focus on my family and my other streams of internet income so I am living out my dreams. I recently had a meeting with my entire office where I made the announcement. I told my personal assistant to cancel all of the rest of the potential dates for the classes and to call the hotel where the event is usually held and inform them that we will not be needing their services. Well, simply stated it means that if you have been on the fence regarding whether or not you want to make the time to come work with Me Personally, NOW is the time to get off the fence! After the August class, there will be no more Millionaire Internet Training Classes! So If you are interested in joining us for either of the last two events ever, then go below right now and apply for a free session to see if you are a good fit for these events. You only have 2 chances left to personally work with me in a small classroom environment. If you want to take advantage of one of these 2 final classes, just give go here right now and fill out the application. P.S. After you fill in the application form you will get scheduled to talk with a strategist, I’d ask them about the “I’m Having a Baby” deal.
import pytest import copy import datetime from anchore_engine.db.entities.policy_engine import ( FixedArtifact, Vulnerability, VulnerableArtifact, ImagePackageVulnerability, ImagePackage, Image, DistroTuple, DistroNamespace, DistroMapping, ) from anchore_engine.subsys import logger logger.enable_test_logging(level="DEBUG") @pytest.fixture def empty_vulnerability(): v = Vulnerability() v.id = "CVE-1" v.namespace_name = "rhel:8" v.description = "test vulnerability" v.metadata_json = {} v.created_at = datetime.datetime.utcnow() v.updated_at = datetime.datetime.utcnow() v.fixed_in = [] v.vulnerable_in = [] v.severity = "high" v.link = "somelink" return v @pytest.fixture def empty_semver_vulnerability(): v = Vulnerability() v.id = "CVE-2000" v.namespace_name = "github:npm" v.description = "test vulnerability for semver handling" v.metadata_json = {} v.created_at = datetime.datetime.utcnow() v.updated_at = datetime.datetime.utcnow() v.fixed_in = [] v.vulnerable_in = [] v.severity = "high" v.link = "somelink" return v @pytest.fixture def vulnerability_with_fix(empty_vulnerability): fixed_vuln = copy.deepcopy(empty_vulnerability) f = FixedArtifact() f.vulnerability_id = fixed_vuln.id f.name = "pkg1" f.namespace_name = fixed_vuln.namespace_name f.version = "0:1.1.el8" f.version_format = "RPM" f.parent = fixed_vuln f.include_later_versions = True f.epochless_version = f.version f.fix_metadata = {} f.created_at = datetime.datetime.now() f.updated_at = datetime.datetime.now() f.fix_observed_at = f.updated_at fixed_vuln.fixed_in = [f] return fixed_vuln @pytest.fixture def vulnerability_with_nofix(empty_vulnerability): fixed_vuln = copy.deepcopy(empty_vulnerability) f = FixedArtifact() f.vulnerability_id = fixed_vuln.id f.name = "pkg1" f.namespace_name = fixed_vuln.namespace_name f.version = "None" f.version_format = "RPM" f.parent = fixed_vuln f.include_later_versions = True f.epochless_version = f.version f.fix_metadata = {} f.created_at = datetime.datetime.now() f.updated_at = datetime.datetime.now() f.fix_observed_at = f.updated_at fixed_vuln.fixed_in = [f] return fixed_vuln @pytest.fixture def vulnerability_with_multifix(empty_semver_vulnerability): fixed_vuln = copy.deepcopy(empty_semver_vulnerability) f = FixedArtifact() f.vulnerability_id = fixed_vuln.id f.name = "semverpkg1" f.namespace_name = fixed_vuln.namespace_name f.version = ">= 1.1.0 < 1.1.2" f.version_format = "semver" f.parent = fixed_vuln f.include_later_versions = False f.epochless_version = f.version f.fix_metadata = {"first_patched_version": "1.1.2"} f.created_at = datetime.datetime.now() f.updated_at = datetime.datetime.now() f.fix_observed_at = f.updated_at fixed_vuln.fixed_in = [f] f = FixedArtifact() f.vulnerability_id = fixed_vuln.id f.name = "semverpkg1" f.namespace_name = fixed_vuln.namespace_name f.version = ">= 2.2.0 < 2.2.2" f.version_format = "semver" f.parent = fixed_vuln f.include_later_versions = False f.epochless_version = f.version f.fix_metadata = {"first_patched_version": "2.2.2"} f.created_at = datetime.datetime.now() f.updated_at = datetime.datetime.now() f.fix_observed_at = f.updated_at return fixed_vuln @pytest.fixture def vulnerability_with_vulnartifact(empty_vulnerability): vuln_art = copy.deepcopy(empty_vulnerability) v = VulnerableArtifact( vulnerability_id=vuln_art.id, namespace_name=vuln_art.namespace_name, name="pkg1", version="1.0.el8", parent=vuln_art, ) v.epochless_version = "0:" + v.version v.version_format = "rpm" v.include_previous_versions = False vuln_art.vulnerable_in = [v] v = VulnerableArtifact( vulnerability_id=vuln_art.id, namespace_name=vuln_art.namespace_name, name="pkg1", version="0.9.el8", parent=vuln_art, ) v.epochless_version = "0:" + v.version v.version_format = "rpm" v.include_previous_versions = False vuln_art.vulnerable_in.append(v) return vuln_art @pytest.fixture def vulnerability_with_both(vulnerability_with_fix, vulnerability_with_vulnartifact): vulnerability_with_fix.fixed_in[0].include_later_versions = False vulnerability_with_fix.vulnerable_in = vulnerability_with_vulnartifact.vulnerable_in return vulnerability_with_fix @pytest.fixture def nvd_vulnerability(): """ Returns a vulnerability similar to an NVD record but with an added fixed record, similar to how GitHub advisories have both vuln range and fix version :return: """ v = Vulnerability() v.id = "CVE-2" v.created_at = v.updated_at = datetime.datetime.utcnow() v.severity = "high" v.namespace_name = "nvdv2:cves" @pytest.fixture def vulnerable_semver_pkg1(): pkg = ImagePackage() pkg.image_id = "image1" pkg.image_user_id = "admin" pkg.name = "semverpkg1" pkg.normalized_src_pkg = "semverpkg1" pkg.version = "1.1.0" pkg.fullversion = "1.1.0" pkg.release = None pkg.pkg_type = "npm" pkg.distro_name = "npm" pkg.distro_version = "N/A" pkg.like_distro = "npm" pkg.arch = "amd64" pkg.pkg_path = "/app/myapp/package.json" return pkg @pytest.fixture def vulnerable_semver_pkg2(): pkg = ImagePackage() pkg.image_id = "image1" pkg.image_user_id = "admin" pkg.name = "semverpkg1" pkg.normalized_src_pkg = "semverpkg1" pkg.version = "2.2.0" pkg.fullversion = "2.2.0" pkg.release = None pkg.pkg_type = "npm" pkg.distro_name = "npm" pkg.distro_version = "N/A" pkg.like_distro = "npm" pkg.arch = "amd64" pkg.pkg_path = "/app/myapp2/package.json" return pkg @pytest.fixture def vulnerable_pkg1(): pkg = ImagePackage() pkg.image_id = "image1" pkg.image_user_id = "admin" pkg.name = "pkg1" pkg.normalized_src_pkg = "pkg1" pkg.version = "0:1.0.el8" pkg.fullversion = "0:1.0.el8" pkg.release = None pkg.pkg_type = "RPM" pkg.distro_name = "rhel" pkg.distro_version = "8" pkg.like_distro = "RHEL" pkg.arch = "amd64" pkg.pkg_path = "rpmdb" return pkg @pytest.fixture def nonvulnerable_pkg1(): pkg = ImagePackage() pkg.image_id = "image1" pkg.image_user_id = "admin" pkg.name = "pkg1" pkg.normalized_src_pkg = "pkg1" pkg.version = "1.1.el8" pkg.fullversion = "0:1.1.el8" pkg.release = None pkg.pkg_type = "RPM" pkg.distro_name = "centos" pkg.distro_version = "8" pkg.like_distro = "RHEL" return pkg @pytest.fixture def python_pkg1_100(): pkg = ImagePackage() pkg.image_id = "image1" pkg.image_user_id = "admin" pkg.name = "pythonpkg1" pkg.normalized_src_pkg = "pythonpkg1" pkg.version = "1.0.0" pkg.fullversion = "1.0.0" pkg.release = None pkg.pkg_type = "python" pkg.distro_name = "centos" pkg.distro_version = "8" pkg.like_distro = "RHEL" return pkg @pytest.fixture def python_pkg1_101(): pkg = ImagePackage() pkg.image_id = "image1" pkg.image_user_id = "admin" pkg.name = "pythonpkg1" pkg.normalized_src_pkg = "pythonpkg1" pkg.version = "1.0.1" pkg.fullversion = "1.0.1" pkg.release = None pkg.pkg_type = "python" pkg.distro_name = "centos" pkg.distro_version = "8" pkg.like_distro = "RHEL" return pkg def mock_distros_for(distro, version, like_distro=""): """ Mock implementation that doesn't use db :param cls: :param distro: :param version: :param like_distro: :return: """ logger.info("Calling mocked distro_for %s %s %s", distro, version, like_distro) return [DistroTuple(distro=distro, version=version, flavor=like_distro)] @pytest.fixture def monkeypatch_distros(monkeysession): """ Creates a monkey patch for the distro lookup to avoid DB operations :return: """ monkeysession.setattr(DistroMapping, "distros_for", mock_distros_for) def test_fixed_match( vulnerability_with_fix, vulnerable_pkg1, nonvulnerable_pkg1, monkeypatch_distros ): """ Test matches against fixed artifacts :return: """ f = vulnerability_with_fix.fixed_in[0] logger.info("Testing package %s", vulnerable_pkg1) logger.info("Testing vuln %s", f) assert isinstance(f, FixedArtifact) assert f.match_but_not_fixed(vulnerable_pkg1) assert not f.match_but_not_fixed(nonvulnerable_pkg1) pkg_vuln = ImagePackageVulnerability() pkg_vuln.package = vulnerable_pkg1 pkg_vuln.vulnerability = vulnerability_with_fix pkg_vuln.pkg_type = vulnerable_pkg1.name pkg_vuln.pkg_version = vulnerable_pkg1.version pkg_vuln.pkg_image_id = vulnerable_pkg1.image_id pkg_vuln.pkg_user_id = vulnerable_pkg1.image_user_id pkg_vuln.pkg_name = vulnerable_pkg1.name pkg_vuln.pkg_arch = vulnerable_pkg1.arch pkg_vuln.vulnerability_id = vulnerability_with_fix.id pkg_vuln.vulnerability_namespace_name = vulnerability_with_fix.namespace_name assert pkg_vuln.fixed_in() == f.version def test_notfixed_match(vulnerability_with_nofix, vulnerable_pkg1, monkeypatch_distros): """ Test matches against fixed artifacts :return: """ f = vulnerability_with_nofix.fixed_in[0] logger.info("Testing package %s", vulnerable_pkg1) logger.info("Testing vuln %s", f) assert isinstance(f, FixedArtifact) assert f.match_but_not_fixed(vulnerable_pkg1) pkg_vuln = ImagePackageVulnerability() pkg_vuln.package = vulnerable_pkg1 pkg_vuln.vulnerability = vulnerability_with_nofix pkg_vuln.pkg_type = vulnerable_pkg1.name pkg_vuln.pkg_version = vulnerable_pkg1.version pkg_vuln.pkg_image_id = vulnerable_pkg1.image_id pkg_vuln.pkg_user_id = vulnerable_pkg1.image_user_id pkg_vuln.pkg_name = vulnerable_pkg1.name pkg_vuln.pkg_arch = vulnerable_pkg1.arch pkg_vuln.vulnerability_id = vulnerability_with_nofix.id pkg_vuln.vulnerability_namespace_name = vulnerability_with_nofix.namespace_name assert pkg_vuln.fixed_in() is None def test_vulnerable_in( vulnerability_with_vulnartifact, vulnerable_pkg1, nonvulnerable_pkg1, monkeypatch_distros, ): """ Test vulnerable in matches :return: """ f = vulnerability_with_vulnartifact.vulnerable_in[0] logger.info("Testing package %s", vulnerable_pkg1) logger.info("Testing vuln %s", f) assert isinstance(f, VulnerableArtifact) assert f.match_and_vulnerable(vulnerable_pkg1) assert not f.match_and_vulnerable(nonvulnerable_pkg1) f = vulnerability_with_vulnartifact.vulnerable_in[1] logger.info("Testing package %s", vulnerable_pkg1) logger.info("Testing vuln %s", f) assert isinstance(f, VulnerableArtifact) assert not f.match_and_vulnerable( vulnerable_pkg1 ) # Both not vuln now, this entry is for 0.9.x assert not f.match_and_vulnerable(nonvulnerable_pkg1) pkg_vuln = ImagePackageVulnerability() pkg_vuln.package = vulnerable_pkg1 pkg_vuln.vulnerability = vulnerability_with_vulnartifact pkg_vuln.pkg_type = vulnerable_pkg1.name pkg_vuln.pkg_version = vulnerable_pkg1.version pkg_vuln.pkg_image_id = vulnerable_pkg1.image_id pkg_vuln.pkg_user_id = vulnerable_pkg1.image_user_id pkg_vuln.pkg_name = vulnerable_pkg1.name pkg_vuln.pkg_arch = vulnerable_pkg1.arch pkg_vuln.vulnerability_id = vulnerability_with_vulnartifact.id pkg_vuln.vulnerability_namespace_name = ( vulnerability_with_vulnartifact.namespace_name ) assert pkg_vuln.fixed_in() == None def test_fixed_and_vulnerable( vulnerability_with_both, vulnerable_pkg1, nonvulnerable_pkg1, monkeypatch_distros ): """ Test both fixed and vulnerable matches :return: """ f = vulnerability_with_both.fixed_in[0] v = vulnerability_with_both.vulnerable_in[0] logger.info("Testing package %s", vulnerable_pkg1) logger.info("Testing vuln %s", f) assert isinstance(v, VulnerableArtifact) assert v.match_and_vulnerable(vulnerable_pkg1) assert not v.match_and_vulnerable(nonvulnerable_pkg1) pkg_vuln = ImagePackageVulnerability() pkg_vuln.package = vulnerable_pkg1 pkg_vuln.vulnerability = vulnerability_with_both pkg_vuln.pkg_type = vulnerable_pkg1.name pkg_vuln.pkg_version = vulnerable_pkg1.version pkg_vuln.pkg_image_id = vulnerable_pkg1.image_id pkg_vuln.pkg_user_id = vulnerable_pkg1.image_user_id pkg_vuln.pkg_name = vulnerable_pkg1.name pkg_vuln.pkg_arch = vulnerable_pkg1.arch pkg_vuln.vulnerability_id = vulnerability_with_both.id pkg_vuln.vulnerability_namespace_name = vulnerability_with_both.namespace_name assert pkg_vuln.fixed_in() == "0:1.1.el8" def test_non_comparable_versions(python_pkg1_100, python_pkg1_101, monkeypatch_distros): """ Tests matching where fixed and vuln records use a version format that doesn't support comparators beyond equality (e.g CPEs) :return: """ assert isinstance(python_pkg1_100, ImagePackage) assert isinstance(python_pkg1_101, ImagePackage) v1 = Vulnerability() v1.id = "CVE-100" v1.namespace_name = "nvdv2:cves" v1.severity = "high" v1.fixed_in = [] v1.vulnerable_in = [] v1.created_at = v1.updated_at = datetime.datetime.utcnow() vuln1 = VulnerableArtifact() vuln1.created_at = vuln1.updated_at = v1.created_at vuln1.namespace_name = v1.namespace_name vuln1.name = python_pkg1_100.name vuln1.vulnerability_id = v1.id vuln1.parent = v1 vuln1.version = python_pkg1_100.version vuln1.include_previous_versions = True vuln1.epochless_version = vuln1.version vuln1.version_format = ( "static" # Random string, but not in set of ['semver', 'rpm', 'deb', 'apk'] ) v1.vulnerable_in.append(vuln1) assert v1.vulnerable_in[0].match_and_vulnerable(python_pkg1_100) assert not v1.vulnerable_in[0].match_and_vulnerable(python_pkg1_101) def test_multifix_vulnerability( vulnerability_with_multifix, vulnerable_semver_pkg1, vulnerable_semver_pkg2, monkeypatch_distros, ): """ Test matches against multiple semver range fixed artifacts (e.g. like a GHSA record) :return: """ f = vulnerability_with_multifix.fixed_in[0] f2 = vulnerability_with_multifix.fixed_in[1] logger.info("Testing package %s", vulnerable_semver_pkg1) logger.info("Testing vuln %s", f) assert isinstance(f, FixedArtifact) assert f.match_but_not_fixed(vulnerable_semver_pkg1) assert not f.match_but_not_fixed(vulnerable_semver_pkg2) t = ImagePackageVulnerability() t.package = vulnerable_semver_pkg1 t.vulnerability = vulnerability_with_multifix assert t.fixed_artifact() == f assert t.fixed_in() == "1.1.2" logger.info("Testing package %s", vulnerable_semver_pkg2) logger.info("Testing vuln %s", f2) assert isinstance(f2, FixedArtifact) assert not f2.match_but_not_fixed(vulnerable_semver_pkg1) assert f2.match_but_not_fixed(vulnerable_semver_pkg2) t = ImagePackageVulnerability() t.package = vulnerable_semver_pkg2 t.vulnerability = vulnerability_with_multifix assert t.fixed_artifact() == f2 assert t.fixed_in() == "2.2.2" # Unset the fix version f2.fix_metadata = {} logger.info("Testing vuln with fix removed %s", f2) assert isinstance(f2, FixedArtifact) assert not f2.match_but_not_fixed(vulnerable_semver_pkg1) assert f2.match_but_not_fixed(vulnerable_semver_pkg2) t = ImagePackageVulnerability() t.package = vulnerable_semver_pkg2 t.vulnerability = vulnerability_with_multifix assert t.fixed_artifact() == f2 assert t.fixed_in() is None
Track issues from various communication channels and react to them. Channel issues to relevant employees in your company to take care of them. Inform the submitters about the status of their issues with automated messages. The issue submitter inputs an issue via webform or email into the SprinxHelpDesk ITS system. An issue can also be submitted via phone and registered into the system by a customer care agent, for example. Alternatively, issues can be automatically sent to the helpdesk from another application such as a CRM. When a new issue is registered, the submitter receives an email notification of the issues‘s acceptance. In additional, the submitter receives a message whenever a status change is made, including the case's final resolution. This feature helps the submitter stay informed during the entire process, from beginning to end. Your issue solvers such as customer care agents can internally communicate with each other, forward issues, ask for comments and solutions to customer requests- all within the SprinxHelpDesk ITS system, a well organized solution to make the issue management system as efficient as possible. SprinxHelpDesk ITS is a cloud based application and therefore all you need is a web-browser and an Internet connection. No worries with fixes or upgrades, you always have the latest version of our helpdesk with all the newest features at your disposal. Detailed history of communication between an issue submitter (customer) and service department is registered, and can include attached files. Microsoft Dynamics CRM is a complex solution for customer-relation management offering a wide selection of tools and functions to keep thorough details about your clients from the first contact to the aftersale support. By integrating MS Dynamics CRM with SprinxHelpDesk ITS you will expend the business system with helpdesk functions - the customer-service task management. SprinxCRM is a sales tool to maximize your sales productivity. A simple to use, yet very powerful CRM designed to help you capture new business opportunities, turn them into sales and stay in touch with your customers. SprinxHelpDesk ITS, the issue management system, and SprinxCRM, the customer-care tool, is the perfect formula for your business. Try them both for FREE! Manage your customer database and allrelevant information from one central system via your Internet web browser. Create and delegate tasks within your sales team. Register and nurture all your leads and business opportunities. Manage requests from your customers! SprinxHelpDesk ITS can be a very effective customer-care application. It will help you to cut costs and maximize your profit. Easy to set up, easy to operate. It can be used as a stand-alone tool or be a part of a complex business system. Set up your own issue tracking system, it takes just a couple of clicks! TRY OUR SPRINX ITS FOR FREE!
# # Copyright (c) 2013 Ashwith Jerome Rego # # 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 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 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 pylab import random import math #================================================================= # Radioactive Decay - Monte Carlo Simulation # #================================================================= def simRadio(nMolecules, halfLife, nTrials, tStop, tStep): """ Performs a Monte Carlo Simulation for radioactive decay Keyword arguments: nMolecules -- number of molecules in the material halfLife -- Half life of the material in time units nTrials -- Number of simulation trials to be performed tStop -- Stop time for each simulation in time units tStep -- Step time in simulation for each time unit. Return a list of time coordinates and a list of the average number of molecules at each time step. """ # Calculate the decay constants, # the number of simulation steps k = math.log(2)/halfLife nSteps = int(tStop/tStep) # initialize list to store average number # of molecules after each simulations step nMol = [0] * nSteps # First loop - runs through each trial for index_i in range(nTrials): tmpNMolecules = nMolecules # Seond loop - runs through each simulations step for index_j in range(nSteps): # Third loop - decide the fate of each molecule # in a simulation step. Delete it randomly # probability k for index_k in range(tmpNMolecules): if random.uniform(0,1) <= k*tStep: tmpNMolecules -= 1 nMol[index_j] += tmpNMolecules tAxis = [] # Calculate the average for each simulation step # and the coordinates for the time axis for index_i in range(nSteps): nMol[index_i] /= float(nTrials) tAxis += [index_i*tStep] return [0] + tAxis, [nMolecules] + nMol def testSim(): nMolecules = 100 nTrials = 1000 tStop = 15 tStep = 0.1 halfLife = 2 pylab.figure(); t, y = simRadio(nMolecules, halfLife, nTrials, tStop, tStep) pylab.plot(t, y) pylab.title("Radioactive Decay - Monte Carlo Simulation") pylab.xlabel("Time") pylab.ylabel("Number of Molecules") pylab.text(6, 90, "Simulated Half Life = " + str(y[int(2/tStep)]) + " time units.") pylab.show()
Foodtech Village is the community for foodtech change-makers and entrepreneurs, shaping the future of food. We at Foodtech Village help startups reach their full potential, providing our corporate partners with our expertise in open innovation and emerging technologies; assisting partner VCs with their portfolio startups, and promoting the foodtech scene at home and abroad through events and conferences. Our aim is to build a stronger ecosystem around foodtech. We intend to transform Stockholm and ultimately Sweden into a global hub for the foodtech revolution and create the conditions for a new industry with global export potential. This is where we start.
from gusto import * import itertools from firedrake import (as_vector, SpatialCoordinate, PeriodicIntervalMesh, ExtrudedMesh, exp, sin, Function, FunctionSpace, VectorFunctionSpace, BrokenElement) from firedrake.petsc import PETSc from argparse import ArgumentParser import numpy as np import sys PETSc.Log.begin() parser = ArgumentParser(description=(""" Nonhydrostatic gravity wave test based on that of Skamarock and Klemp (1994). """), add_help=False) parser.add_argument("--test", action="store_true", help="Enable a quick test run.") parser.add_argument("--dt", action="store", default=6.0, type=float, help="Time step size (s)") parser.add_argument("--res", default=1, type=int, action="store", help="Resolution scaling parameter") parser.add_argument("--debug", action="store_true", help="Turn on KSP monitors") parser.add_argument("--help", action="store_true", help="Show help.") args, _ = parser.parse_known_args() if args.help: help = parser.format_help() PETSc.Sys.Print("%s\n" % help) sys.exit(1) res = args.res nlayers = res*10 # horizontal layers columns = res*300 # number of columns dt = args.dt # Time steps (s) if args.test: tmax = dt else: tmax = 3600. H = 1.0e4 # Height position of the model top L = 3.0e5 PETSc.Sys.Print(""" Number of vertical layers: %s,\n Number of horizontal columns: %s.\n """ % (nlayers, columns)) m = PeriodicIntervalMesh(columns, L) dx = L / columns cfl = 20.0 * dt / dx dz = H / nlayers PETSc.Sys.Print(""" Problem parameters:\n Test case: Skamarock and Klemp gravity wave.\n Time-step size: %s,\n Test run: %s,\n Dx (m): %s,\n Dz (m): %s,\n CFL: %s\n """ % (dt, bool(args.test), dx, dz, cfl)) PETSc.Sys.Print("Initializing problem with dt: %s and tmax: %s.\n" % (dt, tmax)) # build volume mesh mesh = ExtrudedMesh(m, layers=nlayers, layer_height=H/nlayers) fieldlist = ['u', 'rho', 'theta'] timestepping = TimesteppingParameters(dt=dt) dirname = 'sk_nonlinear_dx%s_dz%s_dt%s' % (dx, dz, dt) points_x = np.linspace(0., L, 100) points_z = [H/2.] points = np.array([p for p in itertools.product(points_x, points_z)]) dumptime = 100 # print every 100s dumpfreq = int(dumptime / dt) PETSc.Sys.Print("Output frequency: %s\n" % dumpfreq) output = OutputParameters(dirname=dirname, dumpfreq=dumpfreq, dumplist=['u'], perturbation_fields=['theta', 'rho'], point_data=[('theta_perturbation', points)], log_level='INFO') parameters = CompressibleParameters() diagnostics = Diagnostics(*fieldlist) diagnostic_fields = [CourantNumber()] state = State(mesh, vertical_degree=1, horizontal_degree=1, family="CG", timestepping=timestepping, output=output, parameters=parameters, diagnostics=diagnostics, fieldlist=fieldlist, diagnostic_fields=diagnostic_fields) # Initial conditions u0 = state.fields("u") rho0 = state.fields("rho") theta0 = state.fields("theta") # spaces Vu = u0.function_space() Vt = theta0.function_space() Vr = rho0.function_space() # Thermodynamic constants required for setting initial conditions # and reference profiles g = parameters.g N = parameters.N p_0 = parameters.p_0 c_p = parameters.cp R_d = parameters.R_d kappa = parameters.kappa x, z = SpatialCoordinate(mesh) # N^2 = (g/theta)dtheta/dz => dtheta/dz = theta N^2g => theta=theta_0exp(N^2gz) Tsurf = 300. thetab = Tsurf*exp(N**2*z/g) theta_b = Function(Vt).interpolate(thetab) rho_b = Function(Vr) # Calculate hydrostatic Pi PETSc.Sys.Print("Computing hydrostatic varaibles...\n") # Use vertical hybridization preconditioner for the balance initialization piparams = {'ksp_type': 'preonly', 'pc_type': 'python', 'mat_type': 'matfree', 'pc_python_type': 'gusto.VerticalHybridizationPC', # Vertical trace system is only coupled vertically in columns # block ILU is a direct solver! 'vert_hybridization': {'ksp_type': 'preonly', 'pc_type': 'bjacobi', 'sub_pc_type': 'ilu'}} compressible_hydrostatic_balance(state, theta_b, rho_b, params=piparams) PETSc.Sys.Print("Finished computing hydrostatic varaibles...\n") a = 5.0e3 deltaTheta = 1.0e-2 theta_pert = deltaTheta*sin(np.pi*z/H)/(1 + (x - L/2)**2/a**2) theta0.interpolate(theta_b + theta_pert) rho0.assign(rho_b) u0.project(as_vector([20.0, 0.0])) state.initialise([('u', u0), ('rho', rho0), ('theta', theta0)]) state.set_reference_profiles([('rho', rho_b), ('theta', theta_b)]) # Set up advection schemes ueqn = EulerPoincare(state, Vu) rhoeqn = AdvectionEquation(state, Vr, equation_form="continuity") supg = True if supg: thetaeqn = SUPGAdvection(state, Vt, equation_form="advective") else: thetaeqn = EmbeddedDGAdvection(state, Vt, equation_form="advective", options=EmbeddedDGOptions()) advected_fields = [] advected_fields.append(("u", ThetaMethod(state, u0, ueqn))) advected_fields.append(("rho", SSPRK3(state, rho0, rhoeqn))) advected_fields.append(("theta", SSPRK3(state, theta0, thetaeqn))) # Set up linear solver solver_parameters = {'mat_type': 'matfree', 'ksp_type': 'preonly', 'pc_type': 'python', 'pc_python_type': 'firedrake.SCPC', 'pc_sc_eliminate_fields': '0, 1', # The reduced operator is not symmetric 'condensed_field': {'ksp_type': 'fgmres', 'ksp_rtol': 1.0e-8, 'ksp_atol': 1.0e-8, 'ksp_max_it': 100, 'pc_type': 'gamg', 'pc_gamg_sym_graph': None, 'mg_levels': {'ksp_type': 'gmres', 'ksp_max_it': 5, 'pc_type': 'bjacobi', 'sub_pc_type': 'ilu'}}} if args.debug: solver_parameters['condensed_field']['ksp_monitor_true_residual'] = None linear_solver = CompressibleSolver(state, solver_parameters=solver_parameters, overwrite_solver_parameters=True) # Set up forcing compressible_forcing = CompressibleForcing(state) # Build time stepper stepper = CrankNicolson(state, advected_fields, linear_solver, compressible_forcing) PETSc.Sys.Print("Starting simulation...\n") stepper.run(t=0, tmax=tmax)
It became clear that the future work connected with the continuation of providing health services in these communities couldn’t be implemented without the partnership of municipalities and the identified on project community leaders and groups of self-support. BFPA and NNHM will be available to support local teams in their efforts of looking for financing and implementing the future work on providing health services in the project locations. The team proposes different strategies and approaches - providing mobile services, subsidized by the municipalities, and elaborating health strategies with plans of action are just two of the options to be adapted to local conditions. Among the main difficulties to overcome in the process of implementing the activities were: lack of realizing the importance of taking care of one’s own health status and building confidential relationships between patients and specialists providing health services by locations. The final meeting on the initiative ‘Mission Possible: better sexual and reproductive health for young people from vulnerable communities – ways of overcoming health inequalities’ is to take place on 20 April 2017 in Sofia.
import math from abc import ABC, abstractmethod from collections import UserList from operator import attrgetter from shapely import prepared from shapely.geometry import JOIN_STYLE, MultiPolygon from shapely.ops import unary_union from c3nav.mapdata.render.engines import register_engine from c3nav.mapdata.render.engines.base3d import Base3DEngine from c3nav.mapdata.render.utils import get_full_levels, get_main_levels from c3nav.mapdata.utils.geometry import assert_multipolygon class AbstractOpenScadElem(ABC): @abstractmethod def render(self) -> str: raise NotADirectoryError class AbstractOpenScadBlock(AbstractOpenScadElem, UserList): def render_children(self): return '\n'.join(child.render() for child in self.data if child is not None) class OpenScadRoot(AbstractOpenScadBlock): def render(self): return self.render_children() class OpenScadBlock(AbstractOpenScadBlock): def __init__(self, command, comment=None, children=None): super().__init__(children if children else []) self.command = command self.comment = comment def render(self): if self.comment or len(self.data) != 1: return '%s {%s\n %s\n}' % ( self.command, '' if self.comment is None else (' // '+self.comment), self.render_children().replace('\n', '\n ') ) return '%s %s' % (self.command, self.render_children()) class OpenScadCommand(AbstractOpenScadElem): def __init__(self, command): super().__init__() self.command = command def render(self): return self.command @register_engine class OpenSCADEngine(Base3DEngine): filetype = 'scad' def __init__(self, *args, center=True, **kwargs): super().__init__(*args, center=center, **kwargs) if center: self.root = OpenScadBlock('scale([%(scale)f, %(scale)f, %(scale)f]) translate([%(x)f, %(y)f, 0])' % { 'scale': self.scale, 'x': -(self.minx + self.maxx) / 2, 'y': -(self.miny + self.maxy) / 2, }) else: self.root = OpenScadBlock('scale([%(scale)f, %(scale)f, %(scale)f])' % { 'scale': self.scale, 'x': -(self.minx + self.maxx) / 2, 'y': -(self.miny + self.maxy) / 2, }) def custom_render(self, level_render_data, access_permissions, full_levels): if full_levels: levels = get_full_levels(level_render_data) else: levels = get_main_levels(level_render_data) buildings = None areas = None main_building_block = None main_building_block_diff = None current_upper_bound = None for geoms in levels: # hide indoor and outdoor rooms if their access restriction was not unlocked restricted_spaces_indoors = unary_union( tuple(area.geom for access_restriction, area in geoms.restricted_spaces_indoors.items() if access_restriction not in access_permissions) ) restricted_spaces_outdoors = unary_union( tuple(area.geom for access_restriction, area in geoms.restricted_spaces_outdoors.items() if access_restriction not in access_permissions) ) restricted_spaces = unary_union((restricted_spaces_indoors, restricted_spaces_outdoors)) # noqa # crop altitudeareas for altitudearea in geoms.altitudeareas: altitudearea.geometry = altitudearea.geometry.geom.difference(restricted_spaces) altitudearea.geometry_prep = prepared.prep(altitudearea.geometry) # crop heightareas new_heightareas = [] for geometry, height in geoms.heightareas: geometry = geometry.geom.difference(restricted_spaces) geometry_prep = prepared.prep(geometry) new_heightareas.append((geometry, geometry_prep, height)) geoms.heightareas = new_heightareas if geoms.on_top_of_id is None: buildings = geoms.buildings areas = MultiPolygon() current_upper_bound = geoms.upper_bound holes = geoms.holes.difference(restricted_spaces) buildings = buildings.difference(holes) areas = areas.union(holes.buffer(0).buffer(0.01, join_style=JOIN_STYLE.mitre)) main_building_block = OpenScadBlock('union()', comment='Level %s' % geoms.short_label) self.root.append(main_building_block) main_building_block_diff = OpenScadBlock('difference()') main_building_block.append(main_building_block_diff) main_building_block_inner = OpenScadBlock('union()') main_building_block_diff.append(main_building_block_inner) main_building_block_inner.append( self._add_polygon(None, buildings.intersection(self.bbox), geoms.lower_bound, geoms.upper_bound) ) for altitudearea in sorted(geoms.altitudeareas, key=attrgetter('altitude')): if not altitudearea.geometry.intersects(self.bbox): continue if altitudearea.altitude2 is not None: name = 'Altitudearea %s-%s' % (altitudearea.altitude/1000, altitudearea.altitude2/1000) else: name = 'Altitudearea %s' % (altitudearea.altitude / 1000) # why all this buffering? # buffer(0) ensures a valid geometry, this is sadly needed sometimes # the rest of the buffering is meant to make polygons overlap a little so no glitches appear # the intersections below will ensure that they they only overlap with each other and don't eat walls geometry = altitudearea.geometry.buffer(0) inside_geometry = geometry.intersection(buildings).buffer(0).buffer(0.01, join_style=JOIN_STYLE.mitre) outside_geometry = geometry.difference(buildings).buffer(0).buffer(0.01, join_style=JOIN_STYLE.mitre) geometry_buffered = geometry.buffer(0.01, join_style=JOIN_STYLE.mitre) if geoms.on_top_of_id is None: areas = areas.union(geometry) buildings = buildings.difference(geometry).buffer(0) inside_geometry = inside_geometry.intersection(areas).buffer(0) outside_geometry = outside_geometry.intersection(areas).buffer(0) geometry_buffered = geometry_buffered.intersection(areas).buffer(0) outside_geometry = outside_geometry.intersection(self.bbox) if not inside_geometry.is_empty: if altitudearea.altitude2 is not None: min_slope_altitude = min(altitudearea.altitude, altitudearea.altitude2) max_slope_altitude = max(altitudearea.altitude, altitudearea.altitude2) bounds = inside_geometry.bounds # cut in polygon = self._add_polygon(None, inside_geometry, min_slope_altitude-10, current_upper_bound+1000) slope = self._add_slope(bounds, altitudearea.altitude, altitudearea.altitude2, altitudearea.point1, altitudearea.point2, bottom=True) main_building_block_diff.append( OpenScadBlock('difference()', children=[polygon, slope], comment=name+' inside cut') ) # actual thingy if max_slope_altitude > current_upper_bound and inside_geometry.intersects(self.bbox): polygon = self._add_polygon(None, inside_geometry.intersection(self.bbox), current_upper_bound-10, max_slope_altitude+10) slope = self._add_slope(bounds, altitudearea.altitude, altitudearea.altitude2, altitudearea.point1, altitudearea.point2, bottom=False) main_building_block.append( OpenScadBlock('difference()', children=[polygon, slope], comment=name + 'outside') ) else: if altitudearea.altitude < current_upper_bound: main_building_block_diff.append( self._add_polygon(name+' inside cut', inside_geometry, altitudearea.altitude, current_upper_bound+1000) ) else: main_building_block.append( self._add_polygon(name+' inside', inside_geometry.intersection(self.bbox), min(altitudearea.altitude-700, current_upper_bound-10), altitudearea.altitude) ) if not outside_geometry.is_empty: if altitudearea.altitude2 is not None: min_slope_altitude = min(altitudearea.altitude, altitudearea.altitude2) max_slope_altitude = max(altitudearea.altitude, altitudearea.altitude2) bounds = outside_geometry.bounds polygon = self._add_polygon(None, outside_geometry, min_slope_altitude-710, max_slope_altitude+10) slope1 = self._add_slope(bounds, altitudearea.altitude, altitudearea.altitude2, altitudearea.point1, altitudearea.point2, bottom=False) slope2 = self._add_slope(bounds, altitudearea.altitude-700, altitudearea.altitude2-700, altitudearea.point1, altitudearea.point2, bottom=True) union = OpenScadBlock('union()', children=[slope1, slope2], comment=name+'outside') main_building_block.append( OpenScadBlock('difference()', children=[polygon, union], comment=name+'outside') ) else: if geoms.on_top_of_id is None: lower = geoms.lower_bound else: lower = altitudearea.altitude-700 if lower == current_upper_bound: lower -= 10 main_building_block.append( self._add_polygon(name+' outside', outside_geometry, lower, altitudearea.altitude) ) # obstacles if altitudearea.altitude2 is not None: obstacles_diff_block = OpenScadBlock('difference()', comment=name + ' obstacles') had_obstacles = False obstacles_block = OpenScadBlock('union()') obstacles_diff_block.append(obstacles_block) min_slope_altitude = min(altitudearea.altitude, altitudearea.altitude2) max_slope_altitude = max(altitudearea.altitude, altitudearea.altitude2) bounds = geometry.bounds for height, obstacles in altitudearea.obstacles.items(): height_diff = OpenScadBlock('difference()') had_height_obstacles = None height_union = OpenScadBlock('union()') height_diff.append(height_union) for obstacle in obstacles: if not obstacle.geom.intersects(self.bbox): continue obstacle = obstacle.geom.buffer(0).buffer(0.01, join_style=JOIN_STYLE.mitre) if self.min_width: obstacle = obstacle.union(self._satisfy_min_width(obstacle)).buffer(0) obstacle = obstacle.intersection(geometry_buffered) if not obstacle.is_empty: had_height_obstacles = True had_obstacles = True height_union.append( self._add_polygon(None, obstacle.intersection(self.bbox), min_slope_altitude-20, max_slope_altitude+height+10) ) if had_height_obstacles: obstacles_block.append(height_diff) height_diff.append( self._add_slope(bounds, altitudearea.altitude+height, altitudearea.altitude2+height, altitudearea.point1, altitudearea.point2, bottom=False) ) if had_obstacles: main_building_block.append(obstacles_diff_block) obstacles_diff_block.append( self._add_slope(bounds, altitudearea.altitude-10, altitudearea.altitude2-10, altitudearea.point1, altitudearea.point2, bottom=True) ) else: obstacles_block = OpenScadBlock('union()', comment=name + ' obstacles') had_obstacles = False for height, obstacles in altitudearea.obstacles.items(): for obstacle in obstacles: if not obstacle.geom.intersects(self.bbox): continue obstacle = obstacle.geom.buffer(0).buffer(0.01, join_style=JOIN_STYLE.mitre) if self.min_width: obstacle = obstacle.union(self._satisfy_min_width(obstacle)).buffer(0) obstacle = obstacle.intersection(geometry_buffered).intersection(self.bbox) if not obstacle.is_empty: had_obstacles = True obstacles_block.append( self._add_polygon(None, obstacle, altitudearea.altitude-10, altitudearea.altitude+height) ) if had_obstacles: main_building_block.append(obstacles_block) if self.min_width and geoms.on_top_of_id is None: main_building_block_inner.append( self._add_polygon('min width', self._satisfy_min_width(buildings).intersection(self.bbox).buffer(0), geoms.lower_bound, geoms.upper_bound) ) def _add_polygon(self, name, geometry, minz, maxz): geometry = geometry.buffer(0) polygons = [] for polygon in assert_multipolygon(geometry): points = [] points_lookup = {} output_rings = [] for ring in [polygon.exterior]+list(polygon.interiors): output_ring = [] for coords in ring.coords: try: i = points_lookup[coords] except KeyError: points_lookup[coords] = len(points) i = len(points) points.append(list(coords)) output_ring.append(i) if output_ring[0] == output_ring[-1]: output_ring = output_ring[:-1] output_rings.append(output_ring) polygons.append(OpenScadCommand('polygon(%(points)r, %(rings)r, 10);' % { 'points': points, 'rings': output_rings, })) if not polygons: return None extrude_cmd = 'linear_extrude(height=%f, convexity=10)' % (abs(maxz-minz)/1000) translate_cmd = 'translate([0, 0, %f])' % (min(maxz, minz)/1000) return OpenScadBlock(translate_cmd, children=[OpenScadBlock(extrude_cmd, comment=name, children=polygons)]) def _add_slope(self, bounds, altitude1, altitude2, point1, point2, bottom=False): distance = point1.distance(point2) altitude_diff = (altitude2-altitude1)/1000 rotate_y = -math.degrees(math.atan2(altitude_diff, distance)) rotate_z = math.degrees(math.atan2(point2.y-point1.y, point2.x-point1.x)) if bottom: rotate_y += 180 minx, miny, maxx, maxy = bounds size = ((maxx-minx)+(maxy-miny))*2 cmd = OpenScadCommand('square([%f, %f], center=true);' % (size, size)) cmd = OpenScadBlock('linear_extrude(height=16, convexity=10)', children=[cmd]) cmd = OpenScadBlock('rotate([0, %f, %f])' % (rotate_y, rotate_z), children=[cmd]) cmd = OpenScadBlock('translate([%f, %f, %f])' % (point1.x, point1.y, altitude1/1000), children=[cmd]) return cmd def _satisfy_min_width(self, geometry): return geometry.buffer(self.min_width/2, join_style=JOIN_STYLE.mitre) def render(self, filename=None): return self.root.render().encode()
As the current academic year has come to a close and high school students around the world finish their school years, it’s time for both recruiters and high school seniors to think about applications for the 2018-19 academic year. While domestic students may drag their feet on applications, international students need to plan ahead. As you read this article, approximately 1 million new students worldwide are researching degree programs in other countries (ICEF 2014). The majority are not reading brochures or going to recruitment fairs, they’re doing their research on their smartphones. So you know mobile matters for American teens who are glued to their phones, but is mobile as critical for students abroad? In fact, it’s even more important for these students. Global smartphone usage rates are growing, with tech-friendly South Korea coming in at the top worldwide, and Malaysia, China, Turkey and even Palestine in the top 20. Adoption rates are higher in rapidly developing countries, where students are also more likely to consider studying abroad. China, India, Brazil and Nigeria rank among the countries with the highest numbers of mobile phones in use. In some countries, it’s easier to get online by smartphone than by desktop. In India, for example, 77% of urban users and 92% of rural users use their phones as their primary means of accessing the internet. In areas where landline or internet infrastructure has trailed behind wealthier countries, smartphones have helped bridge the gap. That’s one of the reasons why the number of smartphone users in Africa has doubled in two years. While data on the number of smartphone owners outside the United States shows high adoption rates, it becomes even more critical for recruiters when you break that down by demographics. In South Korea, for example, 88% of the general population owns a smartphone – but 100% of young adults 18-34 have one. And while rates of ownership among adults over 35 hover around 30-50% in many European nations, youth ownership rates are much higher. In Germany, 92% of young adults have a smartphone, versus only 50% among those 35 and up. The 2017 Social Admissions Report by Chegg found that 85% of students used a mobile device to research universities. This data was supported by a 2016 survey conducted by Quacquarelli Symonds in which over 60% of students at UK universities reported using a smartphone during their decision journey. Prioritizing mobile marketing in recruitment strategies is becoming increasingly critical for universities that recruit international students. This means not only making the university website mobile-accessible but also understanding how prospective students research and discover information using smartphones – i.e. how they find your university’s website in the first place. Most universities who are updating their websites to become more mobile-friendly won’t convert the entire site to mobile right away. It makes sense to prioritize specific landing pages and a few key pages of greatest importance for your target audience. So which pages on your site do prospective international students navigate to? Reports from higher education data experts QS looked at what’s most important to students in crucial regions for international recruitment around the globe. While American students listed ROI as their most important criterion in choosing a college, the quality of education was overwhelmingly the most important factor for students from China, India, Latin America and Southeast Asia. Students from all the surveyed regions abroad wanted to know that their credentials would make them stand out in the job marketplace, as well as post-graduation employment rates. The student experience is an important factor for students from some regions, while other students are less concerned about this – only 6% of Chinese students, for example, rated it as a top factor in decision-making. Students from all regions rated availability of financial aid as a primary factor in their choice of college. What can admissions professionals take from this? Ensure that, along with general program information, information on teaching, prominent academic staff and research, employment prospects and rates, and financial aid is available efficiently on your mobile site. Study after study has shown that the longer users need to wait for your site to load, they’re substantially more likely to desert your page and look elsewhere. With people on the go and the possibility of data caps or slow wi-fi connections, that’s even more true for wi-fi, and for teens with limited attention spans. Does your site already load slowly at home in California? Now imagine trying to load it on a patchy connection in India or China. Tech-savvy teens may have the latest devices, but prospective international students can be accessing your site via slow connections, meaning it’s critical to have a fast-loading mobile site where they can get the information they need. Check your website analytics. If your website has a higher bounce rate for mobile users than it does for desktop/laptop users, your site has a mobile problem. See how your university compares to others in the university mobile speed rankings. Keep in mind that an average mobile speed score of 50 equates to a 10 second page load time. According to Google’s research, a page load time of 10 seconds means a 123% increase in bounce rate. It’s easy to start taking the first steps to ensure you’re ready for next year’s application season. Optimizing your site for international students means making sure your site is smartphone-friendly, starting with fast-loading landing pages that provide easy access to the information prospective students need. These pages, specifically designed for mobile devices, provide the initial engagement with prospective students. They load quickly, are easy to navigate, and provide a lot of information in a short amount of time. Setting up mobile-specific landing pages is a much better solution than simply making the main pages of your website responsive. Incorporating video is a very effective way to capture attention and create initial engage with prospective students. Personalizing the information for student from particular regions or countries, is an even better way of creating engagement. For the admissions and marketing teams that want to excel with this approach, you can also consider additional advanced features such as language compatibility, live chat or even chatbots to improve the user experience. Once you are you satisfied that you have created an excellent mobile user experience, you can turn your attention to marketing. Attracting prospective students to your site can be done in many ways. You could add an additional “mobile” link to your listings on the major college portal websites offering students using smartphones the choice of entering your mobile site. This is called referral traffic and you are simply setting up 2 different channels, one for students using Mac or PC computers and another for mobile devices users. Targeted advertising is an excellent way for you to develop an instant connection with prospective students. Google Adwords and Facebook offer extremely powerful targeting options that enable you to reach prospective students all over the world. Both companies have made mobile a top priority and Google even rewards organizations that offer an excellent mobile experience with higher rankings in their search results. Prospective students all over the world are increasingly using smartphones to conduct their research on university programs. Creating a mobile-first recruiting strategy should be a top priority for any university wishing to attract international students. First impressions count and an excellent mobile experience will help your university attract more international student applicants. To get started, contact us today for your free report on optimizing your site for mobile.
"""This platform provides support for sensor data from RainMachine.""" import logging from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from . import ( DATA_CLIENT, DOMAIN as RAINMACHINE_DOMAIN, OPERATION_RESTRICTIONS_UNIVERSAL, SENSOR_UPDATE_TOPIC, SENSORS, RainMachineEntity) _LOGGER = logging.getLogger(__name__) async def async_setup_platform( hass, config, async_add_entities, discovery_info=None): """Set up RainMachine sensors based on the old way.""" pass async def async_setup_entry(hass, entry, async_add_entities): """Set up RainMachine sensors based on a config entry.""" rainmachine = hass.data[RAINMACHINE_DOMAIN][DATA_CLIENT][entry.entry_id] sensors = [] for sensor_type in rainmachine.sensor_conditions: name, icon, unit = SENSORS[sensor_type] sensors.append( RainMachineSensor(rainmachine, sensor_type, name, icon, unit)) async_add_entities(sensors, True) class RainMachineSensor(RainMachineEntity): """A sensor implementation for raincloud device.""" def __init__(self, rainmachine, sensor_type, name, icon, unit): """Initialize.""" super().__init__(rainmachine) self._icon = icon self._name = name self._sensor_type = sensor_type self._state = None self._unit = unit @property def icon(self) -> str: """Return the icon.""" return self._icon @property def should_poll(self): """Disable polling.""" return False @property def state(self) -> str: """Return the name of the entity.""" return self._state @property def unique_id(self) -> str: """Return a unique, HASS-friendly identifier for this entity.""" return '{0}_{1}'.format( self.rainmachine.device_mac.replace(':', ''), self._sensor_type) @property def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self._unit async def async_added_to_hass(self): """Register callbacks.""" @callback def update(): """Update the state.""" self.async_schedule_update_ha_state(True) self._dispatcher_handlers.append(async_dispatcher_connect( self.hass, SENSOR_UPDATE_TOPIC, update)) async def async_update(self): """Update the sensor's state.""" self._state = self.rainmachine.data[OPERATION_RESTRICTIONS_UNIVERSAL][ 'freezeProtectTemp']
Sadie started working in care at the age of sixteen and has worked with a wide range of Service User groups over the years, from adults with learning and physical disabilities, mental health difficulties, the elderly, Dementia, End of life care and many other Health conditions that have impacted on a persons ability to manage in their own Home and personal care needs. So the journey towards management began. Sadie has held many positions within the Care sector, from Carer to head of operations and has been a Registered Care Manager for over 10 years working for Home Instead Senior Care Elmbridge, Heritage Health Care Windsor and started her career in management at Clarendon Home Care Services. Through the positions she has held she has been able to install her care ethics into many Home Carers, through training, mentoring, supporting and setting clear standards, improving the quality of Care delivery over the years. Sadie also believes that care should come before profit and will never knowingly put the standard of care delivery, the welfare of her staff and Service Users before the bottom line. Sadie believes that individuals accessing our services should find it an enjoyable experience. We aim to promote peoples independence and wellbeing and encouraged and support them to pursue their goals and aspirations, leading a fulfilling life irrespective of their age, race, disability, religion and gender. Sadie also believes that the staff should be treated with respect, supported and listened too and aims to be the best employer in the care sector. Copyright © 2018 Mulberry Care Services - All Rights Reserved.
from django.contrib import messages from django.shortcuts import get_object_or_404, redirect from django.views.decorators.http import require_POST from character.models import Character from organization.models.capability import Capability from organization.views.proposal import capability_success from organization.views.decorator import capability_required_decorator @require_POST @capability_required_decorator def heir_capability_view(request, capability_id): capability = get_object_or_404( Capability, id=capability_id, type=Capability.HEIR) first_heir_id = request.POST.get('first_heir') second_heir_id = request.POST.get('second_heir') try: first_heir = Character.objects.get(id=first_heir_id) except Character.DoesNotExist: first_heir = None try: second_heir = Character.objects.get(id=second_heir_id) except Character.DoesNotExist: second_heir = None if ( first_heir not in capability.applying_to.get_heir_candidates() or first_heir == capability.applying_to.get_position_occupier() ): messages.error(request, "Invalid first heir", "danger") return redirect(capability.get_absolute_url()) if ( second_heir not in capability.applying_to.get_heir_candidates() or second_heir == capability.applying_to.get_position_occupier() ) and second_heir is not None: messages.error(request, "Invalid second heir", "danger") return redirect(capability.get_absolute_url()) proposal = { 'first_heir': first_heir.id, 'second_heir': second_heir.id if second_heir is not None else 0 } capability.create_proposal(request.hero, proposal) return capability_success(capability, request)
I was recently introduced to a problem involving a Blackberry Enterprise Server (BES) and Microsoft Exchange Server 2003 in which the Exchange Server was acting up and the source of the problems was semi-obscured. The symptoms of the problem emerged on the Blackberry Server with worker threads failing health checks. After about 5 or 6 failed health checks, the Blackberry Service would restart and the issue would repeat. At firs the Blackberry device users were not receiving emails in a timely manner. At a certain point, they were not receiving emails at all. I dove in head first to see what was going on. From the fact that that worker threads were failing health checks I came to the conclusion that the issue was on the Exchange Server side. Each thread issues Remote Procedure Calls to the Exchange Server and waits for these RPCs to terminate. The RPCs were timing out and as a result the health checks were failing. On the Exchange Server, the RPC traffic was very high, with spikes maxing the server out. It was very evident that the Exchange Server was inundated with RPC requests. The irony of the matter is that the Blackberry Server was mainly responsible for those RPC requests. It is a common assumption that Blackberry Server traffic causes upward of five times the RPC traffic of a normal Outlook MAPI client. You can see where this can cause a vicious cycle. My next step was to find out why the RPCs were not terminating in a timely manner. I looked at the RPC latency and that was high as well. I eventually narrowed down the problem to disk contention issues at the storage array on which the Exchange Server mail store databases were housed. The array attached to the Exchange Server was due for replacement soon anyway, so I decided to move all of the logs and databases to a super-fast SAN that was recently purchased for these types of servers. Suffice it to say that after the move to SAN, all of the issues were resolved. Because of the blistering speed at which Exchange could read from and write to the SAN, the RPCs were terminating in a timely fashion. I saw latency drop to single digit values from triple digit values. The Blackberry Server was no longer having worker threads fail health checks. Although the RPC traffic remained the same, the lower RPC latency improved overall performance by an order of magnitude. I would like to note two things for Exchange or Blackberry administrators to be aware of here. The first is the very obvious point that a high-performance SAN greatly increases performance and reduces problems over all. The second is that when talking with Blackberry Enterprise support, the tech repeatedly tried to convince me that the Blackberry Enterprise Server did not have that great of an effect on an Exchange Server. He flatly denied the 5 fold increase rule, and he even said that it was a myth. He did hit the nail on the head when he suggested that the performance issue was on the Exchange Server side. I want to note, however, that when I turned off the Blackberry Enterprise Server to rule it out as a cause of the issue, the RPC requests dropped through the floor. The moral of the story is that although there were multiple reasons that contributed to the overall problems, never take the word of vendor support at face value. Always test every possible cause of the issue in a methodical fashion. You will probably find the root cause faster and end up much happier as an end result. Installing BesX took a couple of hours and was quite easy, although the download email ended up in my spam - why can't you download straight off the page? I could also gladly live without having to configure the user accounts and directories again, as this was really quite tricky, and I'm an experienced email admin. But other than that Express is easy to install. It offers loads of the same security, management, and push technologies that you get in full BlackBerry Enterprise Server, which makes it a great deal if you have an existing Microsoft server. Using a web-based GUI makes a nice change, and doesn't seem to reduce the effectiveness. And I liked being able to select a policy from BlackBerry's list.
import datetime from django.conf import settings from django.db import models from django.utils import timezone def underscore_to_camel_case(string): words = [word.capitalize() for word in string.split('_')] words[0] = words[0].lower() return ''.join(words) def camel_case_to_underscore(string): words = [] start_index = 0 for index, c in enumerate(string): # Ignore the first character regardless of case if c.isupper() and index: words.append(string[start_index:index].lower()) start_index = index words.append(string[start_index:].lower()) return '_'.join(words) def sanitize_order_by(string): """Make sure the string has no double underscores, also convert from camelcase.""" if string and string.find('__') == -1 and string.find('?') == -1: return camel_case_to_underscore(string) return '' def iso_8601_to_time(iso): """Parse an iso 8601 date into a datetime.time.""" if not iso: return None return datetime.datetime.strptime(iso, '%H:%M:%S').time() def iso_8601_to_date(iso): """Parse an iso 8601 date into a datetime.date.""" if not iso: return None return datetime.datetime.strptime(iso[:10], '%Y-%m-%d').date() def iso_8601_to_datetime(iso): """Parse an iso 8601 string into a timezone aware datetime, ignoring and fractional seconds.""" if not iso: return None dt = datetime.datetime.strptime(iso[:19], '%Y-%m-%dT%H:%M:%S') # strptime doesn't seem to handle timezones, parse them here if len(iso) == 19: return timezone.make_aware(dt, timezone.get_current_timezone()) else: # Make the datetime UTC if Z is the timezone, ignoring fractional seconds in between if (len(iso) == 20 or iso[19] == '.') and iso[-1] == 'Z': return timezone.make_aware(dt, timezone.UTC()) # Parse a complete timezone e.g. +00:00, checking for the correct length or ignored fractional seconds if (len(iso) == 25 or iso[19] == '.') and iso[-6] in ('+', '-') and iso[-3] == ':': try: hours = int(iso[-5:-3]) minutes = int(iso[-2:]) minutes += hours * 60 if iso[-6] == '-': minutes = -minutes return timezone.make_aware(dt, timezone.get_fixed_timezone(minutes)) except: # drop through and raise the exception pass raise ValueError('Invalid timezone %s.' % iso[19:]) def time_to_iso_8601(t): """Format a datetime.time as an iso 8601 string - HH:MM:SS.""" if t: return t.replace(microsecond=0).isoformat() else: return None def date_to_iso_8601(d): """Format a datetime.date as an iso 8601 string - YYYY-MM-DD.""" if d: return d.isoformat() else: return None def datetime_to_iso_8601(dt): """Format a datetime as an iso 8601 string - YYYY-MM-DDTHH:MM:SS with optional timezone +HH:MM.""" if dt: return dt.replace(microsecond=0).isoformat() else: return None def decode_int(value): """Decode an int after checking to make sure it is not already a int, 0.0, or empty.""" if isinstance(value, (int, long)): return value elif value == 0.0: return 0 elif not value: return None return int(value) def decode_float(value): """Decode a float after checking to make sure it is not already a float, 0, or empty.""" if type(value) is float: return value elif value == 0: return 0.0 elif not value: return None return float(value) def decode_bool(value): """Decode a bool after checking to make sure it is not already a bool, int, or empty. If value is 0.0, None is returned because floats shouldn't be used. """ t = type(value) if t is bool: return value elif t is int: return bool(value) elif not value: return None elif t in (str, unicode) and value.lower() in ('false', 'f', 'off', 'no'): return False return True _api_models = {} class _ApiModel(object): def __init__(self, model): # Tuples of (name, encoded_name, encode, decode) self.fields = [] self.list_fields = [] self.encoded_fields = {} self.id_field = None self.select_related_args = [] # data dictionary, set fields instead of creating a new dictionary for each get_data self._data = {} self._list_data = {} include_fields = None exclude_fields = None include_related = () list_fields = None update_fields = None readonly_fields = None camelcase = getattr(settings, 'API_CAMELCASE', True) renameid = getattr(settings, 'API_RENAME_ID', True) if hasattr(model, 'API'): if hasattr(model.API, 'include_fields'): include_fields = model.API.include_fields if hasattr(model.API, 'exclude_fields'): exclude_fields = model.API.exclude_fields if hasattr(model.API, 'include_related'): include_related = model.API.include_related if hasattr(model.API, 'list_fields'): list_fields = model.API.list_fields if hasattr(model.API, 'update_fields'): update_fields = model.API.update_fields if hasattr(model.API, 'readonly_fields'): readonly_fields = model.API.readonly_fields # Calculate all of the fields and list fields for field in model._meta.fields: if include_fields and field.name not in include_fields: continue elif exclude_fields and field.name in exclude_fields: continue else: name = field.name if field.name == 'id' and renameid: encoded_name = camel_case_to_underscore(model.__name__) + '_id' else: encoded_name = field.name if isinstance(field, models.IntegerField): encode = None decode = decode_int elif isinstance(field, models.FloatField): encode = None decode = decode_float elif isinstance(field, models.BooleanField): encode = None decode = decode_bool elif isinstance(field, models.DateTimeField): encode = datetime_to_iso_8601 decode = iso_8601_to_datetime elif isinstance(field, models.TimeField): encode = time_to_iso_8601 decode = iso_8601_to_time elif isinstance(field, models.DateField): encode = date_to_iso_8601 decode = iso_8601_to_date elif isinstance(field, models.ForeignKey): if field.name in include_related: encode = get_object_data decode = set_object_data # Calculate the select_related_args related_model = _get_api_model(field.rel.to) if related_model.select_related_args: for arg in related_model.select_related_args: self.select_related_args.append('%s__%s' % (field.name, arg)) else: self.select_related_args.append(field.name) # For include related fields, also add an encoded_field entry for the option of updating the foreign key to another entry # Setting the name_id attribute to None has the same effect as setting name to None, it will set the foreign key to null in the db field_coding = (name + '_id', underscore_to_camel_case(encoded_name + '_id') if camelcase else encoded_name + '_id', None, decode_int) self.encoded_fields[field_coding[1]] = field_coding else: name += '_id' encoded_name += '_id' encode = None decode = decode_int # For pointers to parent models, add as readonly field without the ptr suffix if isinstance(field, models.OneToOneField) and encoded_name.endswith('_ptr_id'): encoded_name = encoded_name[:-7] + '_id' field_coding = (name, underscore_to_camel_case(encoded_name) if camelcase else encoded_name, None, decode_int) self.fields.append(field_coding) self.list_fields.append(field_coding) continue elif isinstance(field, models.AutoField): encode = None decode = decode_int elif isinstance(field, (models.FileField, models.ManyToManyField)): continue else: encode = None decode = None if camelcase: field_coding = (name, underscore_to_camel_case(encoded_name), encode, decode) else: field_coding = (name, encoded_name, encode, decode) self.fields.append(field_coding) if field.name == 'id': self.id_field = field_coding if not field.editable or field.primary_key: pass elif update_fields and field.name not in update_fields: pass elif readonly_fields and field.name in readonly_fields: pass else: self.encoded_fields[field_coding[1]] = field_coding if list_fields is None or field.name in list_fields: if field_coding[2] == get_object_data: self.list_fields.append((field_coding[0], field_coding[1], get_object_list_data, field_coding[3])) else: self.list_fields.append(field_coding) def get_list_data(self, obj): for name, encoded_name, encode, decode in self.list_fields: if encode: self._list_data[encoded_name] = encode(getattr(obj, name)) else: self._list_data[encoded_name] = getattr(obj, name) return self._list_data def get_data(self, obj): for name, encoded_name, encode, decode in self.fields: if encode: self._data[encoded_name] = encode(getattr(obj, name)) else: self._data[encoded_name] = getattr(obj, name) return self._data def set_data(self, obj, data): for key, value in data.iteritems(): if self.encoded_fields.has_key(key): name, encoded_name, encode, decode = self.encoded_fields[key] if decode: if decode is set_object_data: decode(getattr(obj, name), value) else: setattr(obj, name, decode(value)) else: setattr(obj, name, value) def _get_api_model(model): key = model.__module__ + model.__name__ if not _api_models.has_key(key): _api_models[key] = _ApiModel(model) return _api_models[key] def get_object_list_data(obj): if obj is None: return None model = _get_api_model(type(obj)) return model.get_list_data(obj) def get_object_data(obj): if obj is None: return None model = _get_api_model(type(obj)) data = model.get_data(obj) if hasattr(obj, '_exclude_data'): # Return a copy with specific data fields removed data = dict(data) for excluded in obj._exclude_data: del data[excluded] return data def set_object_data(obj, data): model = _get_api_model(type(obj)) model.set_data(obj, data) def save_object(obj): model = type(obj) if hasattr(model, 'API') and hasattr(model.API, 'include_related'): for field in model.API.include_related: # Do a quick check for readonly status - this is for a slight performance boost only # There are other settings that can cause the sub-object to be readonly, but it's not enforced here if hasattr(model.API, 'readonly_fields') and field in model.API.readonly_fields: continue subobj = getattr(obj, field, None) if subobj: save_object(subobj) obj.full_clean() obj.save()
Culture and organizational performance are inter-related. Organizations that espouse a positive culture on a foundation of shared values have a competitive advantage. Research also shows that people who find their need for meaning and purpose as being met at work exhibit higher levels of performance and expend higher levels of discretionary effort. Culture is also a powerful driver of engagement, which has been linked to better financial performance. How confident can leaders be that their efforts to disseminating organizational culture are reaching all their people? 1. Technology allows more and more people to work remotely, physically removing a portion of the workforce from the corporate or local campuses where people used to congregate. 2. Contingent or “off-balance-sheet” workers are making up a growing portion of the workers – and these employees may not necessarily feel the same investment in an employer’s mission and goals that a traditional employee might. The astonishing fact that emerges out of research is that 95% of new employment in the United States between 2005 and 2015 consisted of alternative work arrangements. An INTUIT report suggests that nearly 40% of all US employees will be engaged in some sort of alternative work arrangement by 2020. A 2015 GALLUP poll revealed that the number of employees working off-campus has grown nearly four-fold since 1995, with one in four employees noting that they mostly telecommute. Thus, we have the reality of the distributed and contingent workforce. Employers face the growing challenge of fostering a shared culture that encompasses all employees, on or off campus, on or off the balance sheet. A consistent culture becomes a great challenge. How can leaders develop a nuanced strategy to extend organizational culture to alternative types of employees? We can segment the entire workforce of an organization along two axes: on vs. off campus; and contract type – on vs. off balance sheet. It is important to recognize that the two axes are not static. Rather, they are fluid to the extent that employees can move from one category to another. The fluidity poses additional challenges for leadership in crafting an appropriate culture. “Hybrid” employees who may alternate between on-campus work and remote locations have some advantages of the on-campus employee, while also facing the challenges of the remote employee. The tenured remote worker. Off-campus but on-balance sheet workers are commonly referred to as teleworkers, but they may also include traveling salespeople, remote customer service workers, and those in other jobs that do not require on-campus accommodations. These workers have the flexibility of location, but are at a disadvantage when it comes to actually observing social norms as well as experiencing in-person collaboration. Research suggests that remote employees often have less trust in each other’s work and capabilities due to a lack of interpersonal communication.16 In addition, remote workers may feel isolated and separated from the company’s headquarters. However, companies still have some traditional levers to pull to engage the tenured remote worker, such as benefits and formal career progression opportunities. Creating a consistent culture across these four unique talent segments requires strategic grounding, as a positive organizational culture is not likely to thrive without focus, intention, and action. While culture may often be viewed as an intangible asset, and even as an emotional or personal aspect of business, using a strategic framework can help bring culture to the forefront of leadership decision making. Just as broader organizational strategy must be crafted deliberately, culture must also be intentionally shaped to make workers feel valued and perform well. Asking a series of questions specifically focused on managing culture can help to guide organizations as they work to sustain and extend their mission amid the growth of alternative work arrangements. Based on the strategic choice cascade—a well-developed framework that is often used to help make intentional decisions about an organization’s strategy—this approach applies similar principles in thinking about how to sustain culture across all four workforce personas (figure 2). What is our culture and purpose? To leverage culture as an asset to organizational performance, organizations must first have a clearly articulated culture—one whose norms and values support the advancement of the organization’s purpose and mission. This may seem self-evident, but just 23 percent of the respondents to the 2017 Deloitte Global Human Capital Trends survey believe that their employees are fully aligned with their corporate purpose. This is an alarming disconnect, with research suggesting that purpose misalignment is a major underlying cause of the rampant disengagement facing many organizations today. A strong corporate purpose—however one defines it—can yield dividends, not just for workforce engagement and productivity, but for the brand and company growth as well. Patagonia, the global outdoor clothing manufacturer, cultivates a positive organizational culture by fostering a sense of commitment, shared beliefs, collective focus, and inclusion. For years, the company has been known for its high-end outdoor clothing and bright-colored fleece jackets. Beyond its products, however, the company also emphasizes environmental sustainability. Sometimes known as “the activist company,” Patagonia’s mission statement reads, “Build the best product, cause no unnecessary harm, use business to inspire and implement solutions to the environmental crisis,” and the company infuses this approach into its work environment. Patagonia’s leadership has implemented and reinforced a culture that motivates employees of all types to play an active role in environment sustainability and live by its mission statement. Employees around the world are given opportunities to participate in programs and initiatives that support the environment; the company donates either 1 percent of total sales or 10 percent of pre-tax profits (whichever is greater) to grassroots environmental groups; and the company takes steps to ensure that the materials and processes used to manufacture their products are environmentally friendly. Through activities like these, Patagonia leaders strive to build an emotional attachment to the company’s mission across its employee base. How do we improve cultural fit? As organizations continue to leverage alternative workers more and more, it will become increasingly important to obtain consistent, high-quality work products from this talent segment. To reduce onboarding, training time, and costs, companies may opt to create a consistent group of alternative employees who work regularly with the organization. Workers who are naturally a good fit for an organization’s culture get along well with the other employees, have a positive experience during their time with the organization, and experience the sense of belonging that can fuel discretionary effort. Therefore, an important step is to screen alternative workers, particularly the transactional remote employees—individuals whose employment relationship was long considered purely transactional—for cultural fit before hiring them. Employers can leverage an array of digital technologies, including video interviews, online value assessments, and even peer-rated feedback, to determine fit throughout the hiring process. Particularly in contexts where teaming and collaboration are important, screening contingent workers for fit during the recruiting process is the first line of defense against diluting an organization’s culture. TaskRabbit, an online marketplace that matches freelance labor with demand for minor home repairs, errand running, moving and packing, and more, understands the value of assessing potential workers—or “taskers,” as they call them—for cultural fit. After seeing early missteps by peers in the gig economy who did not accurately screen or ensure quality of work, TaskRabbit started an early process during the recruiting phase to heavily screen all potential taskers. Now, each tasker goes through a vetting process, which includes writing an essay, submitting a video Q&A, passing a background check, and completing an interview. Additionally, each tasker is reviewed by customers who book his or her services via TaskRabbit’s platform. That feedback helps TaskRabbit ensure that its taskers are demonstrating the company’s desired culture. “The marketplace is all about transparency and performance. You have people out there providing your product that aren’t your employees,” says TaskRabbit CEO Stacy Brown-Philpot. “But you still have to put out there what your values are.” Organizations can use a screening process like TaskRabbit’s, not just for their contingent workers, but for their traditional and full-time remote employees as well. How do we create a consistent employee experience among our unique segments? Traditional workers. Physical spaces can certainly be the most expensive to maintain, but they can also be the most effective in helping to shape an organization’s desired culture. Consider how your organization’s space is designed and what that signals to your traditional workers. Leverage the physical space to reinforce a commitment to your purpose. One financial services firm, seeking to create a culture that emphasized a strong commitment to relationships with advisors and employees, sought to redefine the company’s culture by starting with some low-hanging fruit. Initial activities included dedicating a wall to employee pictures, renaming conference rooms, and reconfiguring office spaces. Over time, town halls were moved from a formal meeting space to an open floor space where employees could easily mingle with senior leaders afterward. Senior leader parking spaces were removed to signify that all workers’ efforts were important to the company’s success. Cubicles were reorganized into team pods to encourage cross-functional collaboration. In addition, the company began a quarterly human-centric award that publicly recognized employees who demonstrated the company’s core values. Utilizing the physical space to create intentional employee experiences helped to reshape the company’s culture around its purpose. Tenured remote workers. Make working remotely as simple as possible for this employee segment. Invest in technologies that support digital collaboration and make working and connecting from off-campus easy. As feelings of being excluded from the goings-on can sometimes plague remote workers, take care to include tenured remote workers when scheduling ad hoc meetings where their involvement would be valuable. In addition, consider creating opportunities for these workers to interact in person with other employees—for instance, through annual retreats or local lunches—to encourage trust and team-building. Lastly, this can be an easy group to overlook when it comes to recognition and acknowledgment of milestones. Openly reward and acknowledge tenured remote workers’ efforts using venues such as company-wide town halls or newsletters. For example, the financial firm discussed above relied heavily on tenured remote employees to fulfill its customer service requests. In an effort to extend the culture beyond the organization’s physical walls, leaders highlighted one remote employee’s exceptional customer service through the company-wide newsletter. This relatively small act of recognition went a long way in helping to reduce turnover within this segment of its employee population. Transactional remote workers. Take the time to understand what these workers are hoping to gain from their temporary assignment, and use this understanding of their needs to build their commitment to your company and its culture. In many cases, transactional remote workers are foregoing traditional worker benefits in exchange for greater freedom and flexibility. Don’t micromanage, but rather, acknowledge their ability to be autonomous and make it clear that you support their flexible work arrangements. In addition, because transactional remote workers aren’t around all the time, Daniel Pink, author of Drive, recommends “spending extra time talking about what the goal is, how it connects to the big picture, and why it matters.”27 Understanding their reasons for accepting the assignment and providing greater context for how their work fits into the larger picture can help leaders better transmit their organization’s culture to the transactional remote worker. The outside contractor. Because this segment of the alternative work population works within your campus, their physical presence can be leveraged to communicate culture through means such as inviting them to all-company meetings and encouraging their participation in lunches or after-work activities. A recent Harvard Business Review article also provides this advice when working with the outsider employee segment: “Try to avoid all the subtle status differentiators that can make contractors feel like second-class citizens—for example, the color of their ID badges or access to the corporate gym—and be exceedingly inclusive instead. Invite them to important meetings, bring them into water-cooler conversations, and add them to the team email list.” Stated simply, don’t overlook these employees working right in front of you and err on the side of greater inclusion in communications, meetings, and company-wide events. What capabilities and reinforcing mechanisms do we need to extend our culture? Leaders should identify both the organizational capabilities and the tools and mechanisms required to help reinforce the desired culture through operations (for example, speed, service, delivery, tools). All aspects of operations should support the desired organizational culture. For instance, if leaders want the culture to encourage continuous learning, they can put in place easily accessible training to upskill employees or reinforce key capabilities or skill sets. Additionally, rewards will come into play as a key reinforcing mechanism; after all, the activities you reward are the ones that employees focus on, so use rewards to reinforce the behaviors that are important to your organization. Airbnb, a home-sharing platform through which travelers can rent a room or an entire home, reinforces culture through a variety of mechanisms. In addition to up-front screening mechanisms of potential hosts, the Airbnb application includes questions about hospitality standards and asks for a commitment to core values that hosts have to agree to support. Airbnb reinforces these values in several ways. First, it has a Superhost program to reward hosts who exemplify Airbnb’s culture. These Superhosts, who now number in the tens of thousands, can earn revenue in the five- to six-figure range; the Superhost designation helps to propel their rentals, creating an incentive that hosts strive to attain. Superhosts also receive a literal badge of honor for their profiles. Airbnb evaluates hosts based on nine criteria, from tactical factors around reliability and cleanliness to the host’s experience, communications with guests, and a number of five-star reviews. These evaluations also help align hosts with Airbnb’s values and purpose. Additionally, Airbnb holds host meetups for knowledge-sharing and community buildin31 For example, in fall 2014, it hosted an Airbnb Open, a conference to “inspire hosts and teach them about making guests feel at home.” The conference ended with a day of community service to reinforce core value. Tactics such as these—from “challenges” like the Superhost program to meetups and events—can be used to reinforce cultural norms and reenergize workers around your purpose. What digital technologies or other tools do we need to extend our culture? Digital technologies offer an array of tools that can enable leaders to share up-to-the-minute information, get instant feedback, and analyze data in real time. Leaders can and should leverage these tools not only to drive collaboration and connectivity, but also to understand the employee experience and its evolution. But don’t limit yourself to just the digital tools. Third-party co-working spaces—such as WeWork, Regus, Spaces (which Regus operates), RocketSpace, LiquidSpace, and a host of city-specific others—can be used to create communities and meeting places where virtual workers, whether on or off the balance sheet, can connect live. An influx of large companies are renting these co-working spaces for employees to create connection points and appeal to a different type of worker. Identify your alternative workforce populations with data. Take an inventory to understand where, precisely, your employees lay within these four populations, to understand how much you need to prioritize thinking about a shared culture and where to focus. Utilize data analytics to determine the percentage of workers in each segment as well as forecast future alternative workforce opportunities. Then review your strategies for how these populations may evolve in the future to ensure your strategy for maintaining a consistent culture remains relevant. Utilize the choice cascade to intentionally create a positive culture across workforce segments. Creating consistent cultural experiences requires an intentional strategy for engaging all worker segments. Just as marketers seek to engage customers under a shared brand experience, albeit through different mechanisms, employers likewise can use the choice cascade to create positive worker experiences under a shared employer brand. Empower leaders to create a positive organizational culture. Commit to supporting the organization’s culture across all levels of leadership. Sustaining a positive culture typically requires great commitment and efforts across all levels. Empower leaders and managers to help workers feel valued and part of a larger effort toward making a difference. This can fuel all employees’ sense of meaning and purpose, regardless of employment type. An organization’s culture can help boost its performance—but to deliver its full potential, culture should extend to all types of workers, not just traditional employees. Given the current and anticipated growth in the off-balance-sheet workforce and in the number of individuals working off-campus, leaders should think about how they can include these workers in their efforts to create and sustain a positive organizational culture. Business leaders who are prepared to directly address this imperative will likely have more success in maintaining a culture that enables their strategy. I recently read an article that discussed how large corporations, such as Amazon, are moving back to the traditional workforce and requiring previously remote workers to work in one of their established offices. Although culture was not a listed reason for that, I wonder how much it impacts the behavior of a remote person, thus affecting their overall contribution to the organization. The trend started with IBM asking all of its employees to be physically present at one of six locations. IBM operates in 120 countries and the move resulted in the disruption of thousands of families. Thus, while technology is an enabler for remote working, the converse is not necessarily true. Physical proximity alone cannot ensure a symmetrical and harmonious culture. Similarly, a few organizations have managed to develop hybrid models that try to leverage on the best of the proximate and remote employees. As new technologies such as AI, Robotics, and the Internet of Things render nearly a billion jobs worldwide redundant over the next decade, it is hazardous to guess where all this would lead us, if anywhere. A constructive conversation at this stage may help mitigate some of the road blocks that we are bound to face along the way.
"""Variant on standard library's cmd with extra features. To use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you were using the standard library's cmd, while enjoying the extra features. Searchable command history (commands: "hi", "li", "run") Load commands from file, save to file, edit commands in file Multi-line commands Case-insensitive commands Special-character shortcut commands (beyond cmd's "@" and "!") Settable environment parameters Optional _onchange_{paramname} called when environment parameter changes Parsing commands with `optparse` options (flags) Redirection to file with >, >>; input from file with < Easy transcript-based testing of applications (see example/example.py) Bash-style ``select`` available Note that redirection with > and | will only work if `self.stdout.write()` is used in place of `print`. The standard library's `cmd` module is written to use `self.stdout.write()`, - Catherine Devlin, Jan 03 2008 - catherinedevlin.blogspot.com mercurial repository at http://www.assembla.com/wiki/show/python-cmd2 """ import cmd import re import os import sys import optparse import subprocess import tempfile import doctest import unittest import datetime import urllib import glob import traceback import platform import copy from code import InteractiveConsole, InteractiveInterpreter from optparse import make_option from exabgp.dep import pyparsing __version__ = '0.6.8' if sys.version_info[0] == 2: pyparsing.ParserElement.enablePackrat() """ Packrat is causing Python3 errors that I don't understand. > /usr/local/Cellar/python3/3.2/lib/python3.2/site-packages/pyparsing-1.5.6-py3.2.egg/pyparsing.py(999)scanString() -> nextLoc,tokens = parseFn( instring, preloc, callPreParse=False ) (Pdb) n NameError: global name 'exc' is not defined (Pdb) parseFn <bound method Or._parseCache of {Python style comment ^ C style comment}> Bug report filed: https://sourceforge.net/tracker/?func=detail&atid=617311&aid=3381439&group_id=97203 """ class OptionParser(optparse.OptionParser): def exit(self, status=0, msg=None): self.values._exit = True if msg: print (msg) def print_help(self, *args, **kwargs): try: print (self._func.__doc__) except AttributeError: pass optparse.OptionParser.print_help(self, *args, **kwargs) def error(self, msg): """error(msg : string) Print a usage message incorporating 'msg' to stderr and exit. If you override this in a subclass, it should not return -- it should either exit or raise an exception. """ raise optparse.OptParseError(msg) def remaining_args(oldArgs, newArgList): ''' Preserves the spacing originally in the argument after the removal of options. >>> remaining_args('-f bar bar cow', ['bar', 'cow']) 'bar cow' ''' pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' matchObj = re.search(pattern, oldArgs) return oldArgs[matchObj.start():] def _attr_get_(obj, attr): '''Returns an attribute's value, or None (no error) if undefined. Analagous to .get() for dictionaries. Useful when checking for value of options that may not have been defined on a given method.''' try: return getattr(obj, attr) except AttributeError: return None def _which(editor): try: return subprocess.Popen(['which', editor], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] except OSError: return None optparse.Values.get = _attr_get_ options_defined = [] # used to distinguish --options from SQL-style --comments def options(option_list, arg_desc="arg"): '''Used as a decorator and passed a list of optparse-style options, alters a cmd2 method to populate its ``opts`` argument from its raw text argument. Example: transform def do_something(self, arg): into @options([make_option('-q', '--quick', action="store_true", help="Makes things fast")], "source dest") def do_something(self, arg, opts): if opts.quick: self.fast_button = True ''' if not isinstance(option_list, list): option_list = [option_list] for opt in option_list: options_defined.append(pyparsing.Literal(opt.get_opt_string())) def option_setup(func): optionParser = OptionParser() for opt in option_list: optionParser.add_option(opt) optionParser.set_usage("%s [options] %s" % (func.__name__[3:], arg_desc)) optionParser._func = func def new_func(instance, arg): try: opts, newArgList = optionParser.parse_args(arg.split()) # Must find the remaining args in the original argument list, but # mustn't include the command itself #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command: # newArgList = newArgList[1:] newArgs = remaining_args(arg, newArgList) if isinstance(arg, ParsedString): arg = arg.with_args_replaced(newArgs) else: arg = newArgs except optparse.OptParseError as e: print (e) optionParser.print_help() return if hasattr(opts, '_exit'): return None result = func(instance, arg, opts) return result new_func.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) return new_func return option_setup class PasteBufferError(EnvironmentError): if sys.platform[:3] == 'win': errmsg = """Redirecting to or from paste buffer requires pywin32 to be installed on operating system. Download from http://sourceforge.net/projects/pywin32/""" elif sys.platform[:3] == 'dar': # Use built in pbcopy on Mac OSX pass else: errmsg = """Redirecting to or from paste buffer requires xclip to be installed on operating system. On Debian/Ubuntu, 'sudo apt-get install xclip' will install it.""" def __init__(self): Exception.__init__(self, self.errmsg) pastebufferr = """Redirecting to or from paste buffer requires %s to be installed on operating system. %s""" if subprocess.mswindows: try: import win32clipboard def get_paste_buffer(): win32clipboard.OpenClipboard(0) try: result = win32clipboard.GetClipboardData() except TypeError: result = '' #non-text win32clipboard.CloseClipboard() return result def write_to_paste_buffer(txt): win32clipboard.OpenClipboard(0) win32clipboard.EmptyClipboard() win32clipboard.SetClipboardText(txt) win32clipboard.CloseClipboard() except ImportError: def get_paste_buffer(*args): raise OSError(pastebufferr % ('pywin32', 'Download from http://sourceforge.net/projects/pywin32/')) write_to_paste_buffer = get_paste_buffer elif sys.platform == 'darwin': can_clip = False try: # test for pbcopy - AFAIK, should always be installed on MacOS subprocess.check_call('pbcopy -help', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) can_clip = True except (subprocess.CalledProcessError, OSError, IOError): pass if can_clip: def get_paste_buffer(): pbcopyproc = subprocess.Popen('pbcopy -help', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) return pbcopyproc.stdout.read() def write_to_paste_buffer(txt): pbcopyproc = subprocess.Popen('pbcopy', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) pbcopyproc.communicate(txt.encode()) else: def get_paste_buffer(*args): raise OSError(pastebufferr % ('pbcopy', 'On MacOS X - error should not occur - part of the default installation')) write_to_paste_buffer = get_paste_buffer else: can_clip = False try: subprocess.check_call('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) can_clip = True except AttributeError: # check_call not defined, Python < 2.5 try: teststring = 'Testing for presence of xclip.' xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) xclipproc.stdin.write(teststring) xclipproc.stdin.close() xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) if xclipproc.stdout.read() == teststring: can_clip = True except Exception: # hate a bare Exception call, but exception classes vary too much b/t stdlib versions pass except Exception: pass # something went wrong with xclip and we cannot use it if can_clip: def get_paste_buffer(): xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) return xclipproc.stdout.read() def write_to_paste_buffer(txt): xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) xclipproc.stdin.write(txt.encode()) xclipproc.stdin.close() # but we want it in both the "primary" and "mouse" clipboards xclipproc = subprocess.Popen('xclip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) xclipproc.stdin.write(txt.encode()) xclipproc.stdin.close() else: def get_paste_buffer(*args): raise OSError(pastebufferr % ('xclip', 'On Debian/Ubuntu, install with "sudo apt-get install xclip"')) write_to_paste_buffer = get_paste_buffer pyparsing.ParserElement.setDefaultWhitespaceChars(' \t') class ParsedString(str): def full_parsed_statement(self): new = ParsedString('%s %s' % (self.parsed.command, self.parsed.args)) new.parsed = self.parsed new.parser = self.parser return new def with_args_replaced(self, newargs): new = ParsedString(newargs) new.parsed = self.parsed new.parser = self.parser new.parsed['args'] = newargs new.parsed.statement['args'] = newargs return new class StubbornDict(dict): '''Dictionary that tolerates many input formats. Create it with stubbornDict(arg) factory function. >>> d = StubbornDict(large='gross', small='klein') >>> sorted(d.items()) [('large', 'gross'), ('small', 'klein')] >>> d.append(['plain', ' plaid']) >>> sorted(d.items()) [('large', 'gross'), ('plaid', ''), ('plain', ''), ('small', 'klein')] >>> d += ' girl Frauelein, Maedchen\\n\\n shoe schuh' >>> sorted(d.items()) [('girl', 'Frauelein, Maedchen'), ('large', 'gross'), ('plaid', ''), ('plain', ''), ('shoe', 'schuh'), ('small', 'klein')] ''' def update(self, arg): dict.update(self, StubbornDict.to_dict(arg)) append = update def __iadd__(self, arg): self.update(arg) return self def __add__(self, arg): selfcopy = copy.copy(self) selfcopy.update(stubbornDict(arg)) return selfcopy def __radd__(self, arg): selfcopy = copy.copy(self) selfcopy.update(stubbornDict(arg)) return selfcopy @classmethod def to_dict(cls, arg): 'Generates dictionary from string or list of strings' if hasattr(arg, 'splitlines'): arg = arg.splitlines() if hasattr(arg, '__reversed__'): result = {} for a in arg: a = a.strip() if a: key_val = a.split(None, 1) key = key_val[0] if len(key_val) > 1: val = key_val[1] else: val = '' result[key] = val else: result = arg return result def stubbornDict(*arg, **kwarg): ''' >>> sorted(stubbornDict('cow a bovine\\nhorse an equine').items()) [('cow', 'a bovine'), ('horse', 'an equine')] >>> sorted(stubbornDict(['badger', 'porcupine a poky creature']).items()) [('badger', ''), ('porcupine', 'a poky creature')] >>> sorted(stubbornDict(turtle='has shell', frog='jumpy').items()) [('frog', 'jumpy'), ('turtle', 'has shell')] ''' result = {} for a in arg: result.update(StubbornDict.to_dict(a)) result.update(kwarg) return StubbornDict(result) def replace_with_file_contents(fname): if fname: try: result = open(os.path.expanduser(fname[0])).read() except IOError: result = '< %s' % fname[0] # wasn't a file after all else: result = get_paste_buffer() return result class EmbeddedConsoleExit(SystemExit): pass class EmptyStatement(Exception): pass def ljust(x, width, fillchar=' '): 'analogous to str.ljust, but works for lists' if hasattr(x, 'ljust'): return x.ljust(width, fillchar) else: if len(x) < width: x = (x + [fillchar] * width)[:width] return x class Cmd(cmd.Cmd): echo = False case_insensitive = True # Commands recognized regardless of case continuation_prompt = '> ' timing = False # Prints elapsed time for each command # make sure your terminators are not in legalChars! legalChars = u'!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit shortcuts = {'?': 'help', '!': 'shell', '@': 'load', '@@': '_relative_load'} excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() default_to_shell = False noSpecialParse = 'set ed edit exit'.split() defaultExtension = 'txt' # For ``save``, ``load``, etc. default_file_name = 'command.txt' # For ``save``, ``load``, etc. abbrev = True # Abbreviated commands recognized current_script_dir = None reserved_words = [] feedback_to_output = False # Do include nonessentials in >, | output quiet = False # Do not suppress nonessential output debug = False locals_in_py = True kept_state = None redirector = '>' # for sending output to file settable = stubbornDict(''' prompt colors Colorized output (*nix only) continuation_prompt On 2nd+ line of input debug Show full error stack on error default_file_name for ``save``, ``load``, etc. editor Program used by ``edit`` case_insensitive upper- and lower-case both OK feedback_to_output include nonessentials in `|`, `>` results quiet Don't print nonessential feedback echo Echo command issued into output timing Report execution times abbrev Accept abbreviated commands ''') def poutput(self, msg): '''Convenient shortcut for self.stdout.write(); adds newline if necessary.''' if msg: self.stdout.write(msg) if msg[-1] != '\n': self.stdout.write('\n') def perror(self, errmsg, statement=None): if self.debug: traceback.print_exc() print (str(errmsg)) def pfeedback(self, msg): """For printing nonessential feedback. Can be silenced with `quiet`. Inclusion in redirected output is controlled by `feedback_to_output`.""" if not self.quiet: if self.feedback_to_output: self.poutput(msg) else: print (msg) _STOP_AND_EXIT = True # distinguish end of script file from actual exit _STOP_SCRIPT_NO_EXIT = -999 editor = os.environ.get('EDITOR') if not editor: if sys.platform[:3] == 'win': editor = 'notepad' else: for editor in ['gedit', 'kate', 'vim', 'vi', 'emacs', 'nano', 'pico']: if _which(editor): break colorcodes = {'bold':{True:'\x1b[1m',False:'\x1b[22m'}, 'cyan':{True:'\x1b[36m',False:'\x1b[39m'}, 'blue':{True:'\x1b[34m',False:'\x1b[39m'}, 'red':{True:'\x1b[31m',False:'\x1b[39m'}, 'magenta':{True:'\x1b[35m',False:'\x1b[39m'}, 'green':{True:'\x1b[32m',False:'\x1b[39m'}, 'underline':{True:'\x1b[4m',False:'\x1b[24m'}} colors = (platform.system() != 'Windows') def colorize(self, val, color): '''Given a string (``val``), returns that string wrapped in UNIX-style special characters that turn on (and then off) text color and style. If the ``colors`` environment paramter is ``False``, or the application is running on Windows, will return ``val`` unchanged. ``color`` should be one of the supported strings (or styles): red/blue/green/cyan/magenta, bold, underline''' if self.colors and (self.stdout == self.initial_stdout): return self.colorcodes[color][True] + val + self.colorcodes[color][False] return val def do_cmdenvironment(self, args): '''Summary report of interactive parameters.''' self.stdout.write(""" Commands are %(casesensitive)scase-sensitive. Commands may be terminated with: %(terminators)s Settable parameters: %(settable)s\n""" % \ { 'casesensitive': (self.case_insensitive and 'not ') or '', 'terminators': str(self.terminators), 'settable': ' '.join(self.settable) }) def do_help(self, arg): if arg: funcname = self.func_named(arg) if funcname: fn = getattr(self, funcname) try: fn.optionParser.print_help(file=self.stdout) except AttributeError: cmd.Cmd.do_help(self, funcname[3:]) else: cmd.Cmd.do_help(self, arg) def __init__(self, *args, **kwargs): cmd.Cmd.__init__(self, *args, **kwargs) self.initial_stdout = sys.stdout self.history = History() self.pystate = {} self.shortcuts = sorted(self.shortcuts.items(), reverse=True) self.keywords = self.reserved_words + [fname[3:] for fname in dir(self) if fname.startswith('do_')] self._init_parser() def do_shortcuts(self, args): """Lists single-key shortcuts available.""" result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) prefixParser = pyparsing.Empty() commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment]) commentGrammars.addParseAction(lambda x: '') commentInProgress = pyparsing.Literal('/*') + pyparsing.SkipTo( pyparsing.stringEnd ^ '*/') terminators = [';'] blankLinesAllowed = False multilineCommands = [] def _init_parser(self): r''' >>> c = Cmd() >>> c.multilineCommands = ['multiline'] >>> c.case_insensitive = True >>> c._init_parser() >>> print (c.parser.parseString('').dump()) [] >>> print (c.parser.parseString('').dump()) [] >>> print (c.parser.parseString('/* empty command */').dump()) [] >>> print (c.parser.parseString('plainword').dump()) ['plainword', ''] - command: plainword - statement: ['plainword', ''] - command: plainword >>> print (c.parser.parseString('termbare;').dump()) ['termbare', '', ';', ''] - command: termbare - statement: ['termbare', '', ';'] - command: termbare - terminator: ; - terminator: ; >>> print (c.parser.parseString('termbare; suffx').dump()) ['termbare', '', ';', 'suffx'] - command: termbare - statement: ['termbare', '', ';'] - command: termbare - terminator: ; - suffix: suffx - terminator: ; >>> print (c.parser.parseString('barecommand').dump()) ['barecommand', ''] - command: barecommand - statement: ['barecommand', ''] - command: barecommand >>> print (c.parser.parseString('COMmand with args').dump()) ['command', 'with args'] - args: with args - command: command - statement: ['command', 'with args'] - args: with args - command: command >>> print (c.parser.parseString('command with args and terminator; and suffix').dump()) ['command', 'with args and terminator', ';', 'and suffix'] - args: with args and terminator - command: command - statement: ['command', 'with args and terminator', ';'] - args: with args and terminator - command: command - terminator: ; - suffix: and suffix - terminator: ; >>> print (c.parser.parseString('simple | piped').dump()) ['simple', '', '|', ' piped'] - command: simple - pipeTo: piped - statement: ['simple', ''] - command: simple >>> print (c.parser.parseString('double-pipe || is not a pipe').dump()) ['double', '-pipe || is not a pipe'] - args: -pipe || is not a pipe - command: double - statement: ['double', '-pipe || is not a pipe'] - args: -pipe || is not a pipe - command: double >>> print (c.parser.parseString('command with args, terminator;sufx | piped').dump()) ['command', 'with args, terminator', ';', 'sufx', '|', ' piped'] - args: with args, terminator - command: command - pipeTo: piped - statement: ['command', 'with args, terminator', ';'] - args: with args, terminator - command: command - terminator: ; - suffix: sufx - terminator: ; >>> print (c.parser.parseString('output into > afile.txt').dump()) ['output', 'into', '>', 'afile.txt'] - args: into - command: output - output: > - outputTo: afile.txt - statement: ['output', 'into'] - args: into - command: output >>> print (c.parser.parseString('output into;sufx | pipethrume plz > afile.txt').dump()) ['output', 'into', ';', 'sufx', '|', ' pipethrume plz', '>', 'afile.txt'] - args: into - command: output - output: > - outputTo: afile.txt - pipeTo: pipethrume plz - statement: ['output', 'into', ';'] - args: into - command: output - terminator: ; - suffix: sufx - terminator: ; >>> print (c.parser.parseString('output to paste buffer >> ').dump()) ['output', 'to paste buffer', '>>', ''] - args: to paste buffer - command: output - output: >> - statement: ['output', 'to paste buffer'] - args: to paste buffer - command: output >>> print (c.parser.parseString('ignore the /* commented | > */ stuff;').dump()) ['ignore', 'the /* commented | > */ stuff', ';', ''] - args: the /* commented | > */ stuff - command: ignore - statement: ['ignore', 'the /* commented | > */ stuff', ';'] - args: the /* commented | > */ stuff - command: ignore - terminator: ; - terminator: ; >>> print (c.parser.parseString('has > inside;').dump()) ['has', '> inside', ';', ''] - args: > inside - command: has - statement: ['has', '> inside', ';'] - args: > inside - command: has - terminator: ; - terminator: ; >>> print (c.parser.parseString('multiline has > inside an unfinished command').dump()) ['multiline', ' has > inside an unfinished command'] - multilineCommand: multiline >>> print (c.parser.parseString('multiline has > inside;').dump()) ['multiline', 'has > inside', ';', ''] - args: has > inside - multilineCommand: multiline - statement: ['multiline', 'has > inside', ';'] - args: has > inside - multilineCommand: multiline - terminator: ; - terminator: ; >>> print (c.parser.parseString('multiline command /* with comment in progress;').dump()) ['multiline', ' command /* with comment in progress;'] - multilineCommand: multiline >>> print (c.parser.parseString('multiline command /* with comment complete */ is done;').dump()) ['multiline', 'command /* with comment complete */ is done', ';', ''] - args: command /* with comment complete */ is done - multilineCommand: multiline - statement: ['multiline', 'command /* with comment complete */ is done', ';'] - args: command /* with comment complete */ is done - multilineCommand: multiline - terminator: ; - terminator: ; >>> print (c.parser.parseString('multiline command ends\n\n').dump()) ['multiline', 'command ends', '\n', '\n'] - args: command ends - multilineCommand: multiline - statement: ['multiline', 'command ends', '\n', '\n'] - args: command ends - multilineCommand: multiline - terminator: ['\n', '\n'] - terminator: ['\n', '\n'] >>> print (c.parser.parseString('multiline command "with term; ends" now\n\n').dump()) ['multiline', 'command "with term; ends" now', '\n', '\n'] - args: command "with term; ends" now - multilineCommand: multiline - statement: ['multiline', 'command "with term; ends" now', '\n', '\n'] - args: command "with term; ends" now - multilineCommand: multiline - terminator: ['\n', '\n'] - terminator: ['\n', '\n'] >>> print (c.parser.parseString('what if "quoted strings /* seem to " start comments?').dump()) ['what', 'if "quoted strings /* seem to " start comments?'] - args: if "quoted strings /* seem to " start comments? - command: what - statement: ['what', 'if "quoted strings /* seem to " start comments?'] - args: if "quoted strings /* seem to " start comments? - command: what ''' #outputParser = (pyparsing.Literal('>>') | (pyparsing.WordStart() + '>') | pyparsing.Regex('[^=]>'))('output') outputParser = (pyparsing.Literal(self.redirector *2) | \ (pyparsing.WordStart() + self.redirector) | \ pyparsing.Regex('[^=]' + self.redirector))('output') terminatorParser = pyparsing.Or([(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in self.terminators])('terminator') stringEnd = pyparsing.stringEnd ^ '\nEOF' self.multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.case_insensitive) for c in self.multilineCommands])('multilineCommand') oneLineCommand = (~self.multilineCommand + pyparsing.Word(self.legalChars))('command') pipe = pyparsing.Keyword('|', identChars='|') self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '') doNotParse = self.commentGrammars | self.commentInProgress | pyparsing.quotedString afterElements = \ pyparsing.Optional(pipe + pyparsing.SkipTo(outputParser ^ stringEnd, ignore=doNotParse)('pipeTo')) + \ pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd, ignore=doNotParse).setParseAction(lambda x: x[0].strip())('outputTo')) if self.case_insensitive: self.multilineCommand.setParseAction(lambda x: x[0].lower()) oneLineCommand.setParseAction(lambda x: x[0].lower()) if self.blankLinesAllowed: self.blankLineTerminationParser = pyparsing.NoMatch else: self.blankLineTerminator = (pyparsing.lineEnd + pyparsing.lineEnd)('terminator') self.blankLineTerminator.setResultsName('terminator') self.blankLineTerminationParser = ((self.multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(self.blankLineTerminator, ignore=doNotParse).setParseAction(lambda x: x[0].strip())('args') + self.blankLineTerminator)('statement') self.multilineParser = (((self.multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(terminatorParser, ignore=doNotParse).setParseAction(lambda x: x[0].strip())('args') + terminatorParser)('statement') + pyparsing.SkipTo(outputParser ^ pipe ^ stringEnd, ignore=doNotParse).setParseAction(lambda x: x[0].strip())('suffix') + afterElements) self.multilineParser.ignore(self.commentInProgress) self.singleLineParser = ((oneLineCommand + pyparsing.SkipTo(terminatorParser ^ stringEnd ^ pipe ^ outputParser, ignore=doNotParse).setParseAction(lambda x:x[0].strip())('args'))('statement') + pyparsing.Optional(terminatorParser) + afterElements) #self.multilineParser = self.multilineParser.setResultsName('multilineParser') #self.singleLineParser = self.singleLineParser.setResultsName('singleLineParser') self.blankLineTerminationParser = self.blankLineTerminationParser.setResultsName('statement') self.parser = self.prefixParser + ( stringEnd | self.multilineParser | self.singleLineParser | self.blankLineTerminationParser | self.multilineCommand + pyparsing.SkipTo(stringEnd, ignore=doNotParse) ) self.parser.ignore(self.commentGrammars) inputMark = pyparsing.Literal('<') inputMark.setParseAction(lambda x: '') fileName = pyparsing.Word(self.legalChars + '/\\') inputFrom = fileName('inputFrom') inputFrom.setParseAction(replace_with_file_contents) # a not-entirely-satisfactory way of distinguishing < as in "import from" from < # as in "lesser than" self.inputParser = inputMark + pyparsing.Optional(inputFrom) + pyparsing.Optional('>') + \ pyparsing.Optional(fileName) + (pyparsing.stringEnd | '|') self.inputParser.ignore(self.commentInProgress) def preparse(self, raw, **kwargs): return raw def postparse(self, parseResult): return parseResult def parsed(self, raw, **kwargs): if isinstance(raw, ParsedString): p = raw else: # preparse is an overridable hook; default makes no changes s = self.preparse(raw, **kwargs) s = self.inputParser.transformString(s.lstrip()) s = self.commentGrammars.transformString(s) for (shortcut, expansion) in self.shortcuts: if s.lower().startswith(shortcut): s = s.replace(shortcut, expansion + ' ', 1) break result = self.parser.parseString(s) result['raw'] = raw result['command'] = result.multilineCommand or result.command result = self.postparse(result) p = ParsedString(result.args) p.parsed = result p.parser = self.parsed for (key, val) in kwargs.items(): p.parsed[key] = val return p def postparsing_precmd(self, statement): stop = 0 return stop, statement def postparsing_postcmd(self, stop): return stop def func_named(self, arg): result = None target = 'do_' + arg if target in dir(self): result = target else: if self.abbrev: # accept shortened versions of commands funcs = [fname for fname in self.keywords if fname.startswith(arg)] if len(funcs) == 1: result = 'do_' + funcs[0] return result def onecmd_plus_hooks(self, line): # The outermost level of try/finally nesting can be condensed once # Python 2.4 support can be dropped. stop = 0 try: try: statement = self.complete_statement(line) (stop, statement) = self.postparsing_precmd(statement) if stop: return self.postparsing_postcmd(stop) if statement.parsed.command not in self.excludeFromHistory: self.history.append(statement.parsed.raw) try: self.redirect_output(statement) timestart = datetime.datetime.now() statement = self.precmd(statement) stop = self.onecmd(statement) stop = self.postcmd(stop, statement) if self.timing: self.pfeedback('Elapsed: %s' % str(datetime.datetime.now() - timestart)) finally: self.restore_output(statement) except EmptyStatement: return 0 except Exception as e: self.perror(str(e), statement) finally: return self.postparsing_postcmd(stop) def complete_statement(self, line): """Keep accepting lines of input until the command is complete.""" if (not line) or ( not pyparsing.Or(self.commentGrammars). setParseAction(lambda x: '').transformString(line)): raise EmptyStatement() statement = self.parsed(line) while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): statement = '%s\n%s' % (statement.parsed.raw, self.pseudo_raw_input(self.continuation_prompt)) statement = self.parsed(statement) if not statement.parsed.command: raise EmptyStatement() return statement def redirect_output(self, statement): if statement.parsed.pipeTo: self.kept_state = Statekeeper(self, ('stdout',)) self.kept_sys = Statekeeper(sys, ('stdout',)) self.redirect = subprocess.Popen(statement.parsed.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) sys.stdout = self.stdout = self.redirect.stdin elif statement.parsed.output: if (not statement.parsed.outputTo) and (not can_clip): raise EnvironmentError('Cannot redirect to paste buffer; install ``xclip`` and re-run to enable') self.kept_state = Statekeeper(self, ('stdout',)) self.kept_sys = Statekeeper(sys, ('stdout',)) if statement.parsed.outputTo: mode = 'w' if statement.parsed.output == 2 * self.redirector: mode = 'a' sys.stdout = self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode) else: sys.stdout = self.stdout = tempfile.TemporaryFile(mode="w+") if statement.parsed.output == '>>': self.stdout.write(get_paste_buffer()) def restore_output(self, statement): if self.kept_state: if statement.parsed.output: if not statement.parsed.outputTo: self.stdout.seek(0) write_to_paste_buffer(self.stdout.read()) elif statement.parsed.pipeTo: for result in self.redirect.communicate(): self.kept_state.stdout.write(result or '') self.stdout.close() self.kept_state.restore() self.kept_sys.restore() self.kept_state = None def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. This may be overridden, but should not normally need to be; see the precmd() and postcmd() methods for useful execution hooks. The return value is a flag indicating whether interpretation of commands by the interpreter should stop. This (`cmd2`) version of `onecmd` already override's `cmd`'s `onecmd`. """ statement = self.parsed(line) self.lastcmd = statement.parsed.raw funcname = self.func_named(statement.parsed.command) if not funcname: return self._default(statement) try: func = getattr(self, funcname) except AttributeError: return self._default(statement) stop = func(statement) return stop def _default(self, statement): arg = statement.full_parsed_statement() if self.default_to_shell: result = os.system(arg) if not result: return self.postparsing_postcmd(None) return self.postparsing_postcmd(self.default(arg)) def pseudo_raw_input(self, prompt): """copied from cmd's cmdloop; like raw_input, but accounts for changed stdin, stdout""" if self.use_rawinput: try: line = raw_input(prompt) except EOFError: line = 'EOF' else: self.stdout.write(prompt) self.stdout.flush() line = self.stdin.readline() if not len(line): line = 'EOF' else: if line[-1] == '\n': # this was always true in Cmd line = line[:-1] return line def _cmdloop(self, intro=None): """Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument. """ # An almost perfect copy from Cmd; however, the pseudo_raw_input portion # has been split out so that it can be called separately self.preloop() if self.use_rawinput and self.completekey: try: import readline self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") except ImportError: pass try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro)+"\n") stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: line = self.pseudo_raw_input(self.prompt) if (self.echo) and (isinstance(self.stdin, file)): self.stdout.write(line + '\n') stop = self.onecmd_plus_hooks(line) self.postloop() finally: if self.use_rawinput and self.completekey: try: import readline readline.set_completer(self.old_completer) except ImportError: pass return stop def do_EOF(self, arg): return self._STOP_SCRIPT_NO_EXIT # End of script; should not exit app do_eof = do_EOF def do_quit(self, arg): return self._STOP_AND_EXIT do_exit = do_quit do_q = do_quit def select(self, options, prompt='Your choice? '): '''Presents a numbered menu to the user. Modelled after the bash shell's SELECT. Returns the item chosen. Argument ``options`` can be: | a single string -> will be split into one-word options | a list of strings -> will be offered as options | a list of tuples -> interpreted as (value, text), so that the return value can differ from the text advertised to the user ''' if isinstance(options, basestring): options = zip(options.split(), options.split()) fulloptions = [] for opt in options: if isinstance(opt, basestring): fulloptions.append((opt, opt)) else: try: fulloptions.append((opt[0], opt[1])) except IndexError: fulloptions.append((opt[0], opt[0])) for (idx, (value, text)) in enumerate(fulloptions): self.poutput(' %2d. %s\n' % (idx+1, text)) while True: response = raw_input(prompt) try: response = int(response) result = fulloptions[response - 1][0] break except ValueError: pass # loop and ask again return result @options([make_option('-l', '--long', action="store_true", help="describe function of parameter")]) def do_show(self, arg, opts): '''Shows value of a parameter.''' param = arg.strip().lower() result = {} maxlen = 0 for p in self.settable: if (not param) or p.startswith(param): result[p] = '%s: %s' % (p, str(getattr(self, p))) maxlen = max(maxlen, len(result[p])) if result: for p in sorted(result): if opts.long: self.poutput('%s # %s' % (result[p].ljust(maxlen), self.settable[p])) else: self.poutput(result[p]) else: raise NotImplementedError("Parameter '%s' not supported (type 'show' for list of parameters)." % param) def do_set(self, arg): ''' Sets a cmd2 parameter. Accepts abbreviated parameter names so long as there is no ambiguity. Call without arguments for a list of settable parameters with their values.''' try: statement, paramName, val = arg.parsed.raw.split(None, 2) val = val.strip() paramName = paramName.strip().lower() if paramName not in self.settable: hits = [p for p in self.settable if p.startswith(paramName)] if len(hits) == 1: paramName = hits[0] else: return self.do_show(paramName) currentVal = getattr(self, paramName) if (val[0] == val[-1]) and val[0] in ("'", '"'): val = val[1:-1] else: val = cast(currentVal, val) setattr(self, paramName, val) self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val)) if currentVal != val: try: onchange_hook = getattr(self, '_onchange_%s' % paramName) onchange_hook(old=currentVal, new=val) except AttributeError: pass except (ValueError, AttributeError, NotSettableError) as e: self.do_show(arg) def do_pause(self, arg): 'Displays the specified text then waits for the user to press RETURN.' raw_input(arg + '\n') def do_shell(self, arg): 'execute a command as if at the OS prompt.' os.system(arg) def do_py(self, arg): ''' py <command>: Executes a Python command. py: Enters interactive Python mode. End with ``Ctrl-D`` (Unix) / ``Ctrl-Z`` (Windows), ``quit()``, '`exit()``. Non-python commands can be issued with ``cmd("your command")``. Run python code from external files with ``run("filename.py")`` ''' self.pystate['self'] = self arg = arg.parsed.raw[2:].strip() localvars = (self.locals_in_py and self.pystate) or {} interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') if arg.strip(): interp.runcode(arg) else: def quit(): raise EmbeddedConsoleExit def onecmd_plus_hooks(arg): return self.onecmd_plus_hooks(arg + '\n') def run(arg): try: file = open(arg) interp.runcode(file.read()) file.close() except IOError as e: self.perror(e) self.pystate['quit'] = quit self.pystate['exit'] = quit self.pystate['cmd'] = onecmd_plus_hooks self.pystate['run'] = run try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' keepstate = Statekeeper(sys, ('stdin','stdout')) sys.stdout = self.stdout sys.stdin = self.stdin interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" % (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) except EmbeddedConsoleExit: pass keepstate.restore() @options([make_option('-s', '--script', action="store_true", help="Script format; no separation lines"), ], arg_desc = '(limit on which commands to include)') def do_history(self, arg, opts): """history [arg]: lists past commands issued | no arg: list all | arg is integer: list one history item, by index | arg is string: string search | arg is /enclosed in forward-slashes/: regular expression search """ if arg: history = self.history.get(arg) else: history = self.history for hi in history: if opts.script: self.poutput(hi) else: self.stdout.write(hi.pr()) def last_matching(self, arg): try: if arg: return self.history.get(arg)[-1] else: return self.history[-1] except IndexError: return None def do_list(self, arg): """list [arg]: lists last command issued no arg -> list most recent command arg is integer -> list one history item, by index a..b, a:b, a:, ..b -> list spans from a (or start) to b (or end) arg is string -> list all commands matching string search arg is /enclosed in forward-slashes/ -> regular expression search """ try: history = self.history.span(arg or '-1') except IndexError: history = self.history.search(arg) for hi in history: self.poutput(hi.pr()) do_hi = do_history do_l = do_list do_li = do_list def do_ed(self, arg): """ed: edit most recent command in text editor ed [N]: edit numbered command from history ed [filename]: edit specified file name commands are run after editor is closed. "set edit (program-name)" or set EDITOR environment variable to control which editing program is used.""" if not self.editor: raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.") filename = self.default_file_name if arg: try: buffer = self.last_matching(int(arg)) except ValueError: filename = arg buffer = '' else: buffer = self.history[-1] if buffer: f = open(os.path.expanduser(filename), 'w') f.write(buffer or '') f.close() os.system('%s %s' % (self.editor, filename)) self.do__load(filename) do_edit = do_ed saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") + pyparsing.Optional(pyparsing.Word(legalChars + '/\\'))("fname") + pyparsing.stringEnd) def do_save(self, arg): """`save [N] [filename.ext]` Saves command from history to file. | N => Number of command (from history), or `*`; | most recent command if omitted""" try: args = self.saveparser.parseString(arg) except pyparsing.ParseException: self.perror('Could not understand save target %s' % arg) raise SyntaxError(self.do_save.__doc__) fname = args.fname or self.default_file_name if args.idx == '*': saveme = '\n\n'.join(self.history[:]) elif args.idx: saveme = self.history[int(args.idx)-1] else: saveme = self.history[-1] try: f = open(os.path.expanduser(fname), 'w') f.write(saveme) f.close() self.pfeedback('Saved to %s' % (fname)) except Exception as e: self.perror('Error saving %s' % (fname)) raise def read_file_or_url(self, fname): # TODO: not working on localhost if isinstance(fname, file): result = open(fname, 'r') else: match = self.urlre.match(fname) if match: result = urllib.urlopen(match.group(1)) else: fname = os.path.expanduser(fname) try: result = open(os.path.expanduser(fname), 'r') except IOError: result = open('%s.%s' % (os.path.expanduser(fname), self.defaultExtension), 'r') return result def do__relative_load(self, arg=None): ''' Runs commands in script at file or URL; if this is called from within an already-running script, the filename will be interpreted relative to the already-running script's directory.''' if arg: arg = arg.split(None, 1) targetname, args = arg[0], (arg[1:] or [''])[0] targetname = os.path.join(self.current_script_dir or '', targetname) self.do__load('%s %s' % (targetname, args)) urlre = re.compile('(https?://[-\\w\\./]+)') def do_load(self, arg=None): """Runs script of command(s) from a file or URL.""" if arg is None: targetname = self.default_file_name else: arg = arg.split(None, 1) targetname, args = arg[0], (arg[1:] or [''])[0].strip() try: target = self.read_file_or_url(targetname) except IOError as e: self.perror('Problem accessing script from %s: \n%s' % (targetname, e)) return keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt', 'continuation_prompt','current_script_dir')) self.stdin = target self.use_rawinput = False self.prompt = self.continuation_prompt = '' self.current_script_dir = os.path.split(targetname)[0] stop = self._cmdloop() self.stdin.close() keepstate.restore() self.lastcmd = '' return stop and (stop != self._STOP_SCRIPT_NO_EXIT) do__load = do_load # avoid an unfortunate legacy use of do_load from sqlpython def do_run(self, arg): """run [arg]: re-runs an earlier command no arg -> run most recent command arg is integer -> run one history item, by index arg is string -> run most recent command by string search arg is /enclosed in forward-slashes/ -> run most recent by regex """ 'run [N]: runs the SQL that was run N commands ago' runme = self.last_matching(arg) self.pfeedback(runme) if runme: stop = self.onecmd_plus_hooks(runme) do_r = do_run def fileimport(self, statement, source): try: f = open(os.path.expanduser(source)) except IOError: self.stdout.write("Couldn't read from file %s\n" % source) return '' data = f.read() f.close() return data def runTranscriptTests(self, callargs): class TestMyAppCase(Cmd2TestCase): CmdApp = self.__class__ self.__class__.testfiles = callargs sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main() testcase = TestMyAppCase() runner = unittest.TextTestRunner() result = runner.run(testcase) result.printErrors() def run_commands_at_invocation(self, callargs): for initial_command in callargs: if self.onecmd_plus_hooks(initial_command + '\n'): return self._STOP_AND_EXIT def cmdloop(self): parser = optparse.OptionParser() parser.add_option('-t', '--test', dest='test', action="store_true", help='Test against transcript(s) in FILE (wildcards OK)') (callopts, callargs) = parser.parse_args() if callopts.test: self.runTranscriptTests(callargs) else: if not self.run_commands_at_invocation(callargs): self._cmdloop() class HistoryItem(str): listformat = '-------------------------[%d]\n%s\n' def __init__(self, instr): str.__init__(self) self.lowercase = self.lower() self.idx = None def pr(self): return self.listformat % (self.idx, str(self)) class History(list): '''A list of HistoryItems that knows how to respond to user requests. >>> h = History([HistoryItem('first'), HistoryItem('second'), HistoryItem('third'), HistoryItem('fourth')]) >>> h.span('-2..') ['third', 'fourth'] >>> h.span('2..3') ['second', 'third'] >>> h.span('3') ['third'] >>> h.span(':') ['first', 'second', 'third', 'fourth'] >>> h.span('2..') ['second', 'third', 'fourth'] >>> h.span('-1') ['fourth'] >>> h.span('-2..-3') ['third', 'second'] >>> h.search('o') ['second', 'fourth'] >>> h.search('/IR/') ['first', 'third'] ''' def zero_based_index(self, onebased): result = onebased if result > 0: result -= 1 return result def to_index(self, raw): if raw: result = self.zero_based_index(int(raw)) else: result = None return result def search(self, target): target = target.strip() if target[0] == target[-1] == '/' and len(target) > 1: target = target[1:-1] else: target = re.escape(target) pattern = re.compile(target, re.IGNORECASE) return [s for s in self if pattern.search(s)] spanpattern = re.compile(r'^\s*(?P<start>\-?\d+)?\s*(?P<separator>:|(\.{2,}))?\s*(?P<end>\-?\d+)?\s*$') def span(self, raw): if raw.lower() in ('*', '-', 'all'): raw = ':' results = self.spanpattern.search(raw) if not results: raise IndexError if not results.group('separator'): return [self[self.to_index(results.group('start'))]] start = self.to_index(results.group('start')) end = self.to_index(results.group('end')) reverse = False if end is not None: if end < start: (start, end) = (end, start) reverse = True end += 1 result = self[start:end] if reverse: result.reverse() return result rangePattern = re.compile(r'^\s*(?P<start>[\d]+)?\s*\-\s*(?P<end>[\d]+)?\s*$') def append(self, new): new = HistoryItem(new) list.append(self, new) new.idx = len(self) def extend(self, new): for n in new: self.append(n) def get(self, getme=None, fromEnd=False): if not getme: return self try: getme = int(getme) if getme < 0: return self[:(-1 * getme)] else: return [self[getme-1]] except IndexError: return [] except ValueError: rangeResult = self.rangePattern.search(getme) if rangeResult: start = rangeResult.group('start') or None end = rangeResult.group('start') or None if start: start = int(start) - 1 if end: end = int(end) return self[start:end] getme = getme.strip() if getme.startswith(r'/') and getme.endswith(r'/'): finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE) def isin(hi): return finder.search(hi) else: def isin(hi): return (getme.lower() in hi.lowercase) return [itm for itm in self if isin(itm)] class NotSettableError(Exception): pass def cast(current, new): """Tries to force a new value into the same type as the current.""" typ = type(current) if typ == bool: try: return bool(int(new)) except (ValueError, TypeError): pass try: new = new.lower() except Exception: pass if (new=='on') or (new[0] in ('y','t')): return True if (new=='off') or (new[0] in ('n','f')): return False else: try: return typ(new) except Exception: pass print ("Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)) return current class Statekeeper(object): def __init__(self, obj, attribs): self.obj = obj self.attribs = attribs if self.obj: self.save() def save(self): for attrib in self.attribs: setattr(self, attrib, getattr(self.obj, attrib)) def restore(self): if self.obj: for attrib in self.attribs: setattr(self.obj, attrib, getattr(self, attrib)) class Borg(object): '''All instances of any Borg subclass will share state. from Python Cookbook, 2nd Ed., recipe 6.16''' _shared_state = {} def __new__(cls, *a, **k): obj = object.__new__(cls, *a, **k) obj.__dict__ = cls._shared_state return obj class OutputTrap(Borg): '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing. Call `tearDown()` to return to normal output.''' def __init__(self): self.contents = '' self.old_stdout = sys.stdout sys.stdout = self def write(self, txt): self.contents += txt def read(self): result = self.contents self.contents = '' return result def tearDown(self): sys.stdout = self.old_stdout self.contents = '' class Cmd2TestCase(unittest.TestCase): '''Subclass this, setting CmdApp, to make a unittest.TestCase class that will execute the commands in a transcript file and expect the results shown. See example.py''' CmdApp = None def fetchTranscripts(self): self.transcripts = {} for fileset in self.CmdApp.testfiles: for fname in glob.glob(fileset): tfile = open(fname) self.transcripts[fname] = iter(tfile.readlines()) tfile.close() if not len(self.transcripts): raise StandardError("No test files found - nothing to test.") def setUp(self): if self.CmdApp: self.outputTrap = OutputTrap() self.cmdapp = self.CmdApp() self.fetchTranscripts() def runTest(self): # was testall if self.CmdApp: its = sorted(self.transcripts.items()) for (fname, transcript) in its: self._test_transcript(fname, transcript) regexPattern = pyparsing.QuotedString(quoteChar=r'/', escChar='\\', multiline=True, unquoteResults=True) regexPattern.ignore(pyparsing.cStyleComment) notRegexPattern = pyparsing.Word(pyparsing.printables) notRegexPattern.setParseAction(lambda t: re.escape(t[0])) expectationParser = regexPattern | notRegexPattern anyWhitespace = re.compile(r'\s', re.DOTALL | re.MULTILINE) def _test_transcript(self, fname, transcript): lineNum = 0 finished = False line = transcript.next() lineNum += 1 tests_run = 0 while not finished: # Scroll forward to where actual commands begin while not line.startswith(self.cmdapp.prompt): try: line = transcript.next() except StopIteration: finished = True break lineNum += 1 command = [line[len(self.cmdapp.prompt):]] line = transcript.next() # Read the entirety of a multi-line command while line.startswith(self.cmdapp.continuation_prompt): command.append(line[len(self.cmdapp.continuation_prompt):]) try: line = transcript.next() except StopIteration: raise (StopIteration, 'Transcript broke off while reading command beginning at line %d with\n%s' % (command[0])) lineNum += 1 command = ''.join(command) # Send the command into the application and capture the resulting output stop = self.cmdapp.onecmd_plus_hooks(command) #TODO: should act on ``stop`` result = self.outputTrap.read() # Read the expected result from transcript if line.startswith(self.cmdapp.prompt): message = '\nFile %s, line %d\nCommand was:\n%r\nExpected: (nothing)\nGot:\n%r\n'%\ (fname, lineNum, command, result) self.assert_(not(result.strip()), message) continue expected = [] while not line.startswith(self.cmdapp.prompt): expected.append(line) try: line = transcript.next() except StopIteration: finished = True break lineNum += 1 expected = ''.join(expected) # Compare actual result to expected message = '\nFile %s, line %d\nCommand was:\n%s\nExpected:\n%s\nGot:\n%s\n'%\ (fname, lineNum, command, expected, result) expected = self.expectationParser.transformString(expected) # checking whitespace is a pain - let's skip it expected = self.anyWhitespace.sub('', expected) result = self.anyWhitespace.sub('', result) self.assert_(re.match(expected, result, re.MULTILINE | re.DOTALL), message) def tearDown(self): if self.CmdApp: self.outputTrap.tearDown() if __name__ == '__main__': doctest.testmod(optionflags = doctest.NORMALIZE_WHITESPACE) ''' To make your application transcript-testable, replace :: app = MyApp() app.cmdloop() with :: app = MyApp() cmd2.run(app) Then run a session of your application and paste the entire screen contents into a file, ``transcript.test``, and invoke the test like:: python myapp.py --test transcript.test Wildcards can be used to test against multiple transcript files. '''
The New York Boylesque Festival weekend kicks off tonight with a teaser party at the Knitting Factory and is followed by tomorrow's main event at B.B. King's. Here's your chance to meet some of the performers before they hit the stage. How many years have you been doing burlesque? How would describe your burlesque style? Have you participated in the New York Boylesque Festival in the past? Who are you most looking forward to seeing perform this weekend? Gilbert de Moccos! and always Waxie Moon. What would you like to say to your New York fans (and future fans)? Love yourself first, then spread it around.
import zlib from urllib import urlencode from StringIO import StringIO from gzip import GzipFile from PyQt5.QtCore import pyqtSignal, QObject, QUrl, pyqtSlot from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest def decodeData(data, headers): encoding = headers.get('Content-Encoding', None) if encoding=='deflate': f = StringIO(zlib.decompress(data)) elif encoding=='x-gzip' or encoding=='gzip': f = GzipFile('', 'rb', 9, StringIO(data)) else: return data # data in object file handler data = f.read() f.close() return data class QRequest(QObject): manager = QNetworkAccessManager() finished = pyqtSignal() def __init__(self, url, params=None, parent=None): QObject.__init__(self, parent=parent) self.data = '' self.headers = {} self.statusCode = None self.params = params if params is not None: url = url + "?" + urlencode(params) self.qUrl = QUrl(url) self.request = QNetworkRequest(self.qUrl) def get(self): self.response = self.manager.get(self.request) self.response.readyRead.connect(self._onDataReady) self.response.finished.connect(self._onFinished) @pyqtSlot() def _onDataReady(self): self.data = self.data + self.response.readAll().data() @pyqtSlot() def _onFinished(self): self.finished.emit()
Jokic finished with 32 points, 18 rebounds and 10 assists. Denver coach Michael Malone said he didn't think Jokic would be any more fired up than usual for his return because "Nikola has a fire every night." "I don't think he's going to use it as any added motivation," Malone said. "I think he'll come back and look to help his team win another game at home against a quality team from the Eastern Conference." The Nuggets were hoping to have their opening night lineup back for the first time since the second game of their season, but guard Jamal Murray was scratched after rolling his left ankle Friday night. This was only the second time he'd missed a game in his three-year career. Murray played all 82 games his rookie season and missed a game last year because of a concussion. Over his last 10 games, Murray has averaged 17.9 points and 4.4 assists. 76ers: Jimmy Butler (sprained right wrist) and Wilson Chandler (left hamstring tightness) also sat out. That's the same hamstring Chandler injured last fall. ... With just three offensive rebounds in the first half, the 76ers managed a single second-chance point, three fewer than the Nuggets, who had just five offensive boards, three from Jokic. Nuggets: Denver's 77-point first half was a season high, besting the 74 the Nuggets scored against Dallas on Dec. 18. ... The Nuggets outscored the 76ers by 20 points in the paint in the first half, 42-22. ... Colorado Rockies SS Trevor Story missed the pregame free throw, failing to match ace Kyle Freeland, who swished his shot on opening night. Story's free throw rattled around the rim before falling out. ... New Denver Broncos coach Vic Fangio got a standing ovation when he was shown on the big screen. 76ers: Visit the Los Angeles Lakers on Tuesday night. Nuggets: Visit the Memphis Grizzlies on Monday night.
#! /usr/bin/env python # Copyright 2016 Hewlett Packard Enterprise Development Company, L.P. # # 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 script is intended to be run as part of a periodic proposal bot # job in OpenStack infrastructure. # # In order to function correctly, the environment in which the # script runs must have # * network access to the review.openstack.org Gerrit API # working directory # * network access to https://git.openstack.org/cgit import json try: # For Python 3.0 and later from urllib.error import HTTPError import urllib.request as urllib except ImportError: # Fall back to Python 2's urllib2 import urllib2 as urllib from urllib2 import HTTPError url = 'https://review.openstack.org/projects/' # This is what a project looks like ''' "openstack-attic/akanda": { "id": "openstack-attic%2Fakanda", "state": "READ_ONLY" }, ''' def is_in_openstack_namespace(proj): return proj.startswith('openstack/') def has_grenade_plugin(proj): try: r = urllib.urlopen( "https://git.openstack.org/cgit/%s/plain/devstack/upgrade/upgrade.sh" % proj) return True except HTTPError as err: if err.code == 404: return False r = urllib.urlopen(url) projects = sorted(filter(is_in_openstack_namespace, json.loads(r.read()[4:]))) found_plugins = filter(has_grenade_plugin, projects) for project in found_plugins: print(project[10:])
Important note: the social events are only for the participants who have registered for the Statutory Meetings & the International Scientific Symposium as well. Accompanying persons can attend the Welcome Cocktail on the 17th of October and the Gala Dinner on the 20th of October. If you aren’t subscribed by e-mail, kindly request availability for your preferred social event(s) at the registration desk between 11:00 and 18:00. Please note that there is a maximum of 25 participants for the site visits: Serefiye Cistern, Cinili Hamam and Yenikapi Excavations.
''' Created on 1 Sep 2012 @author: will ''' from Tkinter import (Label, Frame, Scrollbar, Entry, N, S, E, W, DISABLED, VERTICAL, Button, LEFT, ACTIVE, FLAT) import tkFont from tkSimpleDialog import Dialog license_text = ''' The MIT License (MIT) ===================== 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. ''' class AboutDialog(Dialog): def body(self, master): self.hdgFont = tkFont.Font(family="Helvetica", size=14, weight='bold') self.monoFont = tkFont.Font(family='Monospace', size=10) Label(master, text="Sundial Solver", font=self.hdgFont).grid(row=0, sticky=E + W) Label(master, text="V 0.1.0").grid(row=1, sticky=E + W) Label(master, text=u"\u00A9 2012 Will Bickerstaff").grid(row=2, sticky=E + W) Label(master, text="<will.bickerstaff@gmail.com>").grid(row=3, sticky=E + W) lictxt = Label(master, text=license_text, anchor=W) lictxt.grid(row=4, column=0, sticky=N + S + E + W) def buttonbox(self): box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=LEFT, padx=5, pady=5) self.bind("<Return>", self.ok) box.pack()
The art of the selfie is not a simple one. Getting the right angle and minimum arm in the side of the shot are difficult tasks that only the seasoned veterans have mastered, after countless hours in front of the bathroom mirror. But forget all that, because the Audiovox ShutterBall is here to make it all so much easier, getting rid of those skewed angles, and dispensing with awkward arm. Now, there are some who will claim that the lack of those two things means that the picture really isn’t a selfie at all. That may be. But, if you want to just take a clean picture of you and your friends, you now have somewhere to turn to, besides a real camera with a countdown timer. The ShutterBall is a remote Bluetooth shutter for Android and iOS smartphones. Using the Smart Shutter app, you’ll be able to set up your phone up to 60 feet away and snap a picture by pressing the handheld ShutterBall. That should help you keep it classy. The ShutterBall even comes with an easel stand for your smartphone, without which I guess the ShutterBall would be nearly unusable. ShutterBall – they won’t believe it’s a selfie! Update 7/21/2013: Audiovox has reached out to us with some updated tech specs which you can check out below. The Shutterball is also confirmed to work with the iPhone 5, 4, 4S, iPad Mini, iPod Touch 5th Gen, and the Samsung Galaxy S3, S4 and Note. Bluetooth Remote Shutter for your Smartphone camera – Take perfect pix!
#!/usr/bin/env python """ For more information, see: @see https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element @see https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support """ from __future__ import print_function, unicode_literals from htmlement import HTMLement def example_simple(): """ This example will parse a simple html tree and extract the website title and all anchors >>> example_simple() Parsing: GitHub GitHub => https://github.com/willforde GitHub Project => https://github.com/willforde/python-htmlement """ html = """ <html> <head> <title>GitHub</title> </head> <body> <a href="https://github.com/willforde">GitHub</a> <a href="https://github.com/willforde/python-htmlement">GitHub Project</a> </body> </html> """ # Parse the document parser = HTMLement() parser.feed(html) root = parser.close() # Root is an xml.etree.Element and supports the ElementTree API # (e.g. you may use its limited support for XPath expressions) # Get title title = root.find('head/title').text print("Parsing: {}".format(title)) # Get all anchors for a in root.iterfind(".//a"): # Get href attribute url = a.get("href") # Get anchor name name = a.text print("{} => {}".format(name, url)) def example_filter(): """ This example will parse a simple html tree and extract all the list items within the ul menu element using a tree filter. The tree filter will tell the parser to only parse the elements within the requested section and to ignore all other elements. Useful for speeding up the parsing of html pages. >>> example_filter() Menu Items - Coffee - Tea - Milk """ html = """ <html> <head> <title>Coffee shop</title> </head> <body> <ul class="menu"> <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> <ul class="extras"> <li>Sugar</li> <li>Cream</li> </ul> </body> </html> """ # Parse the document parser = HTMLement("ul", attrs={"class": "menu"}) parser.feed(html) root = parser.close() # Root should now be a 'ul' xml.etree.Element with all it's child elements available # All other elements have been ignored. Way faster to parse. # We are unable to get the title here sense all # elements outside the filter was ignored print("Menu Items") # Get all listitems for item in root.iterfind(".//li"): # Get text from listitem print("- {}".format(item.text)) def example_complex(): """ This example will parse a more complex html tree of python talk's and will extract the image, title, url and date of each talk. A filter will be used to extract the main talks div element >>> example_complex() Image = /presentations/c7f1fbb5d03a409d9de8abb5238d6a68/thumb_slide_0.jpg Url = /pycon2016/alex-martelli-exception-and-error-handling-in-python-2-and-python-3 Title = Alex Martelli - Exception and error handling in Python 2 and Python 3 Date = Jun 1, 2016 <BLANKLINE> Image = /presentations/eef8ffe5b6784f7cb84948cf866b2608/thumb_slide_0.jpg Url = /presentations/518cae54da12460e895163d809e25933/thumb_slide_0.jpg Title = Jake Vanderplas - Statistics for Hackers Date = May 29, 2016 <BLANKLINE> Image = /presentations/8b3ee51b5fcc4a238c4cb4b7787979ac/thumb_slide_0.jpg Url = /pycon2016/brett-slatkin-refactoring-python-why-and-how-to-restructure-your-code Title = Brett Slatkin - Refactoring Python: Why and how to restructure your code Date = May 29, 2016 <BLANKLINE> """ html = """ <html> <head> <title>PyCon 2016</title> </head> <body> <div class="main"> <h1>Talks by PyCon 2016</h1> <div class="talks" id="d5esfbb5d03adfdfede8a342238d6a68"> <div class="talk" data-id="c7f1fbb5d03a409d9de8abb5238d6a68"> <a href="/pycon2016/kelsey-gilmore-innis-seriously-strong-security-on-a-shoestring"> <img src="/presentations/c7f1fbb5d03a409d9de8abb5238d6a68/thumb_slide_0.jpg"> </a> <div class="talk-listing-meta"> <h3 class="title"> <a href="/pycon2016/alex-martelli-exception-and-error-handling-in-python-2-and-python-3"> Alex Martelli - Exception and error handling in Python 2 and Python 3 </a> </h3> <p class="date">Jun 1, 2016</p> </div> </div> <div class="talk" data-id="518cae54da12460e895163d809e25933"> <a href="/pycon2016/manuel-ebert-putting-1-million-new-words-into-the-dictionary"> <img src="/presentations/eef8ffe5b6784f7cb84948cf866b2608/thumb_slide_0.jpg"> </a> <div class="talk-listing-meta"> <h3 class="title"> <a href="/presentations/518cae54da12460e895163d809e25933/thumb_slide_0.jpg"> Jake Vanderplas - Statistics for Hackers </a> </h3> <p class="date">May 29, 2016</p> </div> </div> <div class="talk" data-id="8b3ee51b5fcc4a238c4cb4b7787979ac"> <a href="/pycon2016/brett-slatkin-refactoring-python-why-and-how-to-restructure-your-code"> <img src="/presentations/8b3ee51b5fcc4a238c4cb4b7787979ac/thumb_slide_0.jpg"> </a> <div class="talk-listing-meta"> <h3 class="title"> <a href="/pycon2016/brett-slatkin-refactoring-python-why-and-how-to-restructure-your-code"> Brett Slatkin - Refactoring Python: Why and how to restructure your code </a> </h3> <p class="date">May 29, 2016</p> </div> </div> </div> </div> </body> </html> """ # Parse the document parser = HTMLement("div", attrs={"class": "talks", "id": True}) parser.feed(html) root = parser.close() # Extract all div tags with class of talk for talk in root.iterfind("./div[@class='talk']"): # Fetch image img = talk.find(".//img").get("src") print("Image = {}".format(img)) # Fetch title and url title_anchor = talk.find("./div/h3/a") url = title_anchor.get("href") print("Url = {}".format(url)) title = title_anchor.text print("Title = {}".format(title)) # Fetch date date = talk.find("./div/p").text print("Date = {}".format(date)) print("") if __name__ == "__main__": example_simple() print("") example_filter() print("") example_complex()
Tenneco Announces Clean Air Leadership Change | Tenneco Inc. Lake Forest, Illinois, March 14, 2017 - Tenneco Inc. (NYSE: TEN) announced today that Patrick Guo has been appointed executive vice president and president of the company’s global Clean Air business, effective immediately. Most recently, Guo has been serving as executive vice president and general manager, Asia Pacific, where he successfully led growth throughout the region for both the Clean Air and Ride Performance product lines. Previously, Guo served as vice president and managing director, China and played a key role in Tenneco’s expansion in this important high-growth market. He joined Tenneco in 1996 and has held various leadership positions during his tenure with broad experience in serving both original equipment and aftermarket customers. He began his career as an engineer with the Ford Motor Company. Guo replaces Henry Hummel, executive vice president, Clean Air, who is leaving Tenneco to return to the health care industry in a CEO role. “We also congratulate Henry on his CEO appointment and wish him all the best in his new opportunity,” added Kesseler. Guo earned a bachelor of science degree from Tsinghua University, Beijing, and a master of science degree from the Ohio State University, both in mechanical engineering. He also holds an MBA from the University of Michigan.
#!/usr/bin/env python # Run this tool in two stages: # # 1. Collect data: ./monitor-disk-io.py [command] # 2. Print statistics: ./monitor-disk-io.py # 3. $$$ # # The first command will run strace and write the output to # _monitor_disk_io/strace-out.txt. The second call (without any arguments) # will parse that file and try to find out which file every read, write, # and seek corresponds to. # If you want to profile a BASH command, put it in a script and pass the # path of that script (i. e. BASH voodoo is not allowed here but can be # accomplished if a BASH script is used). import yaml import re import os import subprocess import logging import glob import copy import sys WRITE_PROC_FILES = False logger = logging.getLogger("uap_logger") proc_files = {} if not os.path.exists('_monitor_disk_io'): os.mkdir('_monitor_disk_io') if len(sys.argv) > 1: pigz = subprocess.Popen( "pigz -p 2 -b 4096 -c > _monitor_disk_io/strace-out.txt.gz", stdin=subprocess.PIPE, shell=True) args = ["strace", "-f", "-o", '/dev/stderr'] args.extend(sys.argv[1:]) p = subprocess.Popen(args, stderr=subprocess.PIPE) strace_out = p.stderr for line in strace_out: pigz.stdin.write(line) pigz.stdin.close() pigz.wait() exit(0) pigz = subprocess.Popen("pigz -p 1 -d -c _monitor_disk_io/strace-out.txt.gz", stdout=subprocess.PIPE, shell=True) strace_out = pigz.stdout if len(glob.glob('_monitor_disk_io/*.proc.txt')) > 0: os.system("rm _monitor_disk_io/*.proc.txt") path_for_pid_and_fd = {} stats = {} def handle_line(pid, line): line = line.strip() if WRITE_PROC_FILES: if pid not in proc_files: proc_files[pid] = open("_monitor_disk_io/%s.proc.txt" % pid, 'w') proc_files[pid].write(line + "\n") m = re.search(r'^(\w+)\((.*)\)\s+=\s+(.+)$', line) if m: command = str(m.group(1)) args = str(m.group(2)).strip() retval = str(m.group(3)) if command == 'clone': for _ in path_for_pid_and_fd[pid].keys(): if retval not in path_for_pid_and_fd: path_for_pid_and_fd[retval] = {} path_for_pid_and_fd[retval][_] = copy.copy( path_for_pid_and_fd[pid][_]) if command == 'dup2': fds = [_.strip() for _ in args.split(',')] try: path_for_pid_and_fd[pid][fds[1]] = copy.copy( path_for_pid_and_fd[pid][fds[0]]) except BaseException: path_for_pid_and_fd[pid][fds[1]] = '[unknown]' if command == 'open': if pid not in path_for_pid_and_fd: path_for_pid_and_fd[pid] = {} path_for_pid_and_fd[pid][retval] = re.search( "^\\\"([^\\\"]+)\\\"", args).group(1) if command == 'close': if pid not in path_for_pid_and_fd: path_for_pid_and_fd[pid] = {} fd = args.strip() if command == 'lseek': fd = None m = re.search(r"^(\d+),", args) if m: fd = m.group(1) if fd: path = '[unknown]' try: path = path_for_pid_and_fd[pid][fd] except BaseException: if fd == '0': path = 'stdin' elif fd == '1': path = 'stdout' elif fd == '2': path = 'stderr' else: pass if path not in stats: stats[path] = {'read': {}, 'write': {}, 'lseek': 0} stats[path]['lseek'] += 1 if command == 'read' or command == 'write': fd = None size = None m = re.search(r"^(\d+),", args) if m: fd = m.group(1) size = retval if fd and size: try: sizek = int(size) / 1024 except ValueError: return path = '[unknown]' try: path = path_for_pid_and_fd[pid][fd] except BaseException: if fd == '0': path = 'stdin' elif fd == '1': path = 'stdout' elif fd == '2': path = 'stderr' else: pass if path not in stats: stats[path] = {'read': {}, 'write': {}, 'lseek': 0} if sizek not in stats[path][command]: stats[path][command][sizek] = 0 stats[path][command][sizek] += 1 def size_to_cat(s): if s < 32: return (0, '< 32k ') elif s < 128: return (1, '32k+ ') elif s < 1024: return (2, '128k+ ') elif s < 2048: return (3, '1024k+ ') elif s < 3072: return (4, '2048k+ ') elif s < 4096: return (5, '3072k+ ') elif s < 8192: return (6, '4096k+ ') else: return (7, '8192k+') line_buffer = {} for line in strace_out: line = line.strip() pid = str(re.search(r'^(\d+)\s', line).group(1)) line = line[line.index(' ') + 1:] if 'resumed>' in line: line = re.sub(r'\<.+\>', '', line) line_buffer[pid] += line handle_line(pid, line_buffer[pid]) else: if '<unfinished' in line: line = re.sub(r'\<.+\>', '', line) line_buffer[pid] = line else: line_buffer[pid] = line handle_line(pid, line_buffer[pid]) for path in stats.keys(): cancel = False for _ in [ 'python_env', '/proc', '/etc', '/usr', '.git', '.so', '.py', '.pyc', 'stdin', 'stdout', 'stderr', '/dev']: if _ in path: cancel = True continue if cancel: continue printed_path = False for mode in ['read', 'write']: printed_mode = False hist = {} mod_size = {} for _, count in stats[path][mode].items(): cat = size_to_cat(_) if cat not in mod_size: mod_size[cat] = 0 mod_size[cat] += count for key in sorted(mod_size.keys(), reverse=True): size = key[1] # if key[0] == 0: # continue if not printed_path: print('-' * len(path)) print(path) print('-' * len(path)) printed_path = True if not printed_mode: print(mode.upper() + 'S:') printed_mode = True print('{:>8} {:>5}x'.format(str(size), str(mod_size[key]))) if stats[path]['lseek'] > 0: if not printed_path: print('-' * len(path)) print(path) print('-' * len(path)) printed_path = True print("LSEEKS: " + str(stats[path]['lseek']) + 'x') for pid, f in proc_files.items(): f.close()
Aboriginal Workforce provides strategic advice and leadership aimed at improving the recruitment, retention and career development of Aboriginal people across all clinical, allied and administrative positions throughout the health system in careers that are engaging, challenging, stimulating, meaningful and rewarding. This includes the Back on Track initiative and the Aboriginal and Torres Strait Islander Health Practitioner Awards. For information about Aboriginal and Torres Strait Islander employment in the Department of Health see Careers. To find out more call the Primary Healthcare Transition unit on 08 8999 2871 or email ATSIHPexcellenceawards.doh@nt.gov.au for the Aboriginal and Torres Strait Islander Health Practitioner Excellence Awards coordinator.
import sys import sqlite3 import re import os import aiofiles from time import localtime, strftime import linecache from functions import botfunc import asyncio import global_vars from pprint import pprint def printtf(message): yield from print_to_file(message) async def print_to_file(message): # file = os.path.join(global_vars.cwd, global_vars.log_dir, global_vars.log_file) # async with aiofiles.open(file, mode='a') as f: # await f.write("{}\r\n".format(message)) print(message) def PrintException(message=None): exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename filename = filename.replace(global_vars.cwd,"") linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) time = strftime("%H:%M:%S", localtime()) #line = '[' + str(time) + '] {} IN ({}:{} -> "{}"): {}'.format(exc_type.__name__, filename, lineno, line.strip(), exc_obj) report = "**Bug report**:\r\n" report += "Reported by: Exception catcher\r\n" if message is not None: if message.server is not None: report += "Server: `{}` (ID: {})\r\n".format(message.server.name, message.server.id) if message.author is not None: report += "Author: `{}#{}` (ID: {})\r\n".format(message.author.name, message.author.discriminator, message.author.id) report += "Time: {}\r\n".format(time) report += "Type: `{}`\r\n".format(exc_type.__name__) report += "Exception: `{}`\r\n".format(exc_obj) report += "File: `{}:{}`\r\n".format(filename, lineno) report += "Line: `{}`\r\n".format(line.strip()) if message is not None: report += "Executed command: {}".format(message.content[:1000]) print(report) def GetException(): try: exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename filename = filename.replace(global_vars.cwd,"") linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) time = strftime("%H:%M:%S", localtime()) line = '[' + str(time) + '] {} IN ({}:{} -> "{}"): {}'.format(exc_type.__name__, filename, lineno, line.strip(), exc_obj) return line except: PrintException() def debug(msg): time = strftime("%H:%M:%S", localtime()) yield from printtf("[" + str(time) + "] " + str(msg).encode("UTF-8")) def edit_log(chat, sender, message, messageid): try: # =============== SQLITE WAY =============== try: time = strftime("%H:%M:%S", localtime()) yield from printtf("[" + str(time) + "] [EDITED] " + sender.encode("UTF-8") + ": " + message.encode("UTF-8")) con = False topic = skype.name(chat) con = sqlite3.connect('files/' + topic + '.db') cur = con.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, sender VARCHAR(100), display VARCHAR(100), message TEXT(1000), date VARCHAR(150))") cur.execute( "UPDATE messages SET message=message || '\n[EDITED] ' || ? WHERE id=?", (message, messageid)) con.commit() except sqlite3.Error as e: PrintException() finally: if con: con.close() except: PrintException()
PROS: A great and easy way to create an eye-catching presentation., The basic version of this software is free to download. CONS: Users will have to pay a one-time fee to remove advertisements., More advanced image editing options are not available within Digital Photo Frame. CONS: Takes a while to display or download images if there are many of them.
# synergy -- mouse and keyboard sharing utility # Copyright (C) 2012 Synergy Si Ltd. # Copyright (C) 2010 Nick Bolton # # This package is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # found in the file LICENSE that should have accompanied this file. # # This package 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/>. from ftplib import FTP class FtpUploader: def __init__(self, host, user, password, dir): self.host = host self.user = user self.password = password self.dir = dir def upload(self, src, dest, subDir=None): print "Connecting to '%s'" % self.host ftp = FTP(self.host, self.user, self.password) self.changeDir(ftp, self.dir) if subDir: self.changeDir(ftp, subDir) print "Uploading '%s' as '%s'" % (src, dest) f = open(src, 'rb') ftp.storbinary('STOR ' + dest, f) f.close() ftp.close() print "Done" def changeDir(self, ftp, dir): if dir not in ftp.nlst(): print "Creating dir '%s'" % dir try: ftp.mkd(dir) except: # sometimes nlst may returns nothing, so mkd fails with 'File exists' print "Failed to create dir '%s'" % dir print "Changing to dir '%s'" % dir ftp.cwd(dir)
Time flies; nobody knows and understands this witty-ism more than entrepreneurs and small business owners. Before you know, 2020 will be a day away! To make sure your small business is strong enough to stay afloat in the treacherous waters ahead, here’s a guide to help you prepare for 2020 and the years beyond. Cloud computing has already seen massive adoption by small businesses. From process specific tracking and automation tools to business-wide ERPs like SAP S/4 HANA, from email marketing to social media marketing, from e-store creation to CRM – cloud-based tools and solutions are delivering stellar advantages to small businesses without the initial capital investment. It’s estimated that 78% of US-based small businesses will have adopted cloud computing already by 2020. Considering the kind of efficiency gains that cloud-based solutions have to offer to businesses, along with the transformative power of these technologies, it’s clear that cloud computing is a core component of the tech-driven growth strategy and long-term success plans for small businesses. The days of keeping invoice copies and financial records in a shoebox, for startups and small businesses, are over. In 2015, a Wall Street Journal article mentioned that 50% small businesses used the services of a CFO or financial controlling manager. This is just one of the changes in the small business’ financial management ecosystem. The added complexity of business models, risks of internal and external stakeholder related frauds, and tighter control from VCs and investors – all these factors mean that even the smallest of businesses can’t ignore the critical aspects of financial planning and preparedness. The modern small business owner has to be savvy enough to leverage technology to solve financial issues. From exploring niche business loans to experimenting with alternative financing options such as equipment financing or crowd-funding – small businesses have to be agile in their financial management to stay afloat post 2020. Monday to Friday. 9 to 5. These dated concepts of organizational work practices are bound to give way to novel approaches, including but not limited to highly flexible work rules, and new organizational structures. Think of how Uber and Airbnb use innovative internet and external network partnerships to scale up. Ambidextrous businesses that can focus on existing product lines and still innovate to create new product lines and revenue models will call the shots in the next decade. Agility in execution will also emerge as a key differentiator for small businesses, much like it helps Zara, the fashion brand, translate ‘trends’ in fashion into real products on shelves super quickly. AI is expected to be a $47 billion market by 2020, among the biggest of all. Not only is it an enabling technology for businesses of all sizes, but also a service market in its own rights, which all small tech businesses are keen on entering. Artificial Intelligence as a Service (AIaaS) models will enable small businesses to leverage the power of AI in a very modular fashion. Among these, chatbots are likely to deliver the most immediate benefit to small businesses, by helping them transform the way they manage customer service. Also, chatbots will deliver tremendous cost-cutting advantages to small businesses, with estimated cost savings by the end of 2022 pegged at a staggering $8 billion! Too many times, small businesses adopt a strategy of focusing only on the subsequent year. Don’t be that myopic business; focus on the market-sweeping changes that will have taken full effect by 2020, and be prepared to surf the wave like a pro. Next Toll Manufacturing in Life Sciences… a Potential Use Case for Robotics Process Automation?
from __future__ import division import re from math import sqrt import multiprocessing import Queue import sympy import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas class DiffEquation(object): ''' Class that contains equation information and, if the equation is valid, prepares the plot. ''' def __init__(self, equation_string): self.equation_string = equation_string self.equation = None self.compute_func = None self.figure = None def regex_check(self): '''A quick regular expression check to see that the input resembles an equation''' match1 = re.match('^(([xy+\-*/()0-9. ]+|sin\(|cos\(|exp\(|log\()?)+$', self.equation_string) match2 = re.match('^.*([xy]) *([xy]).*$', self.equation_string) return match1 and not match2 def prep_equation(self): ''' Attempt to convert the string to a SymPy function. From there, use lambdify to generate a function that is efficient to compute numerically. ''' if self.regex_check(): q = multiprocessing.Queue() def prep(conn): try: equation = sympy.sympify(self.equation_string) q.put(equation) except sympy.SympifyError: q.put(None) p = multiprocessing.Process(target=prep, args=(q,)) p.start() # See if we can get the equation within 5 seconds try: equation = q.get(timeout=3) except Queue.Empty: equation = None q.close() # If the process is still running, kill it if p.is_alive(): p.terminate() p.join() if equation: self.equation = equation x, y = sympy.symbols('x,y') compute_func = sympy.utilities.lambdify((x, y), self.equation) self.compute_func = compute_func def make_plot(self): '''Draw the plot on the figure attribute''' if self.compute_func: xvals, yvals = np.arange(-10, 11, 1), np.arange(-10, 11, 1) X, Y = np.meshgrid(xvals, yvals) U, V = np.meshgrid(np.zeros(len(xvals)), np.zeros(len(yvals))) # Iterate through grid and compute function value at each point # If value cannot be computed, default to 0 # If value can be computed, scale by sqrt of the magnitude for i, a in enumerate(xvals): for j, b in enumerate(yvals): dx = 1 try: dy = self.compute_func(a, b) n = sqrt(dx + dy**2) dy /= sqrt(n) dx /= sqrt(n) U[j][i] = dx V[j][i] = dy except (ValueError, ZeroDivisionError): pass # Plot the values self.figure = plt.Figure() axes = self.figure.add_subplot(1,1,1) axes.quiver(X, Y, U, V, angles='xy', color='b', edgecolors=('k',)) axes.axhline(color='black') axes.axvline(color='black') latex = sympy.latex(self.equation) axes.set_title(r'Direction field for $\frac{dy}{dx} = %s$' % latex, y=1.01) def write_data(self, output): '''Write the data out as base64 binary''' if self.figure: canvas = FigureCanvas(self.figure) self.figure.savefig(output, format='png', bbox_inches='tight') output.seek(0) return output.getvalue() return None
The Blue Economy CRC, announced in Launceston today by the Minister for Industry, Science and Technology Karen Andrews, is the largest CRC ever awarded, with funding totalling $329 million underpinned by a $70 million cash investment from the Federal Government. The CRC will be led by the University of Tasmania, with UWA the only Western Australian University on the bid. There are several other universities from Australia and New Zealand, amongst a total of 16 research partners. As part of the CRC, researchers at UWA’s Oceans Institute and Oceans Graduate School will investigate ways to meet growing demand for renewable offshore energy sources with strategic research in aquaculture initiatives, offshore engineering and renewable energy. The Blue Economy CRC builds on Australia’s National Marine Science Plan that has the explicit goal of “driving the development of Australia’s blue economy”; a $100 billion annual economic opportunity by 2025 that will allow Australia to meet growing demand for food and energy. Professor Christophe Gaudin, of UWA’s Oceans Graduate School and Director of the Wave Energy Centre, said the Blue Economy CRC will support Australian marine science and transform Australia’s blue economy. “We are very proud to be a part of this ambitious and very significant endeavour,” Professor Gaudin said. The Director of UWA’s Oceans Institute, Professor Peter Veth, said the CRC would investigate a new generation of technology including advances in offshore platform sensors, innovative use of Artificial Intelligence, robotics, and automated underwater vehicles, towards greatly enhanced and sustainable offshore food production and renewable energy including hydrogen and ammonium. “The University of Western Australia has enormous capacity in the ocean sciences across its four Faculties, having recently been ranked as global leading in 11 areas of Oceans-related research by the Australian Research Council. These skills will flow perfectly into this new Cooperative Research Centre for the Blue Economy,” Professor Veth said. UWA Vice-Chancellor Professor Dawn Freshwater said it was significant that the west coast of Australia would be included in the CRC. “This aligns perfectly with the UWA 2030 vision, advancing the prosperity and welfare of the global community through collaborative engagement in education, research and innovation, global partnerships, and sustainable environments,” Professor Freshwater said. “UWA has a geographic advantage, positioned at the gateway to the Indian Ocean Rim, to play a significant role in marine research that will herald a new era of harnessing the resources of the world’s oceans.
# -*- coding: utf-8 -*- # # Software License Agreement (BSD License) # # Copyright (c) 2010-2011, Antons Rebguns. # 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 University of Arizona 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. __author__ = 'Antons Rebguns' __copyright__ = 'Copyright (c) 2010-2011 Antons Rebguns' __license__ = 'BSD' __maintainer__ = 'Antons Rebguns' __email__ = 'anton@email.arizona.edu' import math import rospy from dynamixel_driver.dynamixel_const import * from dynamixel_controllers.srv import SetSpeed from dynamixel_controllers.srv import TorqueEnable from dynamixel_controllers.srv import SetComplianceSlope from dynamixel_controllers.srv import SetComplianceMargin from dynamixel_controllers.srv import SetCompliancePunch from dynamixel_controllers.srv import SetTorqueLimit from std_msgs.msg import Float64 from dynamixel_msgs.msg import MotorStateList from dynamixel_msgs.msg import JointState class JointController: def __init__(self, dxl_io, controller_namespace, port_namespace): self.running = False self.dxl_io = dxl_io self.controller_namespace = controller_namespace self.port_namespace = port_namespace self.joint_name = rospy.get_param(self.controller_namespace + '/joint_name') self.joint_speed = rospy.get_param(self.controller_namespace + '/joint_speed', 1.0) self.compliance_slope = rospy.get_param(self.controller_namespace + '/joint_compliance_slope', None) self.compliance_margin = rospy.get_param(self.controller_namespace + '/joint_compliance_margin', None) self.compliance_punch = rospy.get_param(self.controller_namespace + '/joint_compliance_punch', None) self.torque_limit = rospy.get_param(self.controller_namespace + '/joint_torque_limit', None) self.__ensure_limits() self.speed_service = rospy.Service(self.controller_namespace + '/set_speed', SetSpeed, self.process_set_speed) self.torque_service = rospy.Service(self.controller_namespace + '/torque_enable', TorqueEnable, self.process_torque_enable) self.compliance_slope_service = rospy.Service(self.controller_namespace + '/set_compliance_slope', SetComplianceSlope, self.process_set_compliance_slope) self.compliance_marigin_service = rospy.Service(self.controller_namespace + '/set_compliance_margin', SetComplianceMargin, self.process_set_compliance_margin) self.compliance_punch_service = rospy.Service(self.controller_namespace + '/set_compliance_punch', SetCompliancePunch, self.process_set_compliance_punch) self.torque_limit_service = rospy.Service(self.controller_namespace + '/set_torque_limit', SetTorqueLimit, self.process_set_torque_limit) def __ensure_limits(self): if self.compliance_slope is not None: if self.compliance_slope < DXL_MIN_COMPLIANCE_SLOPE: self.compliance_slope = DXL_MIN_COMPLIANCE_SLOPE elif self.compliance_slope > DXL_MAX_COMPLIANCE_SLOPE: self.compliance_slope = DXL_MAX_COMPLIANCE_SLOPE else: self.compliance_slope = int(self.compliance_slope) if self.compliance_margin is not None: if self.compliance_margin < DXL_MIN_COMPLIANCE_MARGIN: self.compliance_margin = DXL_MIN_COMPLIANCE_MARGIN elif self.compliance_margin > DXL_MAX_COMPLIANCE_MARGIN: self.compliance_margin = DXL_MAX_COMPLIANCE_MARGIN else: self.compliance_margin = int(self.compliance_margin) if self.compliance_punch is not None: if self.compliance_punch < DXL_MIN_PUNCH: self.compliance_punch = DXL_MIN_PUNCH elif self.compliance_punch > DXL_MAX_PUNCH: self.compliance_punch = DXL_MAX_PUNCH else: self.compliance_punch = int(self.compliance_punch) if self.torque_limit is not None: if self.torque_limit < 0: self.torque_limit = 0.0 elif self.torque_limit > 1: self.torque_limit = 1.0 def initialize(self): raise NotImplementedError def start(self): self.running = True self.joint_state_pub = rospy.Publisher(self.controller_namespace + '/state', JointState, queue_size=1) self.command_sub = rospy.Subscriber(self.controller_namespace + '/command', Float64, self.process_command) self.motor_states_sub = rospy.Subscriber('motor_states/%s' % self.port_namespace, MotorStateList, self.process_motor_states) def stop(self): self.running = False self.joint_state_pub.unregister() self.motor_states_sub.unregister() self.command_sub.unregister() self.speed_service.shutdown('normal shutdown') self.torque_service.shutdown('normal shutdown') self.compliance_slope_service.shutdown('normal shutdown') def set_torque_enable(self, torque_enable): raise NotImplementedError def set_speed(self, speed): raise NotImplementedError def set_compliance_slope(self, slope): raise NotImplementedError def set_compliance_margin(self, margin): raise NotImplementedError def set_compliance_punch(self, punch): raise NotImplementedError def set_torque_limit(self, max_torque): raise NotImplementedError def process_set_speed(self, req): self.set_speed(req.speed) return [] # success def process_torque_enable(self, req): self.set_torque_enable(req.torque_enable) return [] def process_set_compliance_slope(self, req): self.set_compliance_slope(req.slope) return [] def process_set_compliance_margin(self, req): self.set_compliance_margin(req.margin) return [] def process_set_compliance_punch(self, req): self.set_compliance_punch(req.punch) return [] def process_set_torque_limit(self, req): self.set_torque_limit(req.torque_limit) return [] def process_motor_states(self, state_list): raise NotImplementedError def process_command(self, msg): raise NotImplementedError def rad_to_raw(self, angle, initial_position_raw, flipped, encoder_ticks_per_radian): """ angle is in radians """ #print 'flipped = %s, angle_in = %f, init_raw = %d' % (str(flipped), angle, initial_position_raw) angle_raw = angle * encoder_ticks_per_radian #print 'angle = %f, val = %d' % (math.degrees(angle), int(round(initial_position_raw - angle_raw if flipped else initial_position_raw + angle_raw))) return int(round(initial_position_raw - angle_raw if flipped else initial_position_raw + angle_raw)) def raw_to_rad(self, raw, initial_position_raw, flipped, radians_per_encoder_tick): return (initial_position_raw - raw if flipped else raw - initial_position_raw) * radians_per_encoder_tick
Meghan Markle and Prince Harry are engaged and planning a Spring 2018 wedding (!!!!) and it looks like Harry went a pretty traditional route during the proposal process: He asked for permission. Apparently, Harry talked to Meghan's mom Doria Ragland before popping the question, per People. She obviously said yes, and even released a statement of support via Kensington Palace, along with Meghan's father Thomas Markle. Harry's been pretty clear about his desire to get to know Meghan's family. In fact, Doria attended the closing ceremonies of the 2017 Invictus Games with Meghan and Harry in September.
"""trains URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from django.contrib import admin from tutu import views from tutu import views_sim from django.views.static import serve from trains import settings urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name="index"), url(r'^track/new/$', views.new_track, name='new_track'), url(r'^track/edit/(?P<track_id>[0-9]*)$', views.edit_track, name="edit_track"), url(r'^track/delete/(?P<track_id>[0-9]*)$', views.delete_track, name="delete_track"), url(r'^track/(?P<track_id>[0-9]*)/switch/edit/(?P<switch_id>[0-9]*)$', views.edit_switch, name="edit_switch"), url(r'^track/(?P<track_id>[0-9]*)/switch/delete/(?P<switch_id>[0-9]*)$', views.delete_switch, name="delete_switch"), url(r'^track/(?P<track_id>[0-9]*)$', views.show_track, name="show_track"), url(r'^track/(?P<track_id>[0-9]*)/thumbnail$', views.thumbnail_track, name="thumbnail_track"), url(r'^track/(?P<track_id>[0-9]*)/new_switch$', views.new_switch, name="new_switch"), url(r'^track/(?P<track_id>[0-9]*)/simulation/$', views_sim.simulation, name="simulation"), url(r'^reset$', views.reset, name="reset"), url(r'^serve/(?P<path>.*)$', serve, {'document_root': settings.PICS_DIR}), url(r'^files/(?P<file_url>.*)$', views_sim.serve_upload_files, name="file"), url(r'^track/(?P<track_id>[0-9]*)/simulation_start/$', views_sim.simulation_start, name="simulation_start"), ]
bernard.mitchelson has not yet been in a debate. Post a comment to bernard.mitchelson's profile. bernard.mitchelson does not have any Debate.org friends. bernard.mitchelson has not added any photo albums. If you are logged in, you will also see green or red bullets next to each issue, which indicate whether you agree or disagree with bernard.mitchelson on that particular issue. You can also click each issue to find other members that agree with bernard.mitchelson's position on the issue.
# -*- coding: utf-8 -*- import zipfile from dp_tornado.engine.helper import Helper as dpHelper class ZipHelper(dpHelper): def archive(self, destfile, srcfiles, mode='w', compression=zipfile.ZIP_STORED, allowZip64=False): archive = zipfile.ZipFile(file=destfile, mode=mode, compression=compression, allowZip64=allowZip64) if not isinstance(srcfiles, (list, tuple)): srcfiles = (srcfiles, ) for srcfile in srcfiles: arcname = None compress_type = None if isinstance(srcfile, (tuple, list)): filename = srcfile[0] arcname = srcfile[1] if len(srcfile) > 1 else arcname compress_type = srcfile[2] if len(srcfile) > 2 else compress_type else: filename = srcfile self._archive_append(archive, filename, arcname, compress_type) archive.close() return True def _archive_append(self, archive, path, arcname, compress_type): if self.helper.io.path.is_file(path): archive.write(filename=path, arcname=arcname, compress_type=compress_type) elif self.helper.io.path.is_dir(path): for e in self.helper.io.path.browse(path): self._archive_append(archive=archive, path=e, arcname=arcname, compress_type=compress_type) def unarchive(self, srcfile, destpath, mode='r', compression=zipfile.ZIP_STORED, allowZip64=False): with zipfile.ZipFile(file=srcfile, mode=mode, compression=compression, allowZip64=allowZip64) as archive: archive.extractall(destpath) return True
The Iceberg String Quartet was formed in September 2017 at the McGill University Schulich School of Music in Montréal, Québec. Consisting of cellist Jacob Efthimiou, violist Chung-Han Hsiao, and violinists Christopher Stork and Russell Iceberg, the quartet has studied with André Roy and Brian Manker. In December 2017, the quartet won the grand prize at the McGill University chamber music competition, and was sent to study and perform at the Royal Conservatory in The Hague, Netherlands in April 2018. At The Hague, the Iceberg Quartet worked closely with Ásdís Valdimarsdottir of the Miami String Quartet. In July, 2018, the Iceberg String Quartet participated in the Evolution of the String Quartet Program at the Banff Centre for the Arts and Creativity. In Banff, they coached with the Eybler, Parker, and JACK String Quartets. For the 2018-2019 concert season, the Iceberg Quartet will perform in the U.S. states of Vermont, New York, and Delaware, as well as in their home town of Montréal, Québec. We recommend you watch this short film produced by the Banff Center introducing the Iceberg String Quartet.
# Copyright (c) 2010 by Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of hghooks. # # hghooks 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. # # hghooks 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 hghooks. If not, see <http://www.gnu.org/licenses/>. import os.path import re import shutil import tempfile version = "0.6.0" re_options = re.IGNORECASE | re.MULTILINE | re.DOTALL skip_pattern = re.compile('# hghooks: (.*)', re_options) class CheckerManager(object): def __init__(self, ui, repo, node, skip_text=None, extension='.py'): self.ui = ui self.repo = repo self.node = node self.skip_text = skip_text self.extension = extension self.strict_checking = self.ui.configbool('hghooks', 'strict_checking') def skip_file(self, filename, filedata): if not filename.endswith(self.extension): return True for match in skip_pattern.findall(filedata): if self.skip_text in match: return True return False def check(self, checker): warnings = 0 total_revs = len(self.repo.changelog) if self.strict_checking: current_rev = self.repo[self.node].rev() else: # check only files from the last revision current_rev = total_revs - 1 while current_rev < total_revs: rev_warnings = 0 directory = tempfile.mkdtemp(suffix='-r%d' % current_rev, prefix='hghooks') current_rev += 1 self.ui.debug("Checking revision %d\n" % current_rev) ctx = self.repo[current_rev - 1] description = ctx.description() if self.skip_text and self.skip_text in description: continue files_to_check = {} existing_files = tuple(ctx) for filename in ctx.files(): if filename not in existing_files: continue # the file was removed in this changeset filectx = ctx.filectx(filename) filedata = filectx.data() if self.skip_text and self.skip_file(filename, filedata): continue full_path = os.path.join(directory, filename) files_to_check[full_path] = filedata if files_to_check: errors_num, log = checker(files_to_check, description) rev_warnings += errors_num if rev_warnings: self.ui.warn('%s\n\n %d errors in revision %d\n' % (log, rev_warnings, current_rev - 1)) else: self.ui.debug('No warnings in revision %d. Good job!\n' % (current_rev - 1)) warnings += rev_warnings shutil.rmtree(directory) if warnings: return True # failure else: return False # success
Nénuphar Bracelet, 14mm width in a silver finish. Your bracelet, which is made in our workshops in France, can be paired with a reversible leather. Choose between its Raspberry or Petrol blue side to match your outfit... or your mood! Our adjustable bracelet usually fits wrists measuring 14 to 16cm.
from PyQt4 import QtCore, QtGui import Ui_Cursor class Ui_QCursorWindow(QtCore.QObject): valueChanged = QtCore.Signal(str, float) def setupUi(self, Form, data=[]): Form.setObjectName( ("Form")) Form.resize(900, 900) #self.centralwidget = QtGui.QWidget(Form) #self.centralwidget.setObjectName("centralwidget") self.verticalLayout = QtGui.QVBoxLayout(Form) self.verticalLayout.setSpacing(0) self.verticalLayout.setMargin(0) self.verticalLayout.setObjectName("verticalLayout") if len(data): self.setupCursor(Form, data) spacerItem = QtGui.QSpacerItem(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) QtCore.QMetaObject.connectSlotsByName(Form) def valueChangedSlot(self, key, value): self.valueChanged.emit(key, value) def setupCursor(self, Form, data): for key, vmin, value, vmax in data: self.parent = QtGui.QWidget(Form) ui_widget = Ui_Cursor.Ui_Cursor() ui_widget.setupUi(self.parent) ui_widget.setLabel(key) ui_widget.valueChanged.connect(self.valueChangedSlot) ui_widget.setRange(vmin, vmax) ui_widget.setValue(value) self.verticalLayout.addWidget(self.parent)
This is the free distribution of clothing to families with children 0 to 12 years. It’s realized by phone appointment, at the door of via Segneri. The families who benefit from this service must be provided with voucher for withdrawal clothes given by agencies, churches and counseling centers participating in our project. The door is open to the public on the morning of Tuesday and Friday and on Wednesday afternoon. The office is accessible by public transport with bus lines 64 and 50. But where do the clothes come?? The dresses are collected and managed through the CAV Centro di Aiuto alla Vita Ambrosiano, who retired clothing in via Tonezza, 3. The very important work, however, took place Sunday in the labor camps, during which it is sorted and selected all the material received, from clothes, toys and accessories for children. Do you want to help us out?? Do you want to know what kind of material you can bring? visit the PAGE: "Recycled to be donated".
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('FilmRevolutionApp', '0008_auto_20170521_1046'), ] operations = [ migrations.AlterField( model_name='actor', name='age', field=models.IntegerField( validators=[django.core.validators.MaxValueValidator(120), django.core.validators.MinValueValidator(1)]), ), migrations.AlterField( model_name='actor', name='birthday', field=models.DateField(), ), migrations.AlterField( model_name='actor', name='deathday', field=models.DateField(null=True, blank=True), ), migrations.AlterField( model_name='director', name='age', field=models.IntegerField( validators=[django.core.validators.MaxValueValidator(120), django.core.validators.MinValueValidator(1)]), ), migrations.AlterField( model_name='director', name='birthday', field=models.DateField(), ), migrations.AlterField( model_name='director', name='deathday', field=models.DateField(null=True, blank=True), ), ]
A Vancouver Island man has pleaded guilty to charges of animal cruelty after a large number of various animals were found living in filthy conditions earlier this year. The BC SPCA says they had to remove 34 animals from the Ladysmith property of Kramer Lowe on January 18. The animals included cats, bearded dragons, boa constrictors, turtles, guinea pigs and a variety of small animals. One of the snakes found on the property, a reticulated python, is listed in the province’s Controlled Alien Species regulation, which prohibits the possession of alien animals who pose a risk to the health and safety of people or the environment, according to a release from the BC SPCA. Lowe pleaded guilty to one count of animal cruelty and to violating the Wildlife Act. He will next be in court on Nov. 2 for sentencing where Lowe faces a maximum fine of $75,000, up to two years in jail and a maximum lifetime ban on owning animals.
class MQTTMatcher(object): """Intended to manage topic filters including wildcards. Internally, MQTTMatcher use a prefix tree (trie) to store values associated with filters, and has an iter_match() method to iterate efficiently over all filters that match some topic name.""" class Node(object): __slots__ = '_children', '_content' def __init__(self): self._children = {} self._content = None def __init__(self): self._root = self.Node() def __setitem__(self, key, value): """Add a topic filter :key to the prefix tree and associate it to :value""" node = self._root for sym in key.split('/'): node = node._children.setdefault(sym, self.Node()) node._content = value def __getitem__(self, key): """Retrieve the value associated with some topic filter :key""" try: node = self._root for sym in key.split('/'): node = node._children[sym] if node._content is None: raise KeyError(key) return node._content except KeyError: raise KeyError(key) def __delitem__(self, key): """Delete the value associated with some topic filter :key""" lst = [] try: parent, node = None, self._root for k in key.split('/'): parent, node = node, node._children[k] lst.append((parent, k, node)) # TODO node._content = None except KeyError: raise KeyError(key) else: # cleanup for parent, k, node in reversed(lst): if node._children or node._content is not None: break del parent._children[k] def iter_match(self, topic): """Return an iterator on all values associated with filters that match the :topic""" lst = topic.split('/') normal = not topic.startswith('$') def rec(node, i=0): if i == len(lst): if node._content is not None: yield node._content else: part = lst[i] if part in node._children: for content in rec(node._children[part], i + 1): yield content if '+' in node._children and (normal or i > 0): for content in rec(node._children['+'], i + 1): yield content if '#' in node._children and (normal or i > 0): content = node._children['#']._content if content is not None: yield content return rec(self._root)
Need a good excuse to goof off today? Sega has got you covered. The video game publisher is giving away a gaggle of games this week on the Steam digital distribution system as part of its Make War Not Love strategy game promotion. First things first: Go to Steam now and grab the first bundle of titles while they’re available. All totaled, there are six games currently available, including the arcade classic Golden Axe and Jet Set Radio, a player favorite from the company’s Dreamcast console system which remains popular today. There are other games in the bundle, but these are the ones most worth your time. Round two, which unlocks Thursday morning, will include the games Streets of Rage II, Condemned: Criminal Origin, and Binary Domain—and open up an 80% discount on Alpha Protocol. And a third bundle of games, made up of Gunstar Heroes, Renegade Ops, and Viking: Battle for Asgard, is expected to become available Saturday. By giving away older games, Sega (sgamy) is hoping to spark interest in its more recent ones, encouraging fans to buy or play one of three strategy titles—Company of Heroes 2, Total War: Atilla, or Dawn of War II. Whichever game is played the most ‘wins’—and if you’re one of the people who played it in that time, you get additional downloadable content for one of those strategy games. Yeah, it’s overly complicated. But the good news is you don’t have to worry about any of that if you don’t want to. Anyone can download the free titles. Jet Set Radio is, by far, the jewel in the crown here. The game is a fast-paced title that has you controlling a gang of rollerblading graffiti artists who try to avoid the authorities, all to a terrific soundtrack. It was one of the first games to use cell-shaded graphics (an animation style that has since spread to other games, TV shows, and commercials). Since its initial release in 2000, Jet Set Radio been adapted for iOS, Xbox (MSFT), PlayStation (SNE), PlayStation Vita, and the Game Boy Advance. Just be sure to wear headphones and keep an eye open for your supervisor if you decide to play at work.
from datetime import date, datetime, time import logging import formencode from formencode import htmlfill, Invalid, validators from pylons import request, tmpl_context as c from pylons.controllers.util import redirect from pylons.decorators import validate from pylons.i18n import _ from adhocracy import forms, model from adhocracy.lib import helpers as h, pager, tiles, watchlist from adhocracy.lib.auth import csrf, require from adhocracy.lib.base import BaseController from adhocracy.lib.instance import RequireInstance from adhocracy.lib.templating import render, render_json from adhocracy.lib.util import get_entity_or_abort import adhocracy.lib.text as text log = logging.getLogger(__name__) class MilestoneNewForm(formencode.Schema): allow_extra_fields = True class MilestoneCreateForm(MilestoneNewForm): title = validators.String(max=2000, min=4, not_empty=True) text = validators.String(max=60000, min=4, not_empty=True) category = forms.ValidCategoryBadge(if_missing=None, if_empty=None) time = forms.ValidDate() class MilestoneEditForm(formencode.Schema): allow_extra_fields = True class MilestoneUpdateForm(MilestoneEditForm): title = validators.String(max=2000, min=4, not_empty=True) text = validators.String(max=60000, min=4, not_empty=True) category = forms.ValidCategoryBadge(if_missing=None, if_empty=None) time = forms.ValidDate() class MilestoneController(BaseController): def __init__(self): super(MilestoneController, self).__init__() c.active_subheader_nav = 'milestones' @RequireInstance def index(self, format="html"): require.milestone.index() milestones = model.Milestone.all(instance=c.instance) broken = [m for m in milestones if m.time is None] for milestone in broken: log.warning('Time of Milestone is None: %s' % h.entity_url(milestone)) milestones = [m for m in milestones if m.time is not None] today = datetime.combine(date.today(), time(0, 0)) past_milestones = [m for m in milestones if m.time < today] c.show_past_milestones = len(past_milestones) c.past_milestones_pager = pager.milestones(past_milestones) current_milestones = [m for m in milestones if m not in past_milestones] c.show_current_milestones = len(current_milestones) c.current_milestones_pager = pager.milestones(current_milestones) c.milestones = past_milestones + current_milestones # for the timeline if format == 'json': return render_json(c.milestones_pager) c.tile = tiles.instance.InstanceTile(c.instance) c.tutorial = 'milestone_index' c.tutorial_intro = _('tutorial_milestones_tab') return render("/milestone/index.html") @RequireInstance @validate(schema=MilestoneNewForm(), form='bad_request', post_only=False, on_get=True) def new(self, errors=None): require.milestone.create() c.categories = model.CategoryBadge.all(instance=c.instance) defaults = dict(request.params) defaults['watch'] = defaults.get('watch', True) return htmlfill.render(render("/milestone/new.html"), defaults=defaults, errors=errors, force_defaults=False) @RequireInstance @csrf.RequireInternalRequest(methods=['POST']) def create(self, format='html'): require.milestone.create() c.categories = model.CategoryBadge.all(instance=c.instance) try: self.form_result = MilestoneCreateForm().to_python(request.params) except Invalid, i: return self.new(errors=i.unpack_errors()) category = self.form_result.get('category') milestone = model.Milestone.create(c.instance, c.user, self.form_result.get("title"), self.form_result.get('text'), self.form_result.get('time'), category=category) model.meta.Session.commit() watchlist.check_watch(milestone) #event.emit(event.T_PROPOSAL_CREATE, c.user, instance=c.instance, # topics=[proposal], proposal=proposal, rev=description.head) redirect(h.entity_url(milestone, format=format)) @RequireInstance @validate(schema=MilestoneEditForm(), form="bad_request", post_only=False, on_get=True) def edit(self, id, errors={}): c.categories = model.CategoryBadge.all(instance=c.instance) c.milestone = get_entity_or_abort(model.Milestone, id) require.milestone.edit(c.milestone) defaults = {'category': (str(c.milestone.category.id) if c.milestone.category else None)} defaults.update(dict(request.params)) return htmlfill.render(render("/milestone/edit.html"), defaults=defaults, errors=errors, force_defaults=False) @RequireInstance @csrf.RequireInternalRequest(methods=['POST']) def update(self, id, format='html'): try: c.milestone = get_entity_or_abort(model.Milestone, id) self.form_result = MilestoneUpdateForm().to_python(request.params) except Invalid, i: return self.edit(id, errors=i.unpack_errors()) require.milestone.edit(c.milestone) c.milestone.title = self.form_result.get('title') c.milestone.text = self.form_result.get('text') c.milestone.category = self.form_result.get('category') c.milestone.time = self.form_result.get('time') model.meta.Session.commit() watchlist.check_watch(c.milestone) #event.emit(event.T_PROPOSAL_EDIT, c.user, instance=c.instance, # topics=[c.proposal], proposal=c.proposal, rev=_text) redirect(h.entity_url(c.milestone)) @RequireInstance def show(self, id, format='html'): c.milestone = get_entity_or_abort(model.Milestone, id) require.milestone.show(c.milestone) if format == 'json': return render_json(c.milestone) c.tile = tiles.milestone.MilestoneTile(c.milestone) # proposals .. directly assigned by_milestone = model.Proposal.by_milestone(c.milestone, instance=c.instance) # proposals .. with the same category by_category = [] if c.milestone.category: by_category = [d for d in c.milestone.category.delegateables if isinstance(d, model.Proposal) and not d.is_deleted()] proposals = list(set(by_milestone + by_category)) c.proposals_pager = pager.proposals(proposals, size=20, enable_sorts=False) c.show_proposals_pager = len(proposals) # pages pages = model.Page.by_milestone(c.milestone, instance=c.instance, include_deleted=False, functions=[model.Page.NORM]) c.pages_pager = pager.pages(pages, size=20, enable_sorts=False) c.show_pages_pager = len(pages) and c.instance.use_norms self._common_metadata(c.milestone) c.tutorial_intro = _('tutorial_milestone_details_tab') c.tutorial = 'milestone_show' return render("/milestone/show.html") @RequireInstance def ask_delete(self, id): c.milestone = get_entity_or_abort(model.Milestone, id) require.milestone.delete(c.milestone) c.tile = tiles.milestone.MilestoneTile(c.milestone) return render('/milestone/ask_delete.html') @RequireInstance @csrf.RequireInternalRequest() def delete(self, id): c.milestone = get_entity_or_abort(model.Milestone, id) require.milestone.delete(c.milestone) #event.emit(event.T_milestone_DELETE, c.user, instance=c.instance, # topics=[c.milestone], milestone=c.milestone) c.milestone.delete() model.meta.Session.commit() h.flash(_("The milestone %s has been deleted.") % c.milestone.title, 'success') redirect(h.entity_url(c.instance)) def _common_metadata(self, milestone): h.add_meta("description", text.meta_escape(milestone.text, markdown=False)[0:160]) h.add_meta("dc.title", text.meta_escape(milestone.title, markdown=False)) h.add_meta("dc.date", (milestone.time and milestone.time.strftime("%Y-%m-%d") or '')) h.add_meta("dc.author", text.meta_escape(milestone.creator.name, markdown=False))
Few boots have managed to replicate the appeal of the Timberland 6″ boot which has built a dedicated clientele over the past four decades and continues to stay relevant in the current sneaker scenario. The Timberland 40th Anniversary Special Edition Box Set aims to celebrate the rich history of this iconic silhouette and manages to present an interestingly packaged product. The boots are packaged in a wooden crate and are accompanied by a fine book, Icons by Shannon Dooling, which profiles some of the most famous Timberland creations. Take a look at the images. Available at Timberland right now. Hey Sneakerheads! If you liked this Timberland 40th Anniversary Special Edition Box Set article, add our RSS Feed to stay on top of Sneaker News! It's free and hassle-free!
class SuffixTree: """ Suffix tree https://en.wikipedia.org/wiki/Suffix_tree """ def __init__(self, nodes): self.root = {"EOW":False, "next": {} } for node in nodes: self.addNode(node['word'], node['leaf_data']) def addNode(self,word, leaf_data): """ Add node to char :param word: word :param leaf_data: Leaf data :return: None >>> st = SuffixTree([]) >>> st.addNode('abc','1M$') >>> st.addNode('qwe', '2M$') >>> st.addNode('abd', '3M$') >>> st.root['next']['a']['next']['b']['next']['c']['EOW'] '1M$' >>> st.root['next']['a']['next']['b']['next']['d']['EOW'] '3M$' >>> 'c' in st.root['next']['a']['next']['b']['next'] and 'd' in st.root['next']['a']['next']['b']['next'] True >>> 'q' not in st.root['next']['q']['next']['w']['next'] True """ node = self.root for ch in word: if ch not in node['next']: node['next'] [ch] = {"EOW":False, "next": {} } node = node['next'][ch] node['EOW'] = leaf_data def find(self, word): """ Find subword in tree (substring) :param word: Keyword in tree :return: Leaf data if exist else False >>> st = SuffixTree([{'word':'Peppa','leaf_data':'PIG'}, {'word':'Mike', 'leaf_data':'Pro'}, \ {'word':'Peppa','leaf_data':'OVERRITE'}]) >>> st.find('Peppa') 'OVERRITE' >>> st.find('Mike john') 'Pro' >>> st.find('Mikeing') False """ node = self.root for index, ch in enumerate(word): if ch not in node['next']: return False node = node['next'][ch] if node['EOW'] and (index + 1 == len(word) or word[index + 1] == " "): return node['EOW'] return False
The globalized and decentralized Internet has become the new locus for a wide range of human activity, including commerce, crime, communications and cultural production. Activities which were once at the core of domestic jurisdiction have moved onto the Internet, and in doing so, have presented numerous challenges to the ability of states to exercise jurisdiction. In writing about these challenges, some scholars have characterized the Internet as a separate “space” and many refer to state jurisdiction over Internet activities as “extraterritorial.” This article examines these challenges in the context of the overall international law of jurisdiction, rather than focusing on any one substantive area. This article argues that while the Internet may push at the boundaries of traditional principles of jurisdiction in public international law, it has not supplanted them. The article explores the principles of jurisdiction, including the evolving concept of “qualified territoriality,” and demonstrates how these principles continue to apply in the Internet context. The article examines how states exercise their authority with respect to Internet activities by addressing governance issues, by engaging in normative ordering for the Internet, and by extending the reach of their domestic laws to capture Internet-based activities. Lastly, the article concludes by offering a set of “first principles,” in the form of policy precepts, to guide the evolution of public international law norms and to address problems particular to the context of the global Internet.
import sys sys.path.append('./../../..') from optparse import OptionParser import scipy as SP import os import mtSet.pycore.utils.simulator as sim from mtSet.pycore.utils.read_utils import readCovarianceMatrixFile from mtSet.pycore.utils.read_utils import readBimFile from mtSet.pycore.external.limix import plink_reader def genPhenoCube(sim,Xr,vTotR=4e-3,nCausalR=10,pCommonR=0.8,vTotBg=0.4,pHidd=0.6,pCommon=0.8): # region nCommonR = int(SP.around(nCausalR*pCommonR)) # background vCommonBg = pCommon*vTotBg # noise vTotH = pHidd*(1-vTotR-vTotBg) vTotN = (1-pHidd)*(1-vTotR-vTotBg) vCommonH = pCommon*vTotH all_settings = { 'vTotR':vTotR,'nCommonR':nCommonR,'nCausalR':nCausalR, 'vTotBg':vTotBg,'vCommonBg':vCommonBg,'pCausalBg':1.,'use_XX':True, 'vTotH':vTotH,'vCommonH':vCommonH,'nHidden':10, 'vTotN':vTotN,'vCommonN':0.} Y,info = sim.genPheno(Xr,**all_settings) return Y,info def simPheno(options): print 'importing covariance matrix' if options.cfile is None: options.cfile=options.bfile XX = readCovarianceMatrixFile(options.cfile,readEig=False)['K'] print 'simulating phenotypes' SP.random.seed(options.seed) simulator = sim.CSimulator(bfile=options.bfile,XX=XX,P=options.nTraits) Xr,region = simulator.getRegion(chrom_i=options.chrom,size=options.windowSize,min_nSNPs=options.nCausalR,pos_min=options.pos_min,pos_max=options.pos_max) Y,info = genPhenoCube(simulator,Xr,vTotR=options.vTotR,nCausalR=options.nCausalR,pCommonR=options.pCommonR,vTotBg=options.vTotBg,pHidd=options.pHidden,pCommon=options.pCommon) print 'exporting pheno file' if options.pfile is not None: outdir = os.path.split(options.pfile)[0] if not os.path.exists(outdir): os.makedirs(outdir) else: identifier = '_seed%d_nTraits%d_wndSize%d_vTotR%.2f_nCausalR%d_pCommonR%.2f_vTotBg%.2f_pHidden%.2f_pCommon%.2f'%(options.seed,options.nTraits,options.windowSize,options.vTotR,options.nCausalR,options.pCommonR,options.vTotBg,options.pHidden,options.pCommon) options.pfile = os.path.split(options.bfile)[-1] + '%s'%identifier pfile = options.pfile + '.phe' rfile = options.pfile + '.phe.region' SP.savetxt(pfile,Y) SP.savetxt(rfile,region)
94 Acres. Wooded with mature hardwoods and pines. Some high and dry and some wet. Frontage on paved road. South of Hwy 90 and I-10. Short distance to town and I-10 Exchange. Just North of upcoming New International Airport in Panama City, Florida. Great investment.
#!/usr/bin/env python3 from fractions import gcd from time import sleep """ Use the frickin' binomial expansion. Problem solved. """ def get_cyclic_group(seed, modifier): current=seed+modifier cyclic_group=[1, current] mod=seed**2 counter=2 while True: if counter%2==0: next_element=(cyclic_group[-2]+2*current)%mod else: next_element=(cyclic_group[-2]-2*current)%mod if next_element in (cyclic_group[0], cyclic_group[1]): return cyclic_group cyclic_group.append(next_element) counter+=1 def lcm(a,b): if a%b==0: return a elif b%a==0: return b else: return (a*b)//gcd(a,b) def combine_groups(group_a, group_b, mod): a=len(group_a) b=len(group_b) n=lcm(a, b) combined_group=[] for i in range(n): combined_group.append((group_a[i%a]+group_b[i%b])%mod) return combined_group def get_r_max(n): mod=n**2 a=get_cyclic_group(n-1, -1) b=get_cyclic_group(n+1, 1) return max(combine_groups(a,b,mod)) def main(lower=3, upper=1000): return sum(get_r_max(i) for i in range(lower, upper+1))
Charnwood Forest represents elegant apartment living, with special consideration given to the elderly, the developmentally disabled and the handicapped. A community of contemporary apartments for people who enjoy and appreciate fine living. Of special significance at Charnwood Forest is the convenience and security!
import numpy as np import scipy.sparse as ss from sparray import FlatSparray class Construction2D(object): def setup(self): num_rows, num_cols = 3000, 4000 self.spm = ss.rand(num_rows, num_cols, density=0.1, format='coo') self.arr = self.spm.A self.data = self.spm.data self.indices = self.spm.row * num_cols + self.spm.col self.spm_csr = self.spm.tocsr() def time_init(self): FlatSparray(self.indices, self.data, shape=self.arr.shape) def time_from_ndarray(self): FlatSparray.from_ndarray(self.arr) def time_from_spmatrix_coo(self): FlatSparray.from_spmatrix(self.spm) def time_from_spmatrix_csr(self): FlatSparray.from_spmatrix(self.spm_csr) class ConstructionND(object): params = [[(1200000,), (1200,1000), (120,100,100), (20,30,40,50)]] param_names = ['shape'] def setup(self, shape): nnz = 10000 size = np.prod(shape) self.indices = np.random.choice(size, nnz, replace=False) self.sorted_indices = np.sort(self.indices) self.data = np.ones(nnz, dtype=float) arr = np.zeros(size, dtype=float) arr[self.sorted_indices] = 1 self.arr = arr.reshape(shape) def time_init(self, shape): FlatSparray(self.indices, self.data, shape=shape) def time_canonical_init(self, shape): FlatSparray(self.sorted_indices, self.data, shape=shape, is_canonical=True) def time_from_ndarray(self, shape): FlatSparray.from_ndarray(self.arr)
WASHINGTON (Reuters) - AngioDynamics Inc has agreed to pay the U.S. government $12.5 million to resolve allegations it caused healthcare providers to submit false claims to federal healthcare programs over the use of two medical devices, the Justice Department said on Wednesday. The New York-based medical device maker will pay $11.5 million over allegations it was the distributor for Biocompatibles Plc of the LC Bead for use as a drug-delivery device in combination with chemotherapy drugs from May 2006 through December 2011, the department said in a statement. It will pay $1 million to resolve allegations that the company caused false claims to be submitted to federal healthcare programs in connection with the use of the PVAK, later renamed the 400 micron kit, the department said.
import os from hippy.builtin import (wrap_method, Optional, ThisUnwrapper, handle_as_exception, StreamContextArg, Nullable) from hippy.objects.instanceobject import W_InstanceObject from hippy.objects.intobject import W_IntObject from hippy.objects.resources.file_resource import W_FileResource from hippy.objects.resources.dir_resource import W_DirResource from hippy.error import PHPException from hippy.builtin_klass import def_class, GetterSetterWrapper from hippy.module.spl.interface import k_SeekableIterator, k_RecursiveIterator from hippy.module.standard.file.funcs import (_is_dir, _is_file, _is_link, _is_executable, _is_readable, _is_writable, _filetype, _fseek, _fstat, _fopen, _basename, FopenError) from hippy import rpath from hippy import consts from hippy.module.spl.exception import ( k_LogicException, k_RuntimeException, k_UnexpectedValueException) class W_SplFileInfo(W_InstanceObject): def clone(self, interp, contextclass): w_res = W_InstanceObject.clone(self, interp, contextclass) assert isinstance(w_res, W_SplFileInfo) w_res.file_name = self.file_name w_res.path_name = self.path_name return w_res class W_SplFileObject(W_SplFileInfo): def clone(self, interp, contextclass): w_res = W_InstanceObject.clone(self, interp, contextclass) assert isinstance(w_res, W_SplFileObject) w_res.file_name = self.file_name w_res.path_name = self.path_name w_res.delimiter = self.delimiter w_res.enclosure = self.enclosure w_res.open_mode = self.open_mode return w_res @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), str], name='SplFileInfo::__construct') def construct(interp, this, file_name): this.file_name = file_name this.path_name = rpath.realpath(file_name) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::__toString') def spl_toString(interp, this): return interp.space.wrap(this.file_name) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), Optional(str)], name='SplFileInfo::getBasename') def get_basename(interp, this, suffix=''): return _basename(interp.space, this.file_name, suffix) def _extension(interp, filename): name_split = filename.rsplit('.', 1) if len(name_split) == 2: filename, extension = name_split else: extension = '' return interp.space.wrap(extension) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getExtension') def get_extension(interp, this): path = this.file_name filename = rpath.split(path)[1] return _extension(interp, filename) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getFilename') def get_filename(interp, this): return _get_filename(interp, this) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getPath') def get_path(interp, this): parts = this.file_name.split('/') parts.pop() path = '' for i in parts: path += i + '/' path = path.rstrip('/') return interp.space.wrap(path) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getPathname') def get_pathname(interp, this): return interp.space.wrap(this.file_name) def _get_group(interp, filename): res = os.stat(filename).st_gid return interp.space.wrap(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getGroup', error_handler=handle_as_exception) def get_group(interp, this): filename = this.file_name if not filename: return interp.space.w_False try: return _get_group(interp, filename) except OSError: interp.throw("SplFileInfo::getGroup(): stat failed for %s" % filename, klass=k_RuntimeException) def _get_inode(interp, filename): res = os.stat(filename).st_ino return interp.space.wrap(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getInode', error_handler=handle_as_exception) def get_inode(interp, this): filename = this.file_name if not filename: return interp.space.w_False try: return _get_inode(interp, filename) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getInode(): stat failed for %s" % filename)])) def _get_owner(interp, filename): res = os.stat(filename).st_uid return interp.space.wrap(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getOwner', error_handler=handle_as_exception) def get_owner(interp, this): filename = this.file_name if not filename: return interp.space.w_False try: return _get_owner(interp, filename) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getOwner(): stat failed for %s" % filename)])) def _get_perms(interp, filename): res = os.stat(filename).st_mode return interp.space.wrap(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getPerms', error_handler=handle_as_exception) def get_perms(interp, this): filename = this.file_name if not filename: return interp.space.w_False try: return _get_perms(interp, filename) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getPerms(): stat failed for %s" % filename)])) def _get_size(interp, filename): res = os.stat(filename).st_size return interp.space.wrap(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getSize', error_handler=handle_as_exception) def get_size(interp, this): filename = this.file_name if not filename: return interp.space.w_False try: return _get_size(interp, filename) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getSize(): stat failed for %s" % filename)])) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getType', error_handler=handle_as_exception) def get_type(interp, this): filename = this.file_name if not filename: return interp.space.w_False try: return _filetype(interp.space, filename) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getType(): stat failed for %s" % filename)])) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::isDir') def is_dir(interp, this): filename = this.file_name assert filename is not None return _is_dir(interp.space, filename) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::isLink') def is_link(interp, this): filename = this.file_name assert filename is not None return _is_link(interp.space, filename) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::isExecutable') def is_executable(interp, this): return _is_executable(interp.space, this.file_name) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::isFile') def is_file(interp, this): return _is_file(interp.space, this.file_name) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::isReadable') def is_readable(interp, this): return _is_readable(interp.space, this.file_name) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::isWritable') def is_writable(interp, this): return _is_writable(interp.space, this.file_name) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getATime', error_handler=handle_as_exception) def getatime(interp, this): filename = this.file_name assert filename is not None try: res = os.stat(filename).st_atime return interp.space.wrap(int(res)) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getATime(): " "stat failed for %s" % filename)])) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getCTime', error_handler=handle_as_exception) def getctime(interp, this): filename = this.file_name assert filename is not None try: res = os.stat(filename).st_ctime return interp.space.wrap(int(res)) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getCTime(): " "stat failed for %s" % this.file_name)])) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getMTime', error_handler=handle_as_exception) def getmtime(interp, this): filename = this.file_name assert filename is not None try: res = os.stat(filename).st_mtime return interp.space.wrap(int(res)) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getMTime(): " "stat failed for %s" % this.file_name)])) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getRealPath') def get_realpath(interp, this): try: path = rpath.realpath(this.file_name) return interp.space.wrap(path) except OSError: return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo)], name='SplFileInfo::getLinkTarget', error_handler=handle_as_exception) def get_linktarget(interp, this): filename = this.file_name assert filename is not None try: return interp.space.wrap(os.readlink(filename)) except OSError, e: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::getLinkTarget(): %s" % os.strerror(e.errno))])) @wrap_method(['interp', ThisUnwrapper(W_SplFileInfo), Optional(str), Optional(bool), Optional(Nullable(StreamContextArg(None)))], name='SplFileInfo::openFile', error_handler=handle_as_exception) def openfile(interp, this, open_mode='r', use_include_path=False, w_ctx=None): if open_mode == '': raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::openFile(): Invalid parameters")])) args = [interp.space.wrap(this.file_name), interp.space.wrap(open_mode), interp.space.wrap(use_include_path)] if w_ctx: if not interp.space.is_resource(w_ctx): raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::openFile() expects " "parameter 3 to be resource, %s given" % interp.space.get_type_name(w_ctx.tp).lower())])) args.append(w_ctx) try: file_object = SplFileObjectClass.call_args(interp, args) return file_object except OSError, e: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileInfo::openFile(): %s" % os.strerror(e.errno))])) def _get_pathname(interp, this): return interp.space.wrap(this.path_name) def _set_pathname(interp, this, value): raise NotImplementedError() def _get_filename(interp, this): if this.file_name: i = this.file_name.rfind('/') + 1 assert i >= 0 return interp.space.wrap(this.file_name[i:]) def _set_filename(interp, this, value): raise NotImplementedError() k_SplFileInfo = def_class( 'SplFileInfo', methods=[construct, spl_toString, get_basename, get_extension, get_filename, get_path, get_pathname, get_group, get_inode, get_owner, get_perms, get_size, get_type, is_dir, is_link, is_executable, is_file, is_readable, is_writable, getatime, getctime, getmtime, get_realpath, get_linktarget, openfile], properties=[GetterSetterWrapper(_get_pathname, _set_pathname, "pathName", consts.ACC_PRIVATE), GetterSetterWrapper(_get_filename, _set_filename, "fileName", consts.ACC_PRIVATE), ], instance_class=W_SplFileInfo) SFO_DROP_NEW_LINE = 1 SFO_READ_AHEAD = 2 SFO_SKIP_EMPTY = 4 SFO_READ_CSV = 8 def _sfo_readline(interp, sfo): if sfo.open_mode not in ('w', 'a', 'x', 'c'): return sfo.w_res.readline(sfo.flags & SFO_DROP_NEW_LINE) else: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap("SplFileObject: File cannot be read")])) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), str, Optional(str), Optional(bool), Optional(Nullable(StreamContextArg(None)))], name='SplFileObject::__construct', error_handler=handle_as_exception) def sfo_construct(interp, this, filename, open_mode='r', use_include_path=False, w_ctx=None): this.file_name = filename this.path_name = rpath.realpath(filename) this.delimiter = "," this.enclosure = '"' this.flags = 0 this.open_mode = open_mode this.use_include_path = use_include_path this.w_res = None this.max_line_len = 0 if w_ctx: if not interp.space.is_resource(w_ctx): raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileObject::__construct() expects " "parameter 4 to be resource, %s given" % interp.space.get_type_name(w_ctx.tp).lower())])) assert filename is not None if os.path.isdir(filename): raise interp.throw("Cannot use SplFileObject with directories", klass=k_LogicException) try: this.w_res = _fopen(interp.space, filename, this.open_mode, use_include_path, w_ctx) if this.w_res == interp.space.w_False: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileObject::__construct(): Failed to open stream")])) except FopenError as e: raise PHPException(k_RuntimeException.call_args(interp, [interp.space.wrap(e.reasons.pop())])) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::rewind') def sfo_rewind(interp, this): try: this.w_res.rewind() except OSError, e: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileObject::rewind(): %s" % os.strerror(e.errno))])) if this.flags & SFO_READ_AHEAD: _sfo_readline(interp, this) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::valid') def sfo_valid(interp, this): return interp.space.newbool(not this.w_res.feof()) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), int], name='SplFileObject::seek') def sfo_seek(interp, this, line_pos): if line_pos < 0: raise interp.throw("SplFileObject::seek(): Can't seek file %s to " "negative line %d" % (this.file_name, line_pos), klass=k_LogicException) this.w_res.seek_to_line(line_pos, this.flags & SFO_DROP_NEW_LINE) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::getChildren') def sfo_get_children(interp, this): return interp.space.w_Null @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::hasChildren') def sfo_has_children(interp, this): return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), str, Optional(int)], name='SplFileObject::fwrite') def sfo_fwrite(interp, this, data, length=-1): try: if length > 0: n = this.w_res.write(data, length) else: n = this.w_res.writeall(data) this.w_res.flush() return interp.space.newint(n) except IOError: return interp.space.w_Null except ValueError: return interp.space.w_Null @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fgetc') def sfo_fgetc(interp, this): w_res = this.w_res assert isinstance(w_res, W_FileResource) res = w_res.read(1) if w_res.feof(): return interp.space.w_False if res == os.linesep: w_res.cur_line_no += 1 return interp.space.newstr(res) def _fgets(interp, this): line = _sfo_readline(interp, this) w_res = this.w_res assert isinstance(w_res, W_FileResource) if not line: w_res.eof = True return interp.space.w_False return interp.space.newstr(line) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), 'args_w'], name='SplFileObject::fgets', error_handler=handle_as_exception) def sfo_fgets(interp, this, args_w=[]): if len(args_w) != 0: interp.space.ec.warn("SplFileObject::fgets() expects exactly 0 " "parameters, %d given" % len(args_w)) return interp.space.w_Null try: return _fgets(interp, this) except IOError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileObject::fgets(): File cannot be read")])) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::getCurrentLine', error_handler=handle_as_exception) def sfo_get_current_line(interp, this): try: return _fgets(interp, this) except IOError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "SplFileObject::fgets(): File cannot be read")])) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::key') def sfo_key(interp, this): w_res = this.w_res assert isinstance(w_res, W_FileResource) return interp.space.newint(w_res.cur_line_no) def _current(interp, this): w_res = this.w_res assert isinstance(w_res, W_FileResource) res = w_res.cur_line if not res: res = _sfo_readline(interp, this) return interp.space.wrap(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::current') def sfo_current(interp, this): return _current(interp, this) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::__toString') def sfo_tostring(interp, this): return _current(interp, this) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::next') def sfo_next(interp, this): w_res = this.w_res assert isinstance(w_res, W_FileResource) w_res.cur_line = None if this.flags & SFO_READ_AHEAD: _sfo_readline(interp, this) w_res.cur_line_no += 1 @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::eof') def sfo_eof(interp, this): return interp.space.newbool(this.w_res.feof()) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fflush') def sfo_fflush(interp, this): res = this.w_res.flush() return interp.space.newbool(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fstat') def sfo_fstat(interp, this): return _fstat(interp.space, this.w_res) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::ftell') def sfo_ftell(interp, this): pos = this.w_res.tell() return interp.space.newint(pos) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), int], name='SplFileObject::ftruncate') def sfo_ftruncate(interp, this, size): res = this.w_res.truncate(size) return interp.space.newbool(res) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), int, Optional(int)], name='SplFileObject::fseek') def sfo_fseek(interp, this, offset, whence=0): return _fseek(interp.space, this.w_res, offset, whence) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), int, Optional(int)], name='SplFileObject::fpassthru') def sfo_fpassthru(interp, this, offset, whence=0): bytes_thru = this.w_res.passthru() return interp.space.newint(bytes_thru) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::getMaxLineLen') def sfo_get_max_line_len(interp, this): return interp.space.newint(this.max_line_len) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), int], name='SplFileObject::setMaxLineLen', error_handler=handle_as_exception) def sfo_set_max_line_len(interp, this, max_len): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fgetss') def sfo_fgetss(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fgetcsv') def sfo_fgetcsv(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fputcsv') def sfo_fputcsv(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::flock') def sfo_flock(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::fscanf') def sfo_fscanf(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::getCsvControl') def sfo_get_csv_control(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::setCsvControl') def sfo_set_csv_control(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_SplFileObject)], name='SplFileObject::getFlags') def sfo_get_flags(interp, this): return interp.space.wrap(this.flags) @wrap_method(['interp', ThisUnwrapper(W_SplFileObject), int], name='SplFileObject::setFlags') def sfo_set_flags(interp, this, flags): this.flags = flags def _get_openmode(interp, this): return interp.space.wrap(this.open_mode) def _set_openmode(interp, this, w_value): raise NotImplementedError() def _get_delimiter(interp, this): return interp.space.wrap(this.delimiter) def _set_delimiter(interp, this, w_value): raise NotImplementedError() def _get_enclosure(interp, this): return interp.space.wrap(this.enclosure) def _set_enclosure(interp, this, w_value): raise NotImplementedError() SplFileObjectClass = def_class( 'SplFileObject', [sfo_construct, sfo_rewind, sfo_valid, sfo_key, sfo_current, sfo_next, sfo_seek, sfo_get_children, sfo_has_children, sfo_fwrite, sfo_eof, sfo_fgets, sfo_fgetc, sfo_tostring, sfo_get_max_line_len, sfo_fgetss, sfo_set_max_line_len, sfo_fflush, sfo_fgetcsv, sfo_flock, sfo_fputcsv, sfo_fscanf, sfo_fseek, sfo_fstat, sfo_ftell, sfo_ftruncate, sfo_get_csv_control, sfo_set_csv_control, sfo_get_flags, sfo_set_flags, sfo_get_current_line, sfo_fpassthru], properties=[GetterSetterWrapper(_get_openmode, _set_openmode, "openMode", consts.ACC_PRIVATE), GetterSetterWrapper(_get_delimiter, _set_delimiter, "delimiter", consts.ACC_PRIVATE), GetterSetterWrapper(_get_enclosure, _set_enclosure, "enclosure", consts.ACC_PRIVATE)], constants=[ ('DROP_NEW_LINE', W_IntObject(SFO_DROP_NEW_LINE)), ('READ_AHEAD', W_IntObject(SFO_READ_AHEAD)), ('SKIP_EMPTY', W_IntObject(SFO_SKIP_EMPTY)), ('READ_CSV', W_IntObject(SFO_READ_CSV))], implements=[k_RecursiveIterator, k_SeekableIterator], instance_class=W_SplFileObject, extends=k_SplFileInfo,) class W_DirectoryIterator(W_SplFileInfo): w_dir_res = None def clone(self, interp, contextclass): w_res = W_InstanceObject.clone(self, interp, contextclass) assert isinstance(w_res, W_DirectoryIterator) w_res.path_name = self.path_name w_res.w_dir_res = self.w_dir_res return w_res @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator), str], name='DirectoryIterator::__construct', error_handler=handle_as_exception) def di_construct(interp, this, path): if path == "": raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "Directory name must not be empty.")])) this.path = path this.file_name = path this.index = 0 if not os.path.isdir(path): raise PHPException(k_UnexpectedValueException.call_args( interp, [interp.space.wrap( "DirectoryIterator::__construct(%s): failed to open dir: No " "such file or directory" % path)])) try: w_dir = W_DirResource(interp.space, path) w_dir_res = w_dir.open() if not isinstance(w_dir_res, W_DirResource): raise OSError # rare case, but annotation fix this.w_dir_res = w_dir_res this.path_name = _di_pathname(this) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "DirectoryIterator::__construct(): error while opening stream" )])) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::__toString') def di_tostring(interp, this): return interp.space.newstr(this.w_dir_res.items[this.w_dir_res.index]) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::current') def di_current(interp, this): return this @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::key') def di_key(interp, this): return interp.space.newint(this.w_dir_res.index) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::next') def di_next(interp, this): this.w_dir_res.read() @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::rewind') def di_rewind(interp, this): return this.w_dir_res.rewind() @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator), int], name='DirectoryIterator::seek') def di_seek(interp, this, pos): this.w_dir_res.seek_to_item(pos) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::valid') def di_valid(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: return interp.space.w_True else: return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getFilename') def di_get_filename(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: res = this.w_dir_res.items[this.w_dir_res.index] else: res = '' return interp.space.newstr(res) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator), Optional(str)], name='DirectoryIterator::getBasename') def di_get_basename(interp, this, suffix=''): if this.w_dir_res.index < this.w_dir_res.no_of_items: filename = this.w_dir_res.items[this.w_dir_res.index] return _basename(interp.space, filename, suffix) else: return interp.space.newstr('') @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getExtension') def di_get_extension(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: filename = this.w_dir_res.items[this.w_dir_res.index] return _extension(interp, filename) else: return interp.space.newstr('') @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getPath') def di_get_path(interp, this): path = this.path return interp.space.newstr(path) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getPathname') def di_get_pathname(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: return interp.space.newstr(_di_pathname(this)) else: return interp.space.w_False def _di_pathname(di): return di.path + '/' + di.w_dir_res.items[di.w_dir_res.index] @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getGroup') def di_get_group(interp, this): path = this.path assert path is not None return _get_group(interp, path) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getInode') def di_get_inode(interp, this): path = this.path assert path is not None return _get_inode(interp, path) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getOwner') def di_get_owner(interp, this): path = this.path assert path is not None return _get_owner(interp, path) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getPerms') def di_get_perms(interp, this): path = this.path assert path is not None return _get_perms(interp, path) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getSize') def di_get_size(interp, this): path = this.path assert path is not None return _get_size(interp, path) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getType') def di_get_type(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path return _filetype(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isDir') def di_is_dir(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path assert item is not None return _is_dir(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isDot') def di_is_dot(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: if this.w_dir_res.items[this.w_dir_res.index] in ('.', '..'): return interp.space.w_True return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isFile') def di_is_file(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path return _is_file(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isExecutable') def di_is_executable(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path return _is_executable(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isReadable') def di_is_readable(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path return _is_readable(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isWritable') def di_is_writable(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path return _is_writable(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::isLink') def di_is_link(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path assert item is not None return _is_link(interp.space, item) @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getATime') def di_getatime(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path assert item is not None try: res = os.stat(item).st_atime return interp.space.wrap(int(res)) except OSError: return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getCTime') def di_getctime(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path assert item is not None try: res = os.stat(item).st_ctime return interp.space.wrap(int(res)) except OSError: return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_DirectoryIterator)], name='DirectoryIterator::getMTime') def di_getmtime(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: item = _di_pathname(this) else: item = this.path assert item is not None try: res = os.stat(item).st_mtime return interp.space.wrap(int(res)) except OSError: return interp.space.w_False k_DirectoryIterator = def_class( 'DirectoryIterator', [di_construct, di_current, di_key, di_next, di_rewind, di_seek, di_valid, di_get_filename, di_get_basename, di_get_extension, di_get_path, di_get_pathname, di_get_group, di_get_inode, di_get_owner, di_get_perms, di_get_size, di_get_type, di_is_dir, di_is_dot, di_is_file, di_is_link, di_is_executable, di_is_readable, di_is_writable, di_getatime, di_getctime, di_getmtime, di_tostring], implements=[k_SeekableIterator], instance_class=W_DirectoryIterator, extends=k_SplFileInfo,) FI_CURRENT_AS_PATHNAME = 32 FI_CURRENT_AS_FILEINFO = 0 FI_CURRENT_AS_SELF = 16 FI_CURRENT_MODE_MASK = 240 FI_KEY_AS_PATHNAME = 0 FI_KEY_AS_FILENAME = 256 FI_FOLLOW_SYMLINKS = 512 FI_KEY_MODE_MASK = 3840 FI_NEW_CURRENT_AND_KEY = 256 FI_SKIP_DOTS = 4096 FI_UNIX_PATHS = 8192 FI_OTHER_MODE_MASK = 12288 class W_FilesystemIterator(W_DirectoryIterator): w_dir_res = None def clone(self, interp, contextclass): w_res = W_InstanceObject.clone(self, interp, contextclass) assert isinstance(w_res, W_FilesystemIterator) w_res.path_name = self.path_name w_res.w_dir_res = self.w_dir_res w_res.flags = self.flags w_res.path = self.path return w_res @wrap_method(['interp', ThisUnwrapper(W_FilesystemIterator), str, Optional(int)], name='FilesystemIterator::__construct', error_handler=handle_as_exception) def fi_construct(interp, this, path, flags= FI_KEY_AS_PATHNAME | FI_CURRENT_AS_FILEINFO | FI_SKIP_DOTS): if not os.path.isdir(path): raise PHPException(k_UnexpectedValueException.call_args( interp, [interp.space.wrap( "FilesystemIterator::__construct(%s): failed to open dir: No " "such file or directory" % path)])) this.flags = flags | FI_SKIP_DOTS # PHP wants us to do this. this.path = path this.file_name = path this.index = 0 try: w_dir = W_DirResource(interp.space, path, this.flags & FI_SKIP_DOTS) w_dir_res = w_dir.open() if not isinstance(w_dir_res, W_DirResource): raise OSError this.w_dir_res = w_dir_res this.path_name = _di_pathname(this) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "FilesystemIterator::__construct(): error while opening stream" )])) @wrap_method(['interp', ThisUnwrapper(W_FilesystemIterator)], name='FilesystemIterator::current') def fi_current(interp, this): if this.flags & FI_CURRENT_AS_SELF: return this if this.flags & FI_CURRENT_AS_PATHNAME: pathname = _di_pathname(this) return interp.space.newstr(pathname) else: filename = _di_pathname(this) file_info = k_SplFileInfo.call_args(interp, [interp.space.wrap(filename)]) return file_info @wrap_method(['interp', ThisUnwrapper(W_FilesystemIterator)], name='FilesystemIterator::key') def fi_key(interp, this): if this.flags & FI_KEY_AS_FILENAME: filename = this.w_dir_res.items[this.w_dir_res.index] return interp.space.wrap(filename) else: pathname = _di_pathname(this) return interp.space.newstr(pathname) @wrap_method(['interp', ThisUnwrapper(W_FilesystemIterator)], name='FilesystemIterator::getFlags') def fi_get_flags(interp, this): flags = this.flags & (FI_KEY_MODE_MASK | FI_CURRENT_MODE_MASK | FI_OTHER_MODE_MASK) return interp.space.newint(flags) @wrap_method(['interp', ThisUnwrapper(W_FilesystemIterator), int], name='FilesystemIterator::setFlags') def fi_set_flags(interp, this, flags): this.flags &= ~(FI_KEY_MODE_MASK | FI_CURRENT_MODE_MASK | FI_OTHER_MODE_MASK) this.flags |= ((FI_KEY_MODE_MASK | FI_CURRENT_MODE_MASK | FI_OTHER_MODE_MASK) & flags) k_FilesystemIterator = def_class( 'FilesystemIterator', [fi_construct, fi_current, fi_key, fi_get_flags, fi_set_flags], constants=[ ('CURRENT_AS_PATHNAME', W_IntObject(FI_CURRENT_AS_PATHNAME)), ('CURRENT_AS_FILEINFO', W_IntObject(FI_CURRENT_AS_FILEINFO)), ('CURRENT_AS_SELF', W_IntObject(FI_CURRENT_AS_SELF)), ('CURRENT_MODE_MASK', W_IntObject(FI_CURRENT_MODE_MASK)), ('KEY_AS_PATHNAME', W_IntObject(FI_KEY_AS_PATHNAME)), ('KEY_AS_FILENAME', W_IntObject(FI_KEY_AS_FILENAME)), ('FOLLOW_SYMLINKS', W_IntObject(FI_FOLLOW_SYMLINKS)), ('KEY_MODE_MASK', W_IntObject(FI_KEY_MODE_MASK)), ('NEW_CURRENT_AND_KEY', W_IntObject(FI_NEW_CURRENT_AND_KEY)), ('SKIP_DOTS', W_IntObject(FI_SKIP_DOTS)), ('UNIX_PATHS', W_IntObject(FI_UNIX_PATHS)), ('OTHER_MODE_MASK', W_IntObject(FI_OTHER_MODE_MASK))], implements=[k_SeekableIterator], instance_class=W_FilesystemIterator, extends=k_DirectoryIterator,) class W_RecursiveDirectoryIterator(W_FilesystemIterator): w_dir_res = None def clone(self, interp, contextclass): w_res = W_InstanceObject.clone(self, interp, contextclass) assert isinstance(w_res, W_RecursiveDirectoryIterator) w_res.path_name = self.path_name w_res.w_dir_res = self.w_dir_res w_res.flags = self.flags w_res.path = self.path return w_res @wrap_method(['interp', ThisUnwrapper(W_RecursiveDirectoryIterator), str, Optional(int)], name='RecursiveDirectoryIterator::__construct', error_handler=handle_as_exception) def rdi_construct(interp, this, path, flags= FI_KEY_AS_PATHNAME | FI_CURRENT_AS_FILEINFO): if not os.path.isdir(path): raise PHPException(k_UnexpectedValueException.call_args( interp, [interp.space.wrap( "RecursiveDirectoryIterator::__construct(%s): failed to open dir: No " "such file or directory" % path)])) this.flags = flags this.path = path this.file_name = path this.index = 0 try: w_dir = W_DirResource(interp.space, path, this.flags & FI_SKIP_DOTS) w_dir_res = w_dir.open() if not isinstance(w_dir_res, W_DirResource): raise OSError this.w_dir_res = w_dir_res this.path_name = _di_pathname(this) except OSError: raise PHPException(k_RuntimeException.call_args( interp, [interp.space.wrap( "RecursiveDirectoryIterator::__construct(): error while opening stream" )])) @wrap_method(['interp', ThisUnwrapper(W_RecursiveDirectoryIterator)], name='RecursiveDirectoryIterator::hasChildren') def rdi_has_children(interp, this): if this.w_dir_res.index < this.w_dir_res.no_of_items: if this.w_dir_res.items[this.w_dir_res.index] not in ('.', '..'): item = _di_pathname(this) assert item is not None return _is_dir(interp.space, item) return interp.space.w_False @wrap_method(['interp', ThisUnwrapper(W_RecursiveDirectoryIterator)], name='RecursiveDirectoryIterator::getChildren') def rdi_get_children(interp, this): if this.flags & FI_CURRENT_AS_PATHNAME: if this.w_dir_res.index < this.w_dir_res.no_of_items: pathname = _di_pathname(this) return interp.space.newstr(pathname) else: return interp.space.newstr(this.path + '/') else: if this.w_dir_res.index < this.w_dir_res.no_of_items: filename = _di_pathname(this) sub_dir_iter = k_RecursiveDirectoryIterator.call_args(interp, [interp.space.wrap(filename)]) return sub_dir_iter else: return this @wrap_method(['interp', ThisUnwrapper(W_RecursiveDirectoryIterator)], name='RecursiveDirectoryIterator::getSubPath') def rdi_get_subpath(interp, this): raise NotImplementedError @wrap_method(['interp', ThisUnwrapper(W_RecursiveDirectoryIterator)], name='RecursiveDirectoryIterator::getSubPathname') def rdi_get_subpathname(interp, this): raise NotImplementedError k_RecursiveDirectoryIterator = def_class( 'RecursiveDirectoryIterator', [rdi_construct, rdi_has_children, rdi_get_children, rdi_get_subpath, rdi_get_subpathname, ], implements=[k_SeekableIterator, k_RecursiveIterator], instance_class=W_RecursiveDirectoryIterator, extends=k_FilesystemIterator,)
The Menomonee River is one of Milwaukee's three primary rivers and is visited by people fishing, kayaking, canoeing, and boating. As you travel down the Menomonee River, you experience the Menomonee River Valley’s industrial charm and its place in history as you float past the steel dock walls that line the river. These walls created a deep channel historically used as shipping grounds for commercial goods and products that helped to build and power the city in the 18th and 19th centuries. They will also be the foreground for soon-to-be-developed riverfront land and new businesses along the river. People find many spots to fish along the Menomonee River and Burnham Canal. You can access the river at MMSD where you might catch brown trout, salmon, or steelhead. The western end of the Valley near Three Bridges Park and Miller Park offers shallow areas ideal for fly fishing. There are four canoe/kayak launches in the Menomonee River Valley. The Milwaukee Urban Water Trail is a canoe and kayak route through urban protions of the Milwaukee, Menomonee, and Kinnickinnic Rivers—with more than 25 miles of paddling! Railroad bridge at Plankinton Ave - Call 414.278.1385. Generally open 7 days a week, 6am-10pm. City-operated Plankinton Ave Bridge - Monitored remotely via Broadway bridge. Call via radio on Channel 16 or phone at 414.286.2570. The railroad bridge must be open for the city to open the Plankinton Ave bridge. City Lights Brewing Co, the Harley-Davidson Museum®, and Twisted Fisherman offer docks for those who prefer to float to their destination. All Hands Boatworks builds up youth in the greater metro-Milwaukee area through wooden boatbuilding, work experiences, and on-water activities that result in good character, academic confidence, and workforce preparation. Adult classes offered as well! All Hands Boatworks offers free community sailing on student built rowboats on Fridays during the summer.
#!/usr/bin/env python """ Creates a mpileup file from a bam file and a reference. usage: %prog [options] -p, --input1=p: bam file -o, --output1=o: Output pileup -R, --ref=R: Reference file type -n, --ownFile=n: User-supplied fasta reference file -d, --dbkey=d: dbkey of user-supplied file -x, --indexDir=x: Index directory -b, --bamIndex=b: BAM index file -B, --baq=B: use BAQ model or not -C, --mapCo=$mapCo: coefficient for downgrading mapping quality -M, --mapCap=M: Cap mapping quality -d, --readCap=d: Cap read quality -q, --mapq=q: min map quality threshold -Q, --baseq=Q: min base quality threshold -I, --callindels=I: call indels or not -i, --indels=i: Only output lines containing indels -c, --consensus=c: Call the consensus sequence using MAQ consensus model ("10-column pileup") -u, --fformat=$fformat: bcf or vcf format -T, --theta=T: Theta parameter (error dependency coefficient) -N, --hapNum=N: Number of haplotypes in sample -r, --fraction=r: Expected fraction of differences between a pair of haplotypes -P, --phredProb=I: Phred probability of an indel in sequencing/prep -X, --cmdline=$cmdline: X: additional command line options -f, --fileName=f: filename to appear in the vcf """ import os, shutil, subprocess, sys, tempfile from galaxy import eggs import pkg_resources; pkg_resources.require( "bx-python" ) from bx.cookbook import doc_optparse def stop_err( msg ): sys.stderr.write( '%s\n' % msg ) sys.exit() def check_seq_file( dbkey, GALAXY_DATA_INDEX_DIR ): seqFile = '%s/sam_fa_indices.loc' % GALAXY_DATA_INDEX_DIR seqPath = '' for line in open( seqFile ): line = line.rstrip( '\r\n' ) if line and not line.startswith( '#' ) and line.startswith( 'index' ): fields = line.split( '\t' ) if len( fields ) < 3: continue if fields[1] == dbkey: seqPath = fields[2].strip() break return seqPath def __main__(): #Parse Command Line options, args = doc_optparse.parse( __doc__ ) seqPath = check_seq_file( options.dbkey, options.indexDir ) # output version # of tool try: tmp = tempfile.NamedTemporaryFile().name tmp_stdout = open( tmp, 'wb' ) proc = subprocess.Popen( args='samtools 2>&1', shell=True, stdout=tmp_stdout ) tmp_stdout.close() returncode = proc.wait() stdout = None for line in open( tmp_stdout.name, 'rb' ): if line.lower().find( 'version' ) >= 0: stdout = line.strip() break if stdout: sys.stdout.write( 'Samtools %s\n' % stdout ) else: raise Exception except: sys.stdout.write( 'Could not determine Samtools version\n' ) #prepare file names tmpDir = tempfile.mkdtemp() tmpf0 = tempfile.NamedTemporaryFile( dir=tmpDir ) tmpf0_name = tmpf0.name tmpf0.close() tmpf0bam_name = '%s.bam' % tmpf0_name tmpf0bambai_name = '%s.bam.bai' % tmpf0_name tmpf1 = tempfile.NamedTemporaryFile( dir=tmpDir ) tmpf1_name = tmpf1.name tmpf1.close() tmpf1fai_name = '%s.fai' % tmpf1_name #link bam and bam index to working directory (can't move because need to leave original) os.symlink( options.input1, tmpf0bam_name ) os.symlink( options.bamIndex, tmpf0bambai_name ) #get parameters for mpileup command if options.baq == 'yes': baq = '' else: baq = '-B' if options.callindels == 'yes': callindels = '' else: callindels = '-I' if options.indels == 'yes': indels = '-i' else: indels = '' if options.fformat == 'pileup': fformat = '' else: fformat = '-u' opts = '%s -C %s -M %s -d %s -q %s -Q %s %s %s %s %s' % ( baq, options.mapCo, options.mapCap, options.readCap, options.mapq, options.baseq, callindels, indels, fformat, options.cmdline ) # use for debugging # # opts = '-B -C 50 -q 30 -Q 30 -u '# -r 10:20,000,000-35,000,000' # print options.cmdline #use for debugging if options.consensus == 'yes': opts += ' -c' # print opts #use for debugging # else: # print opts #use for debugging # if options.chs_cmdline == 'yes': # opts = opts # print cmdline #use for debugging # else: # opts = opts # print opts #use for debugging # opts # += ' -c -T %s -N %s -r %s -I %s' % ( options.theta, options.hapNum, options.fraction, options.phredProb ) # pileup only subset for troubleshooting: opts += -r 2:100,000-150,000 # samtools mpileup -C50 -d24 -q20 -Q30 -uf /media/DATA1/galaxy/reference_genomes/danrer7/sam_index/danrer7.fa test.bam | /home/ian/samtools-0.1.18/bcftools/bcftools view -bvcg - > var.raw.bcf #/home/ian/samtools-0.1.18/bcftools/bcftools view var.raw.bcf | vcfutils.pl varFilter -D50 > var.flt.vcf' # samtools mpileup -B -C50 -M60 -d24 -q20 -Q30 -I -i -c -T -N -r -uf /media/DATA1/galaxy/reference_genomes/danrer7/sam_index/danrer7.fa test.bam | /home/ian/samtools-0.1.18/bcftools/bcftools view -bvcg - > var.raw.bcf # -C, --mapCo=$mapCo: coefficient for downgrading mapping quality # -M, --mapCap=M: Cap mapping quality # -d, --readCap=d: Cap read quality # -q, --mapq=q: min map quality threshold # -Q, --baseq=Q: min base quality threshold # -c, --consensus=c: Call the consensus sequence using MAQ consensus model # -T, --theta=T: Theta parameter (error dependency coefficient) # -N, --hapNum=N: Number of haplotypes in sample # -r, --fraction=r: Expected fraction of differences between a pair of haplotypes # -P, --phredProb=I: Phred probability of an indel in sequencing/prep # Input Options: # -6 Assume the quality is in the Illumina 1.3+ encoding. -A Do not skip anomalous read pairs in variant calling. # -B Disable probabilistic realignment for the computation of base alignment quality (BAQ). BAQ is the Phred-scaled probability of a read # base being misaligned. Applying this option greatly helps to reduce false SNPs caused by misalignments. # -b FILE List of input BAM files, one file per line [null] # -C INT Coefficient for downgrading mapping quality for reads containing excessive mismatches. Given a read with a phred-scaled probability q of being generated from the mapped position, the new mapping quality is about sqrt((INT-q)/INT)*INT. A zero value disables this functionality; if enabled, the recommended value for BWA is 50. [0] # -d INT At a position, read maximally INT reads per input BAM. [250] # -E Extended BAQ computation. This option helps sensitivity especially for MNPs, but may hurt specificity a little bit. # -f FILE The faidx-indexed reference file in the FASTA format. The file can be optionally compressed by razip. [null] # -l FILE BED or position list file containing a list of regions or sites where pileup or BCF should be generated [null] # -q INT Minimum mapping quality for an alignment to be used [0] # -Q INT Minimum base quality for a base to be considered [13] # -r STR Only generate pileup in region STR [all sites] # Output Options: # -D Output per-sample read depth # -g Compute genotype likelihoods and output them in the binary call format (BCF). # -S Output per-sample Phred-scaled strand bias P-value # -u Similar to -g except that the output is uncompressed BCF, which is preferred for piping. # Options for Genotype Likelihood Computation (for -g or -u): # -e INT Phred-scaled gap extension sequencing error probability. Reducing INT leads to longer indels. [20] # -h INT Coefficient for modeling homopolymer errors. Given an l-long homopolymer run, the sequencing error of an indel of size s is modeled as INT*s/l. [100] # -I Do not perform INDEL calling # -L INT Skip INDEL calling if the average per-sample depth is above INT. [250] # -o INT Phred-scaled gap open sequencing error probability. Reducing INT leads to more indel calls. [40] # -P STR Comma dilimited list of platforms (determined by @RG-PL) from which indel candidates are obtained. It is recommended to collect indel candidates from sequencing technologies that have low indel error rate such as ILLUMINA. [all] #where the -D option sets the maximum read depth to call a SNP. SAMtools acquires sample information from the SM tag in the @RG header lines. One alignment file can contain multiple samples; reads from one sample can also be distributed in different alignment files. SAMtools will regroup the reads anyway. In addition, if no @RG lines are present, each alignment file is taken as one sample. # Tuning the parameters #One should consider to apply the following parameters to mpileup in different scenarios: # Apply -C50 to reduce the effect of reads with excessive mismatches. This aims to fix overestimated mapping quality and appears to be preferred for BWA-short. # Given multiple technologies, apply -P to specify which technologies to use for collecting initial INDEL candidates. It is recommended to find INDEL candidates from technologies with low INDEL error rate, such as Illumina. When this option is in use, the value(s) following the option must appear in the PL tag in the @RG header lines. # Apply -D and -S to keep per-sample read depth and strand bias. This is preferred if there are more than one samples at high coverage. # Adjust -m and -F to control when to initiate indel realignment (requiring r877+). Samtools only finds INDELs where there are sufficient reads containing the INDEL at the same position. It does this to avoid excessive realignment that is computationally demanding. The default works well for many low-coverage samples but not for, say, 500 exomes. In the latter case, using -m 3 -F 0.0002 (3 supporting reads at minimum 0.02% frequency) is necessary to find singletons. # Apply -A to use anomalous read pairs in mpileup, which are not used by default (requring r874+). #prepare basic mpileup command if options.fformat == 'vcf': cmd = 'samtools mpileup %s -f %s %s | bcftools view -vcg - > %s' #| bcftools view -bvcg - > RAL_samtools.raw.bcf % ( opts, tmpf1_name, tmpf0bam_name, options.output1 ) #print cmd # use for debugging if options.fileName != "": cmd = "samtools mpileup %s -f %s %s | bcftools view -vcg - | sed 's|"+ tmpf0bam_name + "|" + options.fileName + "|' > %s" else: cmd = 'samtools mpileup %s -f %s %s > %s' try: # have to nest try-except in try-finally to handle 2.4 try: #index reference if necessary and prepare mpileup command if options.ref == 'indexed': if not os.path.exists( "%s.fai" % seqPath ): raise Exception, "No sequences are available for '%s', request them by reporting this error." % options.dbkey cmd = cmd % ( opts, seqPath, tmpf0bam_name, options.output1 ) print cmd # use for debugging elif options.ref == 'history': os.symlink( options.ownFile, tmpf1_name ) cmdIndex = 'samtools faidx %s' % ( tmpf1_name ) tmp = tempfile.NamedTemporaryFile( dir=tmpDir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=cmdIndex, shell=True, cwd=tmpDir, stderr=tmp_stderr.fileno() ) returncode = proc.wait() tmp_stderr.close() # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' buffsize = 1048576 try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() #did index succeed? if returncode != 0: raise Exception, 'Error creating index file\n' + stderr cmd = cmd % ( opts, tmpf1_name, tmpf0bam_name, options.output1 ) print cmd # use for debugging #perform mpileup command tmp = tempfile.NamedTemporaryFile( dir=tmpDir ).name tmp_stderr = open( tmp, 'wb' ) proc = subprocess.Popen( args=cmd, shell=True, cwd=tmpDir, stderr=tmp_stderr.fileno() ) returncode = proc.communicate() # returncode = proc.wait() tmp_stderr.close() #did it succeed? # get stderr, allowing for case where it's very large tmp_stderr = open( tmp, 'rb' ) stderr = '' buffsize = 1048576 try: while True: stderr += tmp_stderr.read( buffsize ) if not stderr or len( stderr ) % buffsize != 0: break except OverflowError: pass tmp_stderr.close() if returncode != 0: print returncode # raise Exception, stderr except Exception, e: stop_err( 'Error running Samtools mpileup tool\n' + str( e ) ) finally: #clean up temp files if os.path.exists( tmpDir ): shutil.rmtree( tmpDir ) # check that there are results in the output file if os.path.getsize( options.output1 ) > 0: sys.stdout.write( 'Converted BAM to pileup' ) else: stop_err( 'The output file is empty. Your input file may have had no matches, or there may be an error with your input file or settings.' ) if __name__ == "__main__" : __main__()
The Corpus Christi United States Marshals Service developed information that homicide suspect Derek Parra 12-01-1979 had fled the state and was in Lake Charles Louisiana. Our local US Marshals Service contacted their counterparts in Louisiana to let them know where Derek was staying. The US Marshals Service in Louisiana with the assistance of the Lake Charles Police Department and the Calcasieu Sheriff’s Office were able to place Derek into custody. The Corpus Christi Police Department obtained information that Senior Officer Norma Deleon allegedly misrepresented herself as a public servant in an off-duty capacity. An investigation was launched by the Corpus Christi Police Department Criminal Investigation Division. The Officer was placed on administrative leave, pending the outcome of the investigation. During their investigation Corpus Christi Police Department Detectives discovered evidence that Norma DeLeon had inappropriately represented herself as a public servant while attempting to conduct a welfare check. On February 6th, 2019, detectives presented the findings of the investigation to the Nueces County District Attorney’s Office, who accepted the case for prosecution. On February 07, 2019, the Nueces County District Attorney’s Office issued a warrant for Norma DeLeon, charging her with Official Oppression (Class A Misdemeanor) and Impersonating a Public Servant (3F). Norma DeLeon, a 10-year veteran of the Police Department remains on administrative leave while the department continues with the administrative review process. A local criminal defense attorney found himself on the other side of bars yesterday, after Corpus Christi Police Department Narcotics & Vice Investigators conducted an evidentiary search warrant at his residence in the 15000 block of Cruiser Street Wednesday morning. The search warrant was the culmination of a year-long joint investigation between the CCPD Narcotics & Vice Investigations Division and the Nueces County District Attorney’s Office. At approximately 8:00 AM, NVID Officers arrived at the residence and contacted the 66-year-old man as he was leaving for work. Upon detaining the suspect, John R. Perry, (DOB: 9-21-52), officers discovered he was in possession of a small amount of controlled substance and he was immediately arrested. During the execution of the search warrant, Narcotics Investigators found and seized an additional small quantity of suspected cocaine, methamphetamine and drug paraphernalia from inside the residence, along with other items of evidence. Perry was charged with possession of a controlled substance, a second-degree felony punishable by between two and twenty years in prison. Also arrested during the raid was Maria Torres (DOB:9-23-70), whom Investigators discovered had an outstanding motion to revoke warrant for possession of a controlled substance. While searching Torres, Investigators discovered a small quantity of suspected methamphetamine, for which she was additionally charged. This is an ongoing investigation by NVID Detectives and Investigators with the Nueces County District Attorney’s Office. Additional charges are possible. It is important to choose the proper child safety seat or booster for your child as the restraint type is dependent on the age, height, and weight of the child. In Texas, a person commits an offense if the person operates a passenger vehicle, transports a child who is younger than eight years of age, unless the child is taller than four feet, nine inches, and does not keep the child secured during the operation of the vehicle in a child passenger safety seat system according to the instructions of the manufacturer of the safety seat system. Answers to frequently asked questions on child safety seats. Information on how to choose the proper seat for your child and vehicle. Call 361-694-6700 & employees with the Injury Prevention at Driscoll Children’s Hospital can have your car seat inspected to ensure that it is properly installed.
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # # Copyright (C) 2015-2020 Daniel Rodriguez # # 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 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 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/>. # ############################################################################### from __future__ import (absolute_import, division, print_function, unicode_literals) import os.path import backtrader as bt class VChartFile(bt.Store): '''Store provider for Visual Chart binary files Params: - ``path`` (default:``None``): If the path is ``None`` and running under *Windows*, the registry will be examined to find the root directory of the *Visual Chart* files. ''' params = ( ('path', None), ) def __init__(self): self._path = self.p.path if self._path is None: self._path = self._find_vchart() @staticmethod def _find_vchart(): # Find VisualChart registry key to get data directory # If not found returns '' VC_KEYNAME = r'SOFTWARE\VCG\Visual Chart 6\Config' VC_KEYVAL = 'DocsDirectory' VC_DATADIR = ['Realserver', 'Data', '01'] VC_NONE = '' from backtrader.utils.py3 import winreg if winreg is None: return VC_NONE vcdir = None # Search for Directory in the usual root keys for rkey in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE,): try: vckey = winreg.OpenKey(rkey, VC_KEYNAME) except WindowsError as e: continue # Try to get the key value try: vcdir, _ = winreg.QueryValueEx(vckey, VC_KEYVAL) except WindowsError as e: continue else: break # found vcdir if vcdir is not None: # something was found vcdir = os.path.join(vcdir, *VC_DATADIR) else: vcdir = VC_NONE return vcdir def get_datapath(self): return self._path
PLEASE READ THROUGH THE FOLLOWING TERMS OF USAGE WITH GREAT CARE BEFORE ATTEMPTING TO ACCESS THE Utility Tab WEB PAGE. THOUGH THIS Utility Tab WEB PAGE IS FREE FOR ALL VISITORS TO ACCESS, THERE ARE TERMS AND CONDITIONS THAT MUST BE ADHERED TO IN ORDER TO BE GRANTED THE RIGHT TO DO SO. IF AFTER YOU HAVE REVIEWED THESE TERMS AND CONDITIONS IN FULLY, IF YOU DISAGREE WITH THE COMPILATION OF GUIDELINES, YOU ARE FORBIDDEN FROM ACCESSING THE Utility Tab WEB PAGE. You agree that you will abide by the terms and conditions as documented herein for the Utility Tab web page. These terms of usage constitute the full and total agreement between Utility Tab and you, and this terms of usage document supersedes any contemporaneous warranties, understandings, agreements and representations, with full respect to the Utility Tab web page, its content and its services which are provided by or compiled onto the Utility Tab web page, and the matter which is the subject of this terms of usage documentation. This terms of usage documentation is subject to modification at any time by Utility Tab in its sole and exclusive discretion and at any frequency without specifically notifying you. Always look back at these terms of usage to see whether or not changes have been made. If you continue to use the Utility Tab web page after the terms of usage documentation have changed, it is indicative of your continued agreement.
# instructions.py # abstract instruction set, implemented as Code # author: Christophe VG from util.check import isstring, isidentifier from util.visitor import visits, novisiting from util.types import TypedList, Any from codecanvas.base import Code, WithoutChildren, WithoutChildModification, List # Mixins class Identified(object): def get_name(self): return self.id.name name = property(get_name) class Identifier(Code): def __init__(self, name): assert isidentifier(name), "Not an Identifier: " + name self.name = name def __repr__(self): return self.name # Declarations class Constant(Identified, Code): def __init__(self, id, value, type=None): # name if isstring(id): id = Identifier(id) assert isinstance(id, Identifier), "Name should be an identifier, not" + \ id.__class__.__name__ # TODO: add some value-checking ? (to avoid havoc) if isstring(value): value = Identifier(value) if type is None: type = VoidType() assert isinstance(type, Type), "Type should be a Type, not " + \ type.__class__.__name__ super(Constant, self).__init__({"id": id, "value": value, "type": type}) self.id = id self.value = value self.type = type class Function(Identified, Code): def __init__(self, name, type=None, params=[]): # name assert not name is None, "A function needs at least a name." # TODO: extend if isstring(name): name = Identifier(name) assert isinstance(name, Identifier), "Name should be an identifier, not" + \ name.__class__.__name__ # type if type is None: type = VoidType() assert isinstance(type, Type), "Return-type should be a Type, not " + \ type.__class__.__name__ # params if isinstance(params, list): params = TypedList(Parameter, params) super(Function, self).__init__({"id":name, "type":type, "params": params}) self.id = name self.type = type self.params = params class Prototype(WithoutChildren, Function): @classmethod def from_Function(clazz, function): return Prototype(function.name, type=function.type, params=function.params) class Parameter(Identified, Code): def __init__(self, id, type=None, default=None): # name if isstring(id): id = Identifier(id) assert isinstance(id, Identifier) # type if type is None: type = VoidType() assert isinstance(type, Type) assert default == None or isinstance(default, Expression) super(Parameter, self).__init__({"id": id, "type": type, "default": default}) self.id = id self.type = type self.default = default # Statements class Statement(Code): def __init__(self, data): super(Statement, self).__init__(data) class IfStatement(WithoutChildModification, Statement): def __init__(self, expression, true_clause, false_clause=[]): assert isinstance(expression, Expression) assert isinstance(true_clause, list) assert isinstance(false_clause, list) super(IfStatement, self).__init__({"expression": expression}) self.expression = expression self.true_clause = true_clause self.false_clause = false_clause def _children(self): return [self.true_clause, self.false_clause] children = property(_children) class CaseStatement(WithoutChildModification, Statement): def __init__(self, expression, cases, consequences, case_else=None): assert isinstance(expression, Expression) assert isinstance(cases, list) assert isinstance(consequences, list) super(CaseStatement, self).__init__({"expression": expression}) self.expression = expression self.cases = cases self.consequences = consequences self.case_else = case_else def _children(self): return [self.cases, self.consequences] children = property(_children) @novisiting class MutUnOp(WithoutChildren, Statement): def __init__(self, operand): assert isinstance(operand, Variable) super(MutUnOp, self).__init__({"op": operand}) self.operand = operand def ends(self): return True class Inc(MutUnOp): pass class Dec(MutUnOp): pass @novisiting class ImmutUnOp(WithoutChildren, Statement): pass class Print(WithoutChildren, Statement): def __init__(self, string, *args): # string if isstring(string): string = StringLiteral(string) assert isinstance(string, StringLiteral) # TODO: assert args to be expressions super(Print, self).__init__({"string": string, "args": args}) self.string = string self.args = args class Import(Statement): def __init__(self, imported): # TODO: checking super(Import, self).__init__({"imported": imported}) self.imported = imported class Raise(ImmutUnOp): pass class Comment(ImmutUnOp): def __init__(self, comment): assert isstring(comment) super(Comment, self).__init__({"comment": comment}) self.comment = comment def __str__(self): return "# " + self.comment @novisiting class VarExpOp(Statement): def __init__(self, operand, expression): if isstring(operand): operand = SimpleVariable(operand) assert isinstance(operand, Variable) assert isinstance(expression, Expression) Statement.__init__(self, {"operand": operand, "expression": expression}) self.operand = operand self.expression = expression def ends(self): return True class Assign(VarExpOp): pass class Add(VarExpOp): pass class Sub(VarExpOp): pass class Return(Statement): def __init__(self, expression=None): assert expression == None or isinstance(expression, Expression) super(Return, self).__init__({}) self.expression = expression def ends(self): return True @novisiting class CondLoop(Statement): def __init__(self, condition): assert isinstance(condition, Expression) super(CondLoop, self).__init__({"condition": condition}) self.condition = condition class WhileDo(CondLoop): pass class RepeatUntil(CondLoop): pass class For(Statement): def __init__(self, init, check, change): assert isinstance(init, Statement) and not isinstance(init, Block) assert isinstance(check, Expression) assert isinstance(change, Statement) and not isinstance(change, Block) super(For, self).__init__({"init": init, "check": check, "change": change}) self.init = init self.check = check self.change = change class StructuredType(Statement): def __init__(self, name, properties=[]): if isstring(name): name = Identifier(name) assert isinstance(name, Identifier) super(StructuredType, self).__init__({"name":name}) self.name = name def __repr__(self): return "struct " + self.name + \ "(" + ",".join(",", [prop for prop in self]) + ")" class Property(WithoutChildModification, Code): def __init__(self, name, type): if isstring(name): name = Identifier(name) assert isinstance(name, Identifier) assert isinstance(type, Type), "expected Type but got " + type.__class__.__name__ super(Property, self).__init__({"name": name, "type": type}) self.name = name self.type = type def __repr__(self): return "property " + self.name + ":" + self.type # Expressions @novisiting class Expression(Code): def as_label(self): return str(self) @novisiting class Variable(Expression): pass class SimpleVariable(Identified, Variable): # TODO: info here is a small hack to allow semantic typing information :-( def __init__(self, id, info=None): if isstring(id): id = Identifier(id) assert isinstance(id, Identifier) super(SimpleVariable, self).__init__({"id": id, "info": info}) self.id = id self.info = info # TODO: rename to indexer or something like that class ListVariable(Identified, Variable): def __init__(self, id, index): if isstring(id): id = Identifier(id) assert isinstance(id, Identifier) or isinstance(id, Variable) super(ListVariable, self).__init__({"id": id, "index": index}) self.id = id self.index = index class Object(Identified, Variable): def __init__(self, id, type=None): if isstring(id): id = Identifier(id) assert isinstance(id, Identifier) if type is None: type = VoidType() assert isinstance(type, Type) super(Object, self).__init__({"id": id, "type": type}) self.id = id self.type = type def __repr__(self): return "Object(" + repr(self.id) + ":" + repr(self.type) + ")" class ObjectProperty(Variable): def __init__(self, obj, prop, type=None): if isstring(obj): obj = Object(obj) assert isinstance(obj, Object), "got " + obj.__class__.__name__ if isstring(prop): prop = Identifier(prop) assert isinstance(prop, Identifier) if type is None: type = VoidType() assert isinstance(type, Type) super(ObjectProperty, self).__init__({"obj" : obj, "prop": prop}) self.obj = obj self.prop = prop self.type = type def __repr__(self): return "ObjectProperty(" + repr(self.obj) + "." + repr(self.prop) + ":" + repr(self.type) + ")" class StructProperty(Variable): def __init__(self, obj, prop): if isstring(obj): obj = Object(obj) assert isinstance(obj, Object), "got " + obj.__class__.__name__ if isstring(prop): prop = Identifier(prop) assert isinstance(prop, Identifier) super(StructProperty, self).__init__({"obj" : obj, "prop": prop}) self.obj = obj self.prop = prop def __repr__(self): return "ObjectProperty(" + repr(self.obj) + "." + repr(self.prop) + ")" @novisiting class UnOp(Expression): def __init__(self, operand): assert isinstance(operand, Expression) super(UnOp, self).__init__({}) self.operand = operand class Not(UnOp): pass # TODO: extend this a bit ;-) class ShiftLeft(Expression): def __init__(self, var, amount): self.var = var self.amount = amount super(ShiftLeft, self).__init__({"var": var, "amount": amount}) @novisiting class BinOp(Expression): def __init__(self, left, right): assert isinstance(left, Expression) assert isinstance(right, Expression) super(BinOp, self).__init__({"left": left, "right": right}) self.left = left self.right = right class And(BinOp): pass class Or(BinOp): pass class Equals(BinOp): pass class NotEquals(BinOp): pass class LT(BinOp): pass class LTEQ(BinOp): pass class GT(BinOp): pass class GTEQ(BinOp): pass class Plus(BinOp): pass class Minus(BinOp): pass class Mult(BinOp): pass class Div(BinOp): pass class Modulo(BinOp): pass class Call(Expression): def __init__(self, info, arguments=[]): info["arguments"] = len(arguments) super(Call, self).__init__(info) self.arguments = TypedList(Expression, arguments) def ends(self): return True class FunctionCall(Call): def __init__(self, function, arguments=[], type=None): if isstring(function): function = Identifier(function) assert isinstance(function, Identifier) if type is None: type = VoidType() assert isinstance(type, Type), "but got " + type.__class__.__name__ super(FunctionCall, self).__init__({"function": function}, arguments) self.function = function self.type = type def as_label(self): return self.function.name class MethodCall(Call): def __init__(self, obj, method, arguments=[], type=None): assert isinstance(obj, Object) or isinstance(obj, ObjectProperty), \ "Expected Object(Property), but got " + obj.__class__.__name__ if isstring(method): method = Identifier(method) if type is None: type = VoidType() assert isinstance(type, Type), "but got " + type.__class__.__name__ assert isinstance(method, Identifier) super(MethodCall, self).__init__({"obj": obj, "method": method}, arguments) self.obj = obj self.method = method self.type = type # Literals @novisiting class Literal(Expression): pass class StringLiteral(Literal): def __init__(self, data): self.data = data def __repr__(self): return '"' + self.data.replace("\n", "\\n") + '"' class BooleanLiteral(Literal): def __init__(self, value): assert isinstance(value, bool) super(BooleanLiteral, self).__init__({"value": value}) self.value = value def __repr__(self): return "true" if self.value else "false" class IntegerLiteral(Literal): def __init__(self, value): assert isinstance(value, int) super(IntegerLiteral, self).__init__({"value": value}) self.value = value def __repr__(self): return str(self.value) class ByteLiteral(Literal): def __init__(self, value): assert isinstance(value, int) and value < 256 super(ByteLiteral, self).__init__({"value": value}) self.value = value def __repr__(self): return "0x%02x" % self.value def as_label(self): return "0x%02x" % self.value class FloatLiteral(Literal): def __init__(self, value): assert isinstance(value, float) self.value = value def __repr__(self): return str(self.value) class ListLiteral(Literal): def __init__(self): super(ListLiteral, self).__init__({}) def __repr__(self): return "[]" class TupleLiteral(Literal): def __init__(self, expressions=[]): self.expressions = TypedList(Expression, expressions) def __repr__(self): return "(" + ",".join([expr for expr in self.expressions]) + ")" class AtomLiteral(Identified, Literal): def __init__(self, id): if isstring(id): id = Identifier(id) assert isinstance(id, Identifier) super(AtomLiteral, self).__init__({"name": id.name}) self.id = id def __repr__(self): return "atom " + self.name # Types class Type(Code): pass class NamedType(Type): def __init__(self, name): assert isstring(name) super(NamedType, self).__init__({"name": name}) self.name = name def __repr__(self): return "type " + self.name class VoidType(Type): def __repr__(self): return "void" class ManyType(Type): def __init__(self, type): assert isinstance(type, Type), \ "Expected Type but got " + type.__class__.__name__ super(ManyType, self).__init__({}) self.type = type def __repr__(self): return "many " + str(self.type) class AmountType(Type): def __init__(self, type, size): assert isinstance(type, Type), \ "Expected Type but got " + type.__class__.__name__ super(AmountType, self).__init__({}) self.type = type self.size = size def __repr__(self): return str(self.type) + "[" + str(self.size) + "]" class TupleType(Type): def __init__(self, types): for type in types: assert isinstance(type, Type) super(TupleType, self).__init__({}) self.types = types def __repr__(self): return "tuple " + ",".join([repr(type) for type in self.types]) class ObjectType(Type): def __init__(self, name): assert isidentifier(name), name + " is no identifier" super(ObjectType, self).__init__({"name": name}) self.name = name def __repr__(self): return "object " + self.name class ByteType(Type): def __repr__(self): return "byte" class IntegerType(Type): def __repr__(self): return "int" class BooleanType(Type): def __repr__(self): return "bool" class FloatType(Type): def __repr__(self): return "float" class LongType(Type): def __repr__(self): return "long" class UnionType(Type): def __init__(self, name, properties=[]): if isstring(name): name = Identifier(name) assert isinstance(name, Identifier) super(UnionType, self).__init__({"name":name}) self.name = name def __repr__(self): return "union " + self.name.name + \ "(" + ",".join([str(prop) for prop in self]) + ")" # Matching class Match(Expression): def __init__(self, comp, expression=None): if isstring(comp): comp = Comparator(comp) assert isinstance(comp, Comparator), \ "Expected Comparator but got " + comp.__class__.__module__ + ":" + comp.__class__.__name__ assert expression == None or isinstance(expression, Expression) super(Match, self).__init__({"comp": comp, "exp": expression}) self.comp = comp self.expression = expression def as_label(self): if not self.expression is None: return self.comp.as_label() + "_" + self.expression.as_label() else: return self.comp.as_label() class Comparator(Code): def __init__(self, operator): assert operator in [ "<", "<=", ">", ">=", "==", "!=", "!", "*" ] super(Comparator, self).__init__({"operator": operator}) self.operator = operator def as_label(self): return { "<" : "lt", "<=" : "lteq", ">" : "gt", ">=" : "gteq", "==" : "eq", "!=" : "nq", "!" : "not", "*" : "anything" }[self.operator] class Anything(Comparator): def __init__(self): super(Anything, self).__init__("*") class VariableDecl(Identified, Variable): def __init__(self, id, type): if isstring(id): id = Identifier(id) assert isinstance(id, Identifier) assert isinstance(type, Type), "got " + type.__class__.__name__ super(VariableDecl, self).__init__({"id":id, "type":type}) self.id = id self.type = type # A visitor for instructions = Code or Code @visits([Code]) class Visitor(): pass
Flat bar refers to the width 12-300mm, ... 60x8.0x6000mm: 100x7.75x6000mm: ... Hot rolled q235 carbon steel flat bar. Quality Steel Bar Grating manufacturers & exporter - buy Anti Slip Mild steel Steel Bar Grating / Q235 A36 SS304 Stainless Steel Floor Grating from China manufacturer. Quality Steel Bar Grating manufacturers & exporter - buy Galvanised Flat Bar Serrated Steel Grating Platform Steel Floor Grating from China manufacturer. Translate this pageQualität Stabstahl Gitter fabricants & Exporteur - kaufen Galvanisiertes flache Stangen-gezacktes kratzendes Plattform-Stahlboden-Stahlgitter de la Chine fabricant. 60x8.0x6000mm: 100x7.75x6000mm: 25x4.5x6000mm: ... galvanized bar grating, steel floor grating. ... Q235, A36, SS304.
# imports for class implementation import csv import itertools import logging import re import urllib2 from datetime import date from bs4 import BeautifulSoup from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import Select from exceptions import MissingAttributeException from base import BaseJournalScraper class BioMedCentralScraper(BaseJournalScraper): """Web scraper for publisher BioMed Central Attributes: http_address (str): Address of the BioMed Central webpage with journal information """ paid_for_patt = re.compile("do not need to pay") def __init__(self, http_address): f = urllib2.urlopen(http_address, timeout=5) self.soup = BeautifulSoup(f, 'lxml') @staticmethod def __get_price(soup): for tag in soup.find_all(class_="CmsArticle_body"): text = tag.get_text() price_matches = BioMedCentralScraper.PRICE_PATT.findall(text) paid_for_matches = BioMedCentralScraper.paid_for_patt.findall(text) if price_matches: return str(int(round(float(price_matches[0].replace(",", "").replace("$", "").replace("'", ""))))) elif paid_for_matches: return 0 raise MissingAttributeException @staticmethod def __get_journal_name(soup): journal_name_tag = soup.find(class_="identity__title-link") if not journal_name_tag: raise MissingAttributeException return journal_name_tag.string @staticmethod def __get_issn(soup): issn_tag = soup.find(class_="SideBox_defList") if not issn_tag: raise MissingAttributeException issn_matches = BioMedCentralScraper.ISSN_PATT.findall(issn_tag.get_text()) if not issn_matches: raise MissingAttributeException return issn_matches[0] def get_entries(self): for tag in self.soup.find_all(class_="list-stacked__item"): link = tag.find("a")["href"] try: g = urllib2.urlopen(link + "about", timeout=5) about_soup = BeautifulSoup(g, 'lxml') except Exception: print link + ": Connection problems, continuing to the next entry" continue try: price = BioMedCentralScraper.__get_price(about_soup) except MissingAttributeException: print link print "\n\tNo price could be found" continue # skipping to the next entry try: journal_name = BioMedCentralScraper.__get_journal_name(about_soup) except MissingAttributeException: print link print "\n\tNo journal name could be found" continue # skipping to the next entry try: issn = BioMedCentralScraper.__get_issn(about_soup) except MissingAttributeException: print link print "\n\tNo ISSN could be found" continue yield self.to_unicode_row(["BioMed Central", journal_name, str(date.today()), "OA", issn, str(price)]) class ElsevierScraper(BaseJournalScraper): def __init__(self, csv_filepath): f = open(csv_filepath, "r") self.reader = csv.reader(f) next(self.reader) def get_entries(self): for row in self.reader: row = [BaseJournalScraper.clean_string(i) for i in row] yield BaseJournalScraper.to_unicode_row(["Elsevier", row[1], str(date.today()), 'Hybrid' if row[2] == 'Hybrid' else 'OA', row[0], str(int(round(float(row[4]))))]) class ExistingScraper(BaseJournalScraper): def __init__(self, csv_filepath): f = open(csv_filepath, "rU") self.reader = csv.reader(f, dialect=csv.excel_tab) next(self.reader) @staticmethod def __get_row(row): if not row[2]: raise MissingAttributeException return BaseJournalScraper.to_unicode_row((row[0], row[1], row[6], "OA" if row[4] else "Hybrid", row[2], str(int(round(float(row[4])))))) def get_entries(self): for row in self.reader: try: yield ExistingScraper.__get_row(row) except MissingAttributeException as e: logging.warning(str(row) + str(e)) class HindawiScraper(BaseJournalScraper): def __init__(self, http_address): f = urllib2.urlopen(http_address, timeout=5) self.soup = BeautifulSoup(f, 'lxml') @staticmethod def __get_title(tag): return tag.find("a").string.strip() @staticmethod def __get_price(results): price_matches = BaseJournalScraper.PRICE_PATT.findall(results[1]) if not price_matches: raise MissingAttributeException return str(int(round(float(price_matches[0].replace(",", "").replace("$", ""))))) @staticmethod def __get_issn(results): issn_matches = BaseJournalScraper.ISSN_PATT.findall(results[0]) if not issn_matches: raise MissingAttributeException return issn_matches[0] def get_entries(self): for tag in itertools.chain(self.soup.find_all(class_="subscription_table_plus"), self.soup.find_all(class_="subscription_table_minus")): journal_title = HindawiScraper.__get_title(tag) results = [i.string for i in tag.find_all("td") if i.string] if not results or (len(results) != 2): print "ERROR:" print "\t" + str(tag.contents) continue try: price = HindawiScraper.__get_price(results) issn = HindawiScraper.__get_issn(results) except MissingAttributeException: print "ERROR:" print "\t" + str(tag.contents) continue yield BaseJournalScraper.to_unicode_row(["Hindawi", journal_title, str(date.today()), "OA", issn, price]) class PLOSScraper(BaseJournalScraper): """ Scraper isn't actually finished yet. Can't port it """ def __init__(self, http_address): driver = webdriver.PhantomJS(executable_path="/usr/local/bin/phantomjs") driver.set_window_size(1120, 550) driver.get("https://www.plos.org/publication-fees") a = driver.find_elements_by_class_name("feature-block-text") for i in a: # print i.text pass def get_entries(self): raise StopIteration class SageHybridScraper(BaseJournalScraper): """ Scraper isn't actually finished yet. Can't port it """ def __init__(self, http_address): pass def get_entries(self): raise StopIteration class SpringerHybridScraper(BaseJournalScraper): def __init__(self, csv_path): f = open(csv_path, "r") self.reader = csv.reader(f) for i in range(9): next(self.reader) def get_entries(self): for row in self.reader: if row[11] == "Hybrid (Open Choice)": yield BaseJournalScraper.to_unicode_row(["Springer", BaseJournalScraper.clean_string(row[1]), str(date.today()), "Hybrid", row[5], str(3000)]) class SpringerOpenScraper(BaseJournalScraper): def __init__(self, http_address): f = urllib2.urlopen(http_address, timeout=5) self.soup = BeautifulSoup(f, 'lxml') @staticmethod def __get_price(soup): for tag in soup.find_all(class_="CmsArticle_body"): text = tag.get_text() price_matches = SpringerOpenScraper.PRICE_PATT.findall(text) if price_matches: return str(int(round(float(price_matches[0].replace(",", "").replace("$", "").replace("'", ""))))) raise MissingAttributeException @staticmethod def __get_journal_name(soup): journal_name_tag = soup.find(id="journalTitle") if not journal_name_tag: raise MissingAttributeException return journal_name_tag.string @staticmethod def __get_issn(soup): issn_tag = soup.find(class_="SideBox_defList") if not issn_tag: raise MissingAttributeException issn_matches = SpringerOpenScraper.ISSN_PATT.findall(issn_tag.get_text()) if not issn_matches: raise MissingAttributeException return issn_matches[0] def get_entries(self): for tag in self.soup.find_all(class_="list-stacked__item"): link = tag.find("a")["href"] if "springeropen.com" not in link: print link + ": Not valid" continue try: g = urllib2.urlopen(link + "about", timeout=5).read() about_soup = BeautifulSoup(g, 'lxml') except Exception: print link + ": Connection problems, continuing to the next entry" continue try: price = SpringerOpenScraper.__get_price(about_soup) except MissingAttributeException: print link + ": No price could be found" continue # skipping to the next entry try: journal_name = SpringerOpenScraper.__get_journal_name(about_soup) except MissingAttributeException: print link + ": No journal name could be found" continue # skipping to the next entry try: issn = SpringerOpenScraper.__get_issn(about_soup) except MissingAttributeException: print link + ": No ISSN could be found" continue yield self.to_unicode_row(["Springer", journal_name, str(date.today()), "OA", issn, str(price)]) class WileyScraper(BaseJournalScraper): def __init__(self, http_address): f = urllib2.urlopen(http_address) self.soup = BeautifulSoup(f, 'lxml') self.driver = webdriver.PhantomJS(executable_path="/usr/local/bin/phantomjs") self.driver.set_window_size(1120, 550) self.driver.get(http_address) @staticmethod def __get_child_tag_strings(tag): for child in tag.children: if not (str(child) == "\n"): yield child.string def __get_issn(self): issn_matches = (WileyScraper.ISSN_PATT .findall(self.driver .find_element_by_xpath("//div[@id='displayJAPCL']/a[1]") .get_attribute("href"))) if not issn_matches: raise MissingAttributeException return issn_matches[0] def __get_price(self): try: price = str(int(round(float(self.driver.find_element_by_id("displayJAPC") .text.replace(",", "").replace("$", ""))))) except ValueError as e: raise MissingAttributeException return price def get_entries(self): selected = self.soup.find(class_="journal") journal_select = Select(self.driver.find_element_by_id("journal")) # getting rid of first "description" row journal_gen = WileyScraper.__get_child_tag_strings(selected) next(journal_gen) for journal in journal_gen: try: journal_select.select_by_visible_text(journal) except NoSuchElementException: print "Couldn't find matching journal for input: " + str(journal) continue oa_option_element = self.driver.find_element_by_id("displayJOAP") if (oa_option_element.text == "Fully Open Access") or (oa_option_element.text == "OpenChoice"): try: price = self.__get_price() except MissingAttributeException: print journal + ": Unable to find price" continue try: issn_matches = self.__get_issn() except MissingAttributeException: print "Error: " + journal + "\n\t" + oa_option_element.text continue journal_type = "OA" if oa_option_element.text == "Fully Open Access" else "Hybrid" yield self.to_unicode_row(["Wiley", journal, str(date.today()), journal_type, issn_matches, price])
Esato Forums - General discussions : Non mobile discussion : farewell and goodbye - until the next life. General discussions : Non mobile discussion : farewell and goodbye - until the next life. 3 months ago, in fact a day after my 50th birthday, I was told I had terminal cancer. I went through the usual phases of disbelief, rejection, fear, anger etc that my councillor talked me through but that didn't make acceptance any easier. Some have noticed me posting less and less. Now I have finally accepted my fate and will be heading back to oz soon to die in the sun and surf that I know so well. Sadly, against my normal calm and peaceful nature, I have been quite bitter lately and have taken that out on family, friends, and even some members here. For that, I appologise to all unresevedly. I don't know how much time I have (do any of us really know?), but I do feel that I must make the most of what I do have and unfortunately Esato does not feature in my priorities. so now on this sunny Sunday London afternoon in February 2012 I say goodbye to Esato and commit online hari-kari (self ban)... and if I can offer anything of meaning and importance to you all, the best I can come up with is that it has been fun!... live long and prosper! Nan, Grandad... I'm scared but I am comforted that I will see you both soon! All I can say is thank you for all the work here and hope you have peaceful last days. It certainly has been fun masseur and this place would undeniably never have been the same without you. I have lost close family and friends through cancer but what I remember is the great times we had together. You will certainly not be forgotten, not by anyone who has visited Esato. Farewell - till we all meet again. Sadly we often forgot that have to live our lives like we wont be here for long... and actually we never know how much longer we`ll be here. So as I`m extreamly sad to hear this news, even though we don`t know us personally I wish you to have the life you always dream of, to do the things you always want and maybe fear to do, to let your beloved persons how much they mean to you ... and to be satisfied!!! Thanks, masseur, for posting this here, giving us the opportunity to say something, even though it's hard. Thank you for the effort you've put in keeping Esato the way it is, which is why many of us enjoy coming here, even long after we've switched away from SE to other brands. For many years you've managed to do this on your own, being the only active mod, before tranced joined you. I sincerely hope your condition will allow you, to make the most of the time you've left, together with your wife, son, daughter, family and friends. Farewell, we won't forget you. Material things don't matter,but Rock n Roll does!!!! I can't find a way to tell what I'm feeling right now. This feeling has got all over me and the tears are the only way to let you know. It was really fun to have you with us and all I can wish you is to spend the time you have left in peace. Surrounded by the ones who care about you and like wise. I will miss you a lot. My prayers will be with you. I am so shocked to hear this. Esato is like my family and you are one of the chief and important part of my this family. I cant think Esato without you. I always loved you and continue to love you. I am writing these with heavy heart and kinda pain in my mind. My eyes have tears. I love you. Thank you, thank you, thank you for everything you did for Esato and for us. Thank you is such a small word to express our feelings for you. ( i am all chocked up) This is like loosing one of family member. It was a very long time ago since I posted here. Kind of drifted off as I have been using non-SE phones for a while. But coming back and reading this is very sad. Like a very hard slap in the face. None of us know what fate has in store for us. For some, the end comes very suddenly. For others, this comes announced in advance. I don't know if either is better. Perhaps to know when it is going to happen is best, as it gives a chance to put affairs in order.
# -*- coding: utf-8 -*- """ ENERPIWEB tests - Routes """ from io import BytesIO import json import jsondiff import os import re from tests.conftest import TestCaseEnerpiWebServer class TestEnerpiWebServerRoutes(TestCaseEnerpiWebServer): # Enerpi test scenario: subpath_test_files = 'test_context_2probes' cat_check_integrity = True def test_0_routes(self): routes_defined = { "api_endpoints": [ "{}/api/stream/realtime".format(self.url_prefix), "{}/api/stream/bokeh".format(self.url_prefix), "{}/api/email/status".format(self.url_prefix), "{}/api/editconfig/".format(self.url_prefix), "{}/api/bokehplot".format(self.url_prefix), "{}/api/showfile".format(self.url_prefix), "{}/api/monitor".format(self.url_prefix), "{}/api/billing".format(self.url_prefix), "{}/api/bills".format(self.url_prefix), "{}/api/last".format(self.url_prefix), "{}/api/help".format(self.url_prefix), "{}/control".format(self.url_prefix), "{}/index".format(self.url_prefix), "{}/".format(self.url_prefix), "{}/api/stream/bokeh/from/<start>/to/<end>".format(self.url_prefix), '{}/api/consumption/from/<start>/to/<end>'.format(self.url_prefix), '{}/api/billing/from/<start>/to/<end>'.format(self.url_prefix), '{}/api/power/from/<start>/to/<end>'.format(self.url_prefix), "{}/api/stream/bokeh/last/<last_hours>".format(self.url_prefix), "{}/api/stream/bokeh/from/<start>".format(self.url_prefix), '{}/api/consumption/from/<start>'.format(self.url_prefix), '{}/api/billing/from/<start>'.format(self.url_prefix), "{}/api/email/status/<recipients>".format(self.url_prefix), '{}/api/power/from/<start>'.format(self.url_prefix), "{}/api/filedownload/<file_id>".format(self.url_prefix), "{}/api/editconfig/<file>".format(self.url_prefix), "{}/api/uploadfile/<file>".format(self.url_prefix), "{}/api/hdfstores/<relpath_store>".format(self.url_prefix), "{}/api/showfile/<file>".format(self.url_prefix), "{}/api/restart/<service>".format(self.url_prefix) ] } self.endpoint_request('api/help') result = self.endpoint_request('api/help?json=True') routes = json.loads(result.data.decode()) print(routes) print(routes_defined) print(jsondiff.diff(routes, routes_defined)) self.assertEqual(routes, routes_defined) # assert 0 from enerpiweb import app endpoints = [rule.rule for rule in app.url_map.iter_rules() if rule.endpoint != 'static'] self.assertEqual(routes["api_endpoints"], endpoints) self.assertEqual(routes_defined, json.loads(result.data.decode())) self.endpoint_request('notexistent', status_check=404) def test_1_index(self): self.endpoint_request('', status_check=302, verbose=True) self.endpoint_request("index") self.endpoint_request("control") alerta = '?alerta=%7B%22texto_alerta%22%3A+%22LOGFILE+%2FHOME%2FPI%2FENERPIDATA%2FENERPI.LOG' alerta += '+DELETED%22%2C+%22alert_type%22%3A+%22warning%22%7D' self.endpoint_request("control" + alerta) self.endpoint_request("api/monitor") def test_2_filehandler(self): from enerpi.editconf import ENERPI_CONFIG_FILES self.endpoint_request("api/editconfig/") self.endpoint_request("api/editconfig/flask", status_check=404) self.endpoint_request("api/editconfig/rsc", status_check=404) self.endpoint_request("api/editconfig/nginx_err", status_check=404) self.endpoint_request("api/editconfig/nginx", status_check=404) self.endpoint_request("api/editconfig/enerpi", status_check=404) self.endpoint_request("api/editconfig/uwsgi", status_check=404) self.endpoint_request("api/editconfig/daemon_out", status_check=404) self.endpoint_request("api/editconfig/daemon_err", status_check=404) self.endpoint_request("api/editconfig/raw_store", status_check=404) self.endpoint_request("api/editconfig/catalog", status_check=404) self.endpoint_request("api/editconfig/notexistent", status_check=404) rg_pre = re.compile('<pre>(.*)<\/pre>', flags=re.DOTALL) for k, checks in zip(sorted(ENERPI_CONFIG_FILES.keys()), [('[ENERPI_DATA]', 'DATA_PATH', '[BROADCAST]'), ('=',), ('analog_channel', 'is_rms', 'name')]): print('Config file "{}". Checking for {}'.format(k, checks)) r = self.endpoint_request("api/editconfig/{}".format(k)) r2 = self.endpoint_request("api/showfile/{}".format(k)) test = r.data.decode() test_2 = r2.data.decode() lookin = rg_pre.findall(test) lookin_2 = rg_pre.findall(test_2) print(lookin_2) if not lookin: print(test) if not lookin_2: print(test_2) for c in checks: self.assertIn(c, lookin[0], 'No se encuentra "{}" en "{}"'.format(c, lookin)) self.assertIn(c, lookin_2[0], 'No se encuentra "{}" en "{}"'.format(c, lookin)) alerta_js = json.dumps({'alert_type': 'success', 'texto_alerta': 'testing enerpi...'}) self.endpoint_request("api/editconfig/config?alerta={}".format(alerta_js)) self.endpoint_request("api/showfile/enerpi?alerta={}".format(alerta_js)) self.endpoint_request("api/showfile/enerpi?delete=true", status_check=302) self.endpoint_request("api/showfile/notexistent", status_check=404) # TODO tests edit configuration files + POST changes def test_3_download_files(self): from enerpi.editconf import ENERPI_CONFIG_FILES for file in ENERPI_CONFIG_FILES.keys(): print('downloading id_file={}'.format(file)) self.endpoint_request("api/filedownload/{}".format(file)) self.endpoint_request("api/filedownload/notexistent", status_check=404) self.endpoint_request("api/filedownload/{}?as_attachment=true".format('config')) print(os.listdir(self.DATA_PATH)) print(self.raw_file) self.endpoint_request("api/filedownload/{}?as_attachment=true".format('raw_store'), status_check=302, verbose=True) self.endpoint_request("api/hdfstores/DATA_2016_MONTH_11.h5", status_check=200, verbose=True) self.endpoint_request("api/hdfstores/TODAY.h5", status_check=404, verbose=True) self.endpoint_request("api/hdfstores/TODAY.h5?as_attachment=true", status_check=404) def test_4_upload_files(self): print('test_upload_files:') file_bytes = BytesIO(open(os.path.join(self.DATA_PATH, 'sensors_enerpi.json'), 'rb').read()) filename = 'other_sensors.json' r = self.post_file('api/uploadfile/sensors', file_bytes, filename, mimetype_check='text/html', status_check=302, verbose=True) self.assertIn('success', r.location) self.assertIn('editconfig/sensors', r.location) file_bytes = BytesIO(open(os.path.join(self.DATA_PATH, 'config_enerpi.ini'), 'rb').read()) filename = 'other_config.ini' r = self.post_file('api/uploadfile/config', file_bytes, filename, mimetype_check='text/html', status_check=302, verbose=True) self.assertIn('success', r.location) self.assertIn('editconfig/config', r.location) file_bytes = BytesIO(open(os.path.join(self.DATA_PATH, 'secret_key_for_test'), 'rb').read()) filename = 'secret_key' r = self.post_file('api/uploadfile/encryption_key', file_bytes, filename, mimetype_check='text/html', status_check=302, verbose=True) self.assertIn('success', r.location) self.assertIn('editconfig/encryption_key', r.location) file_bytes = BytesIO(open(os.path.join(self.DATA_PATH, 'secret_key_for_test'), 'rb').read()) self.post_file('api/uploadfile/secret_key', file_bytes, filename, status_check=500, verbose=True) file_bytes = BytesIO(open(os.path.join(self.DATA_PATH, 'secret_key_for_test'), 'rb').read()) self.post_file('api/uploadfile/flask', file_bytes, filename, status_check=404, verbose=True) self.endpoint_request("api/uploadfile/lala", status_check=405) def test_5_last_broadcast(self): print('LAST ENTRY:') self.endpoint_request("api/last", mimetype_check='application/json') def test_6_bokeh_plots(self): self.endpoint_request("api/bokehplot") self.endpoint_request("api/stream/bokeh", mimetype_check='text/event-stream') self.endpoint_request("api/stream/bokeh/last/5", mimetype_check='text/event-stream') self.endpoint_request("api/stream/bokeh/from/today", mimetype_check='text/event-stream') self.endpoint_request("api/stream/bokeh/from/2016-08-10/to/2016-08-20/?use_median=true&rs_data=2h", status_check=404) self.endpoint_request("api/stream/bokeh/from/2016-08-01/to/2016-09-01/?rs_data=2h&kwh=true", status_check=404) self.endpoint_request("api/stream/bokeh/from/yesterday/to/today", mimetype_check='text/event-stream') if __name__ == '__main__': import unittest unittest.main()
Christian, Father/Creator, love, poetry, Pondering, Real Life, The Truth to Set One Free!, Tragic Fact, true life, True Story, Truth, unique posts Let’s joined in one Spirit—Behold! The Power Of Love From On High Descending Upon Us All. It Never Fails. It Always Avails! It’s the only way for us all. What inspiration you received. I love that despite our doubt, we can push forward and accomplish what we are supposed to. Looking forward to unity too.
import datetime import json from aws_adfs import login from mock import patch class TestCredentialProcessJson: def setup_method(self, method): self.access_key = 'AKIAIOSFODNN7EXAMPLE' self.secret_key = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY' self.session_token = 'AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==' self.expiration = datetime.datetime(2020,6,20) self.aws_session_token = { 'Credentials': { 'AccessKeyId': self.access_key, 'SecretAccessKey': self.secret_key, 'SessionToken': self.session_token, 'Expiration': self.expiration } } capture = '' def _replace_echo(self, value): self.capture = value def test_json_is_valid_credential_process_format(self): with patch('click.echo', side_effect = self._replace_echo): login._emit_json(self.aws_session_token) result = json.loads(self.capture) print(result) # Version is currently hardlocked at 1, see https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html assert result["Version"] == 1 assert result["AccessKeyId"] == self.access_key assert result["SecretAccessKey"] == self.secret_key assert result["SessionToken"] == self.session_token # Expiration must be ISO8601, see https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html assert result["Expiration"] == self.expiration.isoformat()
Kmart has the Beneful Prepared Meals 9oz-10oz on sale Buy One Get On Free until August 10th. There was a BOGO Free coupon in the 07/28 SmartSource that will make both of them FREE! Of course, the more B1G1 coupons you have, the more you can multiply this into FREE dog food! Special Note: I’m getting reports of some Kmart stores giving couponers a really hard time on this deal. So your mileage may vary! Thanks to my friend Wendy A. for the heads up on this deal!
#!/usr/bin/python import sys, os import select, socket import usbcomm import usb _default_host = 'localhost' _default_port = 23200 _READ_ONLY = select.POLLIN | select.POLLPRI class Stream(object): def __init__(self, host=_default_host, port=_default_port): self.host = host self.port = port self.usb = usbcomm.USBComm(idVendor=usbcomm.ids.Bayer, idProduct=usbcomm.ids.Bayer.Contour) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.setblocking(0) self.poller = select.poll() self.fd_to_socket = {} self.clients = [] def close(self): print >>sys.stderr, '\nMUX > Closing...' for client in self.clients: client.close() self.usb.close() self.server.close() print >>sys.stderr, 'MUX > Done! =)' def add_client(self, client): print >>sys.stderr, 'MUX > New connection from', client.getpeername() client.setblocking(0) self.fd_to_socket[client.fileno()] = client self.clients.append(client) self.poller.register(client, _READ_ONLY) def remove_client(self, client, why='?'): try: name = client.getpeername() except: name = 'client %d' % client.fileno() print >>sys.stderr, 'MUX > Closing %s: %s' % (name, why) self.poller.unregister(client) self.clients.remove(client) client.close() def read(self): self.sink = None try: data = self.usb.read( ) self.sink = data except usb.core.USBError, e: if e.errno != 110: print e, dir(e), e.backend_error_code, e.errno raise return self.sink is not None def flush(self): if self.sink is not None: for client in self.clients: client.send(self.sink) self.sink = None def run(self): try: # self.tty.setTimeout(0) # Non-blocking # self.tty.flushInput() # self.tty.flushOutput() # self.poller.register(self.usb.epout.bEndpointAddress, _READ_ONLY) # self.fd_to_socket[self.usb.epout.bEndpointAddress] = self.usb # print >>sys.stderr, 'MUX > Serial port: %s @ %s' % (self.device, self.baudrate) print >>sys.stderr, 'MUX > usb port: %s' % (self.usb) self.server.bind((self.host, self.port)) self.server.listen(5) self.poller.register(self.server, _READ_ONLY) self.fd_to_socket[self.server.fileno()] = self.server print >>sys.stderr, 'MUX > Server: %s:%d' % self.server.getsockname() print >>sys.stderr, 'MUX > Use ctrl+c to stop...\n' while True: events = self.poller.poll(500) if self.read( ): self.flush( ) for fd, flag in events: # Get socket from fd s = self.fd_to_socket[fd] print fd, flag, s if flag & select.POLLHUP: self.remove_client(s, 'HUP') elif flag & select.POLLERR: self.remove_client(s, 'Received error') elif flag & (_READ_ONLY): # A readable server socket is ready to accept a connection if s is self.server: connection, client_address = s.accept() self.add_client(connection) # Data from serial port elif s is self.usb: data = s.read( ) for client in self.clients: client.send(data) # Data from client else: data = s.recv(80) # Client has data print "send to usb" if data: self.usb.write(data) # Interpret empty result as closed connection else: self.remove_client(s, 'Got no data') except usb.core.USBError, e: print >>sys.stderr, '\nMUX > USB error: "%s". Closing...' % e except socket.error, e: print >>sys.stderr, '\nMUX > Socket error: %s' % e.strerror except (KeyboardInterrupt, SystemExit): pass finally: self.close() if __name__ == '__main__': s = Stream( ) s.run( )
The following sponsored post discusses important considerations for an outstanding medical school interview. Going to medical school is no laughing matter. Not only do you have to be smart and hard working but you also have to be determined, patient, strong etc. On top of that you need to have resources or the money to pay for the tuition fee, expensive books, and all the other requirements you'll need. Furthermore, you have to think a hundred times if you really want to be a doctor so that no matter how hard it gets you won't easily give up. You should also be the type who doesn’t complain when they're swamped with homework and would do every single one of them with enthusiasm. Otherwise, you'll end up like those medical students who purchase assignment just to be able to survive med school. Having said that, you definitely won't be able to enter medical school with only good grades in hand. You must ace the interview or else your chances of getting accepted will be greatly reduced. Interviewing applicants is very important because this is where you'll get essential information that won't appear in any test and academic records. It provides interviewers with an insight on how these students carry themselves in the patient room. Their answers let interviewers know how good and comfortable you sound when interacting with other people which is very important. Since you don't want to fail, there're steps that you can take to ace the interview. To prepare for an interview, the student should know and understand the different types of interviews. A panel interview is where you'll meet several interviewers in a single meeting and is usually a cross section of the medical school faculty and may include a medical student. A stress interview determines how an interviewee would behave under pressure and often involve personal and sensitive topics. In an open interview, the interviewer may choose the specific information to which he is acquainted with. In a blind interview, the interviewer doesn't know anything about the student and would ask him to say something about himself. Behavioral interviews operate under the theory that past performance is often the best indicator of how you’ll perform in the future. Being well prepared is a must in any type of medical school interview. Learn and study the usual interview questions, give good answers, and practice the way you'll answer them. In preparing, you must know your strengths and weaknesses and prepare to address them. Get ready to be asked with ethical and moral questions. You should also try your best to make a good first impression. Furthermore, get ready to answer questions as to why you want a career in the medical field. It's also essential to know the mistakes they’re usually committed so as not to make these mistakes such as answering questions too fast and not staying on topic. You should also stay positive and professional at all times. Always remember to relax and don't give out robotic answers. It's likewise important to listen very carefully to the interviewer so as to get a hint of what they're interested in. Learn about the specific programs and medical specialties the university offers and while you're on campus, talk to medical students and ask them about the program. Radu Anthony is a blogger who writes about education, travel, health, finance and technology.
import re import os import sha import subprocess from . import prepr def getin(d, ks): for p in ks: if p not in d: return None d = d[p] return d def resolve(t): acc = dict(idx=dict(), guard=dict(), deps=[]) for k in t: if k not in acc['idx']: resolve_recur(k, t, acc) return acc['deps'] def resolve_recur(k, t, acc): if getin(acc, ['guard',k]): raise Exception('Cycle dep %s guard %s' % (k,acc['guard'].keys())) if getin(acc, ['idx',k]): return acc acc['guard'][k] = True for d in (t[k] or []): resolve_recur(d, t, acc) acc['guard'][k] = False acc['deps'].append(k) acc['idx'][k] = True return acc def normalize_path(pth): return os.path.abspath(pth) def resolve_import(fl, pth): flpath = os.path.split(fl) return normalize_path('/'.join(flpath[:-1]) + '/' + pth) # TODO: support relative paths def extract_import(fl, l): if not re.search("^\s?--\s?#import",l): return None pth = l.split('#import')[1].strip() return resolve_import(fl, pth) def read_imports(flr, idx): fl = normalize_path(flr) if fl in idx['files']: return idx if not os.path.isfile(fl): raise Exception('Could not find file: %s' % fl) f = open(fl, 'r') idx['files'][fl] = f.read() idx['deps'][fl] = [] f.seek(0) for l in f: dep = extract_import(fl, l) if dep: idx['deps'][fl].append(dep) if dep not in idx['files']: read_imports(dep, idx) f.close() return idx def silent_pgexec(db, sql): return subprocess.Popen("psql -d %s -c \"%s\" &2> /dev/null" % (db,sql),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE).stdout.read() def pgexec(db, sql): pr = subprocess.Popen('psql -v ON_ERROR_STOP=1 -d %s' % db, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pr.stdin.write(sql) pr.stdin.write("\\q\r") pr.stdin.close() pr.wait() returncode = pr.returncode err = pr.stderr and pr.stderr.read() out = pr.stdout and pr.stdout.read() if err and pr.returncode != 0: print '\x1b[31m%s\x1b[0m' % err elif err and pr.returncode == 0: print '\x1b[33m%s\x1b[0m' % err return dict(returncode=returncode, stderr=err, stdout=out) def shell(cmd): pr = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) pr.communicate() return pr def is_changed(fl, content): print 'Digest ' + s.hexdigest() pgexec('SELECT digest FROM modules WHERE file=\'%s\'' % fl) def is_test_file(fl): return fl.find('_spec.sql') > 0 def should_reload(db, fl, digest): res = pgexec(db, 'SELECT digest FROM modules WHERE file=\'%s\'' % fl) if is_test_file(fl): return True return not res['stdout'] or res['stdout'].find(digest) == -1 return True def hl(cl, txt): colors = dict(red=31,green=32,yellow=33) code = colors[cl] return '\x1b[%sm%s\x1b[0m' % (code,txt) def load_to_pg(db, fl, content, force=False): s = sha.new(content).hexdigest() if force or should_reload(db, fl, s): print '\t<- %s' % fl sql = prepr.process(fl, content) res = pgexec(db, sql) #print res['stdout'] if res['returncode'] == 0: pgexec(db, 'DELETE FROM modules WHERE file=\'%s\'' % fl) pgexec(db, 'INSERT INTO modules (file,digest) VALUES (\'%s\',\'%s\')' % (fl, s)) if res['stderr'] and res['returncode'] != 0: raise Exception(res['stderr']) def reload(db, fl, force=False): idx = dict(files=dict(),deps=dict()) read_imports(fl, idx) deps = resolve(idx['deps']) silent_pgexec(db, 'CREATE table IF NOT EXISTS modules (file text primary key, digest text);') print 'Load %s' % fl for f in deps: load_to_pg(db, f, idx['files'][f], force) def reload_test(db, fl, force=False): idx = dict(files=dict(),deps=dict()) read_imports(fl, idx) deps = resolve(idx['deps']) silent_pgexec(db, 'CREATE table IF NOT EXISTS modules (file text primary key, digest text);') print 'Load %s' % fl for f in deps: load_to_pg(db, f, idx['files'][f]) def pgdump(db): print("mkdir -p dist && pg_dump %s --format=plain --no-acl --no-owner --file=dist/fhirbase.sql" % db) os.system("mkdir -p dist && pg_dump %s --format=plain --no-acl --no-owner --file=dist/fhirbase.sql" % db) def test(): deps = dict(a=['b','c','z'], c=['d','z'], b=['d','e'], x=['y','z']) print resolve(deps)
Other than travelling by means of scenic landscapes, visiting historical sights and participating in adventurous actions, one of many key attractions we look forward to when occurring holiday is a cushty, clean and cosy resort room. Ubud Accommodations on TripAdvisor: Discover 21,623 traveler reviews, candid pictures, Bali Wealthy Luxury Villas Ubud. The nearby West Branch Elizabeth River and the Galloping Hill Golf Course offer native outside recreation while a short drive to Jersey Metropolis can lead you to The Liberty Science Middle. Still, LAX is the biggest airport in the area and for most individuals it’s going to be the best option to fly into to your Disneyland trip. If Italy has its leaning tower of Pisa, Laoag Metropolis has its personal native model: the Sinking Bell Tower. This $5,000,000 has also paid for elevators and the big reception space and conference rooms, breakfast room, dining rooms, bars and so forth in the midst of a big metropolis. I stayed downtown and walked virtually all over the place, including Pikes Market and Pioneer Square. One choice if you discover the inns too costly is to search for house/apartment leases. Several of the inns offer convention areas and entice business shoppers who need something unique and inspiring to woo their company and purchasers. We even wakened early and used the non-public lagoon yet one more time earlier than heading to the airport. There are regular bus service from Guangdong Bus Terminal or Fangcun Bus Terminal for these taking a bus from the town. The clerk asked us if we needed to get the Seattle Metropolis Go which we had never heard of. The go gave us entry to the top tourist sights of the town at a discount. Town of Mobile lies at the head of Cell Bay, which separates Alabama from Florida. For starters that you must know that the principle worldwide airport servicing Venice is the Macro Polo Airport (VCE) and it is situated on the mainland about thirteen km from Venice. They’ve partnered with Flagstaff Produce, The Village Baker, and Arizona and New Mexico breweries. We offer the perfect of each worlds, since we’re solely a short 10 minute-stroll from desired locations like Kendall Square and downtown Boston. Jika Anda ingin mencari hotel yang nyaman dengan tarif yang cukup terjangkau, Anda dapat menginap di Dewarna Accommodations Sutoyo. On Orbitz, you can even study more about inns in Hotel Tugu Malang with unbiased opinions from verified Lodge Tugu Malang lodge company. If you’re on the lookout for a real clear nighttime sky, New Mexico is where you will discover it. Those used to the sunshine pollution of populated areas will probably be amazed at how the sky is truly supposed to have a look at night time. At any time when I stay at the Prudential Lodge in Kowloon, Hong Kong I’m all the time stunned at how massive and spacious their guest rooms are. Though there are inns just like the BP Worldwide Resort are small but very comfy because the whole property could be very nicely maintained. After spending an eternity wanting around for a hotel in Seattle, we decided our best bet can be an choice exterior of the town. You may find masses more tips about visiting Soller, and extra detailed information about the sq. in Soller, it’s backstreets, population, local weather, food, travel and the rest that I might think of that I thought could be useful for guests. It is of the most touristy areas, with tons of excessive finish buying, restaurants, golf courses, and miles of skyscraper fashion inns. In the 20th century the city expanded past its walled confines, referred to as Outdated San Juan, to include suburban Miramar, Santurce, Condado, Hato Rey and Rí Piedras. If anybody knows of someone in the Southern Utah, Las Vegas or Salt Lake Metropolis areas who wants a telephone to make use of for job searching, safety, and to stay in touch with family members, please reply to this submit with an e mail address and I’ll see what I can do to get these telephones to individuals who actually need them. Awesome designer Lodge – very unique and nicely thought thru in each detail, spacious rooms, great service, unique lobby, an ideal restaurant inside, a very descend different to overpriced Manhattan resorts. Extra like Europe than Canada, Quebec Metropolis has a allure to it that makes you’re feeling like you could possibly amble around the streets and sit in sidewalk cafes for hours. Both choices embrace admission to the lagoon and spherical journey bus fare to and from the Blue Lagoon from the airport, or from Reykjavik, the busiest tourism metropolis in Iceland. Port St. Joe, Panama Metropolis Seashore, Gulf Breeze, and Pensacola have a number of the top-rated beaches within the USA. At times, flying into one airport can prove to be considerably cheaper than the others depending on where you’re flying from and what airlines have special relationships with particular airports close to Disneyland. Hong Kong’s resorts are expensive to remain in and there are other cheaper lodging alternatives. Worth Place accommodations is an effective possibility over in my location as long as you don’t have a pet. During a latest convention here in Jeddah concerning oil attended by many world leaders and other vital friends the roads across the accommodations have been crammed with armored vehicles and there have been additionally gun boats patrolling the nearby shoreline. Sekianlah artikel Dewarna Lodges Sutoyo Malang kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. Our modern all-suite resort is only a 5-minute stroll from the airport and has quick access to a variety of space sights, historic sites, out of doors recreation and outstanding companies and companies. Be a part of our on-line loyalty program and earn points for every keep, good for discounted lodge stays and all sorts of luxury rewards. I’m very surprised that an airport like Marco Polo that handles flights from all over the world and millions of visitors every year doesn’t have a greater method of coping with very late arriving flights. Luxurious historic resorts: Constructed inside huge, opulent, historic monuments, an experience within this category of motels might be greatest defined as a royal therapy”. For those who’re planning a enterprise assembly in the area, reap the benefits of our 23,000 square feet of subtle venue area, expert planning services and proximity to the Georgia Worldwide Convention Middle Our properly-positioned hotel also an impressed vacation spot for a marriage reception within the space. By air: Cebu Pacific, Philippine Airlines, and Airphil Specific all have day by day scheduled flights to Laoag City. Many resorts are new however have low discount charges to compete towards different motels and there are numerous in Pratunam. You may take pleasure in comfortable lodging and a convenient set of amenities at an airport lodge. TST is surrounded by different widespread districts well-known for discount and low-cost memento shopping that has made the city famous resembling Mongkok, Prince Edward and Yau Ma Tei. Resort Preston brings you the eclectic sights and sounds of Nashville, designed to bring in the artistic feelings of the music city with pieces that get your mind in a artistic state. For this piece, I selected to concentrate on San Antonio hotels and I’ve to confess that I have not included all the haunted locations listed for San Antonio. The Dhoni suite is 807 sq. toes, it’s not on the water but you might be made to feel like it’s just you and the ocean. You presumably need uninterrupted alone time with no outside intrusions inns close by You’ll be able to remain in your room or just take an curiosity in workouts provided by the lodging. I’m speaking about lodges with creepy-crawly things like roaches and even mattress bugs. Hotel Merdeka Kediri Kediri : Instant Confirmation and low rates for Kediri Resort Merdeka Kediri with Agoda. The one major inconvenience of the Long Seaside Airport is the extraordinarily dear car rentals. The owners of those resorts for the most half don’t care about you or your loved ones. From traditional American fare to lobby cocktails, The Westin Atlanta Airport presents lodge friends a variety of dining choices minutes away from the terminals. Resort Kolombo menawarkan lokasi yang nyaman di jantung Kota Kediri, 200 meter dari Kediri City Park. Though there are motels like the BP Worldwide Lodge are small but very comfy because your complete property could be very nicely maintained. After spending an eternity wanting round for a lodge in Seattle, we determined our best guess can be an possibility outdoors of the town. You will find hundreds extra tips about visiting Soller, and more detailed details about the square in Soller, it’s backstreets, inhabitants, climate, meals, journey and anything else that I may consider that I believed may be useful for visitors. I am very surprised that an airport like Marco Polo that handles flights from all over the world and hundreds of thousands of visitors every year doesn’t have a better way of coping with very late arriving flights. Luxurious historic inns: Built inside huge, opulent, historic monuments, an expertise inside this class of inns will be greatest outlined as a royal therapy”. When you’re planning a enterprise meeting within the area, reap the benefits of our 23,000 sq. feet of refined venue area, expert planning companies and proximity to the Georgia Worldwide Convention Center Our effectively-placed resort additionally an inspired destination for a marriage reception in the space. By air: Cebu Pacific, Philippine Airways, and Airphil Categorical all have daily scheduled flights to Laoag City. Many accommodations are new but have low discount rates to compete towards different motels and there are various in Pratunam. You will get pleasure from comfortable accommodations and a handy set of facilities at an airport resort. TST is surrounded by different popular districts well known for bargain and low-cost souvenir buying that has made town well-known such as Mongkok, Prince Edward and Yau Ma Tei. I used to be in a position to stay within the heart of town and catch the websites I wanted to see on the corporate’s dime. Many cheap motels in Bangkok’s Pratunam district are actually fairly a superb worth. Lodging in Saudi Arabia Motels is mostly of high commonplace, similar to what you’d anticipate within the west in any of their different branches. What’s the right itenary in the event you keep in vigan however we need to visit also nlaloag city vacationer spots. Located adjoining to The Avenue procuring complex and surrounded by an untold number of casual dining establishments, this hotel offers Bonnaroo visitors access to large metropolis conveniences while offering fast interstate access so you can get back to the festival. Ubud Resort & Villas menawarkan tempat peristirahatan yang damai di pusat Kota Malang. Plagued by great bars and restaurants, resorts to suit all wants, beautiful views and great climate, this is the one-holiday destination that people actually try to maintain all to themselves. Many lodges and tour companies embrace Pagudpud as a part of their itinerary as properly. Kihei is thought for it is smaller hotels, cottages, condos, and extra budget minded resorts. Taxis cease in entrance of the hotel’s entrance and Hilton’s workers can name them for you at any second: going to the airport or to some good locations with a purpose to spend the evening is very simple if you happen to keep in this lodge. And I’m positive for some who were as a result of spend only half a day in Venice earlier than becoming a member of a cruise, their time within the metropolis was ruined by this experience. I haven’t really useful any inns in this article as a result of most, though nice, were not stand outs. In the event you drive to Pagudpud from Laoag Metropolis in Ilocos Norte, there are lots of points of interest on the way in which such because the Patapat Viaduct and the Bangui windmills. Top accommodations which can be really helpful by visitors are ‘Hotel Vigna’ and ‘Hotel Eden’ which are within the fairly priced bracket. I’m talking about accommodations with creepy-crawly issues like roaches and even mattress bugs. Resort Merdeka Kediri Kediri : On the spot Confirmation and low rates for Kediri Hotel Merdeka Kediri with Agoda. The one main inconvenience of the Long Seashore Airport is the extraordinarily expensive automobile leases. The homeowners of those inns for the most half don’t care about you or your family. From classic American fare to lobby cocktails, The Westin Atlanta Airport offers resort guests a range of dining options minutes away from the terminals. For those who have not seen it, you might be surrised that it is located in the course of town. It may only be a few minutes, but it was enjoyable, took us by a small part of the city and acquired us where we wanted to go for a small worth. However the cheaper accommodations are often in very bad situation with tiny small rooms. Tuanyi International Furnishings Metropolis is opposite the Louvre furniture mall/LFC and has a good selection. Our team of experts will help you pinpoint Resort Tugu Malang accommodations choices suited to your tastes and price range. World Extensive Internet: For 4 years in a row, ReservationBooth has been named as one of the best web site to seek out low-cost lodges. Must you currently title to request costs in the identical resorts; you can be amazed within the difference. Tickets cost 6 euro and will be bought upon arrival in the airport at the computerized ticket machines within the arrivals baggage area or on the ATVO ticket office located within the arrivals hall. I’d discover the lesser known areas of the city and I would not go throughout the summer time. Interstate 10 ends (or begins, relying upon your viewpoint!) within the metropolis of Jacksonville. Heading to Panama City Seashore subsequent week – thanks for the nice ideas about the seashores. With our complimentary airport shuttle working 24 hours a day and solely two miles away, you may be assured your travels will likely be seamless. By flight: Macau has an airport so you may check for airlines which provide this service. The extravagant resorts like The Venetian, Metropolis of Dreams, Studio City, Galaxy, Exhausting Rock are located on the Cotai area. I guess if I’m going again, and never make the identical errors, I will like Seattle much more, and I can once once more say that I’ve never been to a metropolis that I didn’t love. I hope to at least go to it, however I will definitely stay in the city now after studying this. There is positively Bill for subsequent time and you might be right, each city has it’s peculiarities. We are planning to visit Ilocos Norte, what will probably be one of the simplest ways and the primary to visit if we will probably be in Baguio Metropolis first. A brief shuttle ride brings you to Opryland where one can find how Music Metropolis achieved its namesake. Whether you’re trying to find lodges in Hotel Tugu Malang on business, or attempting to find a household getaway, Hotel Tugu Malang resort choices are only a click away. We provide our guest good hotels deals on JFK airport resort, go to right here to grab an excellent deal on the airport resort New York. Discover resorts in Hotel Tugu Malang with the placement, star-score and services you need. We did not make it to the east coast however recalling our drive between Melaka and Penang and some of the different legs on our trip, that remaining leg of yours must have been gruelling! Hôtels Camplong : Trouvez les lodges proches de Camplong (34260), consulter les images, comparez les notes, les prix et réservez le meilleur hôtel en 2 mins ! Singgasana Lodge Surabaya dapat ditempuh dalam 15 menit berkendara dari pusat kota Surabaya. We provide family-friendly (children stay free!) and pet-pleasant lodge suites in over 600 locations all through the United States, with lengthy-stay hotels in most main cities. My good friend and me got our plane tickets and the vouchers for hotel on the airport in Belgrade from very type representatives of the journey agencyThe flight from Begrade was very good and comfortable, without any issues. Tips on how to Get There: Panglao Island is accessible from Bohol, which you can attain by flying into Tagbilaran Airport (about one and a half hours from Manila). He was the one that really informed me to look up haunted inns in order that we might keep in 1 for our honeymoon. Location sensible, the main accommodations in Jeddah and Al-Khobar are on the Cornice (seafront) and the views are terrific. Uncover The Westin Atlanta Airport, positioned a complimentary shuttle experience away from Hartsfield-Jackson Worldwide Airport. We landed to the airport in Antalia, which is much about 130 kilometres from bus for Alanya waited us on the airport of arrived to our hotel in Alanya and we acquired a nice room with a view to the swimming pool and the attractive resort is very close to the sea and the seashores. Awesome designer Lodge – very unique and nicely thought via in every element, spacious rooms, nice service, distinctive foyer, an awesome restaurant inside, a really descend various to overpriced Manhattan motels. Extra like Europe than Canada, Quebec City has a allure to it that makes you feel like you could possibly amble around the streets and sit in sidewalk cafes for hours. Each options embody admission to the lagoon and spherical trip bus fare to and from the Blue Lagoon from the airport, or from Reykjavik, the busiest tourism city in Iceland. Plan to choose her up at airport and spend the week in Seattle doing the tourist attraction thing. Featuring greater than 6,000 sq. ft of flexible indoor and outdoor occasion and banquet facilities, the Kenilworth is an ideal location to host enterprise conferences, company retreats and seminars, and to assemble for special occasions akin to weddings, anniversaries or particular lunches. Despite its status as the house of mega rich oil billionaires, Dubai may be an affordable possibility for a metropolis break. I am an Englishman, who’s now thought-about a local in The Port of Soller and in Mallorca. It is a superb compilation of ‘odd’ destinations to remain in. I am thinking back to see what kind of resorts I have stayed it. I’ve stayed in a castle ( in Scotland) , a country house ( in Yorkshire) , a converted palace ( in France) a floating one ( does a cruise depend?) , a train one ( on an extended journey in India). If potential, arrange in your lodge/s to ship a shuttle to choose you up at the airport. Many apparitions select to seem within the county’s resorts and inns—not what most of us want on our vacation, but if you’re searching for a ghostly roommate, here are a few of the best hotels to verify into. This area is usually a bit dearer, overall, but staying outdoors the hustle and bustle of Panama City Beach, yet nonetheless having entry is worth it. Between the Avalon Lodges in Beverly Hills and Palm Springs – there is a lot to keep up with on this planet of Proper Hospitality. San Juan is middle of Caribbean delivery and is the 2nd largest sea port within the area (after New York City). Travelers can use the user-friendly site to seek out cheap resort rooms nearby or lodges in the area. Prime location: hotel close to Chicago, just minutes from ‘hare Airport and Olympic Park, with free Shuttle to Itasca Metra Station, Woodfield Mall, TopGolf, Canon Coaching Middle and different attractions inside 5-mile radius. Or you cannot fear concerning the visitors, and take an airport shuttle to Anaheim as an alternative. This seaside resort and trip space is gorgeous, peaceable, and I believe one of the best household selection if you wish to be close to Panama Metropolis Seashore. Word: Most hotels in Cuzco will hold your baggage – something you are not taking with you on the Inca Path – in their storage area when you’re away. This edifice is without doubt one of the tallest bell towers in the nation and it’s situated in the coronary heart of town. Surrounded by tropical gardens, Lodge Merdeka Kediri enjoys a handy location in the Central Business District. You won’t find lodges or other luxury objects here; it is actually an untouched paradise. Not only that it’s important to give this city some real time, two weeks or extra The subsequent time I am there I am going to strive Airbnb. The Underground tour was on our list for the 2nd day but as a result of we didn’t go back in we did not get to do it. I’ve heard good things about it. I am undecided about what sort of accessibility the websites in the city have. DeView Resort menawarkan restoran, dan berselang 5 menit berkendara dari Batu Sq.. He was the one that really told me to look up haunted resorts in order that we may stay in 1 for our honeymoon. Location smart, the principle hotels in Jeddah and Al-Khobar are on the Cornice (seafront) and the views are terrific. Uncover The Westin Atlanta Airport, situated a complimentary shuttle journey away from Hartsfield-Jackson Worldwide Airport. We landed to the airport in Antalia, which is far about one hundred thirty kilometres from bus for Alanya waited us on the airport of arrived to our hotel in Alanya and we obtained a pleasant room with a view to the swimming pool and the gorgeous lodge is very near the sea and the beaches. Two additional airport choices are Ontario Airport (ONT) and Burbank Airport (BUR). To get there, you both must fly into Caticlan (the closest airport) or Kalibo (an airport additional away that generally presents cheaper flights). Whether or not you’re on an unwinding weekend break stuffed with meals and leisure lazing at a seaside resort or on a highly intense adventure path, accommodation in different sorts of resorts in India are simply available based on your finances, company and other particular necessities. Ubud Lodges on TripAdvisor: Find 21,623 traveler evaluations, candid photos, Bali Wealthy Luxury Villas Ubud. The close by West Branch Elizabeth River and the Galloping Hill Golf Course offer native out of doors recreation whereas a brief drive to Jersey Metropolis can lead you to The Liberty Science Heart. Still, LAX is the largest airport in the region and for most people it is going to be the best option to fly into on your Disneyland trip. If Italy has its leaning tower of Pisa, Laoag Metropolis has its own native model: the Sinking Bell Tower. It’s a few 30 minute drive from the occasion lifetime of Panama Metropolis Seashore, however quieter and less expensive. We’re situated conveniently across from LaGuardia Airport and even offer shuttle service to and from in your convenience. Seattle accommodations are costly, and I mean actually costly, and since we didn’t make our plans in time, any ones that weren’t outrageous were booked. I took metropolis buses to go to the Area Needle and as much as the University of WA campus. Las Vegas has so many excellent Accommodations for anyone to must undergo this sort of miserable expertise is just unhappy.
# -*- coding: utf-8 -*- # pybroker # Copyright (c) 2016 David Sabatie <pybroker@notrenet.com> # # This file is part of Pybroker. # # Foobar 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. # # Foobar 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 Foobar. If not, see <http://www.gnu.org/licenses/>. import sys import time import logging import socket import zmq import json import threading from zmq.devices import Device class Work(): """ServerWorker""" def __init__(self, options, worker): self.options = options self.worker = worker['out'] self.logger = logging.getLogger( 'pybroker.driver.external.inputs.' + self.worker.identity) self.begin = 0 # Initiate the external socket self.logger.debug("Starting external socket") self._external = zmq.Context.instance() # bind to external socket self.worker_external = self._external.socket(zmq.ROUTER) self.worker_external.bind( self.options['type']+"://" + self.options['bind_address'] + ":"+str(self.options['bind_port'])) # poll_all = zmq.Poller() # poll_all.register(self.worker_external, zmq.POLLIN) def run(self): # Startup message sequence # self.logger.debug("Saying hello to the server from "+self.worker.identity) zmq.proxy(self.worker_external, self.worker) # self.worker.send_multipart(['toto']) # while True: # try: # self.logger.debug('Entering main loop ...') # # self.logger.debug("Polling queues ...") # socks = dict(poll_all.poll(timeout=0)) # # self.logger.debug("Looking for data from the outside world ...") # # Handle worker activity on self.broker_input # if socks.get(self.worker_external) == zmq.POLLIN: # self.logger.debug("getting external message") # # Get client request # msg = self.worker_external.recv_multipart() # self.logger.debug(msg) # if not msg: # break # # # Stop action ! # if msg[3].lower() == 'stop': # self.logger.info("Stop message received ! Stoping ...") # break # # time.sleep(2) # except KeyboardInterrupt: # self.logger.critical( # "Keyboard interrupt received, stopping...") # break self.context.destroy() exit(1)
Knock-Down Pest Control is the leading provider of Pest Control Management Treatments to the real estate industry. With over 20 years of experience, Knock-Down Pest Control specialises in servicing the rental & sales market with over significant experience in dealing with tenants, vendors & purchasers. Knock-Down Pest Control provides the ultimate peace of mind to all. We have a reputation of providing value, reliability, trust and great service. General Pest Control treatments – Cockroaches, Silverfish, Ants, Spiders, Crickets, Carpet Beetles & Rodents. Termites found in a new home can be very damaging and costly and can easily go undetected. These termite infestations can cause serious damage to your home or building and often the damage is not covered by insurance. Knock-Down Pest Control’s inspections are comprehensive and carried out by our highly qualified staff. Full interior inspections starting at the door step and finishing with a thorough roof space inspection. Knock-Down Pest Control supplies written quotes and reports to ensure there are no misunderstandings. We pride ourselves on providing a quick response to attend problems in order to ensure tenants and owners are both satisfied. We have currency certificates, credentials and a portfolio available, we are up to date with legislative requirements. We provide notices of impending treatments for multiple occupancy, which is a requirement from EPA (DECCW) for spraying common areas of strata properties.
# pylint: disable=unused-import """Loads a CWL document.""" import logging import os import re import uuid import requests.sessions import schema_salad.schema as schema from avro.schema import Names from ruamel.yaml.comments import CommentedSeq, CommentedMap from schema_salad.ref_resolver import Loader, Fetcher, file_uri from schema_salad.sourceline import cmap from schema_salad.validate import ValidationException from typing import Any, Callable, cast, Dict, Text, Tuple, Union from six.moves import urllib from six import itervalues, string_types from . import process from . import update from .errors import WorkflowException from .process import Process, shortname _logger = logging.getLogger("cwltool") def fetch_document(argsworkflow, # type: Union[Text, dict[Text, Any]] resolver=None, # type: Callable[[Loader, Union[Text, dict[Text, Any]]], Text] fetcher_constructor=None # type: Callable[[Dict[unicode, unicode], requests.sessions.Session], Fetcher] ): # type: (...) -> Tuple[Loader, CommentedMap, Text] """Retrieve a CWL document.""" document_loader = Loader({"cwl": "https://w3id.org/cwl/cwl#", "id": "@id"}, fetcher_constructor=fetcher_constructor) uri = None # type: Text workflowobj = None # type: CommentedMap if isinstance(argsworkflow, string_types): split = urllib.parse.urlsplit(argsworkflow) if split.scheme: uri = argsworkflow elif os.path.exists(os.path.abspath(argsworkflow)): uri = file_uri(str(os.path.abspath(argsworkflow))) elif resolver: uri = resolver(document_loader, argsworkflow) if uri is None: raise ValidationException("Not found: '%s'" % argsworkflow) if argsworkflow != uri: _logger.info("Resolved '%s' to '%s'", argsworkflow, uri) fileuri = urllib.parse.urldefrag(uri)[0] workflowobj = document_loader.fetch(fileuri) elif isinstance(argsworkflow, dict): uri = "#" + Text(id(argsworkflow)) workflowobj = cast(CommentedMap, cmap(argsworkflow, fn=uri)) else: raise ValidationException("Must be URI or object: '%s'" % argsworkflow) return document_loader, workflowobj, uri def _convert_stdstreams_to_files(workflowobj): # type: (Union[Dict[Text, Any], List[Dict[Text, Any]]]) -> None if isinstance(workflowobj, dict): if workflowobj.get('class') == 'CommandLineTool': for out in workflowobj.get('outputs', []): for streamtype in ['stdout', 'stderr']: if out.get('type') == streamtype: if 'outputBinding' in out: raise ValidationException( "Not allowed to specify outputBinding when" " using %s shortcut." % streamtype) if streamtype in workflowobj: filename = workflowobj[streamtype] else: filename = Text(uuid.uuid4()) workflowobj[streamtype] = filename out['type'] = 'File' out['outputBinding'] = {'glob': filename} for inp in workflowobj.get('inputs', []): if inp.get('type') == 'stdin': if 'inputBinding' in inp: raise ValidationException( "Not allowed to specify inputBinding when" " using stdin shortcut.") if 'stdin' in workflowobj: raise ValidationException( "Not allowed to specify stdin path when" " using stdin type shortcut.") else: workflowobj['stdin'] = \ "$(inputs.%s.path)" % \ inp['id'].rpartition('#')[2] inp['type'] = 'File' else: for entry in itervalues(workflowobj): _convert_stdstreams_to_files(entry) if isinstance(workflowobj, list): for entry in workflowobj: _convert_stdstreams_to_files(entry) def _add_blank_ids(workflowobj): # type: (Union[Dict[Text, Any], List[Dict[Text, Any]]]) -> None if isinstance(workflowobj, dict): if ("run" in workflowobj and isinstance(workflowobj["run"], dict) and "id" not in workflowobj["run"] and "$import" not in workflowobj["run"]): workflowobj["run"]["id"] = Text(uuid.uuid4()) for entry in itervalues(workflowobj): _add_blank_ids(entry) if isinstance(workflowobj, list): for entry in workflowobj: _add_blank_ids(entry) def validate_document(document_loader, # type: Loader workflowobj, # type: CommentedMap uri, # type: Text enable_dev=False, # type: bool strict=True, # type: bool preprocess_only=False, # type: bool fetcher_constructor=None # type: Callable[[Dict[unicode, unicode], requests.sessions.Session], Fetcher] ): # type: (...) -> Tuple[Loader, Names, Union[Dict[Text, Any], List[Dict[Text, Any]]], Dict[Text, Any], Text] """Validate a CWL document.""" if isinstance(workflowobj, list): workflowobj = { "$graph": workflowobj } if not isinstance(workflowobj, dict): raise ValueError("workflowjobj must be a dict, got '%s': %s" % (type(workflowobj), workflowobj)) jobobj = None if "cwl:tool" in workflowobj: jobobj, _ = document_loader.resolve_all(workflowobj, uri) uri = urllib.parse.urljoin(uri, workflowobj["https://w3id.org/cwl/cwl#tool"]) del cast(dict, jobobj)["https://w3id.org/cwl/cwl#tool"] workflowobj = fetch_document(uri, fetcher_constructor=fetcher_constructor)[1] fileuri = urllib.parse.urldefrag(uri)[0] if "cwlVersion" in workflowobj: if not isinstance(workflowobj["cwlVersion"], (str, Text)): raise Exception("'cwlVersion' must be a string, got %s" % type(workflowobj["cwlVersion"])) workflowobj["cwlVersion"] = re.sub( r"^(?:cwl:|https://w3id.org/cwl/cwl#)", "", workflowobj["cwlVersion"]) else: _logger.warn("No cwlVersion found, treating this file as draft-2.") workflowobj["cwlVersion"] = "draft-2" if workflowobj["cwlVersion"] == "draft-2": workflowobj = cast(CommentedMap, cmap(update._draft2toDraft3dev1( workflowobj, document_loader, uri, update_steps=False))) if "@graph" in workflowobj: workflowobj["$graph"] = workflowobj["@graph"] del workflowobj["@graph"] (sch_document_loader, avsc_names) = \ process.get_schema(workflowobj["cwlVersion"])[:2] if isinstance(avsc_names, Exception): raise avsc_names processobj = None # type: Union[CommentedMap, CommentedSeq, unicode] document_loader = Loader(sch_document_loader.ctx, schemagraph=sch_document_loader.graph, idx=document_loader.idx, cache=sch_document_loader.cache, fetcher_constructor=fetcher_constructor) _add_blank_ids(workflowobj) workflowobj["id"] = fileuri processobj, metadata = document_loader.resolve_all(workflowobj, fileuri) if not isinstance(processobj, (CommentedMap, CommentedSeq)): raise ValidationException("Workflow must be a dict or list.") if not metadata: if not isinstance(processobj, dict): raise ValidationException("Draft-2 workflows must be a dict.") metadata = cast(CommentedMap, cmap({"$namespaces": processobj.get("$namespaces", {}), "$schemas": processobj.get("$schemas", []), "cwlVersion": processobj["cwlVersion"]}, fn=fileuri)) _convert_stdstreams_to_files(workflowobj) if preprocess_only: return document_loader, avsc_names, processobj, metadata, uri schema.validate_doc(avsc_names, processobj, document_loader, strict) if metadata.get("cwlVersion") != update.LATEST: processobj = cast(CommentedMap, cmap(update.update( processobj, document_loader, fileuri, enable_dev, metadata))) if jobobj: metadata[u"cwl:defaults"] = jobobj return document_loader, avsc_names, processobj, metadata, uri def make_tool(document_loader, # type: Loader avsc_names, # type: Names metadata, # type: Dict[Text, Any] uri, # type: Text makeTool, # type: Callable[..., Process] kwargs # type: dict ): # type: (...) -> Process """Make a Python CWL object.""" resolveduri = document_loader.resolve_ref(uri)[0] if isinstance(resolveduri, list): if len(resolveduri) == 1: processobj = resolveduri[0] else: raise WorkflowException( u"Tool file contains graph of multiple objects, must specify " "one of #%s" % ", #".join( urllib.parse.urldefrag(i["id"])[1] for i in resolveduri if "id" in i)) elif isinstance(resolveduri, dict): processobj = resolveduri else: raise Exception("Must resolve to list or dict") kwargs = kwargs.copy() kwargs.update({ "makeTool": makeTool, "loader": document_loader, "avsc_names": avsc_names, "metadata": metadata }) tool = makeTool(processobj, **kwargs) if "cwl:defaults" in metadata: jobobj = metadata["cwl:defaults"] for inp in tool.tool["inputs"]: if shortname(inp["id"]) in jobobj: inp["default"] = jobobj[shortname(inp["id"])] return tool def load_tool(argsworkflow, # type: Union[Text, Dict[Text, Any]] makeTool, # type: Callable[..., Process] kwargs=None, # type: dict enable_dev=False, # type: bool strict=True, # type: bool resolver=None, # type: Callable[[Loader, Union[Text, dict[Text, Any]]], Text] fetcher_constructor=None # type: Callable[[Dict[unicode, unicode], requests.sessions.Session], Fetcher] ): # type: (...) -> Process document_loader, workflowobj, uri = fetch_document(argsworkflow, resolver=resolver, fetcher_constructor=fetcher_constructor) document_loader, avsc_names, processobj, metadata, uri = validate_document( document_loader, workflowobj, uri, enable_dev=enable_dev, strict=strict, fetcher_constructor=fetcher_constructor) return make_tool(document_loader, avsc_names, metadata, uri, makeTool, kwargs if kwargs else {})
Total Vectorize is an image to vector converting app. It has been designed to help you convert images of all popular raster formats, including .TIFF, .PNG, .JPEG, and .BMP to .WMF, .EPS or .SVG. With Total Vectorize it is easy to create .EPS images from scanned files as it supports rasterizing single or multiple images in batches. Supports almost all image formats, including .TIFF, .JPEG, .PNG, .BMP, .ICO. Supported output formats include: .WMF, .EPS, .SVG, .PDF. The app can be run via the GUI or from the command line. It is a stable app that produces great looking vector images. The transparent interface is really easy to navigate and the app has some nice features. Apart from conversion you can crop, rotate and resize your images in batch and you are able to compress metafile data to save space. We don't have any change log information yet for version 1.0 of Total Vectorize. Sometimes publishers take a little while to make this information available, so please check back in a few days to see if it has been updated.
#!/bin/python3 # https://hackernoon.com/timsort-the-fastest-sorting-algorithm-youve-never-heard-of-36b28417f399 # https://pt.wikipedia.org/wiki/Timsort # based off of this code https://gist.github.com/nandajavarma/a3a6b62f34e74ec4c31674934327bbd3 # Brandon Skerritt # https://skerritt.tech def binary_search(the_array, item, start, end): if start == end: if the_array[start] > item: return start else: return start + 1 if start > end: return start mid = round((start + end)/ 2) if the_array[mid] < item: return binary_search(the_array, item, mid + 1, end) elif the_array[mid] > item: return binary_search(the_array, item, start, mid - 1) else: return mid """ Insertion sort that timsort uses if the array size is small or if the size of the "run" is small """ def insertion_sort(the_array): l = len(the_array) for index in range(1, l): value = the_array[index] pos = binary_search(the_array, value, 0, index - 1) the_array = the_array[:pos] + [value] + the_array[pos:index] + the_array[index+1:] return the_array def merge(left, right): """Takes two sorted lists and returns a single sorted list by comparing the elements one at a time. [1, 2, 3, 4, 5, 6] """ if not left: return right if not right: return left if left[0] < right[0]: return [left[0]] + merge(left[1:], right) return [right[0]] + merge(left, right[1:]) def timsort(the_array): runs, sorted_runs = [], [] length = len(the_array) new_run = [the_array[0]] # for every i in the range of 1 to length of array for i in range(1, length): # if i is at the end of the list if i == length - 1: new_run.append(the_array[i]) runs.append(new_run) break # if the i'th element of the array is less than the one before it if the_array[i] < the_array[i-1]: # if new_run is set to None (NULL) if not new_run: runs.append([the_array[i]]) new_run.append(the_array[i]) else: runs.append(new_run) new_run = [] # else if its equal to or more than else: new_run.append(the_array[i]) # for every item in runs, append it using insertion sort for item in runs: sorted_runs.append(insertion_sort(item)) # for every run in sorted_runs, merge them sorted_array = [] for run in sorted_runs: sorted_array = merge(sorted_array, run) print(sorted_array) list = [2, 3, 1, 5, 6, 7] timsort(list) # list.sort() print(list) print(sorted(list))
Honey bees will normally build a hive in an open covered area of your building where there is no insulation. If you believe you have a hive of honey bees in your White home more than likely they are in between the floors of your home. Our process for removing the honey bees is to go into the hive from underneath keeping your repair bill down with only drywall repair. Even though the honey bees are entering your White home at one place does not mean that is where the beehive is. They can travel behind the wall all the way up to the soffit. It helps if you can take pictures of the area they are entering your home and send them to us. We can do a lot of assessment with your pictures before we arrive. We will ask you questions when we call about the structure so we can be ready with the tools needed to do the bee removal job properly in White GA.
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014, 2015, 2016 CERN. # # Invenio 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. # # Invenio 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 Invenio; if not, write to the # Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307, USA. # # In applying this license, CERN does not # waive the privileges and immunities granted to it by virtue of its status # as an Intergovernmental Organization or submit itself to any jurisdiction. """API for PID relations concepts.""" from __future__ import absolute_import, print_function from invenio_db import db from invenio_pidstore.models import PersistentIdentifier from sqlalchemy.exc import IntegrityError from .models import PIDRelation class PIDConcept(object): """API for PID version relations.""" def __init__(self, child=None, parent=None, relation_type=None, relation=None): """Create a PID concept API object.""" if relation: self.relation = relation self.child = relation.child self.parent = relation.parent self.relation_type = relation.relation_type else: self.child = child self.parent = parent self.relation_type = relation_type # If child and parent (primary keys) are not None, # try to set the relation if child and parent: self.relation = PIDRelation.query.get( (self.parent.id, self.child.id)) else: self.relation = None @property def parents(self): """Return the PID parents for given relation.""" filter_cond = [PIDRelation.child_id == self.child.id, ] if self.relation_type is not None: filter_cond.append(PIDRelation.relation_type == self.relation_type) return db.session.query(PersistentIdentifier).join( PIDRelation, PIDRelation.parent_id == PersistentIdentifier.id ).filter(*filter_cond) @property def exists(self): """Determine if a PID Concept exists. Determine if constructed API object describes an existing PID Concept. The definition of that will vary across different PID Concepts, but it's intended use is to check if given child/parent PIDs are in the described relation. """ return bool(self.relation) @property def is_ordered(self): """Determine if the concept is an ordered concept.""" return all(val is not None for val in self.children.with_entities( PIDRelation.index)) @property def has_parents(self): """Determine if there are any parents in this relationship.""" return self.parents.count() > 0 @property def parent(self): """Return the parent of the PID in given relation. NOTE: Not supporting relations, which allow for multiple parents, e.g. Collection. None if not found Raises 'sqlalchemy.orm.exc.MultipleResultsFound' for multiple parents. """ if self._parent is None: parent = self.parents.one_or_none() self._parent = parent return self._parent @parent.setter def parent(self, parent): self._parent = parent @property def is_parent(self): """Determine if the provided parent is a parent in the relation.""" return self.has_children def get_children(self, ordered=False, pid_status=None): """Get all children of the parent.""" filter_cond = [PIDRelation.parent_id == self.parent.id, ] if pid_status is not None: filter_cond.append(PersistentIdentifier.status == pid_status) if self.relation_type is not None: filter_cond.append(PIDRelation.relation_type == self.relation_type) q = db.session.query(PersistentIdentifier).join( PIDRelation, PIDRelation.child_id == PersistentIdentifier.id ).filter(*filter_cond) if ordered: return q.order_by(PIDRelation.index.asc()) else: return q @property def index(self): """Index of the child in the relation.""" return self.relation.index @property def children(self): """Children of the parent.""" return self.get_children() @property def has_children(self): """Determine if there are any children in this relationship.""" return self.children.count() > 0 @property def is_last_child(self): """ Determine if 'pid' is the latest version of a resource. Resolves True for Versioned PIDs which are the oldest of its siblings. False otherwise, also for Head PIDs. """ last_child = self.last_child if last_child is None: return False return last_child == self.child @property def last_child(self): """ Get the latest PID as pointed by the Head PID. If the 'pid' is a Head PID, return the latest of its children. If the 'pid' is a Version PID, return the latest of its siblings. Return None for the non-versioned PIDs. """ return self.get_children(ordered=False).filter( PIDRelation.index.isnot(None)).order_by( PIDRelation.index.desc()).first() @property def next(self): """Get the next sibling in the PID relation.""" if self.relation.index is not None: return self.children.filter_by( index=self.relation.index + 1).one_or_none() else: return None @property def previous(self): """Get the previous sibling in the PID relation.""" if self.relation.index is not None: return self.children.filter_by( index=self.relation.index - 1).one_or_none() else: return None @property def is_child(self): """ Determine if 'pid' is a Version PID. Resolves as True for any PID which has a Head PID, False otherwise. """ return self.has_parents def insert_child(self, child, index=None): """Insert a new child into a PID concept. Argument 'index' can take the following values: 0,1,2,... - insert child PID at the specified position -1 - insert the child PID at the last position None - insert child without order (no re-ordering is done) NOTE: If 'index' is specified, all sibling relations should have PIDRelation.index information. """ try: with db.session.begin_nested(): if index is not None: child_relations = self.parent.child_relations.filter( PIDRelation.relation_type == self.relation_type).order_by(PIDRelation.index).all() relation_obj = PIDRelation.create( self.parent, child, self.relation_type, None) if index == -1: child_relations.append(relation_obj) else: child_relations.insert(index, relation_obj) for idx, c in enumerate(child_relations): c.index = idx else: relation_obj = PIDRelation.create( self.parent, child, self.relation_type, None) except IntegrityError: raise Exception("PID Relation already exists.") def remove_child(self, child, reorder=False): """Remove a child from a PID concept.""" with db.session.begin_nested(): relation = PIDRelation.query.filter_by( parent_id=self.parent.id, child_id=child.id, relation_type=self.relation_type).one() db.session.delete(relation) if reorder: child_relations = self.parent.child_relations.filter( PIDRelation.relation_type == self.relation_type).order_by( PIDRelation.index).all() for idx, c in enumerate(child_relations): c.index = idx class PIDConceptOrdered(PIDConcept): """Standard PID Concept with childred ordering.""" @property def children(self): """Overwrite the children property to always return them ordered.""" return self.get_children(ordered=True) @property def is_ordered(self): """Determine if the concept is an ordered concept.""" return True __all__ = ( 'PIDConcept', 'PIDConceptOrdered', )
The National Democratic Congress says claims by the opposition New Patriotic Party that over 1.3 million votes were stolen for John Mahama in the recent Presidential elections are laughable and misleading. The NPP legal team officially filed a petition at the Supreme Court on Friday to challenge the presidential election results which declared John Dramani Mahama as the winner. According to the NPP, it has uncovered that over 1.3 million votes were illegally counted and stolen for the NDC’s John Mahama. (1) That John Dramani Mahama, the 2nd Respondent herein was not validly elected president of the Republic of Ghana. (2) That Nana Addo Dankwa Akufo-Addo, the 1st Petitioner herein, rather was validly elected President of the Republic of Ghana. (3) Consequential orders as to this court may seem meet. But a Press Conference addressed by the General Secretary of the NDC, Johnson Asiedu Nketia said the NPP are bad losers and are still recuperating from the painful defeat suffered in the elections. Mr. Asiedu Nketia, popularly known as General Mosquito said the governing party is very confident that the Supreme Court would rule against them as the elections had been the country's most transparent ever. "We don't have any shred of doubt in our minds that President Mahama has been the choice," Mr Asiedu Nketia said. He stated that Ghanaians must patiently await the outcome of the Supreme Court ruling which would be abided by all.
''' Created on Jun 22, 2013 @author: Yubin Bai All rights reserved. ''' def stronglyConnectedComponents(graph): DFS_WHITE = 0 dfsNum = {} # number of a node dfsLowNum = {} # lowest number met before this node dfsNumCounter = [0] dfsSCC = [] inStack = set() for v in graph: dfsNum[v] = DFS_WHITE resultStr = [] def tarjanSCC(u): dfsNumCounter[0] += 1 dfsLowNum[u] = dfsNum[u] = dfsNumCounter[0] dfsSCC.append(u) inStack.add(u) # stores u based on order of visitation for v in graph[u]: if dfsNum[v] == DFS_WHITE: # a tree edge tarjanSCC(v) if v in inStack: # condition for update dfsLowNum[u] = min( dfsLowNum[u], dfsLowNum[v]) # update dfsLowNum[u] # after dfs for the branch if dfsLowNum[u] == dfsNum[u]: # if this is a root of SCC resultStr.append("SCC: ") while (dfsSCC and dfsSCC[-1] != u): v = dfsSCC[-1] resultStr.append("%d " % v) inStack.remove(v) dfsSCC.pop() v = dfsSCC[-1] resultStr.append("%d\n" % v) inStack.remove(v) dfsSCC.pop() for v in graph: if dfsNum[v] == DFS_WHITE: tarjanSCC(v) print(''.join(resultStr)) if __name__ == '__main__': graph = {0: [1], 1: [3], 2: [1], 3: [2, 4], 4: [5], 5: [7], 6: [4], 7: [6]} stronglyConnectedComponents(graph)
Canal Guides, Books, Maps, Videos, etc. Painted Boats DVD £15.99 £9.99 plus delivery "Docu-drama" featuring the life and characters of the canals in 1945. The Bargee DVD £15.99 £9.99 plus delivery The famous film with Harry H Corbett, Ronnie Barker, Eric Sykes, etc. Nicholson Guide to the Waterways (5): North West and the Pennines Includes Rochdale and Huddersfield Canals, Lancaster Canal and Ribble Link, Bridgewater, Ashton, Peak Forest, Macclesfield and Leeds and Liverpool Canals, Calder and Hebble Navigation, Aire and Calder Navigation west of Castleford and Trent and Mersey Canal north of Harecastle. South Pennine Ring, Part 1 Rochdale Canal and Ashton Canal John Lower £7.50 plus delivery New version of this South Pennine Ring guide, covers Rochdale and Ashton Canals, includes maps, history, walks and commentary. On these pages you will find a selection of books and maps, available from amazon.co.uk, which have been carefully chosen to be of interest to visitors to this site. If you wish to buy something shown on these pages, click the link to it, put the item into your "shopping trolley" and use the Back button if you wish to come back and choose more. When you are ready to order, click "go to checkout". If you wish to look at more than one item, you can use your back button to return to these pages. Any items in your basket should still be there when you go back to the Amazon site. Alternatively you may wish to open links in a new tab or window (right-click on link). Prices shown on these pages were correct at the time each page was revised, but may have changed. Some prices may be higher, some may be lower. Prices are shown as a guide only. Please follow the links to check the current prices. In most web browsers, hovering your mouse over a link will display the current price. Some hard-to-find items may be subject to an additional handling charge of £1.99. Please follow the links and check the details on Amazon's pages. Many of Amazon's prices are below the recommended prices but there may also be a delivery charge for orders under a certain value, for express deliveries, overseas deliveries or for products ordered from one of Amazon's partners, e.g. second-hand books. These charges depend on the type of products ordered and the number of items. Details can be found on the Amazon website, under "Help". No idea what present to buy? Send an Amazon Gift Voucher by email! Click to find out more.