def combine_frames(*frames): result = Observable.combine_latest( frames[0], frames[1], lambda x, y: "{} {}".format(x, y)) for f in frames[2:]: result = Observable.combine_latest( result, f, lambda x, y: "{} {}".format(x, y)) return result
def on_valid_order(self, func): def store_order_and_send_to_subscriber(order): self.latest_valid_order = order func() Observable.combine_latest( self._symbol_stream, self._price_stream, lambda symbol, price: { 'symbol': symbol, 'price': price }).subscribe(store_order_and_send_to_subscriber)
def on_valid_order(self, func): # Combine latest will emit items when any of the observables # have an item to emit. We want the latest valid values that # the user has entered in the symbol and price input # boxes. When we have that, we can enable the "submit order" # button. The form inputs and buttons are manipulated through # the subscription function that was passed in. def store_order_and_send_to_subscriber(order): self.latest_valid_order = order func() Observable.combine_latest( self._symbol_stream, self._price_stream, lambda symbol, price: { 'symbol': symbol, 'price': price } ).subscribe(store_order_and_send_to_subscriber)
def scrape_ui(driver, connection): """ Scrapes ui of application and records """ cursor = connection.cursor() links = Observable.from_(get_description_links()) \ .skip(9) \ .to_dict(lambda e: e.string, lambda e: "http://www.diagnos-online.ru/" + e["href"]) scraped_data = Observable.from_(scrape_diagnosis(driver)) \ .map(lambda e: { "diagnosis": [(d.text.split(" ")[1], float(d.text.split(" ")[0][:-1])) for d in e["diagnosis"]], "symptom_group": e["symptom_group"].text.strip(), "symptom": e["symptom"].text.strip() }) wait_links = Observable.concat(links, scraped_data).skip(1) Observable.combine_latest(wait_links, links, lambda d, l: { "diagnosis": [(i[0], i[1], match_link(l, i[0])) for i in d["diagnosis"]], "symptom_group": d["symptom_group"], "symptom": d["symptom"] }) \ .do_action(print) \ .subscribe(on_next=partial(database_writer, cursor), on_completed=partial(scrape_complete, connection, driver))
def recargaTAE(id, usuario, password, sku_code, celular, monto): #devuelve una trupla #print ("Recarga 1", id, usuario, password, sku_code, celular, monto) #srcCheckTransaction = Observable.of((14)).flat_map(lambda x : Observable.just( (x))) # .on_error_resume_next(lambda x : {'error': x } ) srcCheckTransaction = Observable.timer(2500).flat_map( lambda tiempo: verifyRecargaTAE(id, usuario, password, sku_code, celular, monto)).retry(10).timeout( 62000) source = Observable.combine_latest( solicitaTAE(id, usuario, password, sku_code, celular, monto), srcCheckTransaction, lambda o1, o2: o2) return source
def test_hot_emit_latest(): ''' Test how i can have ahot observable and every time someone new subscribe they get the last emission until a new one? Maybe just buffer or winow works? :return: ''' o1 = Observable.interval(10000).share() o2 = Observable.interval(4000).share() o = Observable.combine_latest(o1.start_with(10), o2.start_with(10), lambda a, b: a + b).replay( lambda x: x.share(), buffer_size=1) o.subscribe(lambda x: print('Im 1: ', x)) time.sleep(6) print('Nr 2 subscribing') o.subscribe(lambda x: print('Im 2: ', x)) time.sleep(100)
def update(self): self.subscription.dispose() self.query = Observable.combine_latest(self.threats, lambda *data: data) self.subscription: Disposable = self.query.subscribe(self.process)
def __init__(self, threats: [Observable], callback=None): self.threats = threats self.on_threat = callback self.query = Observable.combine_latest(threats, lambda *data: data) self.subscription: Disposable = self.query.subscribe(self.process) self.on_threat = None
Observable.from_( range(3)).window_with_count(2).flat_map(lambda x: x).subscribe(print_value) print('window with time') test_scheduler = TestScheduler() Observable.interval(50, test_scheduler).take_until( Observable.timer(100)).window_with_time(10).subscribe( lambda observable: observable.count().subscribe(print_value)) test_scheduler.start() print('combine latest') test_scheduler = TestScheduler() Observable.combine_latest( Observable.interval(1, test_scheduler).map(lambda x: 'a {}'.format(x)), Observable.interval(2, test_scheduler).map(lambda x: 'b {}'.format(x)), lambda a, b, : '{} {}'.format(a, b)).take_until( Observable.timer(5)).subscribe(print) # test_scheduler.start() print('-- zip') # test_scheduler = TestScheduler() Observable.combine_latest( Observable.interval(1, test_scheduler).map(lambda x: 'a {}'.format(x)), Observable.interval(2, test_scheduler).map(lambda x: 'b {}'.format(x)), lambda a, b, : '{} {}'.format(a, b)).take_until( Observable.timer(5)).subscribe(print) test_scheduler.start()
def audio_encoder(sources): http_s3_error, route_s3_error = make_error_router() http_encode_error, route_encode_error = make_error_router() # Parse configuration parsed_argv = (sources.argv.argv.skip(1).let( argparse.argparse, parser=Observable.just( argparse.Parser(description="audio encode server")), arguments=Observable.from_([ argparse.ArgumentDef(name='--config', help="Path of the server configuration file") ])).filter(lambda i: i.key == 'config').subscribe_on( aio_scheduler).share()) # monitor and parse config file monitor_init = (parsed_argv.flat_map(lambda i: Observable.from_([ inotify.AddWatch( id='config', path=i.value, flags=aionotify.Flags.MODIFY), inotify.Start(), ]))) config_update = (sources.inotify.response.debounce(5000).map( lambda i: True).start_with(True)) read_config_file = (Observable.combine_latest( parsed_argv, config_update, lambda config, _: file.Read(id='config', path=config.value))) config = sources.file.response.let(parse_config) # Transcode request handling encode_init = (config.map(lambda i: i.encode).distinct_until_changed().map( lambda i: encoder.Configure(samplerate=i.samplerate, bitdepth=i.bitdepth))) encode_request = ( sources.httpd.route.filter(lambda i: i.id == 'flac_transcode'). flat_map(lambda i: i.request).flat_map(lambda i: Observable.just( i, encode_scheduler)).map(lambda i: encoder.EncodeMp3( id=i.context, data=i.data, key=i.match_info['key']))) encoder_request = Observable.merge(encode_init, encode_request) # store encoded file store_requests = (sources.encoder.response.let( catch_or_flat_map, error_router=route_encode_error, error_map=lambda i: httpd.Response(data='encode error'.encode('utf-8'), context=i.args[0].id, status=500)). observe_on(s3_scheduler).map(lambda i: s3.UploadObject( key=i.key + '.flac', data=i.data, id=i.id, ))) # acknowledge http request http_response = (sources.s3.response.let( catch_or_flat_map, error_router=route_s3_error, error_map=lambda i: httpd.Response(data='upload error'.encode('utf-8'), context=i.args[0].id, status=500)).map( lambda i: httpd.Response( data='ok'.encode('utf-8'), context=i.id, ))) # http server http_init = (config.take(1).flat_map(lambda i: Observable.from_([ httpd.Initialize(request_max_size=0), httpd.AddRoute( methods=['POST'], path='/api/transcode/v1/flac/{key:[a-zA-Z0-9-\._]*}', id='flac_transcode', ), httpd.StartServer(host=i.server.http.host, port=i.server.http.port), ]))) http = Observable.merge(http_init, http_response, http_s3_error, http_encode_error) # s3 database s3_init = (config.take(1).map(lambda i: s3.Configure( access_key=i.s3.access_key, secret_key=i.s3.secret_key, bucket=i.s3.bucket, endpoint_url=i.s3.endpoint_url, region_name=i.s3.region_name, ))) # merge sink requests file_requests = read_config_file s3_requests = Observable.merge(s3_init, store_requests) return Sink( encoder=encoder.Sink(request=encoder_request), s3=s3.Sink(request=s3_requests), file=file.Sink(request=file_requests), httpd=httpd.Sink(control=http), inotify=inotify.Sink(request=monitor_init), )
def camera_processor(): # open a video capture feed cam = cv2.VideoCapture(cam_name) #init ros & camera stuff # pub = rospy.Publisher(topics.CAMERA, String, queue_size=10) no_barrel_pub = rospy.Publisher(topics.CAMERA, String, queue_size=10) line_angle_pub = rospy.Publisher(topics.LINE_ANGLE, Int16, queue_size=0) global lidar lidar_obs = rx_subscribe(topics.LIDAR) Observable.combine_latest(lidar_obs, lambda n: (n)) \ .subscribe(update_lidar) rospy.init_node('camera') rate = rospy.Rate(10) exposure_init = False rawWidth = 640 rawHeight = 480 #camera_info = CameraInfo(53,38,76,91,134)#ground level#half (134 inches out) camera_info = CameraInfo(53, 40, 76, 180, 217, croppedWidth, croppedHeight) #ground level# 3/4 out while not rospy.is_shutdown(): #grab a frame ret_val, img = cam.read() # camera will set its own exposure after the first frame, regardless of mode if not exposure_init: update_exposure(cv2.getTrackbarPos('exposure', 'img_HSV')) update_auto_white(cv2.getTrackbarPos('auto_white', 'img_HSV')) exposure_init = True #record a video simultaneously while processing if ret_val == True: out.write(img) #for debugging # cv2.line(img,(640/2,0),(640/2,480),color=(255,0,0),thickness=2) # cv2.line(img,(0,int(480*.25)),(640,int(480*.25)),color=(255,0,0),thickness=2) #crop down to speed processing time #img = cv2.imread('test_im2.jpg') dim = (rawWidth, rawHeight) img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) cropRatio = float(croppedHeight) / float(rawHeight) crop_img = img[int(rawHeight * float(1 - cropRatio)):rawHeight, 0:rawWidth] # crops off the top 25% of the image cv2.imshow("cropped", crop_img) #process the cropped image. returns a "birds eye" of the contours & binary image img_displayBirdsEye, contours = process_image(crop_img, camera_info) #raw contours = convert_to_cartesian(camera_info.map_width, camera_info.map_height, contours) #for filtered barrels vec2d_contour = contours_to_vectors(contours) #replaces NAV filtered_contours = filter_barrel_lines(camera=vec2d_contour, angle_range=8, lidar_vecs=lidar, mag_cusion=300, barrel_cusion=5) #EXTEND THE LINES filtered_cartesian_contours = vectors_to_contours(filtered_contours) try: closest_filtered_contour = closest_contour( filtered_cartesian_contours) # print "CLOSESTCONTOUR: ",closest_filtered_contour x_range = 5000 contour_lines = [] interval = 40 #just one line_angle, slope, intercept = calculate_line_angle( closest_filtered_contour) for x in range(x_range * -1, x_range): if x % interval == 0: y = slope * x + intercept v = Vec2d.from_point(x, y) contour_lines.append(v) except TypeError: #no camera data contour_lines = [] line_angle = 0 #build the camera message with the contours and binary image # local_map_msg = CameraMsg(contours=contours, camera_info=camera_info) # filtered_map_msg=CameraMsg(contours=contour_lines,camera_info=camera_info)#1 polyfit contour c = [] for cs in filtered_cartesian_contours: for v in cs: c.append(v) filtered_map_msg = CameraMsg( contours=c, camera_info=camera_info) #all raw contours #make bytestream and pass if off to ros # local_map_msg_string = local_map_msg.pickleMe() filtered_map_msg_string = filtered_map_msg.pickleMe() #rospy.loginfo(local_map_msg_string) # pub.publish(local_map_msg_string) no_barrel_pub.publish(filtered_map_msg_string) line_angle_pub.publish(line_angle) if cv2.waitKey(1) == 27: break rate.sleep() cv2.destroyAllWindows()
l1 = [] d = {"x1": 1, "x2": 2} l1.append(d) l1.append(d) d = {"x1": 2, "x2": 2} l2 = [] l2.append(d) d = {"x1": 3, "x2": 2} l2.append(d) l2.append(d) l2.append(d) x1 = Observable.from_(l1) x2 = Observable.from_(l2) xc = Observable.combine_latest(x1, x2, lambda a1, a2: [a1, a2]) xc.subscribe(lambda s: print(s)) print("===================") from rx.subjects import Subject print("50以下は無効化してしまう壁\n") stream = Subject() d = stream.do_action(lambda x: print(x)) \ .filter(lambda param: param>50) \ .subscribe(lambda result: print("壁を貫通!{0}のダメージ".format(result))) # 攻撃! stream.on_next(0) stream.on_next(50) stream.on_next(51)
print('-- window_with_time') wwt_test_scheduler = TestScheduler() Observable.interval(50, wwt_test_scheduler).take_until( Observable.timer(100)).window_with_time(10).subscribe( lambda observable: observable.count().subscribe(print_value)) # test_scheduler.start() print('-- Combine Latest') cl_test_scheduler = TestScheduler() Observable.combine_latest( Observable.interval(1, cl_test_scheduler).map(lambda x: 'a: {}'.format(x)), Observable.interval(2, cl_test_scheduler).map(lambda x: 'b: {}'.format(x)), lambda a, b: '{}; {}'.format(a, b)).take_until( Observable.timer(1)).subscribe(print_value) # cl_test_scheduler.start() print('-- Zip') zip_test_scheduler = TestScheduler() Observable.zip( Observable.interval(1, zip_test_scheduler).map(lambda x: 'a: {}'.format(x)), Observable.interval(2, zip_test_scheduler).map(lambda x: 'b: {}'.format(x)), lambda a, b: '{}; {}'.format(a, b)).take_until( Observable.timer(1)).subscribe(print_value)
Observable.from_(l).filter(filter_x1).subscribe(print) results = [] print("===================") import time import random random.seed(123) x1 = Observable.interval(random.randint(50, 500)) x2 = Observable.interval(random.randint(50, 500)) x3 = Observable.interval(random.randint(50, 500)) xc = Observable.combine_latest(x1, x2, x3, lambda a1, a2, a3: [a1, a2, a3]) xc.subscribe(lambda s: print(s)) # Observable.from_(x1).subscribe(print) print("===================") # from rx import Observable # Observable.interval(1000) \ # .map(lambda i: "{0} Mississippi".format(i)) \ # .subscribe(lambda s: print(s)) # Observable.interval(1000) \ # .subscribe(on_next=print, on_error=\ # lambda e: print('if I try to print the error, it does nothing,', e))
cal_icon = "^fn(material icons)^fn() " time = Observable.interval(6000) \ .map(lambda _: cal_icon+"{dt:%a} {dt:%b} {dt.day} {dt:%H}:{dt:%M}" .format(dt=datetime.now())) \ .distinct_until_changed() ys = Observable.interval(6000) \ .map(get_disks) \ documents = ys.map(lambda x: x[b"Documents"]).map(make_bar) sda2 = ys.map(lambda x: x[b"/dev/sda2"]).map(make_bar) disks = Observable.combine_latest(sda2, documents, lambda x, y: disk_icon + x + " " + y) \ .distinct_until_changed() cpu = Observable.interval(6000) \ .map(get_cpu) \ .map(lambda x: cpu_icon+make_bar(x)) mem = Observable.interval(6000) \ .map(get_mem) \ .map(lambda x: mem_icon+make_bar(x)) mail = Observable.interval(6000).map(lambda x, y: mail_icon+str(get_mail(x))) \ .distinct_until_changed() mail_headings = Observable.interval(6000).map(lambda x, y: get_mail_headings(x)) windows = Observable.interval(500) \