Example #1
0
def url_to_filtered_image(image_url, fil_str, intensity):
    """ Recebe url da imagem, nome do filtro e intensidade e retorna imagem filtrada em string
	de bytes"""

    filename = "image.jpg"
    image = url_to_image(image_url)

    # Inicia classe de Filtros e lista os filtros disponĆ­veis
    fil = Filters()
    for i, item in enumerate(fil.filter_names):
        if item == fil_str:
            break

    # Recebe os inputs do usuƔrio para selecionar o filtro
    # e sua intensidade
    num_filter = i
    num_param = intensity

    # Executa a funcao do filtro sobre a imagem
    image = fil.filter_funcs[num_filter](image, num_param)

    # Salva imagem
    cv2.imwrite(filename, image)

    # Armazena em um buffer e converte para base64
    retval, buff = cv2.imencode('.jpg', image)
    base64_bytes = base64.b64encode(buff.tostring())

    # Envia imagem filtrada
    return base64_bytes
Example #2
0
def filter_obj_alt():
    from filters import Filters
    return Filters(analytical_threshold=0.02,
                   abs_analytical_threshold=11,
                   min_mapq=60,
                   max_mapq=254,
                   remove_deletions=True)
Example #3
0
def getReviewersAndWatchers(db, repository, commits=None, changesets=None, reviewfilters=None,
                            applyfilters=True, applyparentfilters=False):
    """getReviewersAndWatchers(db, commits=None, changesets=None) -> tuple

Returns a tuple containing two dictionaries, each mapping file IDs to
dictionaries mapping user IDs to sets of changeset IDs.  The first dictionary
defines the reviwers of each file, the second dictionary defines the watchers of
each file.  For any changes in a file for which no reviewer is identified, None
is used as a key in the dictionary instead of a real user ID."""

    if changesets is None:
        changesets = []
        changeset_utils.createChangesets(db, repository, commits)
        for commit in commits:
            changesets.extend(changeset_utils.createChangeset(db, None, repository, commit, do_highlight=False))

    cursor = db.cursor()

    filters = Filters()
    filters.setFiles(db, list(getFileIdsFromChangesets(changesets)))

    if applyfilters:
        filters.load(db, repository=repository, recursive=applyparentfilters)

    if reviewfilters:
        filters.addFilters(reviewfilters)

    reviewers = {}
    watchers = {}

    for changeset in changesets:
        author_user_ids = changeset.child.author.getUserIds(db) if changeset.child else set()

        cursor.execute("SELECT DISTINCT file FROM fileversions WHERE changeset=%s", (changeset.id,))

        for (file_id,) in cursor:
            reviewers_found = False

            for user_id, (filter_type, delegate) in filters.listUsers(file_id).items():
                if filter_type == 'reviewer':
                    if user_id not in author_user_ids:
                        reviewer_user_ids = [user_id]
                    elif delegate:
                        reviewer_user_ids = []
                        for delegate_user_name in delegate.split(","):
                            delegate_user = dbutils.User.fromName(db, delegate_user_name)
                            reviewer_user_ids.append(delegate_user.id)
                    else:
                        reviewer_user_ids = []

                    for reviewer_user_id in reviewer_user_ids:
                        reviewers.setdefault(file_id, {}).setdefault(reviewer_user_id, set()).add(changeset.id)
                        reviewers_found = True
                else:
                    watchers.setdefault(file_id, {}).setdefault(user_id, set()).add(changeset.id)

            if not reviewers_found:
                reviewers.setdefault(file_id, {}).setdefault(None, set()).add(changeset.id)

    return reviewers, watchers
Example #4
0
    def init_components(self):
        self.packages = api.get_packages()
        (total, installed, updates) = api.get_stats(self.packages)
        self.categories = api.get_sections(self.packages)

        self.searchbar = AlpsUISearchBar()
        self.toolbar = AlpsUIToolBar(self.searchbar)
        self.toolbar_container = self.toolbar.layout()
        self.packagelist = PackageList(self)
        self.filters = Filters(self.on_filter)
        self.scrolledwindow = self.wrap_scrollbar(self.packagelist.list)
        self.statusbar = AlpsUIStatusBar()

        self.category_list = Categories(self.categories,
                                        self.on_category_change)
        self.packagelist.set_packages(self.packages)
        self.toolbar.init_statusbar(self.statusbar)
        self.toolbar.set_mainframe(self)

        self.searchbar.set_category_list(self.category_list)
        self.searchbar.set_package_list(self.packagelist)

        self.statusbar.set_status_text(0, total)
        self.statusbar.set_status_text(1, installed)
        self.statusbar.set_status_text(2, updates)
Example #5
0
File: main.py Project: heekim1/MH
    def __init__(self,
                 bam,
                 bed,
                 info,
                 out,
                 analytical_threshold=ANALYTICAL_THRESHOLD):

        self.bam = bam
        self.bed = bed
        self.info = info
        self.out = out
        self.analytical_threshold = analytical_threshold

        # Init
        self.bed_obj = Bed(self.bed)
        self.info_obj = Info(self.info)
        self.mh_dict = {}
        self.filters_obj = Filters(
            analytical_threshold=self.analytical_threshold,
            abs_analytical_threshold=self.ABSOLUTE_ANALYTICAL_THRESHOLD,
            min_mapq=self.MIN_MAPPING_QUALITY,
            max_mapq=self.MAX_MAPPING_QUALITY,
            remove_deletions=self.REMOVE_DELETIONS)
        self.short_reads_count = 0
        self.total_reads_count = 0
        self.number_of_contributors_overall = 0
Example #6
0
File: client.py Project: wezu/a4p
    def __init__(self):
        log.debug('Starting Client')
        #open a window... but first set all the needed props
        wp = self.loadWindoProperites()
        #open the window
        base.openMainWindow(props=wp)
        #base.setBackgroundColor(0.06, 0.1, 0.12, 1)
        base.setBackgroundColor(0.0, 0.0, 0.0, 1)
        base.disableMouse()
        base.enableParticles()

        #needed to determine what window event fired
        self.window_focused = base.win.getProperties().getForeground()
        self.window_x = base.win.getXSize()
        self.window_y = base.win.getYSize()
        self.window_minimized = base.win.getProperties().getMinimized()

        #filter manager, post process
        self.filters = Filters()

        #audio sound effects (sfx) + music
        self.audio = Audio()
        self.audio.setMusic('background')
        self.audio.playMusic()

        #light manager
        self.lights = LightManager()

        #setup the user interface (gui+key/mouse bind)
        self.ui = UserInterface()

        #skybox
        self.sun_and_sky = Skybox(self.lights)

        #player (character) droid
        self.droid = PCDroid(self.ui)

        #some vars used later
        self.map_name = None
        self.loading_status = set()
        self.level_root = render.attachNewNode('level_root')
        self.level_root.hide()
        self.is_in_game = False

        #events
        base.win.setCloseRequestEvent('exit-event')
        self.accept('exit-event', self.onClientExit)
        self.accept('window-event', self.onWindowEvent)
        self.accept('window-reset', self.onWindowReset)
        self.accept('client-mouselock', self.setMouseLock)
        self.accept('load-level', self.onLevelLoad)
        self.accept('loading-done', self.onLoadingDone)
        self.accept('reload-shaders', self.onShaderReload)
        self.accept('client-set-team', self.onTeamCahnge)
        self.accept('client-quit', self.onQuit)
        # Task
        taskMgr.add(self.update, 'client_update')

        log.debug('Client started')
Example #7
0
def repeat_median():
    dist = noise.salt_and_pepper(salt_vs_pepper=0.1)
    cv.namedWindow('salt_and_pepper', cv.WINDOW_NORMAL)
    cv.imshow('salt_and_pepper', dist)
    my_filter = Filters(dist)
    out = my_filter.core(mode='median_filter')
    cv.namedWindow('1', cv.WINDOW_NORMAL)
    cv.imshow('1', out)
    my_filter1 = Filters(out)
    out1 = my_filter1.core(mode='median_filter')
    cv.namedWindow('2', cv.WINDOW_NORMAL)
    cv.imshow('2', out1)
    my_filter2 = Filters(out1)
    out2 = my_filter2.core(mode='median_filter')
    cv.namedWindow('3', cv.WINDOW_NORMAL)
    cv.imshow('3', out2)
    cv.waitKey(0)
Example #8
0
 def __init__(self, label):
     self.label = label  # label to display image
     self.image = None  # PIL image modified for display
     self.backup = None  # PIL image backup (base for zoom)
     self.imageTk = None  # PIL TK image displayed
     self.filename = None  # filename
     self.zooming = 0  # zoom in range [min..max]
     self.min = 0  # minimum size of image
     self.max = 0  # maximum size of image
     self.f = Filters()
Example #9
0
def analyze(settings):
    start_time = time.time()

    f = Filters(settings['code'], settings['filters'])
    tree = Tree(settings['path'], f.filters(), settings['antifilters'],
                settings)
    tree.output()

    time_sec = time.time() - start_time
    print("\nanalyze time : {0:2.5f}sec".format(time_sec))
Example #10
0
    def __init__(self, constspeed, carbranch, light):
        # load data
        try:
            file_path = open('filename_path', 'r').readline().split('\n')[0]
            self.file = open(file_path, 'w')
        except Exception:
            print "cannot find file"
            sys.exit(0)
        self.file.write(
            "x,y,z,speed,acceleration,curvature,"
            "curvature_change_rate,time,theta,gear,s,left_turn,right_turn\n")

        self.cars = 0
        self.carcurvature = 0
        self.startmoving = False
        self.terminating = False
        self.constspeed = constspeed
        self.acc_filter = Filters(10)
        self.recordlight = light == 't'

        if carbranch == 'lincoln':
            print "current branch is lincoln"
            self.maxsteer = 470
            self.steerratio = 16
            self.wheelbase = 2.85
        elif carbranch == 'byd':
            print "current branch is byd"
            self.maxsteer = 540
            self.steerratio = 17.5
            self.wheelbase = 2.67
        elif carbranch == 'kinglong':
            print "current branch is kinglong"
            self.maxsteer = 540
            self.steerratio = 17.2
            self.wheelbase = 2.75
        elif carbranch == 'h7phev':
            print "current branch is h7phev"
            self.maxsteer = 540
            self.steerratio = 15.33
            self.wheelbase = 2.96
        elif carbranch == 'daimler':
            print "current branch is daimler"
            self.maxsteer = 38.49
            self.steerratio = 1.0
            self.wheelbase = 3.43
        elif carbranch == 'hongqi':
            print "current branch is hongqi"
            self.maxsteer = 480
            self.steerratio = 16.18
            self.wheelbase = 2.75
        else:
            print "car branch does not exist"
            print "Usage: python recorder_path_cyber.py -b lincoln/byd/kinglong/h7phev/daimler"
            sys.exit(0)
Example #11
0
    def __init__(self):
        # Main parameters
        self.dataset_path = os.getcwd() + "\dataset"
        self.output_path = os.getcwd() + "\identified"
        self.name_output = "frame"
        self.exams = os.listdir(self.dataset_path)
        self.detail_presentation = True
        self.save_output = True
        self.sleep_pause = 3

        self.filters = Filters(self.detail_presentation)
Example #12
0
    def __init__(self, m_length, error_rate, db_host, db_port, \
                 dbname, dbcollections, path=None, debug=False):
        self.logdupes = True
        self.debug = debug
        self.logger = logging.getLogger(__name__)

        self.fingerprints = Filters(m_length, error_rate)
        self.logger.info("created bloomfilter({},{}) <----- wangyf"\
                .format(m_length, error_rate))

        self.mongodb = MongoDBClient(db_host, db_port, dbname, dbcollections)
Example #13
0
def opportunities():
    '''display search results to volunteer'''

    if 'filters' in request.cookies:

        cookie = (request.cookies.get('filters'))  #grabs cookie
        filters = cookie.split("/")  # splits cookie into list

        index = int(filters[0])  # grabs index from list
        cat = filters[1]  # grabs categories from list
        categories = cat.split("-")
        avail = filters[2]  # grabs available days
        availability = avail.split("-")  # splits into list
        zipcode = filters[3]  #grabs zipcode from list
        distance = filters[4]  #grabs distance from list

        search = Filters(
            categories=categories,
            availability=availability,
            zipcode=zipcode,
            distance=distance
        )  # creates filter with given category and availability
        opps = search.search()  #grabs list of opportunities

        error = check_opps(opps)
        if error:
            flash(error)
            return redirect('/filters')

        opp = opps[index]  # picks out the opp at index
        index = increment(index, len(opps))  # increments index

        event_date = readable_date(opp.startDateTime)
        event_time = readable_times(opp.startDateTime, opp.duration)

        resp = make_response(
            render_template('volunteer/opportunities.html',
                            opp=opp,
                            event_date=event_date,
                            event_time=event_time,
                            json=json,
                            title="Voluntr | Browse Opportunities",
                            is_production=is_production)
        )  # tells the cookie what to load while it sets itself

        resp.set_cookie('filters',
                        str(index) + "/" + cat + "/" + avail + "/" + zipcode +
                        "/" + distance)  #preps cookie for setting

        return resp  # sets cookie and displays page

    return redirect("/filters")  # redirects to filters if no cookie exists
Example #14
0
    def __init__(self):
        """
    Configuration
    """

        # Camera settings
        self.FRAME_WIDTH = 341
        self.FRAME_HEIGHT = 256
        self.flip_camera = True  # Mirror image
        self.camera = cv2.VideoCapture(1)

        # ...you can also use a test video for input
        #video = "/Users/matthiasendler/Code/snippets/python/tracker/final/assets/test_video/10.mov"
        #self.camera = cv2.VideoCapture(video)
        #self.skip_input(400) # Skip to an interesting part of the video

        if not self.camera.isOpened():
            print "couldn't load webcam"
            return
        #self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, self.FRAME_WIDTH)
        #self.camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, self.FRAME_HEIGHT)

        self.filters_dir = "filters/"  # Filter settings in trackbar
        self.filters_file = "filters_default"

        # Load filter settings
        current_config = self.filters_dir + self.filters_file
        self.filters = Filters(current_config)

        # No actions will be triggered in test mode
        # (can be used to adjust settings at runtime)
        self.test_mode = False

        # Create a hand detector
        # In fact, this is a wrapper for many detectors
        # to increase detection confidence
        self.detector = Detector(self.filters.config)

        # Knowledge base for all detectors
        self.kb = KB()
        # Create gesture recognizer.
        # A gesture consists of a motion and a hand state.
        self.gesture = Gesture()

        # The action module executes keyboard and mouse commands
        self.action = Action()

        # Show output of detectors
        self.output = Output()

        self.run()
def suggestion_gui(root, account_data, account_found):
    utility.clear_root(root)
    title = tk.Label(root, text="VMedia: Suggestions", font=("arial", 28, "bold"), fg=fg_col, bg=bg_col)
    title.place(relx=0.5, rely=0.05, anchor=tk.CENTER)
    utility.underline(title)

    table = create_table(root)
    table.place(relx=0.1, rely=0.2, relwidth=0.40, relheight=0.75)
    scroll_bar_y = tk.Scrollbar(root, command=table.yview)
    scroll_bar_y.place(relx=0.5, rely=0.2, relheight=0.75)

    select_button = tk.Button(root, text="Select media", font=("arial", 10, "bold"),
                              bg=button_col, command=lambda:
                              select_media(root, table, likes_to_save,
                                           search_bar.get(), filter_obj))
    select_button.place(relx=0.5, rely=0.1, relwidth=0.04, relheight=0.025, anchor=tk.CENTER)

    search_bar = tk.Entry(root, relief=tk.GROOVE, bd=2, font=("arial", 13))
    search_bar.place(relx=0.1, rely=0.15, relwidth=0.68, relheight=0.025)

    search_button = tk.Button(root, text="Search", font=("arial", 10, "bold"), bg=button_col,
                              command=lambda: search(table, search_bar.get(), filter_obj))
    search_button.place(relx=0.8, rely=0.15, relwidth=0.04, relheight=0.025)

    show_all_button = tk.Button(root, text="Show All", font=("arial", 10, "bold"),
                                bg=button_col, command=lambda: search(table, ""))
    show_all_button.place(relx=0.85, rely=0.15, relwidth=0.04, relheight=0.025)

    exit_button = tk.Button(root, text="Exit", font=("arial", 10, "bold"),
                            bg=button_col, command=lambda: updating_account_data(account_found, likes_to_save))
    exit_button.place(relx=0.8, rely=0.05, relwidth=0.09, relheight=0.05)

    filters_label = tk.Label(root, text="Filters:", font=("arial", 25, "bold"), fg=fg_col, bg=bg_col)
    filters_label.place(relx=0.60, rely=0.25)
    utility.underline(filters_label)

    filter_obj = Filters()
    filters(root, filter_obj)

    if account_data == ['']:
        account_data = []

    # A second list is made so media already used to calculate score do not need to be checked again
    likes_to_save: list[int] = [int(x) for x in account_data]
    global global_likes_to_save
    global_likes_to_save = likes_to_save

    media_data_to_set_scores = suggestion_algorithm_single_use(likes_to_save)

    ordered_media_classes = main_algorithm(media_data_to_set_scores)
    insert_media_table(table, ordered_media_classes)
Example #16
0
    def __new_flight__(self,
                       flight_id: int,
                       username: str,
                       depart: str,
                       dest: str,
                       depart_date: str,
                       flight_type: str,
                       return_date: Optional[str] = None):
        """
        Creates a basic flight instance, its table, and its dict.
        :param flight_id:
        :param username:
        :param depart:
        :param dest:
        :param depart_date:
        :param flight_type:
        :param return_date:
        :return:
        COMMENT: need to increment flight_id by 1 in load_app
        """
        self.username = username
        self.flight_id = flight_id
        self.table_name = 'tb_' + str(flight_id)
        self.flight_type = flight_type
        self.depart = depart
        self.dest = dest
        self.depart_date = depart_date
        self.return_date = return_date

        # Create table and dicts
        mydb = mysql.connector.connect(host='localhost',
                                       user='******',
                                       passwd='flightplanner',
                                       database='FP_database')
        mycursor = mydb.cursor()

        set_up_command = 'CREATE TABLE {0} (Flight_id int, Date varchar(255), Min_eco int, Min_bus int, Avg_econ int,' \
                         ' Avg_bus int, Track_date varchar(255));'.format(self.table_name)
        mycursor.execute(set_up_command)
        mydb.commit()
        mycursor.close()

        self.info_dict = dict()

        self.filters = Filters()
        self.filters.require_filters()

        self.notifications = Notification()
        self.notifications.require_notifications()
Example #17
0
def swcli(resource, filter_cmds=None, cache=True):
    api = Swapi(cache)
    resources = api.get_root()
    if resource not in resources:
        raise Exception(
            'Invalid resource name: \'%s\'. Available resources: [%s]' %
            (resource, ', '.join(resources)))

    data = api.get_resource(resource)

    if filter_cmds:
        filters = Filters(api)
        for f in filter_cmds:
            data = filters.filter_data(data,
                                       field_name=f[0],
                                       operator=f[1],
                                       value=f[2])

    return data
Example #18
0
def compare_filter(noise_name, var_list=None, noise_data=None):
    if noise_data is None:
        dist = getattr(noise, noise_name)()
        cv.namedWindow(noise_name, cv.WINDOW_NORMAL)
        cv.imshow(noise_name, dist)
    else:
        dist = noise_data
    if not var_list:
        return
    my_filter = Filters(dist)
    out = None
    for key, value in var_list.items():
        if not value:
            out = my_filter.core(mode=key)
        else:
            out = my_filter.core(mode=key, **value)
        cv.namedWindow(key, cv.WINDOW_NORMAL)
        cv.imshow(key, out)
    cv.waitKey(0)
    return out
Example #19
0
    def __init__(self):
        # Main parameters
        # self.path = os.getcwd()
        # self.dataset_path = os.path.join(self.path, 'dataset')
        # self.output_path = os.path.join(self.path, 'out')

        self.dataset_path = '/media/marcos/Dados/Projects/Datasets/Exams'
        self.output_path = '/media/marcos/Dados/Projects/Results/Qualificacao/AlgoPPL/frames'
        self.labe_output_path = '/media/marcos/Dados/Projects/Results/Qualificacao/AlgoPPL/label'

        self.exams = ['benchmark_final.avi']
        # self.exams = os.listdir(self.dataset_path)

        self.detail_presentation = True
        self.save_output = True
        self.execute_invisible = True
        self.save_csv = True

        self.sleep_pause = 3

        self.filters = Filters(self.detail_presentation)
Example #20
0
    def __load_flight__(self, flight_id: int, flight: Flight):
        """
        loads a flight object by obtaining into from general DB
        :param flight_id:
        :param flight:
        :return:
        """
        info_tuple = self.flights_db.flights_dict[flight_id]

        # load into flight object
        flight.username = info_tuple[0]
        flight.flight_type = info_tuple[1]
        flight.depart = info_tuple[2]
        flight.dest = info_tuple[3]
        flight.depart_date = info_tuple[4]
        flight.return_date = info_tuple[5]
        flight.table_name = 'tb_' + str(flight_id)
        flight.flight_id = flight_id

        temp_filter = Filters()
        temp_filter.insert_day_filter(info_tuple[6])
        temp_filter.insert_depart_time_filter(info_tuple[7])
        temp_filter.insert_max_duration_filter(info_tuple[8])
        temp_filter.insert_price_amount_filter(info_tuple[9])
        flight.filters = temp_filter

        temp_noti = Notification()
        if info_tuple[10] != "NULL":
            limit_min = info_tuple[10].split(';')[0]
            limit_max = info_tuple[10].split(':')[1]
            temp_noti.insert_amount(limit_min, limit_max)
        if info_tuple[11] != "NULL":
            temp_noti.insert_diff(int(info_tuple[11]))
        if info_tuple[12] != "NULL":
            days_since_reset = info_tuple[12].split(';')[0]
            inc_num = info_tuple[12].split(';')[1]
            direction = info_tuple[12].split(';')[2]
            temp_noti.insert_trend(days_since_reset, inc_num, direction)
        flight.notifications = temp_noti
Example #21
0
    def sort(self, elem_links, url):
        fex = Faup()
        f = Filters()
        f.load()
        self.r.switchDB(1)
        extend = True
        domainfilter = True
        schemefilter = True
        try:
            for link in elem_links:
                new_url = link
                self.r.switchDB(2)
                if not self.r.get(new_url) and new_url:
                    self.r.switchDB(1)
                    if not self.r.get(new_url):
                        fex.decode(new_url)
                        domain = fex.get_host()
                        if f.isfilteredscheme(fex.get_scheme()):
                            self.r.switchDB(2)
                            self.r.put(new_url, new_url)
                            schemefilter = False
                        if f.isfiltereddomains(domain):
                            self.r.switchDB(2)
                            self.r.put(new_url, new_url)
                            domainfilter = False
                        if f.isfilteredextention(fex.get_resource_path()):
                            extend = False
                            self.r.switchDB(2)
                            self.r.put(new_url, new_url)

                        if extend and domainfilter and schemefilter:
                            self.r.switchDB(1)
                            self.r.rpush('crawl', new_url)
                            self.queue.append(new_url)
        except TypeError as e:
            print "TypeError"
Example #22
0
def rgb2gray(in_img):
    return np.array(np.mean(in_img, axis=2), dtype=np.uint8)

def subImg(img1, img2):
    img1_16 = img1.astype(np.int16)
    img2_16 = img2.astype(np.int16)
    res = abs(img1_16 - img2_16)
    return res.astype(np.uint8)

if __name__ == "__main__":

    if len(sys.argv) != 2:
        print("main_filter.py <relative/path/to/file>")
        exit(0)
    
    filts = Filters()

    img = cv2.imread(sys.argv[1])
    img = cv2.resize(img, (int(img.shape[1]/2), int(img.shape[0]/2)))
    cv2.imshow("original image", img)

    gray_img = rgb2gray(img)
    cv2.imshow("gray scaled", gray_img)

    vert_fil_img = filts.verticalFilter(gray_img)
    cv2.imshow("vertical filtered", vert_fil_img)
    cv2.imshow("vertical filtered diff", subImg(gray_img[1:-1,1:-1], vert_fil_img))

    horz_fil_img = filts.horizontalFilter(gray_img)
    cv2.imshow("horizontal filtered", horz_fil_img)
    cv2.imshow("horizontal filtered diff", subImg(gray_img[1:-1,1:-1], horz_fil_img))
Example #23
0
 def __init__(self, output_file, get_word_freq = None):
     self.get_word_freq = get_word_freq
     self.new_words = wordb.open(output_file)
     self.filters = Filters()
     self.n_killed = 0
     self.n_added = 0
Example #24
0
def createReview(db,
                 user,
                 repository,
                 commits,
                 branch_name,
                 summary,
                 description,
                 from_branch_name=None,
                 via_push=False,
                 reviewfilters=None,
                 applyfilters=True,
                 applyparentfilters=False,
                 recipientfilters=None):
    cursor = db.cursor()

    if via_push:
        applyparentfilters = bool(
            user.getPreference(db, 'review.applyUpstreamFilters'))

    branch = dbutils.Branch.fromName(db, repository, branch_name)

    if branch is not None:
        raise OperationFailure(
            code="branchexists",
            title="Invalid review branch name",
            message="""\
<p>There is already a branch named <code>%s</code> in the repository.  You have
to select a different name.</p>

<p>If you believe the existing branch was created during an earlier (failed)
attempt to create this review, you can try to delete it from the repository
using the command<p>

<pre>  git push &lt;remote&gt; :%s</pre>

<p>and then press the "Submit Review" button on this page again.""" %
            (htmlutils.htmlify(branch_name), htmlutils.htmlify(branch_name)),
            is_html=True)

    if not commits:
        raise OperationFailure(
            code="nocommits",
            title="No commits specified",
            message="You need at least one commit to create a review.")

    commitset = log_commitset.CommitSet(commits)
    heads = commitset.getHeads()

    if len(heads) != 1:
        # There is really no plausible way for this error to occur.
        raise OperationFailure(
            code="disconnectedtree",
            title="Disconnected tree",
            message=("The specified commits do do not form a single connected "
                     "tree.  Creating a review of them is not supported."))

    head = heads.pop()

    if len(commitset.getTails()) != 1:
        tail_id = None
    else:
        tail_id = gitutils.Commit.fromSHA1(
            db, repository,
            commitset.getTails().pop()).getId(db)

    if not via_push:
        try:
            repository.createBranch(branch_name, head.sha1)
        except gitutils.GitCommandError as error:
            raise OperationFailure(
                code="branchfailed",
                title="Failed to create review branch",
                message=("<p><b>Output from git:</b></p>"
                         "<code style='padding-left: 1em'>%s</code>" %
                         htmlutils.htmlify(error.output)),
                is_html=True)

    createChangesetsForCommits(db, commits)

    try:
        cursor.execute(
            "INSERT INTO branches (repository, name, head, tail, type) VALUES (%s, %s, %s, %s, 'review') RETURNING id",
            [repository.id, branch_name,
             head.getId(db), tail_id])

        branch_id = cursor.fetchone()[0]
        reachable_values = [(branch_id, commit.getId(db))
                            for commit in commits]

        cursor.executemany(
            "INSERT INTO reachable (branch, commit) VALUES (%s, %s)",
            reachable_values)

        cursor.execute(
            "INSERT INTO reviews (type, branch, state, summary, description, applyfilters, applyparentfilters) VALUES ('official', %s, 'open', %s, %s, %s, %s) RETURNING id",
            (branch_id, summary, description, applyfilters,
             applyparentfilters))

        review = dbutils.Review.fromId(db, cursor.fetchone()[0])

        cursor.execute(
            "INSERT INTO reviewusers (review, uid, owner) VALUES (%s, %s, TRUE)",
            (review.id, user.id))

        if reviewfilters is not None:
            cursor.executemany(
                """INSERT INTO reviewfilters (review, uid, path, type, creator)
                                       VALUES (%s, %s, %s, %s, %s)""",
                [(review.id, filter_user_id, filter_path, filter_type, user.id)
                 for filter_user_id, filter_path, filter_type, filter_delegate
                 in reviewfilters])

        is_opt_in = False

        if recipientfilters is not None:
            cursor.executemany(
                "INSERT INTO reviewrecipientfilters (review, uid, include) VALUES (%s, %s, %s)",
                [(review.id, filter_user_id, filter_include)
                 for filter_user_id, filter_include in recipientfilters])

            for filter_user_id, filter_include in recipientfilters:
                if filter_user_id is None and not filter_include:
                    is_opt_in = True

        addCommitsToReview(db, user, review, commits, new_review=True)

        if from_branch_name is not None:
            cursor.execute(
                "UPDATE branches SET review=%s WHERE repository=%s AND name=%s",
                (review.id, repository.id, from_branch_name))

        # Reload to get list of changesets added by addCommitsToReview().
        review = dbutils.Review.fromId(db, review.id)

        pending_mails = []
        recipients = review.getRecipients(db)
        for to_user in recipients:
            pending_mails.extend(
                mail.sendReviewCreated(db, user, to_user, recipients, review))

        if not is_opt_in:
            recipient_by_id = dict(
                (to_user.id, to_user) for to_user in recipients)

            cursor.execute(
                """SELECT userpreferences.uid, userpreferences.repository,
                                     userpreferences.filter, userpreferences.integer
                                FROM userpreferences
                     LEFT OUTER JOIN filters ON (filters.id=userpreferences.filter)
                               WHERE userpreferences.item='review.defaultOptOut'
                                 AND userpreferences.uid=ANY (%s)
                                 AND (userpreferences.filter IS NULL
                                   OR filters.repository=%s)
                                 AND (userpreferences.repository IS NULL
                                   OR userpreferences.repository=%s)""",
                (recipient_by_id.keys(), repository.id, repository.id))

            user_settings = {}
            has_filter_settings = False

            for user_id, repository_id, filter_id, integer in cursor:
                settings = user_settings.setdefault(user_id, [None, None, {}])
                value = bool(integer)

                if repository_id is None and filter_id is None:
                    settings[0] = value
                elif repository_id is not None:
                    settings[1] = value
                else:
                    settings[2][filter_id] = value
                    has_filter_settings = True

            if has_filter_settings:
                filters = Filters()
                filters.setFiles(db, review=review)

            for user_id, (global_default, repository_default,
                          filter_settings) in user_settings.items():
                to_user = recipient_by_id[user_id]
                opt_out = None

                if repository_default is not None:
                    opt_out = repository_default
                elif global_default is not None:
                    opt_out = global_default

                if filter_settings:
                    # Policy:
                    #
                    # If all of the user's filters that matched files in the
                    # review have review.defaultOptOut enabled, then opt out.
                    # When determining this, any review filters of the user's
                    # that match files in the review count as filters that don't
                    # have the review.defaultOptOut enabled.
                    #
                    # If any of the user's filters that matched files in the
                    # review have review.defaultOptOut disabled, then don't opt
                    # out.  When determining this, review filters are ignored.
                    #
                    # Otherwise, ignore the filter settings, and go with either
                    # the user's per-repository or global setting (as set
                    # above.)

                    filters.load(db, review=review, user=to_user)

                    # A set of filter ids.  If None is in the set, the user has
                    # one or more review filters in the review.  (These do not
                    # have ids.)
                    active_filters = filters.getActiveFilters(to_user)

                    for filter_id in active_filters:
                        if filter_id is None:
                            continue
                        elif filter_id in filter_settings:
                            if not filter_settings[filter_id]:
                                opt_out = False
                                break
                        else:
                            break
                    else:
                        if None not in active_filters:
                            opt_out = True

                if opt_out:
                    cursor.execute(
                        """INSERT INTO reviewrecipientfilters (review, uid, include)
                                           VALUES (%s, %s, FALSE)""",
                        (review.id, to_user.id))

        db.commit()

        mail.sendPendingMails(pending_mails)

        return review
    except:
        if not via_push:
            repository.run("branch", "-D", branch_name)
        raise
Example #25
0
def addReviewFilters(db, creator, user, review, reviewer_paths, watcher_paths):
    cursor = db.cursor()

    cursor.execute(
        "INSERT INTO reviewassignmentstransactions (review, assigner) VALUES (%s, %s) RETURNING id",
        (review.id, creator.id))
    transaction_id = cursor.fetchone()[0]

    def add(filter_type, paths):
        for path in paths:
            cursor.execute(
                """SELECT id, type
                                FROM reviewfilters
                               WHERE review=%s
                                 AND uid=%s
                                 AND path=%s""", (review.id, user.id, path))

            row = cursor.fetchone()

            if row:
                old_filter_id, old_filter_type = row

                if old_filter_type == filter_type:
                    continue
                else:
                    cursor.execute(
                        """DELETE FROM reviewfilters
                                            WHERE id=%s""", (old_filter_id, ))
                    cursor.execute(
                        """INSERT INTO reviewfilterchanges (transaction, uid, path, type, created)
                                           VALUES (%s, %s, %s, %s, false)""",
                        (transaction_id, user.id, path, old_filter_type))

            cursor.execute(
                """INSERT INTO reviewfilters (review, uid, path, type, creator)
                                   VALUES (%s, %s, %s, %s, %s)""",
                (review.id, user.id, path, filter_type, creator.id))
            cursor.execute(
                """INSERT INTO reviewfilterchanges (transaction, uid, path, type, created)
                                   VALUES (%s, %s, %s, %s, true)""",
                (transaction_id, user.id, path, filter_type))

    add("reviewer", reviewer_paths)
    add("watcher", watcher_paths)

    filters = Filters()
    filters.setFiles(db, review=review)
    filters.load(db, review=review, user=user)

    if user not in review.reviewers and user not in review.watchers and user not in review.owners:
        cursor.execute(
            """INSERT INTO reviewusers (review, uid, type)
                          VALUES (%s, %s, 'manual')""", (
                review.id,
                user.id,
            ))

    delete_files = set()
    insert_files = set()

    if watcher_paths:
        # Unassign changes currently assigned to the affected user.
        cursor.execute(
            """SELECT reviewfiles.id, reviewfiles.file
                            FROM reviewfiles
                            JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id)
                           WHERE reviewfiles.review=%s
                             AND reviewuserfiles.uid=%s""",
            (review.id, user.id))

        for review_file_id, file_id in cursor:
            if not filters.isReviewer(user.id, file_id):
                delete_files.add(review_file_id)

    if reviewer_paths:
        # Assign changes currently not assigned to the affected user.
        cursor.execute(
            """SELECT reviewfiles.id, reviewfiles.file
                            FROM reviewfiles
                            JOIN changesets ON (changesets.id=reviewfiles.changeset)
                            JOIN commits ON (commits.id=changesets.child)
                            JOIN gitusers ON (gitusers.id=commits.author_gituser)
                 LEFT OUTER JOIN usergitemails ON (usergitemails.email=gitusers.email
                                               AND usergitemails.uid=%s)
                 LEFT OUTER JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id
                                                 AND reviewuserfiles.uid=%s)
                           WHERE reviewfiles.review=%s
                             AND usergitemails.uid IS NULL
                             AND reviewuserfiles.uid IS NULL""",
            (user.id, user.id, review.id))

        for review_file_id, file_id in cursor:
            if filters.isReviewer(user.id, file_id):
                insert_files.add(review_file_id)

    if delete_files:
        cursor.executemany(
            "DELETE FROM reviewuserfiles WHERE file=%s AND uid=%s",
            izip(delete_files, repeat(user.id)))
        cursor.executemany(
            "INSERT INTO reviewassignmentchanges (transaction, file, uid, assigned) VALUES (%s, %s, %s, false)",
            izip(repeat(transaction_id), delete_files, repeat(user.id)))

    if insert_files:
        cursor.executemany(
            "INSERT INTO reviewuserfiles (file, uid) VALUES (%s, %s)",
            izip(insert_files, repeat(user.id)))
        cursor.executemany(
            "INSERT INTO reviewassignmentchanges (transaction, file, uid, assigned) VALUES (%s, %s, %s, true)",
            izip(repeat(transaction_id), insert_files, repeat(user.id)))

    return generateMailsForAssignmentsTransaction(db, transaction_id)
Example #26
0
def assignChanges(db,
                  user,
                  review,
                  commits=None,
                  changesets=None,
                  update=False):
    cursor = db.cursor()

    if changesets is None:
        assert commits is not None

        changesets = []

        for commit in commits:
            changesets.extend(
                changeset_utils.createChangeset(db, user, review.repository,
                                                commit))

    applyfilters = review.applyfilters
    applyparentfilters = review.applyparentfilters

    reviewers, watchers = getReviewersAndWatchers(
        db,
        review.repository,
        changesets=changesets,
        reviewfilters=review.getReviewFilters(db),
        applyfilters=applyfilters,
        applyparentfilters=applyparentfilters)

    cursor.execute("SELECT uid FROM reviewusers WHERE review=%s",
                   (review.id, ))

    reviewusers = set([user_id for (user_id, ) in cursor])
    reviewusers_values = set()
    reviewuserfiles_values = set()

    reviewuserfiles_existing = {}

    if update:
        cursor.execute(
            """SELECT reviewuserfiles.uid, reviewfiles.changeset, reviewfiles.file
                            FROM reviewfiles
                            JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id)
                           WHERE reviewfiles.review=%s""", (review.id, ))
        for user_id, changeset_id, file_id in cursor:
            reviewuserfiles_existing[(user_id, changeset_id, file_id)] = True

    new_reviewers = set()
    new_watchers = set()

    cursor.execute(
        """SELECT DISTINCT uid
                        FROM reviewfiles
                        JOIN reviewuserfiles ON (reviewuserfiles.file=reviewfiles.id)
                       WHERE review=%s""", (review.id, ))
    old_reviewers = set([user_id for (user_id, ) in cursor])

    for file_id, file_users in reviewers.items():
        for user_id, user_changesets in file_users.items():
            if user_id:
                new_reviewers.add(user_id)

                if user_id not in reviewusers:
                    reviewusers.add(user_id)
                    reviewusers_values.add((review.id, user_id))
                for changeset_id in user_changesets:
                    if (user_id, changeset_id,
                            file_id) not in reviewuserfiles_existing:
                        reviewuserfiles_values.add(
                            (user_id, review.id, changeset_id, file_id))

    for file_id, file_users in watchers.items():
        for user_id, user_changesets in file_users.items():
            if user_id:
                if user_id not in reviewusers:
                    new_watchers.add(user_id)
                    reviewusers.add(user_id)
                    reviewusers_values.add((review.id, user_id))

    new_reviewers -= old_reviewers
    new_watchers -= old_reviewers | new_reviewers

    cursor.executemany("INSERT INTO reviewusers (review, uid) VALUES (%s, %s)",
                       reviewusers_values)
    cursor.executemany(
        "INSERT INTO reviewuserfiles (file, uid) SELECT id, %s FROM reviewfiles WHERE review=%s AND changeset=%s AND file=%s",
        reviewuserfiles_values)

    if configuration.extensions.ENABLED:
        cursor.execute(
            """SELECT id, uid, extension, path
                            FROM extensionhookfilters
                           WHERE repository=%s""", (review.repository.id, ))

        rows = cursor.fetchall()

        if rows:
            if commits is None:
                commits = set()
                for changeset in changesets:
                    commits.add(changeset.child)
                commits = list(commits)

            filters = Filters()
            filters.setFiles(db, list(getFileIdsFromChangesets(changesets)))

            for filter_id, user_id, extension_id, path in rows:
                filters.addFilter(user_id, path, None, None, filter_id)

            for filter_id, file_ids in filters.matched_files.items():
                extensions.role.filterhook.queueFilterHookEvent(
                    db, filter_id, review, user, commits, file_ids)

    return new_reviewers, new_watchers
    def __init__(self,
                 overall_rank=None,
                 usnews=None,
                 cwur=None,
                 forbes=None,
                 times=None,
                 state=None,
                 city=None,
                 zipcode=None,
                 region=None,
                 fees_in_state=None,
                 fees_out_of_state=None,
                 gpa=None,
                 verbal=None,
                 quant=None,
                 boarding=None,
                 books=None,
                 overall_expenses=None,
                 admission_rate=None,
                 areas_of_interest=None):
        """Initializing Filter Class."""
        self.overall_rank = overall_rank
        self.usnews = usnews
        self.cwur = cwur
        self.forbes = forbes
        self.times = times

        self.state = state
        self.city = city
        self.zipcode = zipcode
        self.region = region

        self.fees_in_state = fees_in_state
        self.fees_out_of_state = fees_out_of_state

        self.gpa = gpa
        self.verbal = verbal
        self.quant = quant

        self.boarding = boarding
        self.books = books
        self.overall_expenses = overall_expenses

        self.admission_rate = admission_rate

        self.areas_of_interest = areas_of_interest

        # List of programs matching atleast one of the requested criteria
        self.unique_programs = None

        # List of programs meeting all requested criteria
        self.common_programs = []

        # Verbose program dict with all matching info
        self.matches = None

        # creating the object of Filters class
        self.filters = Filters()

        # Program Count
        self.count = self.filters.count
Example #28
0
 def setUp(self):
     self.filters = Filters()
Example #29
0
from PIL import Image, ImageFilter
from filters import Filters


fil = [ImageFilter.BLUR, ImageFilter.CONTOUR,
       ImageFilter.DETAIL, ImageFilter.EDGE_ENHANCE,
       ImageFilter.EMBOSS, ImageFilter.EDGE_ENHANCE_MORE,
       ImageFilter.FIND_EDGES, ImageFilter.SMOOTH,
       ImageFilter.SMOOTH_MORE, ImageFilter.SHARPEN]

file_name = "2sSzuXCn2SE.jpg"
size = (128, 128)
saved = "picture.jpeg"
new_image = Filters(file_name, size, saved)
new_image.filters(fil[1])
Example #30
0
    def __init__(self):
        """Set all connections of the application."""
        super().__init__()
        self.setupUi(self)
        self.setWindowTitle("ARTĪ£MIS " + __VERSION__)
        self.set_initial_size()
        self.closing = False
        self.download_window = DownloadWindow()
        self.download_window.complete.connect(self.show_downloaded_signals)
        self.actionExit.triggered.connect(qApp.quit)
        self.action_update_database.triggered.connect(self.ask_if_download)
        self.action_check_db_ver.triggered.connect(self.check_db_ver)
        self.action_sigidwiki_com.triggered.connect(
            lambda: webbrowser.open(Constants.SIGIDWIKI)
        )
        self.action_add_a_signal.triggered.connect(
            lambda: webbrowser.open(Constants.ADD_SIGNAL_LINK)
        )
        self.action_aresvalley_com.triggered.connect(
            lambda: webbrowser.open(Constants.ARESVALLEY_LINK)
        )
        self.action_forum.triggered.connect(
            lambda: webbrowser.open(Constants.FORUM_LINK)
        )
        self.action_rtl_sdr_com.triggered.connect(
            lambda: webbrowser.open(Constants.RTL_SDL_LINK)
        )
        self.db = None
        self.current_signal_name = ''
        self.signal_names = []
        self.total_signals = 0

        # Forecast
        self.forecast_info_btn.clicked.connect(
            lambda: webbrowser.open(Constants.SPACE_WEATHER_INFO)
        )
        self.forecast_data = ForecastData(self)
        self.update_forecast_bar.clicked.connect(self.start_update_forecast)
        self.update_forecast_bar.set_idle()
        self.forecast_data.update_complete.connect(self.update_forecast)

        # Spaceweather manager
        self.spaceweather_screen = SpaceWeatherManager(self)

        self.theme_manager = ThemeManager(self)

        self.filters = Filters(self)

# #######################################################################################

        UrlColors = namedtuple("UrlColors", ["inactive", "active", "clicked"])
        self.url_button.colors = UrlColors("#9f9f9f", "#4c75ff", "#942ccc")
        self.category_labels = [
            self.cat_mil,
            self.cat_rad,
            self.cat_active,
            self.cat_inactive,
            self.cat_ham,
            self.cat_comm,
            self.cat_avi,
            self.cat_mar,
            self.cat_ana,
            self.cat_dig,
            self.cat_trunked,
            self.cat_utility,
            self.cat_sat,
            self.cat_navi,
            self.cat_interf,
            self.cat_num_stat,
            self.cat_time_sig
        ]

        self.property_labels = [
            self.freq_lab,
            self.band_lab,
            self.mode_lab,
            self.modul_lab,
            self.loc_lab,
            self.acf_lab,
            self.description_text
        ]

        self.url_button.clicked.connect(self.go_to_web_page_signal)

        # GFD
        self.freq_search_gfd_btn.clicked.connect(partial(self.go_to_gfd, GfdType.FREQ))
        self.location_search_gfd_btn.clicked.connect(partial(self.go_to_gfd, GfdType.LOC))
        self.gfd_line_edit.returnPressed.connect(partial(self.go_to_gfd, GfdType.LOC))

# ##########################################################################################

        # Left list widget and search bar.
        self.search_bar.textChanged.connect(self.display_signals)
        self.signals_list.currentItemChanged.connect(self.display_specs)
        self.signals_list.itemDoubleClicked.connect(self.set_visible_tab)

        self.audio_widget = AudioPlayer(
            self.play,
            self.pause,
            self.stop,
            self.volume,
            self.loop,
            self.audio_progress,
            self.active_color,
            self.inactive_color
        )

        BandLabel = namedtuple("BandLabel", ["left", "center", "right"])
        self.band_labels = [
            BandLabel(self.elf_left, self.elf, self.elf_right),
            BandLabel(self.slf_left, self.slf, self.slf_right),
            BandLabel(self.ulf_left, self.ulf, self.ulf_right),
            BandLabel(self.vlf_left, self.vlf, self.vlf_right),
            BandLabel(self.lf_left, self.lf, self.lf_right),
            BandLabel(self.mf_left, self.mf, self.mf_right),
            BandLabel(self.hf_left, self.hf, self.hf_right),
            BandLabel(self.vhf_left, self.vhf, self.vhf_right),
            BandLabel(self.uhf_left, self.uhf, self.uhf_right),
            BandLabel(self.shf_left, self.shf, self.shf_right),
            BandLabel(self.ehf_left, self.ehf, self.ehf_right),
        ]

        self.main_tab.currentChanged.connect(self.hide_show_right_widget)

# Final operations.
        self.theme_manager.start()
        self.load_db()
        self.display_signals()