def __init__(self, source): """ Create a video instance from the given source :param source: either Device ID or video file name """ AlgoClass.__init__(self) self.web_cam, self.capture = self.set_capture(source) self.TOTAL_FRAMES, self.NUM_FRAMES_SKIPPED = self.set_read() # all should be called img self.before_process = None # updated by read(), make sure a frame exists self.has_frame, self.current_frame = False, None self.read() # use to skip frame self.count_frame = 1 self.motion, self.motion_region = self.set_motion_tracker(), None self.skin, self.skin_regions = Skin(), None self.masked_frame = None self.hand_img = None self.hand = None
def test_foo_copy(): s = Skin() s.foo = [] t = Skin(s.copy()) u = copy.copy(s) assert s is not t assert s is not u assert s.foo.value is t.foo.value assert s.foo.value is u.foo.value
def __init__(self, cells): """ """ pygame.init() self.window = pygame.display.set_mode(constants.SET_MODE) self.cells = cells self.skin = Skin() self.display_maze(self.cells) self.draw_maze()
def __init__(self, user_agent=False, proxy=False): self.skin = Skin() if user_agent and proxy: self.network = Motor(user_agent=True, proxy=True) elif user_agent: self.network = Motor(user_agent=True) elif proxy: self.network = Motor(proxy=True) else: self.network = Motor() if not os.path.exists('./{}'.format(__CONFIG__['download']['folder'])): os.mkdir('./{}'.format(__CONFIG__['download']['folder']))
def test_set_known_attribute(): class A: def __init__(self): self.x = [] def __getitem__(self, name): raise NotImplementedError a = A() s = Skin(a) assert a.x is s.x s.x = 2 assert a.x is s.x
def test_equality(s, d): s2 = Skin(d) assert s is not s2 assert s == s2 assert s != d assert s.value is s2.value assert s2.value is d
def _resolve_loot_filter_aliases(self): uri = self.config["loot_filter_aliases_url"] if not uri: text = pkg_resources.resource_string("pypod_launcher", "d2.yaml") else: text = self._try_open_then_download(uri) return Skin(yaml.load(text))
async def generate_loot_filter(self): with self.disabled_buttons(): target = self.pod_path / "item.filter" if target.exists(): answer = QtWidgets.QMessageBox.question( self.ui, "Confirmation", "Are you sure you want to rewrite your 'item.filter'?") if answer == QtWidgets.QMessageBox.StandardButton.No: return logger.info("generating loot filter...") uri = self.config["loot_filter_url"] try: template = pathlib.Path(uri).read_text() except Exception: async with self.session.get(uri.strip()) as response: template = await response.text() d2 = Skin( yaml.load( pkg_resources.resource_string("pypod_launcher", "d2.yaml"))) rendered = jinja2.Template(template, line_statement_prefix="#", line_comment_prefix="##").render(d2=d2) header = "// Generated with pypod-launcher v{} ({})\n".format( version, datetime.datetime.now()) target.write_text(header + rendered) logger.info("generation done") self.ui.status.setText("done")
def __init__(self, device_name, avd_root, avd_repo_root, android_sdk_root=os.getenv('ANDROID_SDK_ROOT')): self.AVD_ROOT = avd_root self.AVD_REPO_ROOT = avd_repo_root # don't catch any exceptions so that they bubble up device_file = os.path.abspath(os.path.join(self.AVD_ROOT, 'devices', device_name + '.json')) device_dict = json.load(open(device_file, 'r')) # the loops is more elegant but the manual way will uncover any missing fields # for key in device_dict: # self[key] = device_dict[key] self.name = device_dict['name'] self.supported_versions = device_dict['supported_versions'] if 'skin' in device_dict: self.skin = Skin(device_dict['skin'], self.AVD_ROOT, android_sdk_root) # so people have to only test 'if myDevice.skin: ...' and not for its existence else: self.skin = None if 'sdcard' in device_dict: self.sdcard = device_dict['sdcard'] # so people have to only test 'if myDevice.sdcard: ...' and not for its existence else: self.sdcard = None if 'options' in device_dict: self.options = device_dict['options'] # so people have to only test 'if myDevice.options: ...' and not for its existence else: self.options = None
def get_text_messages(message): global status global skin_name if status == 'main_menu': if message.text == "Построить графики": bot.send_message(message.from_user.id, "Введи название скина:") status = 'check_skin' else: bot.send_message(message.from_user.id, 'Ошибка в команде', reply_markup=keyboard1) elif status == 'check_skin': skin_name = message.text bot.send_message(message.from_user.id, "Введи название индикатора:", reply_markup=keyboard2) status = 'indicators_input' elif status == 'indicators_input': if message.text == "Построить графики": test_skin = Skin(name=skin_name, app_id=730) analyst = SkinAnalyst(test_skin) indicators_result = analyst.get_graphs_BBANDS(indicators) with open(f'{skin_name}.png', 'rb') as result: bot.send_message(message.from_user.id, "Результат получен:") bot.send_document(message.from_user.id, result) bot.send_message(message.from_user.id, str(indicators_result), reply_markup=keyboard3) status = 'main_menu' else: indicators.append(eval(message.text)) print(indicators)
def test_defaultdict(): d = collections.defaultdict(list) s = Skin(d) assert isinstance(s.foo.value, list) assert len(s) == 1 s.bar.append(1) assert s.bar.value == [1] assert s.foo.value is d["foo"] assert s.bar.value is d["bar"]
class MazeGrid: """ """ def __init__(self, cells): """ """ pygame.init() self.window = pygame.display.set_mode(constants.SET_MODE) self.cells = cells self.skin = Skin() self.display_maze(self.cells) self.draw_maze() def draw_maze(self): """ """ while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() def display_maze(self, cells): """ """ paths = list(cells.cells) i = 0 for path in paths: pos = list(list(paths)[i])[0] typ = list(list(paths)[i])[1] if typ == 'wall': self.image = pygame.image.load( self.skin.image('wall')).convert() if typ == 'path': self.image = pygame.image.load( self.skin.image('path')).convert() if typ == 'start': self.image = pygame.image.load( self.skin.image('start')).convert() if typ == 'goal': self.image = pygame.image.load( self.skin.image('goal')).convert() pos_x = pos.y * 44 pos_y = pos.x * 44 self.window.blit(self.image, (pos_x, pos_y)) i = i + 1 pygame.display.flip()
def test_del_known_attribute(): class A: def __init__(self): self.x = [] def __getitem__(self, name): raise NotImplementedError a = A() s = Skin(a) assert a.x is s.x del s.x with pytest.raises(AttributeError): print(a.x)
def get_skin(cls, function=False): """ See if this skin will do. If not create an overlay skin and return it. If you want a specific skin type use 'set_skin' and then this. - function: Specify that you will need the skin for storing functions. Will overlay a new one. """ need_skin = function and not isinstance(cls._skin, FunctionSkin) or \ cls._skin is None if need_skin: cls.set_skin(function and FunctionSkin() or Skin()) return cls._skin
def update(self): with self.disabled_buttons(): logger.info("checking for update...") url = self.config["update_url"].strip() response = requests.get(url) response.raise_for_status() parsed = etree.fromstring(response.content) descriptions = [] for file_desc in parsed: crc = file_desc.get("crc") if crc: crc = crc.lower() descriptions.append(Skin(dict( urls=[link.text for link in file_desc], target=self.pod_path / file_desc.get("name"), crc=crc, ))) self._update_files(descriptions) (self.pod_path / "config").mkdir(parents=True, exist_ok=True) logger.debug("update done") self.ui.status.setText("done")
def __init__(self, in_stats={}): """Create a new monster, setting stats, etc. as needed.""" self.lvl = 0 # self.awr might not even need to be a thing, remove this if it ends up not mattering self.awr = 0# awareness, this is a thing for conversations / progress through the game # it might make more sense to hold info for conversations flow in shared.state, but I'm not sure # depends on how this number interacts with monster stuff self.personality = Personality.random() self.name = Personality.generateName(self.personality) self.skin = Skin.random(self.personality) # access the SkinTone with self.skin[self.lvl] self.mood = Mood.Neutral# mood might only be changed by and do stuff during battles / convos? maybe self.stats = {x: 2 for x in self.__class__.main_stats} self.stats['drv'] = self.__class__.drv_max//2 self._levelStats() self.stats.update(in_stats) self.setHealth() self.sprite_groups = tuple(random.choice(('A','B','C')) for x in range(5)) self._setSpritePaths() self._setSprites()
from xonstat.models import * from xonstat.util import datetime_seconds from skin import Skin from playerdata import PlayerData # maximal number of query results (for testing, set to None to get all) NUM_PLAYERS = None # we look for players who have activity within the past DELTA hours DELTA = 6 # classic skin WITHOUT NAME - writes PNGs into "output//###.png" skin_classic = Skin( "", bg="broken_noise", overlay="overlay_classic", ) # more fancy skin [** WIP **]- writes PNGs into "output/archer/###.png" skin_archer = Skin( "archer", bg="background_archer-v1", overlay=None, ) # minimal skin - writes PNGs into "output/minimal/###.png" skin_minimal = Skin( "minimal", bg=None, bgcolor=(0.04, 0.04, 0.04, 1.0),
from context import Context from skin import Skin, DictSkinConfig DEFAULTS_DOMAIN = 'default_kwargs' # Note that append as None means the user has not set the behaviour # explicitly. It should be interpreted to true by the Context. DEFAULTS_KW = dict(domain='functions', append=None, mapping=True) DEFAULTS = DictSkinConfig(functions={}, default_kwargs=DEFAULTS_KW) if Context._skin == None: Context.set_skin(Skin(config=DEFAULTS))
class Device(object): """ A class representing an Android Virtual Device device. """ def __init__(self, device_name, avd_root, avd_repo_root, android_sdk_root=os.getenv('ANDROID_SDK_ROOT')): self.AVD_ROOT = avd_root self.AVD_REPO_ROOT = avd_repo_root # don't catch any exceptions so that they bubble up device_file = os.path.abspath(os.path.join(self.AVD_ROOT, 'devices', device_name + '.json')) device_dict = json.load(open(device_file, 'r')) # the loops is more elegant but the manual way will uncover any missing fields # for key in device_dict: # self[key] = device_dict[key] self.name = device_dict['name'] self.supported_versions = device_dict['supported_versions'] if 'skin' in device_dict: self.skin = Skin(device_dict['skin'], self.AVD_ROOT, android_sdk_root) # so people have to only test 'if myDevice.skin: ...' and not for its existence else: self.skin = None if 'sdcard' in device_dict: self.sdcard = device_dict['sdcard'] # so people have to only test 'if myDevice.sdcard: ...' and not for its existence else: self.sdcard = None if 'options' in device_dict: self.options = device_dict['options'] # so people have to only test 'if myDevice.options: ...' and not for its existence else: self.options = None def versioned_name(self, android_version): return self.name + '-' + android_version def is_installed(self, android_version): device_avd_dir = os.path.abspath(os.path.join(self.AVD_REPO_ROOT, self.versioned_name(android_version) + '.avd')) device_avd_ini = os.path.abspath(os.path.join(self.AVD_REPO_ROOT, self.versioned_name(android_version) + '.ini')) return ( os.path.exists(device_avd_dir) and os.path.isdir(device_avd_dir) and os.path.exists(device_avd_ini) and os.path.isfile(device_avd_ini) ) def installed_versions(self): return [t[0] for t in [(version, self.is_installed(version)) for version in self.supported_versions] if t[1]] def install(self, android_version): # first check the user isn't trying to install an unsupported version if (not android_version in self.supported_versions): return False device_avd_dir = os.path.abspath(os.path.join(self.AVD_REPO_ROOT, self.versioned_name(android_version) + '.avd')) device_avd_ini = os.path.abspath(os.path.join(self.AVD_REPO_ROOT, self.versioned_name(android_version) + '.ini')) # return False if it already exists if (os.path.isdir(device_avd_dir) and os.path.isfile(device_avd_ini)): return False command = ['android', 'create', 'avd'] # force creation, since we've already checked that both files don't already exist command.append('-f') # add the name command.extend(['-n', self.versioned_name(android_version)]) # add the target command.extend(['-t', android_version]) if self.sdcard: if 'file' in self.sdcard: img_path = os.path.abspath(os.path.join(self.AVD_ROOT, 'devices', self.sdcard['file'])) command.extend(['-c', img_path]) elif 'size' in self.sdcard: command.extend(['-c', self.sdcard['size']]) if self.skin: if (self.skin.is_installed(android_version) or self.skin.install(android_version)): command.extend(['-s', self.skin.name]) else: return False retcode = call(command) if (os.path.isdir(device_avd_dir) and os.path.isfile(device_avd_ini)): # now add any additional options if specified if self.options: fp = open(device_avd_ini, 'a+') lines = ['{key}={value}\n'.format(key=option, value=self.options[option]) for option in self.options] fp.writelines(lines) fp.close() return True else: return False def uninstall(self, android_version): # first check the user isn't trying to uninstall an unsupported version if (not android_version in self.supported_versions): return False device_avd_dir = os.path.abspath(os.path.join(self.AVD_REPO_ROOT, self.versioned_name(android_version) + '.avd')) device_avd_ini = os.path.abspath(os.path.join(self.AVD_REPO_ROOT, self.versioned_name(android_version) + '.ini')) # return True if it already doesn't exist if (not os.path.isdir(device_avd_dir) and not os.path.isfile(device_avd_ini)): return True retcode = call(['android', 'delete', 'avd', '-n', self.versioned_name(android_version)]) return not os.path.exists(device_avd_dir) and not os.path.exists(device_avd_ini)
class Trawler(object): def __init__(self, user_agent=False, proxy=False): self.skin = Skin() if user_agent and proxy: self.network = Motor(user_agent=True, proxy=True) elif user_agent: self.network = Motor(user_agent=True) elif proxy: self.network = Motor(proxy=True) else: self.network = Motor() if not os.path.exists('./{}'.format(__CONFIG__['download']['folder'])): os.mkdir('./{}'.format(__CONFIG__['download']['folder'])) def trawl(self, url): # making sure url is formatted correctly (aka skinning) skinned_url = self.skin.url(url) return_dict = {} return_dict[skinned_url] = None # Determining if the site is up url_info = self.is_site_up(skinned_url) if url_info: # Generating a url list based on previously identified patterns with phish kits attempt_to_download_list = [] # Trying our generated kit locations to see if files are present for url in Generator(skinned_url).url_list: print('generated item: %s' % url) generated_parsed_files = Parser(url, self.network).parsed_files if generated_parsed_files: for item in generated_parsed_files: attempt_to_download_list.append(item) attempt_to_download_list.append(url) for url in Parser(skinned_url, self.network).parsed_files: generated_files = Generator(url).url_list if generated_files: for item in generated_files: attempt_to_download_list.append(item) attempt_to_download_list.append(url) return_dict[skinned_url] = self._download_from_url_list( attempt_to_download_list) return return_dict def _download_from_url_list(self, url_list): return_list = [] if isinstance(url_list, list): for url in url_list: try: print('parsed item: %s' % url) bin_trawl = BinaryTrawl(url, self.network) bin_trawl.download() return_list.append(bin_trawl.file_name) except: print( 'Unable to access kit based on the following path: {}'. format(url)) pass return return_list def is_site_up(self, value): url = value.replace(" ", "%20") response = self.network.get(url) return response
def test_skin_of_skin(): s1 = Skin(dict(a=1)) s2 = Skin(s1) assert s1.a is s2.a assert s1.a == s2.a == 1
from skin import Skin from skin_analyst import SkinAnalyst from momentum_indicators import * if __name__ == '__main__': test_skin = Skin(name='Gamma 2 Case', app_id=730) analyst = SkinAnalyst(test_skin) analyst.get_graphs([RSI, ROC, STOCH])
def test_not_allowed(): with pytest.raises(SkinValueError): Skin(dict(), allowed=(str,))
def test_no_getitem(): with pytest.raises(SkinValueError): Skin(1)
def test_config_inheritance(): s1 = Skin(forbidden=(set,)) s2 = s1.foo.bar.baz assert super(Skin, s1).__getattribute__("forbidden") is super(Skin, s2).__getattribute__("forbidden")
def test_deepcopy(): s = Skin() s.foo = [] t = copy.deepcopy(s) assert s.foo.value is not t.foo.value
class Video(AlgoClass): """ Reads frames from a video source and broadcast them to motion and skin Instance Variables: web_cam: bool - True when web camera is the source and is still on False when video file is the source capture: VideoCapture object - use to read frames has_frame: bool - a frame exists (necessary?) current_frame: image - current video frame count_frame: int - total number of frames read from video source """ def __init__(self, source): """ Create a video instance from the given source :param source: either Device ID or video file name """ AlgoClass.__init__(self) self.web_cam, self.capture = self.set_capture(source) self.TOTAL_FRAMES, self.NUM_FRAMES_SKIPPED = self.set_read() # all should be called img self.before_process = None # updated by read(), make sure a frame exists self.has_frame, self.current_frame = False, None self.read() # use to skip frame self.count_frame = 1 self.motion, self.motion_region = self.set_motion_tracker(), None self.skin, self.skin_regions = Skin(), None self.masked_frame = None self.hand_img = None self.hand = None def update(self): """ Video control center. If there is a new non-skipped frame with sufficient changes based on main areas of concern - on motion (including background sub) and - skin color the existing hand is process for gesture recognition :return: bool """ # TODO: rank among multiple hands if self.has_more_frames() and self.is_retrieved( ) and self.motion.detected(): print "frame", self.count_frame self.masked_frame = self.create_masked_frame() hand_silhouette = self.find_hand_silhouette() if hand_silhouette is not None: self.process_hand(hand_silhouette) return True return False def create_masked_frame(self): """ Create and return a masked version of the current frame The mask rejects non-skin colors and static parts by filtering for skin and motion regions :return: image """ self.motion_region = self.motion.get_motion_region() self.skin_regions = self.skin.get_active_regions(self.current_frame) # main area of concern return cv2.bitwise_and(self.skin_regions, self.skin_regions, mask=self.motion_region) def find_hand_silhouette(self, frame=None): """ Return Silhouette of the hand by processing the geometries of all the contours :param frame: image :return: Silhouette """ if frame is None: frame = self.masked_frame contours = Silhouette.get_contours(frame, constants.CONTOURS_MIN_AREA) # onion geometries for all large contours (likely face and hand) silhouettes = Silhouette.create_geometries(frame, contours) if len(silhouettes) > 0: #for idx in range(len(sils)): #sils[idx].draw_all() return Silhouette.select_hand_like(silhouettes) return None def process_hand(self, hand_silhouette): """ Process the hand silhouette to identify the thumb and fingers :param hand_silhouette: Silhouette :return: """ hand_silhouette.log_all() self.hand = Hand(self.current_frame, hand_silhouette.onion_geometry, hand_silhouette.shape_like) # drawn after the Hand constructor call to track the refined poly_curve hand_silhouette.draw_all() self.hand.draw(self.current_frame) def read(self): """ Update current frame with next read and some initial image processing :return: None """ self.has_frame, self.current_frame = self.capture.read() self.before_process = self.current_frame.copy() self.current_frame = Tools.pre_process_image(self.current_frame) def is_running(self): """ Return True if video source has more frames and user has not issued a quit command :return: bool """ if self.has_more_frames() and not self.video_key_interrupt(): return True else: self.capture.release() cv2.destroyAllWindows() return False def is_retrieved(self): """ One frame out of NUM_FRAMES_SKIPPED is to be read For example out with FPS 30 and 3 FRAMES_USED_PER_SEC 1 is read, meaning grabbed and retrieved (latter is a slow op) 9 are skipped, VideoCapture.grab() applied to advance video :return: bool """ self.count_frame += 1 if (self.count_frame % self.NUM_FRAMES_SKIPPED) == 0: self.read() self.motion.update_frame(self.current_frame) return True else: self.has_frame = self.capture.grab() return False def has_more_frames(self): """ Return True if the video source has more frames :return: bool """ return self.web_cam or self.count_frame < self.TOTAL_FRAMES # # constructor helpers def set_capture(self, source): """ :param source: int/str ( live camera index/video file name) :return: VideoCapture """ web_cam = False if source == constants.DEFAULT_DEVICE: self.log_text("Webcam " + source + " in use") web_cam = True capture = cv2.VideoCapture(source) if not capture.isOpened(): self.log_text("Failed to open video source. Exiting...") exit() self.log_text(source) return web_cam, capture def set_read(self): """ Set video statistics Return total number of frames in video source and frames to skip in between two reads :return: int, int """ total_frames = self.capture.get(cv2.CAP_PROP_FRAME_COUNT) num_frames_skipped = int( self.capture.get(cv2.CAP_PROP_FPS) / constants.FRAMES_USED_PER_SEC) self.log_text("total frames %d" % total_frames) self.log_text("used frames %d" % constants.FRAMES_USED_PER_SEC) self.log_text("skip %d" % num_frames_skipped) return total_frames, num_frames_skipped def set_motion_tracker(self): """ :return: Motion object """ width, height = self.get_frame_size() return Motion(height, width, self.current_frame) def get_frame_size(self): """ :return: int, int """ return self.capture.get(cv2.CAP_PROP_FRAME_WIDTH), \ self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT) @staticmethod def video_key_interrupt(): """ Delay for keyboard interrupt callbacks. Return True if the predefined quit key was pressed :return: bool """ """ Note: & 0xff needed for 64-bit machine: see following link http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_image_display/ ...py_image_display.html """ k = cv2.waitKey(constants.VIDEO_KEY_EVENT_DELAY) & 0xff return k == ord(constants.PROGRAM_QUIT_KEY.lower())
def get_result(to_user_id): test_skin = Skin(name=skin_name, app_id=730) analyst = SkinAnalyst(test_skin) indicators_result = analyst.get_graphs(indicators) send_result_message(to_user_id, f'{skin_name}.png')
def test_forbidden(): with pytest.raises(SkinValueError): Skin(dict(), forbidden=(dict,))
def s(d): return Skin(d)
def test_repr(): s = Skin() assert repr(s) == "Skin({})"