Exemplo n.º 1
0
    def post(self, uid):
        try:
            body = json.loads(self.request.body)
            pid = body.get('pin_id')
            content = body.get('content')
            image = body.get('image')
            title = body.get('title')
            caption = body.get('caption')
            private = body.get('private', False)
            if pid is None and content is None:
                raise KeyError
        except (KeyError, ValueError, TypeError):
            self.send_error(httplib.BAD_REQUEST)
            return

        try:
            pin = yield Pin.fetch(guid=pid, content=content)
        except KeyError:
            if not content:
                self.send_error(httplib.NOT_FOUND)
                return
            pin = Pin(content, image, title)
            yield pin.save()

        userpin = UserPin(uid, pin, caption, private)
        yield userpin.save()
        self.write(self.application.userpin_representation(userpin))
        self.set_status(httplib.CREATED)
Exemplo n.º 2
0
 def __init__(self):
     self.board = "na-satbus-3c0-gcc"
     self.arch = "ARM"
     self.cpu = "stm32f405"
     self.binfiletype = "ELF"
     self.pins = {
         'rst': Pin(name='rst', number=17),
         'pwr': Pin(name='pwr', number=27)
     }
Exemplo n.º 3
0
    def __init__(self, pin1, pin2):
        self.pin1 = pin1
        self.pin2 = pin2
        io.setmode(io.BCM)
        io.setup(pin1, io.OUT)
        io.setup(pin2, io.OUT)

        self.Pin1 = Pin(pin1)
        self.Pin2 = Pin(pin2)
Exemplo n.º 4
0
 def __init__(self):
     for code in self.OUTPUT_PINS:
         pin = Pin(code, code in self.STARTING_HIGH, self, True)
         setattr(self, 'pin_{}'.format(pin.code), pin)
     for code in self.INPUT_PINS:
         pin = Pin(code, code in self.STARTING_HIGH, self)
         setattr(self, 'pin_{}'.format(pin.code), pin)
     self.vcc = Pin('VCC', True, self)
     self.update()
Exemplo n.º 5
0
    def test_pin_multiple(self):
        p1 = Pin()
        p1.id = '400'

        p2 = Pin()
        p2.id = '500'

        self.assertTrue(p1.id.value == '400')
        self.assertTrue(p2.id.value == '500')
Exemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     for code in self.OUTPUT_PINS:
         pin = Pin(code, code in self.STARTING_HIGH, self, True)
         setattr(self, 'pin_{}'.format(pin.code), pin)
     for code in self.INPUT_PINS:
         pin = Pin(code, code in self.STARTING_HIGH, self)
         setattr(self, 'pin_{}'.format(pin.code), pin)
     self.vcc = Pin('VCC', True, self)
     self.update()
     self.leds = {pin.code: LED(self.vcc, pin) for pin in self.getpins(self.INPUT_PINS)}
Exemplo n.º 7
0
 def __init__(self):
     self.board = "msp430f5529-gcc"
     self.arch = "MSP430"
     self.cpu = "msp430f5529"
     self.binfiletype = "ELF"
     self.pins = {
         'rst' : Pin(name = 'rst', number = 17),
         'pwr' : Pin(name = 'pwr', number = 27),
         'opt' : Pin(name = 'opt', number = 22)  # optional
     }
Exemplo n.º 8
0
 def __init__(self):
     self.board = "stm32f407-disco-gcc"
     self.arch = "ARM"
     self.cpu = "stm32f407"
     self.binfiletype = "ELF"
     self.pins = {
         'rst' : Pin(name = 'rst', number = 17),
         'pwr' : Pin(name = 'pwr', number = 27),
         'opt' : Pin(name = 'opt', number = 22)  # optional
     }
Exemplo n.º 9
0
    def __init__(self, directionIO, stepIO):
        self.directionIO = Pin(directionIO, 'OUT')

        self.stepIO = Pin(stepIO, 'OUT')

        self.direction = False
        self.velocity = DEFAULT_VELOCITY
        self.default_wait = DEFAULT_WAIT

        self.position = 0
        self.turn = DEFAULT_POSITION_STEP
Exemplo n.º 10
0
 def __init__(self):
     self.board = "pyboard-gcc"
     self.arch = "ARM"
     self.cpu = "stm32f405"
     self.binfiletype = "BIN"
     self.pins = {
         'rst' : Pin(name = 'rst', number = 17),
         'pwr' : Pin(name = 'pwr', number = 27),
         'prg' : Pin(name = 'prg', number = 18),
         'opt' : Pin(name = 'opt', number = 22)
     } 
Exemplo n.º 11
0
 def __init__(self, *args, **kwargs):
     self.value = 0
     self.prev_clock_high = False
     for code in self.OUTPUT_PINS:
         pin = Pin(code, code in self.STARTING_HIGH, self, True)
         setattr(self, 'pin_{}'.format(pin.code), pin)
     for code in self.INPUT_PINS:
         pin = Pin(code, code in self.STARTING_HIGH, self)
         setattr(self, 'pin_{}'.format(pin.code), pin)
     self.vcc = Pin('VCC', True, self)
     self.update()
Exemplo n.º 12
0
    def __init__(self):
        # input/output pins:
        self.__a = Pin()
        self.__x = Pin()

        # components
        self.__nand1 = Nand()

        # connections:
        self.__connection1 = Connection(
            [self.__a, self.__nand1.b, self.__nand1.a])
        self.__connection2 = Connection([self.__x, self.__nand1.x])
Exemplo n.º 13
0
class Motor:
    def __init__(self, directionIO, stepIO):
        self.directionIO = Pin(directionIO, 'OUT')

        self.stepIO = Pin(stepIO, 'OUT')

        self.direction = False
        self.velocity = DEFAULT_VELOCITY
        self.default_wait = DEFAULT_WAIT

        self.position = 0
        self.turn = DEFAULT_POSITION_STEP

    def set_direction(self, direction):
        if direction == "F":
            self.direction = True
        else:
            self.direction = False
        self.directionIO.set_state(self.direction)

    def step(self, counter, direction):
        self.set_direction(direction)
        self.do_step(counter)

    def do_step(self, counter):
        while counter > 0:
            self.send_step()
            counter -= 1

    def send_step(self):
        self.stepIO.send_signal()
        self.wait_time()

    def wait_time(self):
        time.sleep(self.default_wait / self.velocity)

    def next_position(self):
        self.step(self.turn, "F")
        self.position += 1

    def back_position(self):
        self.step(self.turn, "B")
        self.position -= 1

    def move_to(self, destination):
        if destination != self.position:
            if destination > self.position:
                self.next_position()
            else:
                self.back_position()
            self.move_to(destination)
Exemplo n.º 14
0
class Motor(object):
    
    def __init__(self, pin1, pin2):
        self.pin1 = pin1
        self.pin2 = pin2
        io.setmode(io.BCM)
        io.setup(pin1, io.OUT)
        io.setup(pin2, io.OUT)

        self.Pin1 = Pin(pin1)
        self.Pin2 = Pin(pin2)

    def drive_forward(self):
        io.output(self.pin1, io.HIGH)
        io.output(self.pin2, io.LOW)

    def drive_back(self):
        io.output(self.pin1, io.LOW)
        io.output(self.pin2, io.HIGH)

    def stop(self):
        io.output(self.pin1, io.LOW)
        io.output(self.pin2, io.LOW)

    def drive(self, speed=0.0):
        if speed >= 0.0:
            self.Pin1.output(speed)
            self.Pin2.output(0)
        else:
            self.Pin1.output(0)
            self.Pin2.output(abs(speed))
Exemplo n.º 15
0
def suggestion(request):
	if request.is_ajax() and request.method=='GET':
		try:
			user_id = request.GET['user_id']
		except KeyError:
			return HttpResponse(dumps({'status':'ERR', 'data':'No user id'}, cls=MyEncoder), mimetype='application/json')
		
		
		u=User(user_id)
		
		try:
			if re.search('[^a-zA-Z0-9_]',user_id):
				raise NotFound
			pin_list=u.getToRepin(10)
			u.saveDB()
		except NotFound:
			return HttpResponse(dumps({'status':'ERR', 'data':'Wrong name, nobody have this name on pinterest'}, cls=MyEncoder), mimetype='application/json')
		
		if not pin_list:
			print 'not_pinlist'
			pin_list=[Pin.modelToPin(p) for p in random.sample(PinModel.objects.all(),10)]
		res = {'status':'OK', 'data':{'pin_list':pin_list,'user':u}, }
		return HttpResponse(dumps(res, cls=MyEncoder), mimetype='application/json')
	else:
		FB_INFO['meta']=None
		return render_to_response('map/suggestion.html', {'fb_info':FB_INFO,})
Exemplo n.º 16
0
 def get(self, pid):
     try:
         pin = yield Pin.fetch(guid=pid)
     except KeyError:
         self.send_error(httplib.NOT_FOUND)
         return
     self.write(self.application.pin_representation(pin))
Exemplo n.º 17
0
 def generate_pins(self):
     self.fetch_pin_constants()
     for pin_name in self.pin_data:
         pin_number = self.pin_data[pin_name]["number"]
         pin_node = self.pin_data[pin_name]["node"]
         pin_is_input = self.pin_data[pin_name]["is_input"]
         pin = Pin(pin_node, self, pin_is_input, pin_name, pin_name)
         self.pins[pin_name] = pin
Exemplo n.º 18
0
    def test_pin_full_example(self):
        p = Pin()

        action = Action()
        action.launch_code = 13
        action.title = 'Open in Watchapp'
        action.type = 'openWatchApp'

        self.assertDoesNotRaise(ValidationException, action.validate)

        p.add_action(action)

        reminder = Reminder()
        reminder.time = '2015-08-04T20:00:00+00:00Z'
        reminder.layout.backgroundColor = '#FFFFFF'
        reminder.layout.body = 'Drama about a police unit...'
        reminder.layout.foregroundColor = '#000000'
        reminder.layout.largeIcon = 'system://images/TV_SHOW'
        reminder.layout.smallIcon = 'system://images/TV_SHOW'
        reminder.layout.tinyIcon = 'system://images/TV_SHOW'
        reminder.layout.subtitle = 'New Tricks'
        reminder.layout.title = 'Last Man Standing'
        reminder.layout.type = 'genericReminder'

        self.assertDoesNotRaise(ValidationException, reminder.validate)

        p.add_reminder(reminder)

        p.layout.backgroundColor = '#FFFFFF'
        p.layout.foregroundColor = '#000000'
        p.layout.tinyIcon = 'system://images/TV_SHOW'
        p.layout.title = 'Last Man Standing'
        p.layout.subtitle = 'New Tricks'
        p.layout.type = 'genericPin'
        p.layout.shortTitle = 'Last Man Standing'
        p.layout.body = 'Drama about a police unit...'
        p.layout.add_section('Series', 'New Tricks')

        self.assertDoesNotRaise(ValidationException, p.layout.validate)

        p.duration = 60
        p.id = '101'
        p.time = '2015-08-04T20:00:00+00:00Z'

        self.assertDoesNotRaise(ValidationException, p.validate)

        p.time = ''

        self.assertRaises(ValidationException, p.validate)
Exemplo n.º 19
0
    def test_pin_json(self):
        p = Pin()
        p.layout.add_section('Hello', 'Goodbye')
        data = p.json()

        self.assertTrue(len(data['layout']['headings']) == 1)
        self.assertTrue(len(data['layout']['paragraphs']) == 1)
        self.assertTrue(data['layout']['headings'][0] == 'Hello')
        self.assertTrue(data['layout']['paragraphs'][0] == 'Goodbye')

        p.layout.add_section('Goodbye', 'Hello')
        data = p.json()

        self.assertTrue(len(data['layout']['headings']) == 2)
        self.assertTrue(len(data['layout']['paragraphs']) == 2)
        self.assertTrue(data['layout']['headings'][0] == 'Hello')
        self.assertTrue(data['layout']['paragraphs'][0] == 'Goodbye')
        self.assertTrue(data['layout']['headings'][1] == 'Goodbye')
        self.assertTrue(data['layout']['paragraphs'][1] == 'Hello')
Exemplo n.º 20
0
 def fetch(cls, user_id, pin_id):
     cursor = yield cls.db_pool().execute("SELECT caption, private, modified FROM userpin WHERE user_id=%s AND pin_id=%s", (user_id, pin_id))
     if cursor.rowcount != 1:
         cursor.close()
         raise KeyError
     row = cursor.fetchone()
     cursor.close()
     pin = yield Pin.fetch(guid=pin_id)
     userpin = cls(user_id, pin, row[0], row[1], row[2])
     userpin._stored = True
     raise gen.Return(userpin)
Exemplo n.º 21
0
 def cb(obj, event):
     nonlocal first_time_usage
     if event == lv.EVENT.RELEASED:
         c = obj.get_active_btn_text()
         if c is None:
             return
         if c == lv.SYMBOL.CLOSE:
             pin_lbl.set_text("")
             antiphish_label.set_text(antiphishing_word(""))
         elif c == lv.SYMBOL.OK:
             # FIXME: check PIN len
             Key.generate_key(pin_lbl.get_text())
             if first_time_usage:
                 Secret.save_secret(alert)
                 callback()
             else:
                 Pin.counter -= 1
                 Pin.save_counter(alert)
                 if Pin.is_pin_valid():
                     Pin.reset_counter(alert)
                     callback()
                 else:
                     instruct_label.set_text(
                         "#f07070 Wrong pin: %d/%d #" %
                         (Pin.counter, Pin.ATTEMPTS_MAX))
                     if Pin.counter <= 0:
                         Factory_settings.restore(alert)
                         Secret.generate_secret()
                         alert("Security", "Device has been factory reset!")
                         first_time_usage = True
                         title_lbl.set_text(first_time_title)
                         instruct_label.set_text(instruct_txt)
             pin_lbl.set_text("")
             antiphish_label.set_text(antiphishing_word(""))
         else:
             instruct_label.set_text(instruct_txt)
             pin_lbl.add_text(c)
             word = antiphishing_word(pin_lbl.get_text())
             antiphish_label.set_text(antiphish_label.get_text() + " " +
                                      word)
Exemplo n.º 22
0
    def test_pin_simple(self):
        p = Pin()
        p.id = '400'
        p.time = '2012-10-06T04:13:00+00:00Z'
        p.duration = 200

        self.assertTrue(isinstance(p.id, StringField))
        self.assertTrue(p.id.value == '400')
        self.assertRaises(ValidationException, p.validate)

        p.layout.type = PIN_LAYOUTS['GENERIC']
        p.layout.title = 'Hello World!'
        p.layout.body = 'Hello'
        p.layout.tinyIcon = ICONS['MISC']['SHOW']

        p.validate()
        self.assertDoesNotRaise(ValidationException, p.validate)

        p.layout.foregroundColor = '0xdeadbeef'

        self.assertRaises(ValidationException, p.validate)

        p.layout.foregroundColor = COLOURS['INCH_WORM']
        p.layout.add_section('Hello', 'World')

        self.assertDoesNotRaise(ValidationException, p.validate)
Exemplo n.º 23
0
    def __init__(self, IN1, IN2, IN3, IN4, timeout):
        self.P1 = Pin(IN1, Pin.OUT)
        self.P2 = Pin(IN2, Pin.OUT)
        self.P3 = Pin(IN3, Pin.OUT)
        self.P4 = Pin(IN4, Pin.OUT)
        self.P1.value(0)
        self.P2.value(0)
        self.P3.value(0)
        self.P4.value(0)
        self.timeout = timeout

        self.stop = False
        self.turning = False
        self.command = None
        self.loop_running = False
Exemplo n.º 24
0
 def list_for_user(cls, user_id, limit=None):
     userpins = []
     # TODO: replace this with a join, but to do that need to know internals of pin table...
     cursor = yield cls.db_pool().execute("SELECT caption, private, modified, pin_id FROM userpin WHERE user_id=%s", (user_id,))
     cursor.arraysize = min(cursor.rowcount, limit or cursor.rowcount)
     rows = cursor.fetchmany()
     for row in rows:
         pid = row[3]
         try:
             pin = yield Pin.fetch(guid=pid)
         except KeyError:
             Log.warning('Userpin record references Pin record that isn\'t in DB, user={}, pin={}'.format(user_id, pid))
             continue
         userpins.append(cls(user_id, pin, row[0], row[1], row[2]))
     raise gen.Return(userpins)
Exemplo n.º 25
0
def savematch(request):
	if request.is_ajax() and request.method == 'POST':
		try:
			pin1_id = request.POST['pin1_id']
			pin2_id = request.POST['pin2_id']
			choice = request.POST['choice']
			
			pin1 = PinModel.objects.get(pin_id=pin1_id)
			pin2 = PinModel.objects.get(pin_id=pin2_id)
			
			pin1.score, pin2.score = Pin.getNewScore(pin1.score, pin2.score, pin1_id == choice)
			pin1.save()
			pin2.save()
			
			try: # Save the match history if the user is logged with facebook
				fb_id = request.POST['fb_id']
				if fb_id == 'null':
					raise KeyError
				fb_user = SocialUserModel.objects.get_or_create(social_id=fb_id, net_name="facebook")[0]
				pin1_perso = fb_user.pinpersomodel_set.get_or_create(pin=pin1)[0]
				pin2_perso = fb_user.pinpersomodel_set.get_or_create(pin=pin2)[0]
				pin1_perso.score, pin2_perso.score = Pin.getNewScore(pin1_perso.score, pin2_perso.score, pin1_id == choice)
				pin1_perso.save()
				pin2_perso.save()	
			except KeyError:
				pass
			
			request.session.modified = True
			request.session['match_list'].append((pin1.pin_id, pin2.pin_id, choice))
	
			msg = "OK"
			return HttpResponse(msg)
		
		except KeyError, PinModel.DoesNotExist:
			msg = "Pin not found"
			return HttpResponse(msg)
Exemplo n.º 26
0
def profile(user):
    dbgp(user)
    profile_img = user.profile_image_url
    profile_bg_img = user.profile_banner_url
    profile_bio = default_str_new_line(user.description)
    profile_location = default_str_new_line(user.location)
    profile_stats = [user.statuses_count, user.friends_count, user.followers_count]
    profile_mapping = ["Tweets", "Following", "Followers"]
    profile_stats_text = ""
    for (i, stat) in enumerate(profile_stats):
        profile_stats_text += "{} {},".format(stat, profile_mapping[i])
    if profile_stats_text:
        profile_stats_text = profile_stats_text[:-1] + "\n"
    profile_elem = (profile_img, profile_bg_img, profile_stats, profile_bio, profile_location)
    content = profile_bio + profile_location + profile_stats_text
    return profile_elem, Pin(profile_url = profile_img, content = content)
Exemplo n.º 27
0
def insert_all_pins_or_boards(all_data, class_name):
    counter = 0
    for index, item in enumerate(all_data):
        counter += 1
        data = json.loads(item)

        if class_name == "pin":
            if store.get(Pin, data['id']) is None:
                store.add(Pin(data))
        elif class_name == "board":
            if store.get(Board, data['id']) is None:
                store.add(Board(data))

        if counter == MAX_INMEMORY:
            store_to_db()
            counter = 0
    store_to_db()
Exemplo n.º 28
0
class Car(object):
    """
    Control of our lego buggy via left, right and gas pins
    """
    def __init__(self):
        self.left = ExclusivePin(17, None)
        self.right = ExclusivePin(14, self.left)
        self.gas = Pin(0)
        self.left.xpin = self.left
        
    def turn(self, s, is_left, angle=0.05):
        first = self.left if is_left else self.right
        second = self.right if is_left else self.left
        first.drive(angle)
        end = time.time() + s
        while time.time() < end:
            sleep(0.25)
            first.drive(angle/10)
        second.drive(angle)

    def turn_left(self, s):
        self.turn(s, True)
        
    def turn_right(self, s):
        self.turn(s, False)

    def rev(self, s=0.4):
        self.gas.drive(s)

    def start(self, wait=None):
        self.gas.on()
        if wait:
            sleep(wait)

    def pause(self, s):
        self.stop()
        sleep(s)
        self.start()
        
    def stop(self):
        self.gas.off()
        
    def all_stop(self):
        self.stop()
        self.left.off()
        self.right.off()
Exemplo n.º 29
0
 def test_output_zero(self):
     p24 = Pin(24)
     p24.output(0)
     self.assertEqual(p24.value, 0.0)
     self.assertTrue(p24._stopped)
Exemplo n.º 30
0
 def get(self):
     limit = self.get_argument('limit', None)
     pins = yield Pin.list(limit)
     self.write({pin.guid: self.application.pin_representation(pin) for pin in pins})
Exemplo n.º 31
0
 def test_output_one(self):
     p24 = Pin(24)
     p24.output(1)
     self.assertEqual(p24.value, 1.0)
     self.assertTrue(p24._stopped)
Exemplo n.º 32
0
 def __init__(self):
     self.left = ExclusivePin(17, None)
     self.right = ExclusivePin(14, self.left)
     self.gas = Pin(0)
     self.left.xpin = self.left
Exemplo n.º 33
0
 def test_output_zero(self):
     p24 = Pin(24)
     p24.output(0)
     self.assertEqual(p24.value, 0.0)
     self.assertTrue(p24._stopped)
Exemplo n.º 34
0
 def test_output(self):
     p24 = Pin(24)
     p24.output(.5)
     self.assertEqual(p24.value, 0.5)
class Buzzer:
    def __init__(self):
        self.pin = Pin(Board.BUZZ_PIN)

    def execWarningSound(self):
        self.pin.data(1)
        time.sleep(0.2)
        self.pin.data(0)
        time.sleep(0.4)
        self.pin.data(1)
        time.sleep(0.4)
        self.pin.data(0)
        time.sleep(0.4)
        self.pin.data(1)
        time.sleep(0.6)
        self.pin.data(0)
        time.sleep(0.4)

    def serverReadySound(self):
        for i in range(1, 6):
            self.pin.data(1)
            time.sleep(0.1)
            self.pin.data(0)
            time.sleep(0.1)
Exemplo n.º 36
0
class PinSet:
    def __init__(self, enable, pin1, pin2):
        self._enable = Pin(enable, GPIO.OUT)
        self._pin1 = Pin(pin1, GPIO.OUT)
        self._pin2 = Pin(pin2, GPIO.OUT)

    def get_enable_number(self):
        return self._enable.get_pin_number()

    def get_pin1_number(self):
        return self._pin1.get_pin_number()

    def get_pin2_number(self):
        return self._pin2.get_pin_number()

    def get_all_pin_numbers(self):
        return self._enable.get_pin_number(), self._pin1.get_pin_number(), \
               self._pin2.get_pin_number()

    def get_enable_val(self):
        return self._enable.get_pin_value()

    def get_pin1_val(self):
        return self._pin1.get_pin_value()

    def get_pin2_val(self):
        return self._pin2.get_pin_value()

    def get_all(self):
        return self._enable.get_pin_value(), self._pin1.get_pin_value(), \
               self._pin2.get_pin_value()

    def set_enable_val(self, val):
        self._enable.set_pin_value(val)

    def set_pin1_val(self, val):
        self._pin1.set_pin_value(val)

    def set_pin2(self, val):
        self._pin2.set_pin_value(val)

    def set_all(self, enable, pin1, pin2):
        self._enable.set_pin_value(enable)
        self._pin1.set_pin_value(pin1)
        self._pin2.set_pin_value(pin2)
Exemplo n.º 37
0
 def __init__(self):
     # input pins
     self.a = Pin()
     self.b = Pin()
     # output pins
     self.x = Pin()
Exemplo n.º 38
0
 def test_output(self):
     p24 = Pin(24)
     p24.output(.5)
     self.assertEqual(p24.value, 0.5)
Exemplo n.º 39
0
 def __init__(self, enable, pin1, pin2):
     self._enable = Pin(enable, GPIO.OUT)
     self._pin1 = Pin(pin1, GPIO.OUT)
     self._pin2 = Pin(pin2, GPIO.OUT)
Exemplo n.º 40
0
def get_tweets_api(twitter_id, dtos, api):
    dbgpi("Getting tweets for {}".format(twitter_id))
    # get profile contents
    profile_elem = None
    user = api.GetUser(screen_name=twitter_id)
    profile_elem, profile_pin = profile(user)
    profile_img, profile_bg_img, profile_stats, profile_bio, profile_location = profile_elem
    # activities
    # TODO: indicates profile in activities
    # Or always has profile at 0th index
    # and other activities for e.g next page
    # starting at 1th index
    acts = [profile_pin]
    # TODO : Get all tweets for days
    timeline = api.GetUserTimeline(screen_name=twitter_id, count=number_of_tweets)
    tweets = []
    for tweet in timeline:
        tweets.append(str(tweet))
        dbgp(tweet)
        replies = ()
        author = () # (screen_name, profile_image_url)
        # favor whatever url it has
        urls = None
        medias = None
        profile_name = ""
        profile_url = ""
        created_at = tweet.created_at
        relations = []
        if tweet.retweeted_status: # retweet has to pull different stuff
            dbgp("Retweeting")
            rt = tweet.retweeted_status
            profile_name = tweet.user.screen_name
            profile_url = rt.user.profile_image_url
            medias = rt.media
            # TODO: medias on all these
        elif tweet.quoted_status:
            dbgp("Quote status")
            qt = tweet.quoted_status
            profile_name = tweet.user.screen_name
            profile_url = qt.user.profile_image_url
            medias = qt.media
        else:
            dbgp("Not Retweeting")
            profile_name = tweet.user.screen_name
            profile_url = tweet.user.profile_image_url
            medias = tweet.media

        urls = [status_link.format(profile_name, tweet.id)]
        media_urls = []
        if medias:
            for media in medias:
                media_url = [media.type, media.media_url]
                media_url.append(media.media_url)
                # TODO: Confirm gif saved as mp4 ?
                if media.type == "video" or media.type == "animated_gif":
                    video_url = media.video_info["variants"][-1]["url"]
                    dbgp("video {}".format(video_url))
                    media_url = ["video", media.media_url, video_url]
                media_urls.append(media_url)
        content = "@" + profile_name
        if tweet.in_reply_to_screen_name: # not replying to self
            dbgp("Replying to {}".format(tweet.in_reply_to_screen_name))
            content += " replies to @" + tweet.in_reply_to_screen_name
            if not urls:
                dbgp("Reconstructing urls:")
                urls = [status_link.format(tweet.in_reply_to_screen_name, tweet.in_reply_to_status_id)]
        elif tweet.quoted_status: # TODO: Refactor these
            content += " (quoted @" + tweet.quoted_status.user.screen_name + ": \"" + tweet.quoted_status.text + "\")"
        content += " : " + tweet.text
        dbgp(("final_urls:", urls))
        # TODO: relation
        acts.append(Pin(profile_name, profile_url, created_at, content, urls, media_urls))
    if debug:
        with open(twitter_id + ".json", "w") as json_file:
            json_dict = {}
            json_dict["profile_img"] = profile_img
            json_dict["profile_bg_img"] = profile_bg_img
            json_dict["profile_stats"] = profile_stats
            json_dict["profile_bio"] = profile_bio
            json_dict["profile_location"] = profile_location
            json_dict["acts"] = [json.dumps(dataclasses.asdict(act)) for act in acts]
            json_dict["tweets"] = tweets
            json.dump(json_dict, json_file, indent=4)
    dtos[twitter_id] = (profile_elem, acts)
    dbgpi("Finished getting tweets for {}".format(twitter_id))
    return dtos
Exemplo n.º 41
0
def ranking(request):
	if request.is_ajax() and request.method == 'GET':
		
		try:
			cat = request.GET['category']
			try:
				if cat == 'all':
					ranking_q = PinModel.objects.all()
				else:
					cat_model = CategoryModel.objects.get(category_id=cat)
					ranking_q = cat_model.pinmodel_set.all()
			except CategoryModel.DoesNotExist:
				d = {'status': 'ERR', 'data':'This category does not exist on the database '}
				data = dumps(d, cls=MyEncoder)
				return HttpResponse(data, mimetype='application/json')
		except KeyError:
			ranking_q = PinModel.objects.all()
			
		# Personal ranking
		if request.GET['perso'] == u'true':
			info_open_graph = []
			try:
				# Db-based personal ranking (only if the user is logged in with Facebook)
				fb_id = request.GET['fb_id']
				#access_token=request.GET['access_token']
				if fb_id == 'null':
					raise KeyError
				fb_u = SocialUserModel.objects.get_or_create(social_id=fb_id, net_name="facebook")[0]
				pin_id_list = [p.pin_id for p in ranking_q]
				pin_list = fb_u.pinpersomodel_set.order_by('-score').filter(pin__pin_id__in=pin_id_list)
				
				ranking_list = fun.group(lambda p: p.score, pin_list)
				ranking_list = [[e.pin for e in sub] for sub in ranking_list ]

				if ranking_list:
					nb=3 # Number of pin to post on facebook
					if len(ranking_list[0])>3:
						to_post=random.sample(ranking_list[0],nb)
					else:
						to_post=pin_list[:3]
					for p in to_post:
						p_url = 'http://'+request.get_host() + '/pin?pin_id=' + p.pin_id
						info_open_graph.append({'fb_id':fb_id, 'action':'vote for', 'obj':'pin', 'obj_url':p_url})
			except KeyError:
				# Cookie-based personal ranking
				match_list = request.session['match_list']
				score = {}
				
				for t in match_list:
					pin1, pin2, choice = t
					score.setdefault(pin1, 0)
					score.setdefault(pin2, 0)
					score[pin1], score[pin2] = Pin.getNewScore(score[pin1], score[pin2], choice == pin1)
				
				ranking_list = list(ranking_q.filter(pin_id__in=score.keys()))
				ranking_list.sort(key=lambda pin:-score[pin.pin_id])
				ranking_list = fun.group(lambda p: p.score, ranking_list)
			
			if len(ranking_list) > 0:
				data = dumps({'status':'OK', 'data':{'ranking_list':ranking_list, 'info_open_graph':info_open_graph}}, cls=MyEncoder)
				return HttpResponse(data, mimetype='application/json')
			else:
				d = {'status': 'ERR', 'data':'No pins in this category'}
				data = dumps(d, cls=MyEncoder)
				return HttpResponse(data, mimetype='application/json')
			
		# Overall ranking
		if len(ranking_q) > 0:
			ranking_q = ranking_q.order_by('-score')[:10]
			ranking_list = []
			for pin in ranking_q:
				ranking_list.append(pin)
			
			ranking_list = fun.group(lambda p: p.score, ranking_list)
			data = dumps({'status':'OK', 'data':{'ranking_list':ranking_list}}, cls=MyEncoder)
			return HttpResponse(data, mimetype='application/json')
		else:
			d = {'status': 'ERR', 'data':'Error: No pins in this category'}
			data = dumps(d, cls=MyEncoder)
			return HttpResponse(data, mimetype='application/json')
	else:
		raise Http404  
Exemplo n.º 42
0
                dbgp("{} does not exist!!!".format(twitter_id_json))
            else:
                with open(twitter_id_json, "r") as json_file:
                    json_dict = json.load(json_file)
                    # TODO: idiomatic way of deserialize json
                    # TODO : better way to write out debugs
                    acts = []
                    for act_str in json_dict["acts"]:
                        act = json.loads(act_str)
                        profile_name = act["profile_name"]
                        profile_url = act["profile_url"]
                        created_at = act["created_at"]
                        content = act["content"]
                        urls = act["urls"]
                        media_urls = act["media_urls"]
                        acts.append(Pin(profile_name, profile_url, created_at, content, urls, media_urls))
                    profile_elem = (json_dict["profile_img"], json_dict["profile_bg_img"], json_dict["profile_stats"], json_dict["profile_bio"], json_dict["profile_location"])
                    dtos[twitter_id] = (profile_elem, acts)
            continue

        if not use_api:
            dbgp("not user api")
            dtos = get_tweets(twitter_id, dtos)
        else:
            dbgp("use api")
            dtos = get_tweets_api(twitter_id, dtos, api)
        dbgp(dtos[twitter_id])


    if ui:
        app = QApplication([])
Exemplo n.º 43
0
 def test_thread_running(self):
     p24 = Pin(24)
     p24.output(.5)
     self.assertTrue(p24._thread.is_alive())
Exemplo n.º 44
0
def ask_pin(first_time_usage, callback):
    scr = switch_to_new_screen()
    first_time_title = "Choose a PIN code"
    title = "Enter your PIN code"
    if first_time_usage:
        title = first_time_title
    title_lbl = add_label(title, y=PADDING, style="title")
    btnm = lv.btnm(scr)
    # shuffle numbers to make sure 
    # no constant fingerprints left on screen
    buttons = ["%d" % i for i in range(0,10)]
    btnmap = []
    for j in range(3):
        for i in range(3):
            v = rng.get_random_bytes(1)[0] % len(buttons)
            btnmap.append(buttons.pop(v))
        btnmap.append("\n")
    btnmap = btnmap+[lv.SYMBOL.CLOSE, buttons.pop(), lv.SYMBOL.OK, ""]
    btnm.set_map(btnmap)
    btnm.set_width(HOR_RES)
    btnm.set_height(HOR_RES)
    btnm.align(scr, lv.ALIGN.IN_BOTTOM_MID, 0, 0)
    # remove feedback on press to avoid sidechannels
    btnm.set_style(lv.btnm.STYLE.BTN_PR,btnm.get_style(lv.btnm.STYLE.BTN_REL))

    pin_lbl = lv.ta(scr)
    pin_lbl.set_text("")
    pin_lbl.set_pwd_mode(True)
    style = lv.style_t()
    lv.style_copy(style, styles["theme"].style.ta.oneline)
    style.text.font = lv.font_roboto_28
    style.text.color = lv.color_hex(0xffffff)
    style.text.letter_space = 15
    pin_lbl.set_style(lv.label.STYLE.MAIN, style)
    pin_lbl.set_width(HOR_RES-2*PADDING)
    pin_lbl.set_x(PADDING)
    pin_lbl.set_y(PADDING+50)
    pin_lbl.set_cursor_type(lv.CURSOR.HIDDEN)
    pin_lbl.set_one_line(True)
    pin_lbl.set_text_align(lv.label.ALIGN.CENTER)
    pin_lbl.set_pwd_show_time(0)

    instruct_txt = "Device tamper check.\nThese words should remain #ffffff the same every time#:"
    instruct_label = add_label(instruct_txt, 180, style="hint")
    instruct_label.set_recolor(True)
    antiphish_label = add_label(antiphishing_word(""), 250)
    Pin.read_counter()

    @feed_rng
    def cb(obj, event):
        nonlocal first_time_usage
        if event == lv.EVENT.RELEASED:
            c = obj.get_active_btn_text()
            if c is None:
                return
            if c == lv.SYMBOL.CLOSE:
                pin_lbl.set_text("")
                antiphish_label.set_text(antiphishing_word(""))
            elif c == lv.SYMBOL.OK:
                # FIXME: check PIN len
                Key.generate_key(pin_lbl.get_text());
                if first_time_usage:
                    Secret.save_secret(alert);
                    callback()
                else:
                    Pin.counter -= 1
                    Pin.save_counter(alert)
                    if Pin.is_pin_valid():
                        Pin.reset_counter(alert)
                        callback()
                    else:
                        instruct_label.set_text("#f07070 Wrong pin: %d/%d #" % (Pin.counter, Pin.ATTEMPTS_MAX))
                        if Pin.counter <= 0:
                            Factory_settings.restore(alert)
                            Secret.generate_secret()
                            alert("Security","Device has been factory reset!")
                            first_time_usage = True
                            title_lbl.set_text(first_time_title)
                            instruct_label.set_text(instruct_txt)
                pin_lbl.set_text("")
                antiphish_label.set_text(antiphishing_word(""))
            else:
                instruct_label.set_text(instruct_txt)
                pin_lbl.add_text(c)
                word = antiphishing_word(pin_lbl.get_text())
                antiphish_label.set_text(antiphish_label.get_text() + " " + word)

    btnm.set_event_cb(cb);
Exemplo n.º 45
0
g_server = None
stream_enabled = True
webserver_restart = True

# Stepper
pin_IN1 = 15
pin_IN2 = 18
pin_IN3 = 4
pin_IN4 = 17
pulse_timeout = 0.001 # time to wait before sending another pulse to the stepper motor (smaller = faster but less strong and less precise)
stepper = Stepper(pin_IN1, pin_IN2, pin_IN3, pin_IN4, pulse_timeout)

# PIR sensors
IR_PIN = 23
IR2_PIN = 27
IR_front = Pin(IR_PIN, Pin.IN)
IR_back = Pin(IR2_PIN, Pin.IN)
IR_timestamp = monotonic()
IR_time_threshold = 15 # seconds before subsequent IR input is recognized again
IR_loop_running = False

# Processes object detection results and calculates if the device should adjust its rotation or not
def process_coords(data):
    im_width = stream_resolution[0]
    prioritized_target = None
    targets = data["tar"]
    for target in targets:
        if not prioritized_target:
            prioritized_target = target
        else:
            if object_detection_targets.index(target["n"]) < object_detection_targets.index(prioritized_target["n"]):
Exemplo n.º 46
0
class PinSet:

    def __init__(self, enable, pin1, pin2):
        self._enable = Pin(enable, GPIO.OUT)
        self._pin1 = Pin(pin1, GPIO.OUT)
        self._pin2 = Pin(pin2, GPIO.OUT)

    def get_enable_number(self):
        return self._enable.get_pin_number()

    def get_pin1_number(self):
        return self._pin1.get_pin_number()

    def get_pin2_number(self):
        return self._pin2.get_pin_number()

    def get_all_pin_numbers(self):
        return self._enable.get_pin_number(), self._pin1.get_pin_number(), \
               self._pin2.get_pin_number()

    def get_enable_val(self):
        return self._enable.get_pin_value()

    def get_pin1_val(self):
        return self._pin1.get_pin_value()

    def get_pin2_val(self):
        return self._pin2.get_pin_value()

    def get_all(self):
        return self._enable.get_pin_value(), self._pin1.get_pin_value(), \
               self._pin2.get_pin_value()

    def set_enable_val(self, val):
        self._enable.set_pin_value(val)

    def set_pin1_val(self, val):
        self._pin1.set_pin_value(val)

    def set_pin2(self, val):
        self._pin2.set_pin_value(val)

    def set_all(self, enable, pin1, pin2):
        self._enable.set_pin_value(enable)
        self._pin1.set_pin_value(pin1)
        self._pin2.set_pin_value(pin2)
 def __init__(self):
     self.pin = Pin(Board.BUZZ_PIN)
Exemplo n.º 48
0
 def __init__(self, enable, pin1, pin2):
     self._enable = Pin(enable, GPIO.OUT)
     self._pin1 = Pin(pin1, GPIO.OUT)
     self._pin2 = Pin(pin2, GPIO.OUT)
Exemplo n.º 49
0
        if left > 580:
            left = 300
            top += 60


#----------------------------------------------------------------------------# Main

initialise_gpio()
initialise_window()

screen = pygame.display.set_mode(window_size)
button_font = pygame.font.Font(None, 36)

pins7 = [
    Pin(a_pin_num, False, True),
    Pin(b_pin_num, False, True),
    Pin(c_pin_num, False, True),
    Pin(d_pin_num, False, True),
    Pin(e_pin_num, False, True),
    Pin(f_pin_num, False, True),
    Pin(g_pin_num, False, True)
]

buttons = [
    PinButton(20, 20, 'Red', button_font, red, off, 120, 75, 31, 22,
              Pin(red_pin)),
    PinButton(160, 20, 'Amber', button_font, amber, off, 120, 75, 22, 22,
              Pin(amber_pin)),
    PinButton(300, 20, 'Green', button_font, green, off, 120, 75, 22, 22,
              Pin(green_pin)),
Exemplo n.º 50
0
 def test_intitialization(self):
     p24 = Pin(24)
     self.assertEqual(p24.pin_number, 24)
     self.assertEqual(p24.period, 10e-3)
     self.assertEqual(p24.value, 0.0)
     self.assertTrue(p24._stopped)
Exemplo n.º 51
0
 def test_thread_running(self):
     p24 = Pin(24)
     p24.output(.5)
     self.assertTrue(p24._thread.is_alive())
Exemplo n.º 52
0
 def test_output_one(self):
     p24 = Pin(24)
     p24.output(1)
     self.assertEqual(p24.value, 1.0)
     self.assertTrue(p24._stopped)