Exemple #1
0
def affinities_by_school(school_id):
    """return affinities got from that school"""
    school_ = api.data.schools.get(school_id)
    if not school_:
        return []

    ret_ = []
    ranks_ = query(api.character.rankadv.get_all()).where(
        lambda x: x.school == school_id and len(x.affinities) > 0).to_list()
    for r in ranks_:
        ret_ += r.affinities

    # special affinities
    if school_id == 'scorpion_yogo_wardmaster_school':
        ret_.append('wards')

    is_phoenix_embrace_the_elements = query(school_.techs).where(
        lambda x: x.id == 'phoenix_embrace_the_elements').count() > 0
    if is_phoenix_embrace_the_elements:
        affinity_, deficiencies_ = phoenix_embrace_the_elements()
        ret_.append(affinity_)

    is_mantis_favor_of_the_sun = query(school_.techs).where(
        lambda x: x.id == 'mantis_favor_of_the_sun').count() > 0
    if is_mantis_favor_of_the_sun:
        ret_.append('fire')

    return ret_
def get_tech_by_rank(rank):
    """returns the technique learned at the given insight rank, or None"""

    # get the school rank at that insight rank
    rank_ = query(api.character.rankadv.get_all()).where(
        lambda x: x.rank == rank).first_or_default(None)

    if not rank_:
        log.api.error(u"get_tech_by_rank. rank advancement not found: %d",
                      rank)
        return None

    school_id = rank_.school
    school_rank = query(api.character.rankadv.get_all()).where(
        lambda x: (x.school == school_id or x.replaced == school_id
                   ) and x.rank <= rank).count()

    school_ = api.data.schools.get(school_id)

    if not school_:
        return None

    # for path use the school rank as a tech index
    if api.data.schools.is_path(school_.id):
        try:
            return school_.techs[school_rank - 1].id
        except:
            return None

    return query(school_.techs).where(lambda x: x.rank == school_rank).select(
        a_('id')).first_or_default(None)
Exemple #3
0
    def search(self, term=None):
        if (term is None):
            template = Template(filename=TEMPLATE_BASE + "search.html")
            return template.render(model=None, title="Enter a Hostname, Location or Channel")
        else:
            print("Searching for {0}".format(term))
            repo = Repository()
            allchannels = repo.GetAllChannels()
            servers = query(allchannels).where(lambda x: x['Hostname'] == term).to_list()
            locations = query(allchannels).where(lambda x: x['Location'] == term).to_list()
            channels = query(allchannels).where(lambda x: x['Channel'] == term).to_list()
            template = Template(filename=TEMPLATE_BASE + "search.html")

            if (len(servers) > 0):
                to_return = servers
                title = "Found Server(s)"
            elif (len(locations) > 0):
                to_return = locations
                title = "Found Location(s)"
            elif (len(channels) > 0):
                to_return = channels
                title = "Found Channel(s)"
            else:
                to_return = []
                title = "Did not find any matches"

            if (to_return is not None):
               for row in to_return:
                   row.setdefault('URL', "/server?{0}".format(urlencode({'name':row['IPAddress']})))
            return template.render(model=to_return, title=title)
Exemple #4
0
    def put(self, plan_id, item_id, **kwargs):
        user = kwargs['user']
        json = request.json
        new_item = Item.from_json(json)

        if new_item.id != item_id:
            on_error(error_message="Could not update item, ids do not match")

        plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
            default=None)
        if not plan:
            abort(404, message="This plan does not exist")

        old_item = query(plan.items).where(lambda i: i.id ==
                                                 item_id).single_or_default(default=None)
        if not old_item:
            abort(404, message="This item does not exist")

        result = self.item_repository.add_or_update(new_item)

        if not result.success():
            on_error(error_message="Could not update item", result=result)

        self.item_repository.save_changes()
        return new_item
Exemple #5
0
def get_school_rank(sid):
    """return the school rank"""

    if api.data.schools.is_path(sid):
        return query(api.data.schools.get(sid).techs).select(a_('rank')).first_or_default(1)
    return query(api.character.rankadv.get_all()).where(
            lambda x: x.school == sid or x.replaced == sid).count()
def get_paths_with_rank(rank):
    """returns alternate schools list with rank equal to `rank`"""

    return query(__api.ds.schools) \
        .where(lambda x: 'alternate' in x.tags) \
        .where(lambda x: query(x.techs).select(a_('rank')).first_or_default(0) == rank) \
        .to_list()
def get_tech_by_rank(rank):
    """returns the technique learned at the given insight rank, or None"""

    # get the school rank at that insight rank
    rank_ = query(api.character.rankadv.get_all()).where(
        lambda x: x.rank == rank).to_list()

    if not rank_:
        #log.api.error(u"get_tech_by_rank. rank advancement not found: %d", rank)
        return None

    school_id = rank_[0].school
    if len(rank_) > 1:
        # find a replacement
        replacement_ = query(rank_).where(
            lambda x: x.replaced == school_id).first_or_default(None)
        if replacement_:
            school_id = replacement_.school

    school_ = api.data.schools.get(school_id)

    if not school_:
        return None

    return query(school_.techs).where(lambda x: x.rank == rank).select(
        a_('id')).first_or_default(None)
Exemple #8
0
    def auto_lib(self,
                 base_dir='.',
                 include_root=False,
                 filter_func=None,
                 **kwargs):
        srcs, headers = opa_waf.get_files(os.path.join(self.path, base_dir),
                                          include_root)
        if filter_func:
            srcs = query(srcs).where(filter_func).to_list()
            headers = query(srcs).where(filter_func).to_list()

        ipath = ['./include-internal']
        eipath = ['./inc', './include']

        ipath = [os.path.join(base_dir, x) for x in ipath]
        eipath = [os.path.join(base_dir, x) for x in eipath]
        if include_root:
            eipath.append(base_dir)
            ipath.append(base_dir)

        num_inc_dir = query(eipath).where(lambda x: self.has_child(x)).count()
        found = False

        if len(srcs) + len(headers) == 0 and num_inc_dir == 0:
            return

        return self.create_conf(BuilderType.LIB,
                                **kwargs).update(includes=ipath + eipath,
                                                 exports=eipath,
                                                 sources=srcs,
                                                 headers=headers)
def affinities_by_school(school_id):
    """return affinities got from that school"""
    school_ = api.data.schools.get(school_id)
    if not school_:
        return []

    ret_ = []
    ranks_ = query(api.character.rankadv.get_all()).where(
        lambda x: x.school == school_id and len(x.affinities) > 0).to_list()
    for r in ranks_:
        ret_ += r.affinities

    # special affinities
    if school_id == 'scorpion_yogo_wardmaster_school':
        ret_.append('wards')

    is_phoenix_embrace_the_elements = query(school_.techs).where(
        lambda x: x.id == 'phoenix_embrace_the_elements').count() > 0
    if is_phoenix_embrace_the_elements:
        affinity_, deficiencies_ = phoenix_embrace_the_elements()
        ret_.append(affinity_)

    is_mantis_favor_of_the_sun = query(school_.techs).where(lambda x: x.id == 'mantis_favor_of_the_sun').count() > 0
    if is_mantis_favor_of_the_sun:
        ret_.append('fire')

    return ret_
def get_paths_with_rank(rank):
    """returns alternate schools list with rank equal to `rank`"""

    return query(__api.ds.schools) \
        .where(lambda x: 'alternate' in x.tags) \
        .where(lambda x: query(x.techs).select(a_('rank')).first_or_default(0) == rank) \
        .to_list()
Exemple #11
0
    def post(self, plan_id, **kwargs):
        plan = query(self.plan_repository.get(user_id=kwargs['user'].id, id=plan_id)).single_or_default(
            default=None)
        if not plan:
            abort(404, message="This plan does not exist")

        post_body = request.json
        if type(post_body) is not list:
            on_error(error_message="Invalid post body")

        result = ChangeResult()
        try:
            shares = query(post_body)
            for shared_user in plan.shared_users:
                if not shares.contains(shared_user, lambda lhs, rhs: rhs['user_id'] == lhs.id):
                    result.add_child_result(
                        self.plan_repository.unshare(plan, shared_user.id))

            for share in post_body:
                user_id = share['user_id']
                permission = share['permission']
                result.add_child_result(
                    self.plan_repository.share(plan, user_id, permission))

        except KeyError as ke:
            on_error(error_message="Invalid post body")

        if not result.success():
            on_error(error_message="Could not share plan", result=result)

        self.plan_repository.save_changes()
        return plan
Exemple #12
0
def get_yelp_item(coordinate, category, strategy=DistanceStrategy()):
    extra_yelp_params = {}
    yelp_item_repository = YelpItemRepository()

    # for these strategies, use YelpAPI
    # then reset strategy_name so that we can still call strategy module below
    extra_yelp_params['radius_filters'] = 7500

    if strategy.type == StrategyType.popularity:
        extra_yelp_params['sort'] = 2
        strategy = FirstStrategy()
    elif strategy.type == StrategyType.distance:
        extra_yelp_params['sort'] = 1
        strategy = FirstRandomStrategy()

    try:
        search_results = query(yelpapi.search(coordinate.latitude,
                                              coordinate.longitude,
                                              category.search_term,
                                              query(category.search_filters).select(lambda f: f.filter).to_list(),
                                              **extra_yelp_params)).where(
            lambda r: ['Food Trucks', 'foodtrucks'] not in r['categories'])
        yelp_items = [YelpItem.create_from_dict(result) for result in search_results]
        yelp_item = strategy.run_strategy(yelp_items)
        yelp_item = yelp_item_repository.get_or_insert(yelp_item)
        yelp_item_repository.save_changes()
        return yelp_item
    except:
        return None
def get_school_rank(sid):
    """return the school rank"""

    if api.data.schools.is_path(sid):
        return query(api.data.schools.get(sid).techs).select(a_('rank')).first_or_default(1)
    return query(api.character.rankadv.get_all()).where(
            lambda x: x.school == sid or x.replaced == sid).count()
def get_tech_by_rank(rank):
    """returns the technique learned at the given insight rank, or None"""

    # get the school rank at that insight rank
    rank_ = query(api.character.rankadv.get_all()).where(
        lambda x: x.rank == rank).to_list()

    if not rank_:
        #log.api.error(u"get_tech_by_rank. rank advancement not found: %d", rank)
        return None


    school_id = rank_[0].school
    if len(rank_) > 1:        
        # find a replacement
        replacement_ = query(rank_).where(lambda x: x.replaced == school_id).first_or_default(None)
        if replacement_:
            school_id = replacement_.school

    school_ = api.data.schools.get(school_id)

    if not school_:
        return None

    return query(school_.techs).where(lambda x: x.rank == rank).select(a_('id')).first_or_default(None)
def get_spells(ring, mastery, maho=True):
    """returns all the maho spells for the given ring and mastery, if maho include maho spells"""
    including_maho = query(
        all()).where(lambda x: x.element == ring and x.mastery == mastery)
    if not maho:
        return query(including_maho).where(
            lambda x: 'maho' not in tags(x.id)).to_list()
    return including_maho.to_list()
Exemple #16
0
def getThemeInstances(theme, pages):
    print "instanceOf::Theme:" + theme
    instances = query(pages).where(lambda p: ("instanceOf" in p)).to_list()
    insts = (
        query(instances).where(lambda p: any(filter(lambda i: "n" in i and i["n"] == theme, p["instanceOf"]))).to_list()
    )
    print insts
    return insts
def get_locations_from_site_map(site_map):
    site_map_elements = site_map.getroot().getchildren()

    return (
        query(site_map_elements)
            .select(lambda e: query(e.getchildren()).single(lambda e: e.tag == 'loc'))
            .select(lambda e: e.text)
            .to_list()
    )
def realtime_volume_ratio(Coin):
    Transaction_history = pybithumb.transaction_history(Coin)
    Realtime_bid = query(Transaction_history['data']).where(lambda item: item[
        'type'] == 'bid').select(lambda item: item['units_traded']).to_list()
    Realtime_ask = query(Transaction_history['data']).where(lambda item: item[
        'type'] == 'ask').select(lambda item: item['units_traded']).to_list()
    Realtime_bid = sum(list(map(float, Realtime_bid)))
    Realtime_ask = sum(list(map(float, Realtime_ask)))
    Realtime_Volume_Ratio = Realtime_bid / Realtime_ask
    return Realtime_Volume_Ratio
Exemple #19
0
 def get(self, plan_id, item_id, **kwargs):
     user = kwargs['user']
     plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
         default=None)
     if not plan:
         abort(404, message="This plan does not exist")
     item = query(plan.items).where(lambda i: i.id ==
                                              item_id).single_or_default(default=None)
     if not item:
         abort(404, message="This item does not exist")
     return item
Exemple #20
0
def generate_ratio_chart(results, report_dir):
    data = query(results) \
        .where(lambda x: x['compare']) \
        .where(lambda x: x['ratio']) \
        .order_by(lambda x: x['info'].label()) \
        .select(lambda x: new(label=x['info'].label(), value=x['ratio'])) \
        .to_list()
    labels = query(data).select(lambda x: x.label).to_list()
    values = query(data).select(lambda x: x.value).to_list()
    if len(labels):
        filename = report_dir / 'ratios.png'
        ratio_plot(filename, labels, values, 'Throughput compared to golden')
        return Image(filename)
    return None
Exemple #21
0
def generate_efficiency_chart(results, report_dir):
    data = query(results) \
        .where(lambda x: x['compare']) \
        .where(lambda x: x['efficiency']) \
        .order_by(lambda x: x['info'].label()) \
        .select(lambda x: new(label=x['info'].label(), value=x['efficiency'])) \
        .to_list()
    labels = query(data).select(lambda x: x.label).to_list()
    values = query(data).select(lambda x: x.value).to_list()
    if len(values):
        filename = report_dir / 'efficiency.png'
        ratio_plot(filename, labels, values, 'Efficiency relative to TF/GP100')
        return Image(filename)
    return None
    def load_families(self, clanid=None):
        self.cb_family.blockSignals(True)
        self.cb_family.clear()

        if clanid:
            family_list = query(api.data.families.get_all()).where(lambda x: x.clanid == clanid).order_by(a_('name'))
        else:
            family_list = query(api.data.families.get_all()).order_by(a_('name'))

        for f in family_list:
            self.cb_family.addItem(f.name, f.id)
        self.cb_family.blockSignals(False)

        # select first family
        self.on_family_changed(0)
    def load_families(self, clanid=None):
        self.cb_family.blockSignals(True)
        self.cb_family.clear()

        if clanid:
            family_list = query(api.data.families.get_all()).where(lambda x: x.clanid == clanid).order_by(a_('name'))
        else:
            family_list = query(api.data.families.get_all()).order_by(a_('name'))

        for f in family_list:
            self.cb_family.addItem(f.name, f.id)
        self.cb_family.blockSignals(False)

        # select first family
        self.on_family_changed(0)
def get_school_by_rank(rank):
    """returns the school joined at the given insight rank, considering alternate paths"""
    rank_ = query(api.character.rankadv.get_all()).where(lambda x: x.rank == rank).first_or_default(None)
    if not rank_:
        log.api.error(u"get_school_by_rank. rank advancement not found: %d", rank)
        return None
    return rank_.school
def realtime_volume(Coin):
    Transaction_history = pybithumb.transaction_history(Coin)
    Realtime_Volume = query(Transaction_history['data']).where(
        lambda item: item['type'] == 'bid').select(
            lambda item: item['units_traded']).to_list()
    Realtime_Volume = sum(list(map(float, Realtime_Volume)))
    return Realtime_Volume
def get_rank(mid, rank):
    """returns a merit rank"""
    merit_ = get(mid)
    if not merit_:
        return None
    return query(
        merit_.ranks).where(lambda x: x.id == rank).first_or_default(None)
Exemple #27
0
    def get_longpoll_collision(self):
        def common(l1, l2):
            return list(set(l1).intersection(l2))

        # glc str is laik '
        # {"ts":1814582040,"pts":1707239,"updates":[[61,275403018,1],[8,-262426908,4],[61,275403018,1]]};
        # {"ts":1801587829,"pts":1333083,"updates":[[9,-7837569,1]]};
        # {"ts":1654083789,"pts":284006,"updates":[[8,-229675882,4]]};
        # {"ts":1654083793,"pts":284006,"updates":[[8,-15683318,7]]};
        # {"ts":1814582464,"pts":1707465,"updates":[[8,-180240104,4]]}'
        with open(ARGS.glc) as f:
            updates_input = f.read()

        updates = query(updates_input.splitlines()) \
            .select(lambda x: json.loads(x)) \
            .select_many(lambda x: x['updates']) \
            .where(lambda x: x[0] == 9 or x[0] == 8) \
            .select(lambda x: abs(x[1])) \
            .to_list()

        possible_user = self.api.friends.get(user_id=updates[0])
        updates = updates[1:]
        for id in updates:
            friends = self.api.friends.get(user_id=id)
            new_possible_user = common(possible_user, friends)
            print('checked: ' + str(id))
            if len(new_possible_user) != 0:
                possible_user = new_possible_user
                # if len(new_possible_user) == 1:
                #     break
        print(possible_user)
def get_rank(fid, rank):
    """returns a flaw rank"""
    flaw_ = get(fid)
    if not flaw_:
        return None
    return query(
        flaw_.ranks).where(lambda x: x.id == rank).first_or_default(None)
	def createTable(resource, contribs, classification, classname):
		classificationBase = root + "/" + classification + '/'
		logging.info(classificationBase)
		classBase = classificationBase + classname.replace('_',' ')
		if not os.path.exists(classificationBase):
			os.makedirs(classificationBase)
		if not os.path.exists(classBase):
			os.makedirs(classBase)
		if not os.path.exists(classBase + "/" + resource):
			os.makedirs(classBase + "/" + resource)
		level0Links = {}
		level1Links = {}
		for contribName in sorted(contribs.keys()):
			logging.info('Checking' + contribName + '...')
			clevel0Links = contribs[contribName]
			level0Links[contribName] = clevel0Links
			clevel1Links = []
			logging.info('' + str(len(clevel0Links)) + 'level 0 links found.')
			logging.info(' Finding level 1 links...')
			for rawlink in clevel0Links:
				split = rawlink.split('::')[-1].replace('_',' ').split(':')
				n = split[-1]
				p = split[0].title() if len(split) > 1 else ''
				ls = query(pages).where(lambda page: handlePrefix(page['p']).lower() == p.lower() and page['n'].lower() == n.lower() and 'internal_links' in page).select(lambda page: map(lambda l: l.split('::')[-1].lower(),page['internal_links'])).to_list()
				clevel1Links.extend(filter(lambda l: l not in clevel0Links, ls[0]) if ls else [])
			level1Links[contribName] = clevel1Links
			logging.info(''+ str(len(clevel1Links))+ 'level 1 links found.')
		flipped = {}
		for contribName in sorted(level0Links.keys()):
			logging.info(contribName)
			for term in level0Links[contribName]:
				term = term.encode('utf-8')
				logging.info(term)
				if term in flipped:
					flipped[term].append(contribName)
				else:
					flipped[term] = [contribName]
		uniqueLevel0 = {}
		lowerMappedTerms = set(map(lambda r: r.lower(), mappedTerms))
		for term in flipped:
			for contribName in sorted(contribs.keys()):
				if not contribName in uniqueLevel0:
					uniqueLevel0[contribName] = []
				if contribName in flipped[term] and len(flipped[term]) == 1:
					if contribName in uniqueLevel0:
						if term in lowerMappedTerms:
							logging.info(contribName + "-> " + term)
							uniqueLevel0[contribName].append(term)
		mytemplate = Template(filename='templates/coverageTemplate.txt')
		table = mytemplate.render(mappedTerms=mappedTerms, contribs=contribs.keys(), level0Links = level0Links, level1Links=level1Links, uniqueLevel0=uniqueLevel0)
		logging.info( "Creating " + classBase + "/" + resource + '/coverage.html')
		with open(classBase + "/" + resource + '/coverage.html', 'write') as tablef:
			tablef.write(table)
		coverage = {}
		for term in mappedTerms:
			coverage[term] = {}
			coverage[term]['level0'] = filter(lambda c: term.lower() in map(lambda t: t.lower(), level0Links[c]), contribs)
			coverage[term]['level1'] = filter(lambda c: term.lower() in map(lambda t: t.lower(), level1Links[c]) and not c in coverage[term]['level0'], contribs)
		with open(classBase + "/" + resource + '/coverage.json', 'write') as tablefjson:
			json.dump(coverage, tablefjson,indent=4 )
Exemple #30
0
def list_files_rec(base, *paths):
    lst = []
    for path_entry in paths:
        for root, dirs, files in os.walk(os.path.join(base, path_entry)):
            for f in files:
                lst.append(os.path.join(root, f))
    return query(lst)
def find_indexed_element_for_first_maximum(histogram):
    return query(histogram)                               \
            .copy_padded_triples()                        \
            .select_with_index()                          \
            .where(lambda item: is_maxima(*item.element)) \
            .select(a_('index'))                          \
            .first_or_default(0)
Exemple #32
0
 def get(self, plan_id, **kwargs):
     user = kwargs['user']
     plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
         default=None)
     if not plan:
         abort(404, message="This plan does not exist")
     return plan.items
def get_bought():
    """return all merits that comes from advancements"""
    if not __api.pc:
        return []
    return query(
        __api.pc.advans).where(lambda x: x.type == 'perk' and
                               (x.cost > 0 or x.tag == 'merit')).to_list()
Exemple #34
0
def calc_section(section_spec, metrics, section_baseline=None):
    display.vv("calculate section {}".format(section_spec['name']))
    display.vvv("spec: {}".format(section_spec))
    display.vvv("metrics: {}".format(metrics))
    display.vvv("baseline: {}".format(section_baseline))

    metric_results = []
    section_score = 0
    if section_baseline:
        for m in section_spec['metrics']:
            m_baseline = query(section_baseline['metrics']).first(
                lambda metric: metric['name'] == m['name'])
            metric_results.append(
                calc_metric(m, metrics[m['name']], m_baseline))
        section_score = mean([r['score'] for r in metric_results])
    else:
        for m in section_spec['metrics']:
            metric_results.append(calc_metric(m, metrics[m['name']]))

    # TODO(yujunz): use formula in spec
    return {
        'score': section_score,
        'name': section_spec['name'],
        'description': section_spec.get('description', 'section'),
        'metrics': metric_results
    }
def get_requirements(sid):
    """returns the requirements to join the given school"""
    school_ = get(sid)
    if not school_:
        log.api.error(u"school not found: %s", sid)
        return []

    requirements_by_data_ = school_.require

    # fixme. since i can't rewrite all alternate path
    # I decided to patch these requirement by code

    import l5r.api.character.schools
    from l5rdal.requirements import Requirement
    coded_requirements_ = []

    if is_path(sid):
        # An alternate path can only be joined
        # on the same school rank that its technique replaces

        path_rank_ = query(school_.techs).select(a_('rank')).first_or_default(0)

        if path_rank_ > 0:

            r = Requirement()
            r.field = api.character.schools.get_current()
            r.type = 'school'
            r.min = path_rank_ - 1
            r.max = path_rank_ - 1
            r.trg = None
            r.text = __api.tr("Replaces School Rank: {0}").format(path_rank_)

            coded_requirements_.append(r)

    return requirements_by_data_ + coded_requirements_
def get_learned():
    """return all the learned ( not starting ) skills"""
    if not __api.pc:
        return []
    return query(__api.pc.advans).where(
        lambda x: x.type == 'skill').select(
        lambda x: x.skill).distinct().to_list()
Exemple #37
0
    def delete(self, plan_id, item_id, **kwargs):
        user = kwargs['user']
        plan = query(self.plan_repository.get(user_id=user.id, id=plan_id)).single_or_default(
            default=None)
        if not plan:
            abort(404, message="This plan does not exist")

        item = query(plan.items).where(lambda i: i.id ==
                                                 item_id).single_or_default(default=None)
        if not item:
            abort(404, message="This item does not exist")

        plan.remove_item(item)
        self.item_repository.delete(id)
        self.item_repository.save_changes()
        return {"message": "Deleted item"}
def get_skill_rank(skill_id):
    """return the character skill rank"""
    if not __api.pc:
        return 0

    sk_rank_ = 0
    for r in api.character.rankadv.get_all():
        sk_rank_ += query(r.skills).where(lambda x: x == skill_id).count()

    sk_rank_ += query(__api.pc.advans).where(
        lambda x: x.type == 'skill' and x.skill == skill_id).count()

    if skill_id in get_acquired():
        sk_rank_ += 1

    return sk_rank_
def get_skill_rank(skill_id):
    """return the character skill rank"""
    if not __api.pc:
        return 0

    sk_rank_ = 0
    for r in api.character.rankadv.get_all():
        sk_rank_ += query(r.skills).where(lambda x: x == skill_id).count()

    sk_rank_ += query(__api.pc.advans).where(
        lambda x: x.type == 'skill' and x.skill == skill_id).count()

    if skill_id in get_acquired():
        sk_rank_ += 1

    return sk_rank_
def get_all():
    """return all character skills"""
    if not __api.pc:
        return []

    return query(get_starting() + get_learned() +
                 get_acquired()).distinct().to_list()
Exemple #41
0
    def add_step(self,
                 name,
                 data,
                 log_debug=True,
                 print_step=True,
                 overwrite=False):
        if not overwrite:
            self._steps.append(
                ImageTrace(step=self._step, name=name, data=data))
        else:
            step = next(
                iter(query(self._steps).where(lambda s: s.name == name)), None)
            if step is not None:
                step.data = data
            else:
                self._steps.append(
                    ImageTrace(step=self._step, name=name, data=data))

        if log_debug:
            log.debug(name + (': ' + data) if data is not None else '')

        if print_step:
            printer.printf(name, data if data is not None else '')

        self._step += 1
def get_mastery_ability(skill_id, rank):
    """returns the mastery ability for a given rank"""
    skill_ = get(skill_id)
    if not skill_:
        return None
    return query(skill_.mastery_abilities).where(
        lambda x: x.rank == rank).first_or_default(None)
Exemple #43
0
def mandelbrot():
    MaxIterations = 200
    SampleWidth = 3.2
    SampleHeight = 2.5
    OffsetX = -2.1
    OffsetY = -1.25

    ImageWidth = 480
    ImageHeight = int(SampleHeight * ImageWidth / SampleWidth)

    query = integers(0, ImageHeight).select(lambda y: (y * SampleHeight) / ImageHeight + OffsetY) \
            .select_many_with_correspondence(
                lambda y: integers(0, ImageWidth).select(lambda x: (x * SampleWidth) / ImageWidth + OffsetX),
                lambda y, x: (x, y)) \
            .select(lambda real_imag: complex(*real_imag)) \
            .select(lambda c: query(generate(c, lambda x: x * x + c))
                              .take_while(lambda x: x.real ** 2 + x.imag ** 2 < 4)
                              .take(MaxIterations)
                              .count()) \
            .select(lambda c: ((c * 7) % 255, (c * 5) % 255, (c * 11) % 255) if c != MaxIterations else (0, 0, 0))

    data = q.to_list()

    image = Image.new("RGB", (ImageWidth, ImageHeight))
    image.putdata(data)
    image.show()
def get_references():
    """return a list of data-packs that are referenced by the character"""

    refs_ = []
    # get references from families
    family_ = api.data.families.get(api.character.get_family())
    if family_:
        refs_.append(family_.pack)

    # get references from schools
    for s in [
            api.data.schools.get(x) for x in api.character.schools.get_all()
            if api.data.schools.get(x) is not None
    ]:
        refs_.append(s.pack)

    # get references from skills
    for s in [
            api.data.skills.get(x) for x in api.character.skills.get_all()
            if api.data.skills.get(x) is not None
    ]:
        refs_.append(s.pack)

    # get references from spells
    for s in [
            api.data.spells.get(x) for x in api.character.spells.get_all()
            if api.data.spells.get(x) is not None
    ]:
        refs_.append(s.pack)

    return query(refs_).where(lambda y: y is not None).distinct(
        a_('id')).to_list()
Exemple #45
0
def make_html_suites(results):
    return query(results) \
        .group_by(
            lambda x: x['info'].suite_name,
            result_selector=lambda k, g: new(name=k, results=make_html_results(g))) \
        .order_by(lambda x: x.name) \
        .to_list()
Exemple #46
0
def make_html_summary(results):
    counts = query(results) \
        .group_by(lambda x: x['status']) \
        .to_dictionary(lambda x: x.key, len)

    errors = counts.get('ERROR', 0)
    failures = counts.get('FAIL', 0)
    skipped = counts.get('SKIP', 0)
    passed = counts.get('PASS', 0)
    total = errors + failures + skipped + passed

    if errors:
        status = 'ERROR'
    elif failures:
        status = 'FAIL'
    else:
        status = 'PASS'

    return new(
        status=status,
        css=CSS_MAP.get(status),
        errors_count=errors,
        failures_count=failures,
        skipped_count=skipped,
        passed_count=passed,
        total_count=total,
    )
Exemple #47
0
 def _register(self, rid, name):
     if not query(self.report_registry).any(lambda r: r['id'] == rid):
         self.report_registry.append({
             'id': rid,
             'name': name,
             'path': 'reporter/%s.html' % rid
         })
Exemple #48
0
 def get_report_name(self, report_id):
     report = query(self.report_registry).first_or_default(
         None, lambda r: r['id'] == report_id)
     if report is not None:
         return report['name']
     else:
         return None
def get_techs_by_school(sid):
    """returns all the techniques learned in the given school"""

    school_ = api.data.schools.get(sid)
    if not school_:
        return []

    return query(school_.techs).where(lambda x: api.character.has_rule(x.id)).select(a_('id')).to_list()
    def get_filtered_clan_list(self):
        schools = self.get_filtered_school_list()
        clanids = query(schools) \
            .distinct(a_('clanid')) \
            .select(a_('clanid')) \
            .to_list()

        return [api.data.clans.get(x) for x in clanids]
def get_emphasis_to_choose(sid):
    """returns player choose emphasis"""
    school = get(sid)
    if not school:
        return []
    return query(school.skills) \
        .where(lambda x: x.emph and x.emph.startswith('*')) \
        .to_list()
def get_starting():
    """get character starting skills"""
    # get first rank advancement
    rank_ = api.character.rankadv.get(1)
    if not rank_:
        return []

    return query(rank_.skills).distinct().to_list()
Exemple #53
0
 def get_shared_user_permission(self, plan_id, user_id):
     shared_user = query(
         PlanShares.query.filter_by(plan_id=plan_id, user_id=user_id).all()).single_or_default(
         default=None
     )
     if not shared_user:
         return None
     return shared_user.permission
Exemple #54
0
def getPermutations(listOfLists):
	numEntries = len(listOfLists)
	listOfLists = query(listOfLists).select(lambda x:filter(None,x)).to_list()
	if not len(listOfLists):
		return []	
	listLengths = query(list(listOfLists)).select(lambda x:len(x)).to_list()
	totalPermutations = query(listLengths).aggregate(lambda cur,sum: sum*cur)	
	retList=[]
	for p in range(0,totalPermutations):
		scalePerm = totalPermutations+0
		oneList=[]
		for l in range(0,numEntries):
			scalePerm = scalePerm/listLengths[l]
			pos= p/scalePerm
			p=p-(scalePerm*pos)
			oneList.append(listOfLists[l][pos])
		retList.append(oneList)
	return retList		
Exemple #55
0
def getFeatures(pages):
    techs = (
        query(pages)
        .where(lambda p: any(filter(lambda i: i.startswith("implements::Feature:"), p.get("internal_links", []))))
        .select(lambda p: filter(lambda i: i.startswith("implements::Feature:"), p["internal_links"]))
        .to_list()
    )
    s = reduce(lambda a, b: a + b, techs) if techs else []
    return map(lambda n: n.replace("implements::Feature:", ""), s)
Exemple #56
0
def getConcepts(pages):
    cs = (
        query(pages)
        .where(lambda p: any(filter(lambda i: re.match(r"^[a-zA-Z0-9 ]+$", i), p.get("internal_links", []))))
        .select(lambda p: filter(lambda i: re.match(r"^[a-zA-Z0-9 ]+$", i), p["internal_links"]))
        .to_list()
    )
    s = reduce(lambda a, b: a + b, cs) if cs else []
    return s
Exemple #57
0
def getLangs(pages):
    langs = (
        query(pages)
        .where(lambda p: any(filter(lambda i: i.startswith("uses::Language"), p.get("internal_links", []))))
        .select(lambda p: filter(lambda i: i.startswith("uses::Language"), p["internal_links"]))
        .to_list()
    )
    s = reduce(lambda a, b: a + b, langs) if langs else []
    return map(lambda n: n.replace("uses::Language:", ""), s)
    def load_clans(self):
        self.cb_clan.blockSignals(True)
        self.cb_clan.clear()
        self.cb_clan.addItem(self.tr("No Clan"), None)

        for c in query(api.data.clans.all()).order_by(a_('name')):
            self.cb_clan.addItem(c.name, c.id)
        self.cb_clan.blockSignals(False)

        # select first clan
        self.on_clan_changed(0)