Ejemplo n.º 1
0
    def _set(self, obj, value, from_opposite=False, do_notify=True):
        """
        Set a new value for our attribute. If this is a collection, append
        to the existing collection.

        This method is called from the opposite association property.
        """
        #print '__set__', self, obj, value, self._get(obj)
        if not (isinstance(value, self.type) or \
                (value is None and self.upper == 1)):
            raise AttributeError, 'Value should be of type %s' % self.type.__name__
        # Remove old value only for uni-directional associations
        if self.upper == 1:
            old = self._get(obj)

            # do nothing if we are assigned our current value:
            # Still do your thing, since undo handlers expect that.
            if value is old:
                return

            if old:
                self._del(obj, old, from_opposite=from_opposite, do_notify=False)

            if do_notify:
                event = AssociationSetEvent(obj, self, old, value)

            if value is None:
                if do_notify:
                    self.handle(event)
                return

            setattr(obj, self._name, value)

        else:
            # Set the actual value
            c = self._get(obj)
            if not c:
                c = collection(self, obj, self.type)
                setattr(obj, self._name, c)
            elif value in c:
                return

            c.items.append(value)
            if do_notify:
                event = AssociationAddEvent(obj, self, value)

        if not from_opposite and self.opposite:
            opposite = getattr(type(value), self.opposite)
            if not opposite.opposite:
                opposite.stub = self
            opposite._set(value, obj, from_opposite=True, do_notify=do_notify)
        elif not self.opposite:
            if not self.stub:
                self.stub = associationstub(self)
                setattr(self.type, 'UML_associationstub_%x' % id(self), self.stub)
            self.stub._set(value, obj)

        if do_notify:
            self.handle(event)
Ejemplo n.º 2
0
def ebay_params(response):
    price = create_array(prices(response))
    name = create_array(names(response))
    ship_addr = create_array(ship_from(response))
    bid_cnt = create_array(num_of_bids(response))
    item_c = create_array(item_condition(response))

    return collection(name, price, ship_addr, bid_cnt, item_c)
Ejemplo n.º 3
0
 def __init__(self, domain):
     # When you instantiate a client, you must include the domain of your Write Freely instance
     # For example, c = writefreely.client('write.house')
     self.domain = domain
     # The token for making authenticated requests
     self.token = ''
     self.u = user(domain)
     self.p = post(domain)
     self.c = collection(domain)
     self.r = read(domain)
def ebay_parser(search_string):
    url = create_url(search_string)

    # create browser object
    browser = mechanicalsoup.StatefulBrowser()
    response = browser.open(url)

    # Search only on items on Ebays page
    item_bar = response.soup.find("div", class_="srp-river-main clearfix")

    # create collection object
    Col = collection()

    # If no auction items found
    if not item_bar:
        return Col

    itm = item_bar.find_all("div", class_="s-item__wrapper clearfix")
    for item in itm:
        name = item.find("h3", class_="s-item__title").text
        raw_price = item.find("span", class_="s-item__price").text
        # shipping sometimes is not specified
        shipping = item.find("span",
                             class_="s-item__shipping s-item__logisticsCost")
        if shipping:
            shipping = shipping.text
        else:
            shipping = "Null"

        img_url = item.find("div", class_="s-item__image-wrapper").img["src"]
        bid_cnt = item.find("span",
                            class_="s-item__bids s-item__bidCount").text
        product_url = item.find("a", class_="s-item__link")["href"]
        # Item condition is optional
        item_condition = item.find("span", class_="SECONDARY_INFO")
        if item_condition:
            item_condition = item_condition.text
        else:
            item_condition = "Null"

        # assign search result to structure
        e_itm = ebay_items()
        e_itm.Names = name
        e_itm.Raw_prices = raw_price
        e_itm.Shipping = shipping
        e_itm.Img_url = img_url
        e_itm.Bid_cnt = bid_cnt
        e_itm.Item_condition = item_condition

        # save item in object vector
        Col.append(e_itm)

    return Col
Ejemplo n.º 5
0
 def _get(self, obj):
     #print '_get', self, obj
     # TODO: Handle lower and add items if lower > 0
     try:
         return getattr(obj, self._name)
     except AttributeError:
         if self.upper == 1:
             return None
         else:
             # Create the empty collection here since it might be used to
             # add 
             c = collection(self, obj, self.type)
             setattr(obj, self._name, c)
             return c
Ejemplo n.º 6
0
 def _get(self, obj):
     #print '_get', self, obj
     # TODO: Handle lower and add items if lower > 0
     try:
         return getattr(obj, self._name)
     except AttributeError:
         if self.upper == 1:
             return None
         else:
             # Create the empty collection here since it might be used to
             # add
             c = collection(self, obj, self.type)
             setattr(obj, self._name, c)
             return c
Ejemplo n.º 7
0
def benchmark(dims, rang, collectionSize, setSize, functionList):
    '''Takes a list of set-finding functions and benchmarks them with the same collection
	'''
    print "Benchmark:"
    print " %d dimensions," % dims,
    print "%d values per dimension," % rang,
    print "%d cards total," % collectionSize,
    print "%d cards per set." % setSize
    coll = collection(dims, rang, collectionSize)
    setCount = len(findSets(coll, setSize))
    print " Time taken to find", setCount, "sets:"
    for f in functionList:
        fname = f.__name__
        timer = Timer(lambda: f(coll, setSize))
        print " %s%s:  " % (fname, " " * (15 - len(fname))),
        print timer.timeit(number=1)
    print ""
Ejemplo n.º 8
0
def consistencyTest(dims, rang, collectionSize, setSize, func1, func2, trials):
    '''Takes two set-finding functions and runs them both multiple times with randomly generated sets, to test if their results are consistent
	'''
    print "Consistency test on functions %s and %s." % (func1.__name__,
                                                        func2.__name__)
    print " %s trials, " % trials,
    print "%d dimensions," % dims,
    print "%d values per dimension," % rang,
    print "%d cards total," % collectionSize,
    print "%d cards per set:" % setSize
    total = 0
    for _ in xrange(trials):
        coll = collection(dims, rang, collectionSize)
        r1 = func1(coll, setSize)
        r2 = func2(coll, setSize)
        if set(r1) != set(r2):
            print " FAILURE\n"
            return False
        total += len(r1)
    print " Average number of sets: %d" % (total / trials)
    print " Pass\n"
    return True
Ejemplo n.º 9
0
            for self.i in self.out:
                if (self.i["view"] == "pro"):
                    self.procount = self.procount + 1
                else:
                    self.negcount = self.negcount + 1
            print("Tweets for:", self.procount)
            print("Tweets against:", self.negcount)
            if self.procount > self.negcount:
                print("Twitter user are in favor of:", self.input)
            else:
                print("Twitter user are not in favor of:", self.input)
        elif (self.userAnswer == "4"):
            anas.twitPollCompare()
        elif (self.userAnswer == "5"):
            anas.outOldData()
        else:
            print("Plase enter a valid input (1,2,3,4,5).")
            go.menu()
        return 0


dis = display()
threading.Thread(target=dis.slider, args=("Connecting ", )).start()
twit = twitterAPI()
mong = mongo()
anas = analyse(mong.conn())
coll = collection(twit.authentigate(False), mong.conn())
go = Main(twit.authentigate(False), mong.conn())
dis.stop()
go.menu()  #calls the function that gets tweets and puts them in the DB
Ejemplo n.º 10
0
#!/usr/bin/env python

from collection import collection
from setSolver import findSets
from testFunctions import *

# Test fringe cases
print "Test with setsize of -1:", findSets(collection(4, 3, 15), -1)
print "Test with setsize of  0:", findSets(collection(4, 3, 15), 0)
print "Test with setsize of  1:", findSets(collection(4, 3, 15), 1)
print "Test with setsize of  2:", findSets(collection(4, 3, 4), 2)
try:
    findSets("Wrong type", 2)
except ValueError as e:
    print "Invalid type check:", e
try:
    print findSets(collection(4, 3, 15), "Wrong type")
except ValueError as e:
    print "Invalid type check:", e

# Test findSets and findSetsTest for consistency

# Make sure findSetsTest actually works
assert (consistencyTest(4, 3, 15, 3, findSetsTest, findSetsBrute, 30))
assert (consistencyTest(2, 4, 15, 4, findSetsTest, findSetsBrute, 10))
assert (consistencyTest(2, 100, 100, 2, findSetsTest, findSetsBrute, 5))
assert (consistencyTest(2, 1000, 10, 10, findSetsTest, findSetsBrute, 2))

# Test findSets against findSetsBrute
assert (consistencyTest(4, 3, 15, 3, findSets, findSetsBrute, 30))
assert (consistencyTest(2, 4, 15, 4, findSets, findSetsBrute, 10))
def tracking(choice,current_x=0,current_y=0):
    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-v", "--video",
        help="path to the (optional) video file")
    ap.add_argument("-b", "--buffer", type=int, default=64,
        help="max buffer size")
    ap.add_argument("--collect", action='store_true', help="Collect all the position data")
    args = vars(ap.parse_args())
    # define the lower and upper boundaries of the "green"
    # ball in the HSV color space, then initialize the
    # list of tracked points
    greenLower = (29, 86, 6) #29, 86, 6
    greenUpper = (64, 255, 255) #64, 255, 255  
    pts = deque(maxlen=args["buffer"])

    # if a video path was not supplied, grab the reference
    # to the webcam
    if not args.get("video", False):
        vs = VideoStream(src=0).start()

    # otherwise, grab a reference to the video file
    else:
        vs = cv2.VideoCapture(args["video"])

    # allow the camera or video file to warm up
    time.sleep(2.0)

    # keep looping
    while True:
        #Get the time for the object moving
        start_time = clock()
        # grab the current frame
        frame = vs.read()

        # handle the frame from VideoCapture or VideoStream
        frame = frame[1] if args.get("video", False) else frame

        # if we are viewing a video and we did not grab a frame,
        # then we have reached the end of the video
        if frame is None:
            break

        # resize the frame, blur it, and convert it to the HSV
        # color space
        frame = imutils.resize(frame, width=600)
        blurred = cv2.GaussianBlur(frame, (11, 11), 0)
        hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)

        # construct a mask for the color "green", then perform
        # a series of dilations and erosions to remove any small
        # blobs left in the mask
        mask = cv2.inRange(hsv, greenLower, greenUpper)
        mask = cv2.erode(mask, None, iterations=2)
        mask = cv2.dilate(mask, None, iterations=2)

        # find contours in the mask and initialize the current
        # (x, y) center of the ball
        cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
            cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        center = None
        
        #depth_analysis(len(cnts))

        # only proceed if at least one contour was found
        if len(cnts) > 0:
            # find the largest contour in the mask, then use
            # it to compute the minimum enclosing circle and
            # centroid
            c = max(cnts, key=cv2.contourArea)
            ((x, y), radius) = cv2.minEnclosingCircle(c)
            M = cv2.moments(c)
            center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

            # only proceed if the radius meets a minimum size
            if radius > 10:
                # draw the circle and centroid on the frame,
                # then update the list of tracked points
                cv2.circle(frame, (int(x), int(y)), int(radius),
                    (0, 255, 255), 2)
                cv2.circle(frame, center, 5, (0, 0, 255), -1)
                #Track time
                moving_time = clock()- start_time

                #Print center of circle coordinates
                #Not sure about the unit!!!!
                dX = int(x) - current_x
                dY = int(y) - current_y
                
                if choice !='collect':
                    #Print the displacement
                    print("dX = {0}, dY = {1}".format(dX,dY))
                    #Print the location for tracking and time
                    print ("X = {0}, Y = {1}, time = {0}".format(int(x), int(y), moving_time))
                else:
                    #Collision analysis
                    collection.collection(dX,dY,x,y,moving_time)
                #Get the current location to get the displacement
                current_x = x
                current_y = y
                
                #Classify the x and y using one and zero
                
                
        # update the points queue
        pts.appendleft(center)

        # loop over the set of tracked points
        for i in range(1, len(pts)):
            # if either of the tracked points are None, ignore
            # them
            if pts[i - 1] is None or pts[i] is None:
                continue
    
            # otherwise, compute the thickness of the line and
            # draw the connecting lines
            thickness = int(np.sqrt(args["buffer"] / float(i + 1)) * 2.5)
            cv2.line(frame, pts[i - 1], pts[i], (0, 0, 255), thickness)


        # show the frame to our screen
        cv2.imshow("Frame", frame)
        key = cv2.waitKey(1) & 0xFF

        # if the 'q' key is pressed, stop the loop
        if key == ord("q"):
            break

    # if we are not using a video file, stop the camera video stream
    if not args.get("video", False):
        vs.stop()

    # otherwise, release the camera
    else:
        vs.release()

    # close all windows
    cv2.destroyAllWindows()
Ejemplo n.º 12
0
 def __init__(self):
     self.token = ""
     self.u = user()
     self.p = post()
     self.c = collection()
     self.r = readwa()
Ejemplo n.º 13
0
    def _set(self, obj, value, from_opposite=False, do_notify=True):
        """
        Set a new value for our attribute. If this is a collection, append
        to the existing collection.

        This method is called from the opposite association property.
        """
        #print '__set__', self, obj, value, self._get(obj)
        if not (isinstance(value, self.type) or \
                (value is None and self.upper == 1)):
            raise AttributeError, 'Value should be of type %s' % self.type.__name__
        # Remove old value only for uni-directional associations
        if self.upper == 1:
            old = self._get(obj)

            # do nothing if we are assigned our current value:
            # Still do your thing, since undo handlers expect that.
            if value is old:
                return

            if old:
                self._del(obj,
                          old,
                          from_opposite=from_opposite,
                          do_notify=False)

            if do_notify:
                event = AssociationSetEvent(obj, self, old, value)

            if value is None:
                if do_notify:
                    self.handle(event)
                return

            setattr(obj, self._name, value)

        else:
            # Set the actual value
            c = self._get(obj)
            if not c:
                c = collection(self, obj, self.type)
                setattr(obj, self._name, c)
            elif value in c:
                return

            c.items.append(value)
            if do_notify:
                event = AssociationAddEvent(obj, self, value)

        if not from_opposite and self.opposite:
            opposite = getattr(type(value), self.opposite)
            if not opposite.opposite:
                opposite.stub = self
            opposite._set(value, obj, from_opposite=True, do_notify=do_notify)
        elif not self.opposite:
            if not self.stub:
                self.stub = associationstub(self)
                setattr(self.type, 'UML_associationstub_%x' % id(self),
                        self.stub)
            self.stub._set(value, obj)

        if do_notify:
            self.handle(event)