示例#1
0
    def head_tilt_async(self, degrees):
        """Tilt Dash/Cue's head up or down.

        See Also: Robot.head_tilt()

        Returns: wonder.future.Future object.
        """
        if degrees > 7:
            degrees = 7
        if degrees < -22.5:
            degrees = -22.5
        head_tilt_threshold = 2.0
        self._head_tilt(degrees)
        fut = future.Future()
        call_time = time.time()
        head_tilt_timeout = 1.0

        def head_tilt_done_cb(sensor_obj):
            if (time.time() - call_time) < MIN_TIMEOUT:
                return True
            if (time.time() - call_time) > head_tilt_timeout:
                fut.set_result(None)
                return False
            try:
                tilt_angle = sensor_obj['HEAD_POSITION_TILT']['degree']
            except KeyError:
                return True
            if abs(tilt_angle - degrees) < head_tilt_threshold:
                fut.set_result(None)
                return False
            else:
                return True

        self._add_sensor_event_listener(head_tilt_done_cb)
        return fut
示例#2
0
    def head_pan_async(self, degrees):
        """ Pan Dash/Cue's head (asynchronous)

        See also: Robot.head_pan()

        Returns: A wonder.future.Future object.
        """
        if degrees > 120:
            degrees = 120
        if degrees < -120:
            degrees = -120
        head_pan_threshold = 2.0
        self._head_pan(degrees)
        fut = future.Future()
        call_time = time.time()
        head_pan_timeout = 1.0

        def head_pan_done_cb(sensor_obj):
            if (time.time() - call_time) < MIN_TIMEOUT:
                return True
            if (time.time() - call_time) > head_pan_timeout:
                fut.set_result(None)
                return False
            try:
                pan_angle = sensor_obj['HEAD_POSITION_PAN']['degree']
            except KeyError:
                return True
            if abs(pan_angle - degrees) < head_pan_threshold:
                fut.set_result(None)
                return False
            else:
                return True

        self._add_sensor_event_listener(head_pan_done_cb)
        return fut
示例#3
0
    def pose_async(self, x, y, degrees, pose_time):
        """Move the robot to a new position (asynchronous)

        See also: robot.pose()

        Returns: a wonder.future.Future object.
        """
        self._pose(x, y, degrees, pose_time)
        fut = future.Future()
        call_time = time.time()

        def pose_done_cb(sensor_obj):
            if (time.time() - call_time) < MIN_TIMEOUT:
                return True
            try:
                # The watermark field is "sparse" so it may not appear in every sensor packet
                if sensor_obj['BODY_POSE']['watermark'] == 255:
                    fut.set_result(None)
                    return False
                else:
                    return True
            except KeyError:
                return True

        self._add_sensor_event_listener(pose_done_cb)
        return fut
示例#4
0
    def wait_until_robot_tilted(self):
        """Halt the program until the robot is tilted"""
        fut = future.Future()

        def _cb(tilted):
            if tilted:
                fut.set_result(None)
                return False
            return True

        self.on_robot_tilted(_cb)
        fut.wait()
示例#5
0
    def wait_until_button(self, button_id):
        # Wait for a button press.
        # button_id: A string. One of 'BUTTON_MAIN', 'BUTTON_1', 'BUTTON_2', 'BUTTON_3'
        fut = future.Future()

        def _cb(button_down):
            if button_down:
                fut.set_result(None)
                return False
            return True

        self.on_button(button_id, _cb)
        fut.wait()
示例#6
0
    def wait_until_voice(self):
        """Halt the program until a voice is heard.

        Example:
            import wonder

            robot = wonder.Robot()

            print("Please speak.")
            robot.wait_until_voice()
            print("Voice detected!")
        """
        fut = future.Future()

        def _cb():
            fut.set_result(None)
            return False

        self.on_voice_heard(_cb)
        fut.wait()
示例#7
0
    def wait_until_clap(self):
        """Halt the program until a clap is heard.

        Example:
            import wonder

            robot = wonder.Robot()

            print("Please clap.")
            robot.wait_until_clap()
            print("Clap detected!")
        """
        fut = future.Future()

        def _cb():
            fut.set_result(None)
            return False

        self.on_clap_heard(_cb)
        fut.wait()
示例#8
0
    def sound_async(self, filename, volume):
        """The asynchronous version of Robot.sound().

        See also: Robot.sound()

        Returns:
            A Future object. See: future.Future() in :mod:`future`
        """
        self._sound(filename, volume)
        fut = future.Future()
        call_time = time.time()

        def sound_done_cb(sensor_obj):
            if (time.time() - call_time) < MIN_TIMEOUT:
                return True
            if not sensor_obj.SOUND_PLAYING.flag:
                fut.set_result(None)
                return False
            else:
                return True

        self._add_sensor_event_listener(sound_done_cb)
        return fut
示例#9
0
    keyRast.nodataToZero()
    regionRast.nodataToZero()
    total=keyRast.sum()

    #Creates a raster with all cells within a region given the regions fraction of the national total
    totFractionRast=regionRast.replace(totFractionList)
    totFractionRast.nodataToZero()
    #For all regions, calculate the regional sum, set the key values to key/regSum
    resKeyArray=numpy.zeros(keyRast.data.shape)
    maskArray=numpy.zeros(regionRast.data.shape)
    print "Regionalizing key raster"
    print "Original sum: ",total
    for code in codesInRegionRast:
        totalEmis=regionalTotals.totalDict[str(int(code))]
        emission=totalEmis.emisDict[subst]
        print "Regionalizing region: " + str(code)+" with the regional total: ",emission     
        regDistThread=future.Future(distributeRegion,[regionRast.data,keyRast.data,code,resKeyArray,emission])         
        resKeyArray=regDistThread()
    keyRast.data=resKeyArray
    
    
    resultRast=(totFractionRast*keyRast)*regionalTotals.regSum(subst)
    
    #Assure that the total is unchanged
    resultRast=(resultRast/resultRast.sum())*total
    
    resultRasterName=path.join(resultRasterPath,"redist_"+keyRastPrefix+subst+keyRastPostfix)        
    resultRast.write(resultRasterName)
    print "wrote result for substance: ",subst

示例#10
0
import sys
import os

sys.path.append("../util")
import util
import future

#google_news_rss_url =

feed_url_list = [
    "https://www.google.com/alerts/feeds/13351239696798776176/3559988229559370877",
    "http://feeds.reuters.com/reuters/businessNews",
]

future_calls = [
    future.Future(feedparser.parse, rss_url) for rss_url in feed_url_list
]
feeds = [future_obj() for future_obj in future_calls]

entries = []
for feed in feeds:
    entries.extend(feed["items"])

#for entry in entries:
#    print(entry.keys())
#    if not "date_parsed" in entry:
#        entry["date_parsed"] = entry["published"]

try:
    sorted_entries = sorted(entries,
                            key=lambda entry: parser.parse(entry["published"]))
示例#11
0
                print "Summing sector: ", sector, "year: ", year, "substance: ", substance

                headerYear.append(year)
                headerSubstance.append(substance)
                headerSector.append(sector)

                emisRast.nodataToZero()
                if flippa:
                    emisRast.flip()
                print "Finding all mask codes"

                for i in range(len(maskCodes)):
                    ortRast = PyRaster.raster()
                    code = maskCodes[i]
                    #print "summing for mask code: ", code
                    sumThread = future.Future(
                        sumRegion, [maskRast.data, emisRast.data, code])
                    sum = sumThread()
                    rows[i].append(sum)
            except:
                print "No ", substance, " in sector ", sector, " year: ", year

output = open(summaryFile, 'w')

for i in range(len(headerYear)):
    output.write(headerYear[i] + "\t")
output.write("\n")

for i in range(len(headerSector)):
    output.write(headerSector[i] + "\t")
output.write("\n")
示例#12
0
def clean_html(content):
    soup = BeautifulSoup(content, 'html.parser')
    return soup.get_text()[:850]

def get_date(entry):
    date = entry.get('published_parsed') or entry.get('date_parsed') or entry.get('updated_parsed')
    return f"{date[0]}-{date[1]}-{date[2]} {date[3]}:{date[4]}"

def get_content(entry):
    if 'content' in entry and len(entry.get('content')) > 0:
        return entry.get('content')[0]['value']
    elif 'summary' in entry:
        return entry.get('summary')

if __name__ == '__main__':
    future_calls = [future.Future(feedparser.parse, feed) for feed in urls]
    feeds = [feed() for feed in future_calls]

    entries = []
    for feed in feeds:
        if not feed or 'items' not in feed:
            print('<!--{}-->'.format(feed))
            continue
        for item in feed['items']:
            item['feed'] = feed.feed
        entries.extend(feed['items'])

    sorted_entries = sorted(entries, key=lambda x: x.get('published_parsed', None) or x.get('date_parsed', 0))
    sorted_entries.reverse() # Most recent first

    doc, tag, text = yattag.Doc().tagtext()