def simulate_stop_before_crash(first_car_speed=10.0, first_lane=0, first_intention='s', iterations=1000, collision_x=335, collision_y=345): screen_width = 768 screen, background, intersection_background, font = init_graphic_environment( screen_width, 768) channel = Channel() first_car = random_car(name=1, initial_speed=first_car_speed, acceleration_rate=5, full_intersection=full_intersection_rect, channel=channel, inner_intersection=inner_intersection_rect, lane=first_lane, intention=first_intention, create_sensor_flag=True) simulation_car = SimulationCar(first_car) ticks = simulation_car.get_ticks_to_goal(collision_x, collision_y) print(ticks) for i in range(iterations): screen.blit(background, (0, 0)) screen.blit(intersection_background, (0, 0)) screen.blit(simulation_car.rotated_image, simulation_car.screen_car) pygame.display.update(screen.get_rect()) simulation_car.update() if simulation_car.collision_with_point(collision_x, collision_y): print('Collision with point: ' + str(i)) if i > 140: print(simulation_car.get_ticks_to_goal(collision_x, collision_y)) print(simulation_car.collision_with_point(collision_x, collision_y)) pygame.display.quit()
def get_channel(channel_name): if Channel.exists(channel_name): channel = Channel.get(channel_name) else: channel = Channel(channel_name) channel.save() return channel
def check_channel(id, json=True, attempts=MAX_DEFAULT_ATTEMPTS): if not check_request_key(request): return 'Unauthorized', 401 logger.debug("Checking channel: %s", id) # get the channel info channel = db.get_channel(int(id)) # get the attempts parameter if not (request.json is None) and 'attempts' in request.json: attempts = request.json['attempts'] logger.debug("Attempts: %s", attempts) attempts = int(attempts) # check the channel url logger.debug("Checking channel url: %s", channel['url']) result = m3uchecker.check_link(channel['url'], attempts) logger.debug("Result: %s", result) print(result) # save the result last_check = int(time.mktime(datetime.datetime.now().timetuple())) * 1000 newChannel = Channel(position=channel['position'], name=channel['name'], metadata=channel.get('metadata', ''), url=channel['url'], checked=result, last_check=last_check) db.update_channel(int(id), newChannel) if json: return jsonify({'checked': result, 'last_check': last_check}) else: return result
def play_channel(self, channel, play_index): log.debug('Playing channel: {0}'.format(channel.id)) self.channel = Channel(channel.to_dict()) self.channel.play_index = play_index url = self.channel.streamurls[play_index] log.debug('Selected url: {0}'.format(url)) url_components = urlparse(url) app = QApplication.instance() if app.protocol_plugins.get(url_components.scheme, None): protocol_class = app.protocol_plugins[url_components.scheme] log.debug('Using {0} to process {1}'.format(protocol_class.name, url)) try: self.protocol = protocol_class(self) self.protocol.protocol_ready.connect(self.protocol_ready) self.protocol.protocol_error.connect(self.protocol_error) self.protocol.load_url(url, channel.args(url)) except ProtocolException as e: log.error(e.message) QMessageBox.critical( self, self.tr("Error playing channel"), self.tr("Protocol crashed with error: {0}").format(e.message) ) self.playback_error.emit(self.channel) self.channel = None else: log.error('No suitable protocol found for {0}'.format(url))
def test_destination_lane(self): channel = Channel() car1 = random_car(name=1, initial_speed=20, full_intersection=self.full_intersection_rect, channel=channel, inner_intersection=self.inner_intersection_rect, lane=0, intention='s') car2 = random_car(name=1, initial_speed=20, full_intersection=self.full_intersection_rect, channel=channel, inner_intersection=self.inner_intersection_rect, lane=0, intention='l') car3 = random_car(name=1, initial_speed=20, full_intersection=self.full_intersection_rect, channel=channel, inner_intersection=self.inner_intersection_rect, lane=0, intention='r') self.assertEqual(2, car1.destination_lane()) self.assertEqual(3, car2.destination_lane()) self.assertEqual(1, car3.destination_lane())
def test_info_messages(self): channel = Channel() sup_car = Car(name=1, lane=0, intention='s', channel=channel, pos_x=1, pos_y=1) second_car = Car(name=2, lane=1, intention='s', channel=channel, pos_x=2, pos_y=2) normal_car = Car(name=3, lane=3, intention='l', channel=channel, pos_x=3, pos_y=3) # Car 1 enters do_round([sup_car], channel) sup_car.enter_intersection() self.assertTrue(1 in sup_car.get_leaf_cars()) # Car 2 enters and Car 1 becomes supervisor, Car 1 sends info message before Car 2 enters do_round([sup_car, second_car], channel) second_car.enter_intersection() # Car 3 enters and Car2 receives WelcomeMessage and Second At Charge, Car 1 and Car 2 send Info # before Car 3 enters do_round([sup_car, second_car, normal_car], channel) # Check leaf cars update self.assertEqual({2}, sup_car.get_leaf_cars()) self.assertEqual({2}, second_car.get_leaf_cars()) # Check info message from sup_car and follow lists self.assertEqual({}, sup_car.get_following_cars()) self.assertEqual([1], list(second_car.get_following_cars().keys())) self.assertEqual(1, second_car.get_following_cars()[1]['pos_x']) normal_car.enter_intersection() # Car 3 receives Welcome Message do_round([sup_car, second_car, normal_car], channel) self.assertEqual({3}, sup_car.get_leaf_cars()) self.assertEqual({3}, second_car.get_leaf_cars()) self.assertEqual({3}, normal_car.get_leaf_cars()) self.assertEqual([1], list(second_car.get_following_cars().keys())) self.assertEqual([2], list(normal_car.get_following_cars().keys())) self.assertTrue(2, normal_car.get_following_cars()[2]['pos_x'])
def create_channel(channel_payload: ChannelType, request: Request, response: Response): # Get logged in user user = auth_module.get_me(request=request) if user is None: return {"msg": "access denied!"} # Channel fields channel = Channel() channel.name = channel_payload.name channel.summary = channel_payload.summary channel.tags = channel_payload.tags channel.admins = [user.get("_id")] # Channel cover cover = Photo() cover._id = uuid.uuid4() cover.filename = "path-filename" cover.path = "path-photo" channel.cover = cover channel.save() return {"msg": "create channel route!"}
def generate_channels(self): num_channels = randint(100, 200) for i in range(0, num_channels): self.channels.append(Channel(i, name="Channel %d" % i, description="Description of channel %d" % i)) if CREATE_MY_CHANNEL: # Pick one of these channels as your channel self.my_channel = randint(0, len(self.channels) - 1)
async def get_channel_records(skip: int, take: int): collection = get_channel_collection() results = [] async for channel in collection.find({}).skip(skip).limit(take): results.append(Channel(**channel)) return results
def init_db(): with app.app_context(): db.create_all() default_channel = { 'name': '大厅', 'description': '没有描述', } Channel(default_channel).save()
def setUp(self): self.intention_list = ['l', 's', 'r'] self.ticks = 15 self.channel = Channel() self.test_case = {1: {'lane': 0, 'intention': 's', 'tick': 0}, 2: {'lane': 0, 'intention': 'l', 'tick': 1}, 3: {'lane': 3, 'intention': 'l', 'tick': 3}, 4: {'lane': 1, 'intention': 'r', 'tick': 5}, 5: {'lane': 2, 'intention': 's', 'tick': 7}}
def accept(self): channel_name = self.channel_name_lineedit.text() channel_type = 'tv' if self.channel_type_buttongroup.checkedButton( ) == self.tv_radiobutton else 'radio' stream_url = self.stream_url_lineedit.text() if len(channel_name.strip()) == 0: QMessageBox.critical(self, self.tr("Could not save channel"), self.tr("Channel name cannot be empty.")) return if len(stream_url.strip()) == 0: QMessageBox.critical(self, self.tr("Could not save channel"), self.tr("Stream address cannot be empty.")) return schema_supported = False for schema in list(QApplication.instance().protocol_plugins.keys()): if stream_url.startswith(schema): schema_supported = True break if not schema_supported: QMessageBox.critical( self, self.tr("Could not save channel"), self.tr( "This protocol is not supported by TV-Maxe or your system." )) return byte_array = QByteArray() buffer = QBuffer(byte_array) buffer.open(QIODevice.WriteOnly) self.select_icon_button.icon().pixmap(256, 256).save(buffer, 'PNG') string_io = BytesIO(byte_array) string_io.seek(0) icon_data = string_io.read() params_dict = {} for i in range(self.params_treeview.model().rowCount()): key = self.params_treeview.model().item(i, 0).text() value = self.params_treeview.model().item(i, 1).text() params_dict[key] = value channel_dict = { "id": uuid.uuid4().hex, "icon": icon_data, "name": channel_name, "streamurls": json.dumps([stream_url]), "params": json.dumps({stream_url: params_dict}) } channel = Channel(channel_dict, channel_type) self.channel_saved.emit(channel) self.close() self.deleteLater()
def parsem3u(infile): """ Parse a m3u file generating a list of Channel objects. Channels file is formatted in this way: #EXTINF:-1 metadata, channel_name channel_url e.g.: #EXTINF:-1 tvg-id="" group-title="GROUP1" tvg-logo="001.png",Channel 1 http://url :param infile: the file to parse :return: a dict with 'stats': [parsedChannel, parsedErrors], 'channels': [channels_list] """ infile = open(infile, 'r') errors = 0 success = 0 channels = [] line = infile.readline() while line: if line.startswith('#EXTINF:'): channelInfo = line.strip('#EXTINF:-1 ').split(',') try: metadata = channelInfo[0].strip() name = re.sub(r'\[[^]]*\]', '', channelInfo[1].strip()) # read the url on the next line url = infile.readline().strip() channel = Channel(position=len(channels) + 1, metadata=metadata, name=name, url=url) channels.append(channel) success += 1 # new entry line = infile.readline() except IndexError: # the channel has no name, skip it errors += 1 print("error") # skip the url infile.readline() line = infile.readline() else: # non interesting line, skip it line = infile.readline() infile.close() return {'stats': [success, errors], 'channels': channels}
def update_channel(id): if not check_request_key(request): return 'Unauthorized', 401 logger.debug("Updating channel: %s", id) channel = Channel(position=request.json['position'], name=request.json['name'], metadata=request.json.get('metadata', ''), url=request.json['url'], checked=request.json['checked'], last_check=request.json['last_check']) newId = db.update_channel(int(id), channel) return jsonify(newId)
def channel_creation(): channel = request.form.get("channel") description = request.form.get("description") u_id = request.form.get("u_id") channel_dao.saveChannel( Channel(channel=channel, description=description, u_id=u_id)) # db.execute("INSERT INTO user_channel(channel,description,u_id) VALUES(:channel,:description,:u_id)", # {"channel": channel, "description": description, "u_id": u_id}) # db.commit() # db.close() return redirect(url_for('channels'))
def add_channel(): if not check_request_key(request): return 'Unauthorized', 401 logger.debug("Adding a channel: %s %s %s %s", request.json['position'], request.json['name'], request.json.get('metadata', ''), request.json['url']) newChannel = Channel(position=request.json['position'], name=request.json['name'], metadata=request.json.get('metadata', ''), url=request.json['url']) id = db.add_channel(newChannel) return jsonify(id)
def __convert_item_to_channel(item): if 'channelId' not in item['snippet']: cid = item['id'] else: cid = item['snippet']['channelId'] return Channel( name=item['snippet']['title'], cid=cid, description=item['snippet']['description'], picture=item['snippet']['thumbnails']['default']['url'] )
def setUp(self): self.full_intersection_rect = pygame.Rect(0, 0, 768, 768) self.inner_intersection_rect = pygame.Rect(280, 280, 210, 210) self.default_channel = Channel() self.default_car = random_car( name=1, initial_speed=20, full_intersection=self.full_intersection_rect, channel=self.default_channel, inner_intersection=self.inner_intersection_rect, lane=0, intention='s')
def test_coordination_ticks(self): channel = Channel() car = Car(name=1, lane=randint(0, 3), intention=choice(self.intention_list), channel=channel, pos_x=randint(0, 3), pos_y=randint(0, 3)) self.assertEqual(None, car.get_supervisor_car()) do_round(cars=[car], channel=channel) car.enter_intersection() do_round(cars=[car], channel=channel) self.assertTrue(1 in car.get_graph()) self.assertEqual([], list(car.get_following_cars().keys())) self.assertEqual(1, car.get_supervisor_car()) self.assertEqual(None, car.get_second_at_charge())
def register(): name = request.form.get('name') icon = request.form.get('icon') if not name: return to_error_json("name is required") elif Channel.query.filter(Channel.name == name).first() is not None: return to_error_json("name {} is already in use".format(name)) channel = Channel(name=name, icon=icon) db.session.add(channel) db.session.commit() return jsonify(channel.dict(True))
def render_PUT(self, request): parameters = http.parse_qs(request.content.read(), 1) print parameters channel_name = parameters['name'][0] channel_description = parameters['description'][0] my_channel = Channel(len(tribler_utils.tribler_data.channels) - 1, name=channel_name, description=channel_description) tribler_utils.tribler_data.channels.append(my_channel) tribler_utils.tribler_data.my_channel = my_channel.id return json.dumps({"added": my_channel.id})
def test_second_at_charge_leave(self): channel = Channel() car1 = Car(name=1, lane=0, intention='l', channel=channel) do_round([car1], channel) car1.enter_intersection() for i in range(4): do_round([car1], channel) self.assertTrue(car1.is_supervisor()) car2 = Car(name=2, lane=1, intention='l', channel=channel) do_round([car1, car2], channel) car2.enter_intersection() car3 = Car(name=3, lane=2, intention='s', channel=channel) do_round([car1, car2, car3], channel) car3.enter_intersection() car4 = Car(name=4, lane=2, intention='r', channel=channel) do_round([car1, car2, car3, car4], channel) car4.enter_intersection() # follow lists: # 1: [] # 2: [1] # 3: [2] # 4: [3] channel.do_round() for car in [car1, car2, car3, car4]: self.assertEqual([1, 2], [car.get_supervisor_car(), car.get_second_at_charge()]) # Before car 2 leaves self.assertEqual([], list(car1.get_following_cars().keys())) self.assertEqual([1], list(car2.get_following_cars().keys())) self.assertEqual([2], list(car3.get_following_cars().keys())) self.assertEqual([3], list(car4.get_following_cars().keys())) for car in [car1, car2, car3, car4]: self.assertEqual({4}, car.get_leaf_cars()) do_round([car1, car2, car3, car4], channel) car2.leave_inner_intersection() do_round([car1, car2, car3, car4], channel) for car in [car1, car3, car4]: self.assertEqual([1, 3], [car.get_supervisor_car(), car.get_second_at_charge()]) self.assertEqual([1, None], [car2.get_supervisor_car(), car2.get_second_at_charge()]) self.assertTrue(car1.is_supervisor()) self.assertTrue(car3.is_second_at_charge()) self.assertFalse(car4.is_supervisor()) self.assertFalse(car4.is_second_at_charge()) for car in [car1, car2, car3, car4]: self.assertTrue(2 not in car.get_graph()) for node in car.get_graph().values(): self.assertTrue(2 not in node.get_follow_list()) # After self.assertEqual([], list(car1.get_following_cars().keys())) self.assertEqual([1], list(car2.get_following_cars().keys())) self.assertEqual([], list(car3.get_following_cars().keys())) self.assertEqual([3], list(car4.get_following_cars().keys()))
def test_enter_intersection(self): channel = Channel() car = random_car(name=1, initial_speed=20, full_intersection=self.full_intersection_rect, channel=channel, inner_intersection=self.inner_intersection_rect, lane=0, intention='s') self.assertFalse(car.get_inside_full_rectangle()) self.assertFalse(car.inside_full_intersection()) self.assertTrue(car not in channel.get_cars()) for _ in range(25): do_round([car], channel) self.assertTrue(car in channel.get_cars()) self.assertTrue(car.get_inside_full_rectangle()) self.assertTrue(car.inside_full_intersection())
def tv_channels(self): channels = [] conn = sqlite3.connect(self.cached_path) conn.row_factory = sqlite3.Row c = conn.cursor() c.execute("SELECT * FROM tv_channels") for row in c.fetchall(): channel = Channel(row, 'tv', self.origin_url) channels.append(channel) log.debug('Found TV Channel: {0} with ID: {1}'.format( channel.name, channel.id)) conn.close() return channels
def test_second_at_charge_message(self): channel = Channel() sup_car = Car(name=1, lane=randint(0, 3), intention=choice(self.intention_list), channel=channel, pos_x=randint(0, 3), pos_y=randint(0, 3)) second_car = Car(name=2, lane=randint(0, 3), intention=choice(self.intention_list), channel=channel, pos_x=randint(0, 3), pos_y=randint(0, 3)) do_round([sup_car], channel) sup_car.enter_intersection() self.assertEqual(None, sup_car.get_supervisor_car()) do_round([sup_car, second_car], channel) second_car.enter_intersection() self.assertTrue(sup_car.is_supervisor()) self.assertTrue(1 in sup_car.get_graph() and 2 in sup_car.get_graph()) self.assertEqual(None, second_car.get_supervisor_car()) do_round([sup_car, second_car], channel) self.assertEqual(1, second_car.get_supervisor_car()) self.assertTrue(second_car.is_second_at_charge())
def channels_add(): rdata = request.get_json() name = rdata.get('name', None) sim_id = rdata.get('sim_id', None) sim_pass = rdata.get('sim_pass', None) phone = rdata.get('phone', None) balance_ussd = rdata.get('balance_ussd', None) channel = Channel() channel.name = name channel.sim_id = sim_id channel.sim_pass = sim_pass channel.phone = phone channel.balance_ussd = balance_ussd channel.save() return jsonify(channel)
def test_three_car_coordination(self): channel = Channel() sup_car = Car(name=1, lane=randint(0, 3), intention=choice(self.intention_list), channel=channel, pos_x=randint(0, 3), pos_y=randint(0, 3)) second_car = Car(name=2, lane=randint(0, 3), intention=choice(self.intention_list), channel=channel, pos_x=randint(0, 3), pos_y=randint(0, 3)) normal_car = Car(name=3, lane=randint(0, 3), intention=choice(self.intention_list), channel=channel, pos_x=randint(0, 3), pos_y=randint(0, 3)) do_round([sup_car], channel) sup_car.enter_intersection() do_round([sup_car, second_car], channel) second_car.enter_intersection() do_round([sup_car, second_car, normal_car], channel) normal_car.enter_intersection() do_round([sup_car, second_car, normal_car], channel) self.assertEqual(1, normal_car.get_supervisor_car()) self.assertEqual(2, normal_car.get_second_at_charge()) self.assertFalse(normal_car.is_supervisor() or normal_car.is_second_at_charge())
def test_add_car(self): channel = Channel() cars = [] lanes = [0, 2, 1, 2, 3, 2] intentions = ['s', 's', 'r', 's', 'l', 'l'] for i in range(6): car = Car(name=(i + 1), lane=lanes[i], intention=intentions[i], channel=channel) cars.append(car) do_round(cars, channel) car.enter_intersection() do_round(cars, channel) # This should be the resulting graph after adding the 6 cars and the leaf cars should only contain the last car # number 6 nodes = [ Node(name=1, lane=0, intention='s', follow_list=[]), Node(name=2, lane=2, intention='s', follow_list=[]), Node(name=3, lane=1, intention='r', follow_list=[1]), Node(name=4, lane=2, intention='s', follow_list=[2]), Node(name=5, lane=3, intention='l', follow_list=[3, 4]), Node(name=6, lane=2, intention='l', follow_list=[5]) ] graph = {} for node in nodes: graph[node.get_name()] = node for car in cars: # graph_to_string(car) self.assertEqual(graph, car.get_graph()) self.assertEqual({6}, car.get_leaf_cars()) car = Car(name=7, lane=1, intention='s', channel=channel) new_node = Node(name=7, lane=1, intention='s', follow_list=[6]) graph[new_node.get_name()] = new_node # Note: the new leaf cars should be just number 7 cars.append(car) do_round(cars, channel) car.enter_intersection() do_round(cars, channel) # asserting that the graphs are the same checks that the nodes contain the same information for car in cars: self.assertEqual(graph, car.get_graph()) self.assertEqual({7}, car.get_leaf_cars())
def create_simulation_file(ticks=100, spawn_rate=1): from models.channel import Channel from utils.utils import random_car import os file = os.path.dirname(os.path.abspath( __file__)) + "/../simulation_files/" + str(ticks) + '_ticks' channel = Channel() cars = {'cars': []} lanes = [0, 1, 2, 3] intentions = ['l', 's', 'r'] for name in range(ticks): if next_time(spawn_rate) <= spawn_rate: lane = random.choice(lanes) intention = random.choice(intentions) car = random_car(name=name, channel=channel, creation_time=name, lane=lane, intention=intention) cars['cars'].append(car.to_json()) with open(file, 'w') as outfile: json.dump(cars, outfile)
def test_leave_intersection_supervisor(self): channel = Channel() sup_car = Car(name=1, lane=0, intention='s', channel=channel, pos_x=1, pos_y=1) second_car = Car(name=2, lane=1, intention='s', channel=channel, pos_x=2, pos_y=2) normal_car = Car(name=3, lane=3, intention='l', channel=channel, pos_x=3, pos_y=3) last_car = Car(name=4, lane=3, intention='l', channel=channel, pos_x=4, pos_y=4) # Car 1 enters do_round([sup_car], channel) sup_car.enter_intersection() # Car 2 enters and Car 1 becomes supervisor do_round([sup_car, second_car], channel) second_car.enter_intersection() # Car 3 enters and Car2 receives WelcomeMessage and Second At Charge do_round([sup_car, second_car, normal_car], channel) normal_car.enter_intersection() # Car 3 receives Welcome Message do_round([sup_car, second_car, normal_car, last_car], channel) last_car.enter_intersection() # Last car receives Welcome here do_round([sup_car, second_car, normal_car, last_car], channel) # Extra round do_round([sup_car, second_car, normal_car, last_car], channel) sup_car.leave_inner_intersection() self.assertTrue(second_car.is_supervisor()) self.assertEqual(2, second_car.get_supervisor_car()) self.assertEqual(3, second_car.get_second_at_charge()) self.assertEqual(2, normal_car.get_supervisor_car()) self.assertEqual(None, normal_car.get_second_at_charge()) self.assertEqual(2, last_car.get_supervisor_car()) self.assertEqual(None, last_car.get_second_at_charge()) # Car3 receives SecondAtChargeMessage from Car 2 do_round([sup_car, second_car, normal_car, last_car], channel) self.assertTrue(normal_car.is_second_at_charge()) self.assertEqual(3, last_car.get_second_at_charge())