Beispiel #1
0
 def params(self):
     '''
     Construct a dict of dicts: parameters are keys and
     dictionary of attributes/values are values. Cached too.
     '''
     id = "ra_params-%s" % self.ra_string()
     if cache.is_cached(id):
         return cache.retrieve(id)
     if self.mk_ra_node() is None:
         return None
     d = {}
     for c in self.ra_elem.xpath("//parameters/parameter"):
         name = c.get("name")
         if not name:
             continue
         required = c.get("required")
         unique = c.get("unique")
         type, default = self.param_type_default(c)
         d[name] = {
             "required": required,
             "unique": unique,
             "type": type,
             "default": default,
         }
     return cache.store(id, d)
Beispiel #2
0
 def params(self):
     '''
     Construct a dict of dicts: parameters are keys and
     dictionary of attributes/values are values. Cached too.
     '''
     id = "ra_params-%s" % self.ra_string()
     if cache.is_cached(id):
         return cache.retrieve(id)
     if self.mk_ra_node() is None:
         return None
     d = {}
     for c in self.ra_elem.xpath("//parameters/parameter"):
         name = c.get("name")
         if not name:
             continue
         required = c.get("required")
         unique = c.get("unique")
         type, default = self.param_type_default(c)
         d[name] = {
             "required": required,
             "unique": unique,
             "type": type,
             "default": default,
         }
     return cache.store(id, d)
Beispiel #3
0
def country_report(country_code):
    """
    """

    country_code = country_code.upper()
    if not available_countries.get(country_code):
        raise ApiException(400, "Reports are not available for the country that you specified.")
    if g.user is None or not g.user.is_active():
        raise ApiException(401, "You need to be logged-in in order to access this resource.")

    country = Country.query.filter_by(code=country_code).one()

    report_json = cache.retrieve('country_overview_' + country.code)
    if report_json:
        logger.debug('loading country overview from cache')
    else:
        report = {}
        procurement_list = []
        procurements = Procurement.query.filter_by(country=country).filter_by(approved=True).order_by(Procurement.start_date.desc(), Procurement.end_date.desc()).all()
        for procurement in procurements:
            procurement_list.append(procurement.to_dict(include_related=True))
        report['country'] = country.to_dict()
        report['medicines'] = calculate_country_overview(country)
        report['procurements'] = procurement_list
        report_json = json.dumps(report, cls=serializers.CustomEncoder)
        cache.store('country_overview_' + country.code, report_json)

    return send_api_response(report_json)
Beispiel #4
0
 def actions(self):
     '''
     Construct a dict of dicts: actions are keys and
     dictionary of attributes/values are values. Cached too.
     '''
     id = "ra_actions-%s" % self.ra_string()
     if cache.is_cached(id):
         return cache.retrieve(id)
     if self.mk_ra_node() is None:
         return None
     d = {}
     for c in self.ra_elem.xpath("//actions/action"):
         name = c.get("name")
         if not name or name in self.skip_ops:
             continue
         if name == "monitor":
             name = monitor_name_node(c)
         d[name] = {}
         for a in c.attrib.keys():
             if a in self.skip_op_attr:
                 continue
             v = c.get(a)
             if v:
                 d[name][a] = v
     # add monitor ops without role, if they don't already
     # exist
     d2 = {}
     for op in d.keys():
         if re.match("monitor_[^0-9]", op):
             norole_op = re.sub(r'monitor_[^0-9_]+_(.*)', r'monitor_\1', op)
             if not norole_op in d:
                 d2[norole_op] = d[op]
     d.update(d2)
     return cache.store(id, d)
Beispiel #5
0
def autocomplete(query):
    """
    Return the name and medicine_id of each medicine that matches the given query.
    """

    out = []
    medicine_list_json = cache.retrieve('medicine_list')
    if medicine_list_json:
        logger.debug('calculating autocomplete from cache')
        medicine_list = json.loads(medicine_list_json)
    else:
        medicine_list = calculate_autocomplete()
        cache.store('medicine_list', json.dumps(medicine_list, cls=serializers.CustomEncoder))
    for medicine in medicine_list:
        tmp = {}
        query_index = medicine['name'].lower().find(query.lower())
        if query_index > -1:
            tmp['medicine_id'] = medicine['medicine_id']
            tmp['name'] = medicine['name']
            tmp['index'] = query_index
            out.append(tmp)
        if len(out) > 20:
            break
    out = sorted(out, key=itemgetter('index'))
    if len(out) > 10:
        out = out[0:10]
    return send_api_response(json.dumps(out))
Beispiel #6
0
 def actions(self):
     '''
     Construct a dict of dicts: actions are keys and
     dictionary of attributes/values are values. Cached too.
     '''
     id = "ra_actions-%s" % self.ra_string()
     if cache.is_cached(id):
         return cache.retrieve(id)
     if self.mk_ra_node() is None:
         return None
     d = {}
     for c in self.ra_elem.xpath("//actions/action"):
         name = c.get("name")
         if not name or name in self.skip_ops:
             continue
         if name == "monitor":
             name = monitor_name_node(c)
         d[name] = {}
         for a in c.attrib.keys():
             if a in self.skip_op_attr:
                 continue
             v = c.get(a)
             if v:
                 d[name][a] = v
     # add monitor ops without role, if they don't already
     # exist
     d2 = {}
     for op in d.keys():
         if re.match("monitor_[^0-9]", op):
             norole_op = re.sub(r'monitor_[^0-9_]+_(.*)', r'monitor_\1', op)
             if not norole_op in d:
                 d2[norole_op] = d[op]
     d.update(d2)
     return cache.store(id, d)
Beispiel #7
0
def ra_providers(ra_type, ra_class="ocf"):
    'List of providers for a class:type.'
    id = "ra_providers-%s-%s" % (ra_class, ra_type)
    if cache.is_cached(id):
        return cache.retrieve(id)
    l = ra_if().providers(ra_type, ra_class)
    l.sort()
    return cache.store(id, l)
Beispiel #8
0
def ra_providers(ra_type, ra_class="ocf"):
    'List of providers for a class:type.'
    id = "ra_providers-%s-%s" % (ra_class, ra_type)
    if cache.is_cached(id):
        return cache.retrieve(id)
    l = ra_if().providers(ra_type, ra_class)
    l.sort()
    return cache.store(id, l)
Beispiel #9
0
def ra_classes():
    '''
    List of RA classes.
    '''
    if cache.is_cached("ra_classes"):
        return cache.retrieve("ra_classes")
    l = ra_if().classes()
    l.sort()
    return cache.store("ra_classes", l)
Beispiel #10
0
def ra_classes():
    '''
    List of RA classes.
    '''
    if cache.is_cached("ra_classes"):
        return cache.retrieve("ra_classes")
    l = ra_if().classes()
    l.sort()
    return cache.store("ra_classes", l)
Beispiel #11
0
def main():
    args, cmd, capturer = arg.parse_args()

    log.configure_logging(args.output_directory, args.log_to_stderr)
    log.log_header()

    javac_commands, jars = cache.retrieve(cmd, args, capturer)

    log.info('Results: %s', pprint.pformat(javac_commands))

    tools.run(args, javac_commands, jars)
Beispiel #12
0
def ra_providers_all(ra_class="ocf"):
    '''
    List of providers for a class.
    '''
    id = "ra_providers_all-%s" % ra_class
    if cache.is_cached(id):
        return cache.retrieve(id)
    ocf = os.path.join(os.environ["OCF_ROOT"], "resource.d")
    if os.path.isdir(ocf):
        return cache.store(id, sorted([s for s in os.listdir(ocf)
                                       if os.path.isdir(os.path.join(ocf, s))]))
    return []
Beispiel #13
0
def country_ranking():
    """
    """

    ranking_json = cache.retrieve('country_ranking')
    if ranking_json:
        logger.debug('loading country ranking from cache')
    else:
        ranking = calculate_country_rankings()
        ranking_json = json.dumps(ranking)
        cache.store('country_ranking', ranking_json)
    return send_api_response(ranking_json)
Beispiel #14
0
def overview():
    """
    Give a broad overview of the size of -, and recent activity related to, the database.
    """

    tmp = cache.retrieve('db_overview')
    if tmp:
        logger.debug("DB overview served from cache")
        return send_api_response(tmp)
    else:
        tmp = calculate_db_overview()
        cache.store('db_overview', json.dumps(tmp, cls=serializers.CustomEncoder))
        return send_api_response(json.dumps(tmp))
Beispiel #15
0
def ra_providers_all(ra_class="ocf"):
    '''
    List of providers for a class.
    '''
    id = "ra_providers_all-%s" % ra_class
    if cache.is_cached(id):
        return cache.retrieve(id)
    dir = "%s/resource.d" % os.environ["OCF_ROOT"]
    l = []
    for s in os.listdir(dir):
        if os.path.isdir("%s/%s" % (dir, s)):
            l.append(s)
    l.sort()
    return cache.store(id, l)
Beispiel #16
0
 def meta(self):
     '''
     RA meta-data as raw xml.
     '''
     sid = "ra_meta-%s" % self.ra_string()
     if cache.is_cached(sid):
         return cache.retrieve(sid)
     if self.ra_class in constants.meta_progs:
         l = prog_meta(self.ra_class)
     else:
         l = ra_if().meta(self.ra_class, self.ra_type, self.ra_provider)
     if not l:
         return None
     self.debug("read and cached meta-data")
     return cache.store(sid, l)
Beispiel #17
0
 def meta(self):
     '''
     RA meta-data as raw xml.
     '''
     sid = "ra_meta-%s" % self.ra_string()
     if cache.is_cached(sid):
         return cache.retrieve(sid)
     if self.ra_class in constants.meta_progs:
         l = prog_meta(self.ra_class)
     else:
         l = ra_if().meta(self.ra_class, self.ra_type, self.ra_provider)
     if not l:
         return None
     self.debug("read and cached meta-data")
     return cache.store(sid, l)
Beispiel #18
0
def ra_providers_all(ra_class="ocf"):
    '''
    List of providers for a class.
    '''
    id = "ra_providers_all-%s" % ra_class
    if cache.is_cached(id):
        return cache.retrieve(id)
    ocf = os.path.join(os.environ["OCF_ROOT"], "resource.d")
    if os.path.isdir(ocf):
        return cache.store(
            id,
            sorted([
                s for s in os.listdir(ocf)
                if os.path.isdir(os.path.join(ocf, s))
            ]))
    return []
Beispiel #19
0
def ra_types(ra_class="ocf", ra_provider=""):
    '''
    List of RA type for a class.
    '''
    if not ra_class:
        ra_class = "ocf"
    id = "ra_types-%s-%s" % (ra_class, ra_provider)
    if cache.is_cached(id):
        return cache.retrieve(id)
    list = []
    for ra in ra_if().types(ra_class):
        if (not ra_provider or
                ra_provider in ra_providers(ra, ra_class)) \
                and ra not in list:
            list.append(ra)
    list.sort()
    return cache.store(id, list)
Beispiel #20
0
def ra_types(ra_class="ocf", ra_provider=""):
    '''
    List of RA type for a class.
    '''
    if not ra_class:
        ra_class = "ocf"
    id = "ra_types-%s-%s" % (ra_class, ra_provider)
    if cache.is_cached(id):
        return cache.retrieve(id)
    list = []
    for ra in ra_if().types(ra_class):
        if (not ra_provider or
                ra_provider in ra_providers(ra, ra_class)) \
                and ra not in list:
            list.append(ra)
    list.sort()
    return cache.store(id, list)
Beispiel #21
0
def speak(text):
	"""Synthesize and play a speech

	Args:
		text (str): Text to synthesize
		silent: don't play speech
		lazy: play speech after getting all segments

	Returns:
		byte: A byte stream
	"""

	# Preprocess text
	text = Text.clean(text)

	# Play cached speech if possible
	cached_speech = cache.retrieve(text)
	if cached_speech:
		CACHE_REPORT((text,))
		play(cached_speech[1])
		return

	print("Synthesizing speech")
	segments = Text.paginate(text, conf.page_limit)

	# If speech is short, flush it to disk before play
	# (speed up retries for interrupted speeches)
	if len(segments) == 1:
		text = segments[0][1]
		SHORT_REPORT((text,))
		buffer = speech.synth(text)
		mp3 = cache.store(text, buffer)
		play(mp3)
		return

	buffers = []
	for num, text in segments:
		PROGRESS_REPORT((num, text))
		stream = speech.synth(text)
		buffers.append(stream)
		play(stream)
	buffer = b"".join(buffers)
	cache.store(text, buffer)
Beispiel #22
0
def main():
    args, cmd, capturer = arg.parse_args()

    log.configure_logging(args.output_directory, args.log_to_stderr)
    log.log_header()

    result = cache.retrieve(cmd, args, capturer)

    if not result:
        print "DLJC: Build command failed."
        sys.exit(1)

    javac_commands, jars, stats = result

    log.info('Results: %s', pprint.pformat(javac_commands))
    output_json(os.path.join(args.output_directory, 'javac.json'), javac_commands)
    output_json(os.path.join(args.output_directory, 'jars.json'), jars)
    output_json(os.path.join(args.output_directory, 'stats.json'), stats)

    tools.run(args, javac_commands, jars)
Beispiel #23
0
def read_event_log(description):
    return str(cache.retrieve(clean_description(description)))