def insert(self, obj):

        attributes = ''
        values = ''

        items = obj.__dict__.items()
        class_name = obj.__class__.__name__

        is_first = True  # for first ','
        for i in items:

            if is_first:
                attributes = attributes + i[0]

        # If is None, then insert NULL
                if i[1] is None:
                    i[1] = 'NULL'
                values = values + quote(str(i[1]))
                is_first = False
                continue

            attributes = attributes + ' , ' + i[0]
            val = i[1]
            if i[1] is None:
                i[1] = 'NULL'
            val = quote(str(i[1]))
            values = values + ' , ' + val

        insert_query = f'INSERT INTO {class_name}({attributes}) VALUES({values})'
        err, result = self.exectue_query(insert_query)
        if err:
            return result
        return None
Example #2
0
 def set_cookie(self,
                name,
                value,
                max_age=None,
                expires=None,
                path='/',
                domain=None,
                secure=False,
                http_only=True):
     """
     Set a cookie.
     Args:
       name: the cookie name.
       value: the cookie value.
       max_age: optional, seconds of cookie's max age.
       expires: optional, unix timestamp, datetime or date object that indicate an absolute time of the
                expiration time of cookie. Note that if expires specified, the max_age will be ignored.
       path: the cookie path, default to '/'.
       domain: the cookie domain, default to None.
       secure: if the cookie secure, default to False.
       http_only: if the cookie is for http only, default to True for better safty
                  (client-side script cannot access cookies with HttpOnly flag).
     >>> r = Response()
     >>> r.set_cookie('company', 'Abc, Inc.', max_age=3600)
     >>> r._cookies
     {'company': 'company=Abc%2C%20Inc.; Max-Age=3600; Path=/; HttpOnly'}
     >>> r.set_cookie('company', r'Example="Limited"', expires=1342274794.123, path='/sub/')
     >>> r._cookies
     {'company': 'company=Example%3D%22Limited%22; Expires=Sat, 14-Jul-2012 14:06:34 GMT; Path=/sub/; HttpOnly'}
     >>> dt = datetime.datetime(2012, 7, 14, 22, 6, 34, tzinfo=UTC('+8:00'))
     >>> r.set_cookie('company', 'Expires', expires=dt)
     >>> r._cookies
     {'company': 'company=Expires; Expires=Sat, 14-Jul-2012 14:06:34 GMT; Path=/; HttpOnly'}
     """
     if not hasattr(self, '_cookies'):
         self._cookies = {}
     L = ['%s=%s' % (utils.quote(name), utils.quote(value))]
     if expires is not None:
         if isinstance(expires, (float, int, long)):
             L.append('Expires=%s' % datetime.datetime.fromtimestamp(
                 expires, UTC_0).strftime('%a, %d-%b-%Y %H:%M:%S GMT'))
         if isinstance(expires, (datetime.date, datetime.datetime)):
             L.append('Expires=%s' % expires.astimezone(UTC_0).strftime(
                 '%a, %d-%b-%Y %H:%M:%S GMT'))
     elif isinstance(max_age, (int, long)):
         L.append('Max-Age=%d' % max_age)
     L.append('Path=%s' % path)
     if domain:
         L.append('Domain=%s' % domain)
     if secure:
         L.append('Secure')
     if http_only:
         L.append('HttpOnly')
     self._cookies[name] = '; '.join(L)
Example #3
0
def provider_profile(email):
    email = utils.unquote(email)
    if not check_login():
        return redirect(url_for('login'))
    pvd = provider.Provider(email)
    info = pvd.info()
    ptype = info['provider_type']
    rate = pvd.get_rate()
    centres = pvd.list_centers()

    for item in centres:
        item['qs'] = utils.gen_query_string({
            'center':
            item['health_centre_name'],
            'provider':
            item['provider_email']
        })
        item['health_centre_name_quote'] = utils.quote(
            item['health_centre_name'])
    if session['role'] == 'patient':
        if request.method == 'GET':
            return render_template(
                'provider_profile.html',
                provider_email_quote=utils.quote(item['provider_email']),
                success=False,
                patient_email=session['email'],
                patient_email_quote=utils.quote(session['email']),
                provider_email=email,
                provider_type=ptype,
                provider_rate=rate,
                center_list=centres,
                patient_mode=True)
        else:
            new_rate = request.form["rate"]
            flag = pvd.set_rate(session['email'], new_rate)
            return render_template('provider_profile.html',
                                   provider_email_quote=utils.quote(
                                       item['provider_email']),
                                   success=flag,
                                   provider_email=email,
                                   provider_type=ptype,
                                   provider_rate=new_rate,
                                   center_list=centres,
                                   patient_mode=True)
    elif session['email'] == email:
        return render_template('provider_profile.html',
                               provider_email=email,
                               provider_type=ptype,
                               provider_rate=rate,
                               center_list=centres,
                               patient_mode=False)
    else:
        abort(401)
Example #4
0
	def get_oauth_header(self, method, url, callback_url = None, get = None, post = None):
		if not self._multipart:
			get_data = (get or {}).items()
			post_data = (post or {}).items()
		else:
			get_data = []
			post_data = []
		auth_data = self.get_oauth_header_data(callback_url = callback_url).items()
		data = [(quote(key, safe = "~"), quote(value, safe = "~")) for key, value in get_data + post_data + auth_data]
		data = sorted(sorted(data), key = lambda item: item[0].upper())
		param_string = []
		for key, value in data:
			param_string.append("%s=%s" % (key, value))
		param_string = "&".join(param_string)
		signature_base = []
		signature_base.append(method.upper())
		signature_base.append(quote(url, safe = "~"))
		signature_base.append(quote(param_string, safe = "~"))
		signature_base = "&".join(signature_base)
		if self.request_token:
			token_secret = quote(self.request_token_secret, safe = "~")
		elif self.access_token:
			token_secret = quote(self.access_token_secret, safe = "~")
		else:
			token_secret = ""
		signing_key = "&".join([quote(self.consumer_secret, safe = "~"), token_secret])
		signature = hmac.new(signing_key, signature_base, hashlib.sha1)
		signature = quote(binascii.b2a_base64(signature.digest())[:-1], safe = "~")
		auth_data.append(('oauth_signature', signature))
		return self.generate_oauth_header(dict(auth_data))
Example #5
0
	def get_oauth_header(self, method, url, callback_url = None, get = None, post = None):
		if not self._multipart:
			get_data = (get or {}).items()
			post_data = (post or {}).items()
		else:
			get_data = []
			post_data = []
		auth_data = self.get_oauth_header_data(callback_url = callback_url).items()
		data = [(quote(key, safe = "~"), quote(value, safe = "~")) for key, value in get_data + post_data + auth_data]
		data = sorted(sorted(data), key = lambda item: item[0].upper())
		param_string = []
		for key, value in data:
			param_string.append("%s=%s" % (key, value))
		param_string = "&".join(param_string)
		signature_base = []
		signature_base.append(method.upper())
		signature_base.append(quote(url, safe = "~"))
		signature_base.append(quote(param_string, safe = "~"))
		signature_base = "&".join(signature_base)
		if self.request_token:
			token_secret = quote(self.request_token_secret, safe = "~")
		elif self.access_token:
			token_secret = quote(self.access_token_secret, safe = "~")
		else:
			token_secret = ""
		signing_key = "&".join([quote(self.consumer_secret, safe = "~"), token_secret])
		signature = hmac.new(signing_key, signature_base, hashlib.sha1)
		signature = quote(binascii.b2a_base64(signature.digest())[:-1], safe = "~")
		auth_data.append(('oauth_signature', signature))
		return self.generate_oauth_header(dict(auth_data))
Example #6
0
def consult_patient():
    qs = request.query_string
    query_info = utils.parse_query_string(qs)
    if not check_login():
        return redirect(url_for('login'))
    pvd = provider.Provider(session['email'])

    email = session['email']
    email_q = utils.quote(session['email'])

    if request.method == 'GET':
        return render_template('consultation.html',
                               qs=qs,
                               provider_email=email,
                               provider_email_quote=email_q,
                               patient=query_info,
                               consult_list=pvd.query_consult(
                                   query_info['patient']))
    else:
        note = request.form["note"]
        mp = request.form["medication-prescribed"]
        pvd.consult(query_info['patient'], query_info['center'],
                    query_info['time'], note, mp)
        return render_template('consultation.html',
                               qs=qs,
                               provider_email=email,
                               provider_email_quote=email_q,
                               patient=query_info,
                               consult_list=pvd.query_consult(
                                   query_info['patient']))
Example #7
0
    def comment(self, path):
        """
        Comment part of the configuration (one option or subtree)
        """
        path = quote(path)
        parent_els = self._find_all(os.path.join(path,'..'))
        if not parent_els:
            return

        el_to_comment_path = os.path.basename(path)

        for parent_el in parent_els:
            nodes_to_cmt = parent_el.findall(el_to_comment_path)
            for node_to_cmt in nodes_to_cmt:
                comment_value = StringIO()
                temp_root       = ET.Element('mc_conf')
                temp_tree       = ET.ElementTree(temp_root)
                temp_root.append(node_to_cmt)
                new_conf        = Configuration(format=self._format, etree=temp_tree)
                new_conf._init()
                new_conf.write_fp(comment_value, close = False)
                index = list(parent_el).index(node_to_cmt)
                comment         = ET.Comment(comment_value.getvalue().strip())
                parent_el.insert(index, comment)
                parent_el.remove(node_to_cmt)
Example #8
0
    def metadata(self, **kwargs):
        parameters = self._oauth_parameter()
        if not kwargs.get('list', True):
            parameters['list'] = False
        if kwargs.get('file_limit', 10000) < 10000:
            parameters['list'] = kwargs['file_limit']
        if kwargs.get('page', 0):
            parameters['list'] = kwargs['page']
            if kwargs.get('page_size', 20) != 20:
                parameters['page_size'] = kwargs['page_size']
        if kwargs.has_key('filter_ext'):
            parameters['filter_ext'] = kwargs['filter_ext']
        if kwargs.get('sort_by', '') and (
                kwargs['sort_by'] in ('time', 'rtime', 'name', 'rname', 'size', 'rsize')):
            parameters['sort_by'] = kwargs['sort_by']

        root = kwargs.get('root', 'app_folder')
        path = quote(kwargs.get('path', ''))

        base_url = METADATA_BASE_URL % (root, path)

        s = self._sig_request_url(base_url, parameters)

        rf = urllib.urlopen(s)
        status = rf.getcode()
        if status == 200:
            js = rf.read()
            return js
        else:
            raise OpenAPIHTTPError(status, rf.read())
Example #9
0
File: rsctest.py Project: lge/crmsh
 def runop(self, op, nodes=None, local_only=False):
     '''
     Execute an operation.
     '''
     if not nodes or self.run_on_all(op):
         nodes = self.nodes
     self.last_op = op
     self.set_rscenv(op)
     real_op = (op == "probe" and "monitor" or op)
     cmd = self.exec_cmd(real_op)
     common_debug("running %s on %s" % (real_op, nodes))
     for attr in self.rscenv.keys():
         # shell doesn't allow "-" in var names
         envvar = attr.replace("-", "_")
         cmd = "%s=%s %s" % (envvar, quote(self.rscenv[attr]), cmd)
     if local_only:
         self.ec_l[this_node()] = ext_cmd(cmd)
     else:
         from crm_pssh import do_pssh_cmd
         statuses = do_pssh_cmd(cmd, nodes, self.outdir, self.errdir, self.timeout)
         for i in range(len(nodes)):
             try:
                 self.ec_l[nodes[i]] = statuses[i]
             except:
                 self.ec_l[nodes[i]] = self.undef
     return
Example #10
0
    def comment(self, path):
        """
        Comment part of the configuration (one option or subtree)
        """
        path = quote(path)
        parent_els = self._find_all(os.path.join(path, '..'))
        if not parent_els:
            return

        el_to_comment_path = os.path.basename(path)

        for parent_el in parent_els:
            nodes_to_cmt = parent_el.findall(el_to_comment_path)
            for node_to_cmt in nodes_to_cmt:
                comment_value = StringIO()
                temp_root = ET.Element('mc_conf')
                temp_tree = ET.ElementTree(temp_root)
                temp_root.append(node_to_cmt)
                new_conf = Configuration(format=self._format, etree=temp_tree)
                new_conf._init()
                new_conf.write_fp(comment_value, close=False)
                index = list(parent_el).index(node_to_cmt)
                comment = ET.Comment(comment_value.getvalue().strip())
                parent_el.insert(index, comment)
                parent_el.remove(node_to_cmt)
Example #11
0
    def uncomment(self, path):
        """
        Try to find appropriate configuration piece in comments on path's level,
        And then uncomment it
        """
        path = quote(path)
        parent_path = os.path.dirname(path)
        el_name = os.path.basename(path)
        temp_nodes = self._find_all(parent_path)

        if not temp_nodes:
            raise MetaconfError("Path %s doesn't exist" % unquote(path))
        for temp_node in temp_nodes:
            for child in temp_node:

                if not callable(child.tag):
                    continue
                temp_conf = Configuration(self._format)

                try:
                    temp_conf.readfp(StringIO(child.text.strip()))
                except:
                    continue

                comment_node = temp_conf.etree.find(el_name)

                if comment_node == None:
                    continue

                temp_node.insert(list(temp_node).index(child), comment_node)
                temp_node.remove(child)
                del (temp_conf)
Example #12
0
def mp3_to_wav(path):
    """Converts an MP3 file to a WAVE file.

  Args:
    path: The path to an MP3 file.

  Returns:
    The generated WAVE file.
  """
    tmp_file = utils.get_tmp_file(path)
    os.system(
        "/course/cs4500f13/bin/lame --decode --mp3input --quiet {0} {1}".format(
            utils.quote(path), utils.quote(tmp_file.name)
        )
    )
    return tmp_file
Example #13
0
 def runop(self, op, nodes=None, local_only=False):
     '''
     Execute an operation.
     '''
     if not nodes or self.run_on_all(op):
         nodes = self.nodes
     self.last_op = op
     self.set_rscenv(op)
     real_op = (op == "probe" and "monitor" or op)
     cmd = self.exec_cmd(real_op)
     common_debug("running %s on %s" % (real_op, nodes))
     for attr in self.rscenv.keys():
         # shell doesn't allow "-" in var names
         envvar = attr.replace("-", "_")
         cmd = "%s=%s %s" % (envvar, quote(self.rscenv[attr]), cmd)
     if local_only:
         self.ec_l[this_node()] = ext_cmd(cmd)
     else:
         from crm_pssh import do_pssh_cmd
         statuses = do_pssh_cmd(cmd, nodes, self.outdir, self.errdir,
                                self.timeout)
         for i in range(len(nodes)):
             try:
                 self.ec_l[nodes[i]] = statuses[i]
             except:
                 self.ec_l[nodes[i]] = self.undef
     return
Example #14
0
    def __init__(self,
                 format=default_format,
                 root_path="",
                 etree=None,
                 filename=None):

        if etree and not isinstance(etree, ET.ElementTree):
            raise MetaconfError(
                "etree param must be instance of ElementTree. %s passed" %
                (etree, ))

        try:
            pvd_name = '%sFormatProvider' % format.capitalize()
            pvd_module = __import__('providers.%s_pvd' % format, globals(),
                                    locals(), [pvd_name], -1)
            self._provider = getattr(pvd_module, pvd_name)()
        except:
            raise MetaconfError('Unknown or broken format provider: %s' %
                                format)
        #if not format_providers.has_key(format):
        #       raise MetaconfError("Unknown format: %s" % format)

        self._root_path = quote(root_path)
        self._format = format
        self.etree = etree
        self._config_count = 0
        if filename:
            self._read0(filename)
Example #15
0
    def uncomment(self, path):
        """
        Try to find appropriate configuration piece in comments on path's level,
        And then uncomment it
        """
        path = quote(path)
        parent_path = os.path.dirname(path)
        el_name = os.path.basename(path)
        temp_nodes = self._find_all(parent_path)

        if not temp_nodes:
            raise MetaconfError("Path %s doesn't exist" % unquote(path))
        for temp_node in temp_nodes:
            for child in temp_node:

                if not callable(child.tag):
                    continue
                temp_conf = Configuration(self._format)

                try:
                    temp_conf.readfp(StringIO(child.text.strip()))
                except:
                    continue

                comment_node = temp_conf.etree.find(el_name)

                if comment_node == None:
                    continue

                temp_node.insert(list(temp_node).index(child), comment_node)
                temp_node.remove(child)
                del(temp_conf)
Example #16
0
    def delete_database(self, dbname, allow_missing=True):
        """Create a database with the given name.

        """
        return self.do_request(
            'dbs/' + utils.quote(dbname),
            'DELETE',
            queryargs={'allow_missing': int(bool(allow_missing))})
Example #17
0
    def set_cookie(self, name, value, max_age=None, expires=None, path='/', domain=None, secure=False, http_only=True):
        '''
        Set a cookie.

        Args:
          name: the cookie name.
          value: the cookie value.
          max_age: optional, seconds of cookie's max age.
          expires: optional, unix timestamp, datetime or date object that indicate an absolute time of the 
                   expiration time of cookie. Note that if expires specified, the max_age will be ignored.
          path: the cookie path, default to '/'.
          domain: the cookie domain, default to None.
          secure: if the cookie secure, default to False.
          http_only: if the cookie is for http only, default to True for better safty 
                     (client-side script cannot access cookies with HttpOnly flag).

        >>> r = Response()
        >>> r.set_cookie('company', 'Abc, Inc.', max_age=3600)
        >>> r._cookies
        {'company': 'company=Abc%2C%20Inc.; Max-Age=3600; Path=/; HttpOnly'}
        >>> r.set_cookie('company', r'Example="Limited"', expires=1342274794.123, path='/sub/')
        >>> r._cookies
        {'company': 'company=Example%3D%22Limited%22; Expires=Sat, 14-Jul-2012 14:06:34 GMT; Path=/sub/; HttpOnly'}
        >>> dt = datetime.datetime(2012, 7, 14, 22, 6, 34, tzinfo=UTC('+8:00'))
        >>> r.set_cookie('company', 'Expires', expires=dt)
        >>> r._cookies
        {'company': 'company=Expires; Expires=Sat, 14-Jul-2012 14:06:34 GMT; Path=/; HttpOnly'}
        '''
        if not hasattr(self, '_cookies'):
            self._cookies = {}
        L = ['%s=%s' % (quote(name), quote(value))]
        if expires is not None:
            if isinstance(expires, (float, int, long)):
                L.append('Expires=%s' % datetime.datetime.fromtimestamp(expires, UTC_0).strftime('%a, %d-%b-%Y %H:%M:%S GMT'))
            if isinstance(expires, (datetime.date, datetime.datetime)):
                L.append('Expires=%s' % expires.astimezone(UTC_0).strftime('%a, %d-%b-%Y %H:%M:%S GMT'))
        elif isinstance(max_age, (int, long)):
            L.append('Max-Age=%d' % max_age)
        L.append('Path=%s' % path)
        if domain:
            L.append('Domain=%s' % domain)
        if secure:
            L.append('Secure')
        if http_only:
            L.append('HttpOnly')
        self._cookies[name] = '; '.join(L)
Example #18
0
 def _find(self, path):
     if not self.etree:
         self._init()
     el = self.etree.find(self._root_path + path)
     # el = ElementPath13.find(self.etree, self._root_path + quote(path))
     if el != None:
         return el
     else:
         raise NoPathError(quote(path))
Example #19
0
 def signWrap (data, secret):
     "Signs json-stringifiable `data` using `secret`. Produces wrapped string.";
     msTs = ms_now();
     sig = signDetached(data, msTs, secret);
     signWrappedData = {"data": data, "msTs": msTs, "sig": sig};
     signWrappedDataStr = json.dumps(signWrappedData);
     signWrappedDataStrQ = utils.quote(signWrappedDataStr);
     #print("signWrappedDataStr = ", signWrappedDataStr);
     return signWrappedDataStrQ;# <--.
Example #20
0
    def add_document(self, doc, docid=None):
        """Add a document - if the docid is specified, replaces any existing
        one with that id (but doesn't complain if the document doesn't exist).

        """
        uri = self._basepath + '/docs'
        if docid is not None:
            uri += '/' + utils.quote(str(docid))
        return self._client.do_request(uri, 'POST', json=doc)
Example #21
0
 def _find(self, path):
     if not self.etree:
         self._init()
     el = self.etree.find(self._root_path + path)
     # el = ElementPath13.find(self.etree, self._root_path + quote(path))
     if el != None:
         return el
     else:
         raise NoPathError(quote(path))
Example #22
0
def patient_profile(email):
    email = utils.unquote(email)
    if not check_login():
        return redirect(url_for('login'))
    pt = patient.Patient(email)
    book_history = pt.query_book()
    for item in book_history:
        item['provider_email_quote'] = utils.quote(item['provider_email'])
        item['center_name_quote'] = utils.quote(item['center_name'])
    if session['role'] == 'patient':
        return render_template('patient_profile.html',
                               patient_email=email,
                               book_history=book_history,
                               patient_mode=True)
    else:
        return render_template('patient_profile.html',
                               patient_email=email,
                               book_history=book_history,
                               patient_mode=False)
Example #23
0
 def set_cookie(self,
                name,
                value,
                max_age=None,
                expires=None,
                path='/',
                domain=None,
                secure=False,
                http_only=True):
     """
     Set a cookie.
     Args:
       name: the cookie name.
       value: the cookie value.
       max_age: optional, seconds of cookie's max age.
       expires: optional, unix timestamp, datetime or date object that indicate an absolute time of the
                expiration time of cookie. Note that if expires specified, the max_age will be ignored.
       path: the cookie path, default to '/'.
       domain: the cookie domain, default to None.
       secure: if the cookie secure, default to False.
       http_only: if the cookie is for http only, default to True for better safty
                  (client-side script cannot access cookies with HttpOnly flag).
     """
     if not hasattr(self, '_cookies'):
         self._cookies = {}
     L = ['%s=%s' % (quote(name), quote(value))]
     if expires is not None:
         if isinstance(expires, (float, int, long)):
             L.append('Expires=%s' % datetime.datetime.fromtimestamp(
                 expires, UTC_0).strftime('%a, %d-%b-%Y %H:%M:%S GMT'))
         if isinstance(expires, (datetime.date, datetime.datetime)):
             L.append('Expires=%s' % expires.astimezone(UTC_0).strftime(
                 '%a, %d-%b-%Y %H:%M:%S GMT'))
     elif isinstance(max_age, (int, long)):
         L.append('Max-Age=%d' % max_age)
     L.append('Path=%s' % path)
     if domain:
         L.append('Domain=%s' % domain)
     if secure:
         L.append('Secure')
     if http_only:
         L.append('HttpOnly')
     self._cookies[name] = '; '.join(L)
Example #24
0
def index():
    if not check_login():
        return redirect(url_for('login'))
    if session['role'] != 'patient':
        return redirect('/provider_profile/' + utils.quote(session['email']))
    pt = patient.Patient(session['email'])
    center_v = ""
    provider_v = ""
    service_v = ""

    if request.method == "GET":
        results = pt.search(center=center_v,
                            provider=provider_v,
                            service=service_v)
        for res in results:
            pvd = provider.Provider(res['provider_email'])
            ct = center.Center(res['health_centre_name'])
            res['center_rate'] = ct.get_rate()
            res['provider_rate'] = pvd.get_rate()
            res['health_centre_name_quote'] = utils.quote(
                res['health_centre_name'])
            res['provider_email_quote'] = utils.quote(res['provider_email'])
        return render_template('index.html',
                               patient_email=session['email'],
                               result_list=results)

    center_v = request.form["center"]
    provider_v = request.form["provider"]
    service_v = request.form["service"]
    results = pt.search(center=center_v,
                        provider=provider_v,
                        service=service_v)
    for res in results:
        pvd = provider.Provider(res['provider_email'])
        ct = center.Center(res['health_centre_name'])
        res['center_rate'] = ct.get_rate()
        res['provider_rate'] = pvd.get_rate()
        res['health_centre_name_quote'] = utils.quote(
            res['health_centre_name'])
        res['provider_email_quote'] = utils.quote(res['provider_email'])
    return render_template('index.html',
                           patient_email=session['email'],
                           result_list=results)
Example #25
0
def book():
    tp = [
        str(i).zfill(2) + ":" + str(j).zfill(2) for i in range(24)
        for j in [0, 30]
    ]
    if not check_login():
        return redirect(url_for('login'))
    if request.method == 'GET':
        qs = request.query_string
        query_info = utils.parse_query_string(qs)
        query_info['patient'] = session['email']
        return render_template('make_appointment.html',
                               qs=qs,
                               service_time=query_info['time'],
                               patient_email_quote=utils.quote(
                                   query_info['patient']),
                               patient_email=query_info['patient'],
                               center_name=query_info['center'],
                               provider_email=query_info['provider'],
                               success=False,
                               tp=tp)
    else:
        begin = request.form["begin-time"]
        end = request.form["end-time"]
        comment = request.form["comment"]
        provider = request.form["provider"]
        center = request.form["center"]
        pt = patient.Patient(session['email'])
        flag = pt.book(provider, center, begin, end, comment)
        qs = request.query_string
        query_info = utils.parse_query_string(qs)
        query_info['patient'] = session['email']
        return render_template('make_appointment.html',
                               qs=qs,
                               service_time=query_info['time'],
                               patient_email_quote=utils.quote(
                                   query_info['patient']),
                               patient_email=query_info['patient'],
                               center_name=query_info['center'],
                               provider_email=query_info['provider'],
                               success=flag,
                               tp=tp)
Example #26
0
    async def clan_place(self, ctx, *, guild_name: UserInputSanitizer):
        guild_id = await self.find_clan_id_by_name(ctx, guild_name)
        if not guild_id:
            return

        clan = await GemstoneStatsApi.get_api_response('clans/' + quote(guild_id) + '/place')
        place = clan.get('rankingPlace', '')
        name = clan.get('name', '')
        message = f"**{name}** - Ranking Place: #{place} :trophy:"

        await send_message_to_channel(ctx, message)
Example #27
0
 def set_cookie(self, name, value, max_age=None, expires=None, path='/', domain=None, secure=False, http_only=True):
     if not hasattr(self, '_cookies'):
         self._cookies = {}
     L = ['%s=%s' % (utils.quote(name), utils.quote(value))]
     if expires is not None:
         if isinstance(expires, (float, int, long)):
             L.append('Expires=%s' % datetime.datetime.fromtimestamp(expires, UTC_0).strftime(
                 '%a, %d-%b-%Y %H:%M:%S GMT'))
         if isinstance(expires, (datetime.date, datetime.datetime)):
             L.append('Expires=%s' % expires.astimezone(UTC_0).strftime('%a, %d-%b-%Y %H:%M:%S GMT'))
     elif isinstance(max_age, (int, long)):
         L.append('Max-Age=%d' % max_age)
     L.append('Path=%s' % path)
     if domain:
         L.append('Domain=%s' % domain)
     if secure:
         L.append('Secure')
     if http_only:
         L.append('HttpOnly')
     self._cookies[name] = '; '.join(L)
Example #28
0
    def next( self ) :
        if self._footer_sent :
            self._conn.close()
            os.unlink( self._dbfile )
            self._lock.release()
            raise StopIteration

        if self._header_sent :
            row = self._curs.fetchone()
            self._row += 1
            if row == None :
                self._curs.close()
                self._footer_sent = True
                return "stop_"

            txt = "   "
            i = -1
            if self._verbose : print >> sys.stderr, row
            for col in row :
                i += 1
                if self._verbose : print >> sys.stderr, "** %d : %s %s" % (i,str( col ),self._curs.description[i][0])
                if self._curs.description[i][0] == "Sf_ID" : continue
                val = utils.quote( col )
                if val == "?" : val = "."
                if val[0] == ";" :
                    txt += "\n";
                    txt += val;
                    txt += "\n";
                else :
                    txt += ("%" + str( self._widths[i] ) + "s") % (val)
            txt += "\n"
            return txt

# else send header & run query
        if not os.path.exists( self._dbfile ) : raise UnboundLocalError( "File not found: %s" % (self._dbfile) )
        self._lock.acquire()
        self._conn = sqlite3.connect( self._dbfile )
        self._curs = self._conn.cursor()
        curs = self._conn.cursor()
        self._curs.execute( 'select * from "%s"' % (self._table) ) # not a parameter
        txt = "loop_\n"
        for col in self._curs.description : 
            if col[0] == "Sf_ID" :
                self._widths.append( 2 ) # only doing this to keep the field count right
            else :
                txt += "    _%s.%s\n" % (self._table,col[0])
                sql = 'select max(coalesce(length("%s"),1)) from %s' % (col[0],self._table)
                curs.execute( sql )
                row = curs.fetchone()
                self._widths.append( 2 if (row[0] == 1) else (row[0] + 3) )

        txt += "\n"
        self._header_sent = True
        return txt
Example #29
0
def wav_to_mp3(path):
    """Converts a WAVE file to an MP3 file.

  Args:
    pat: The path to a WAVE file.

  Returns:
    The generated MP3 file.
  """
    tmp_file = utils.get_tmp_file(path)
    os.system("/course/cs4500f13/bin/lame -h --quiet {0} {1}".format(utils.quote(path), utils.quote(tmp_file.name)))
    return tmp_file
Example #30
0
    async def hero_stats(self, ctx, *, hero_name: UserInputSanitizer):
        if not hero_name:
            await send_message_to_channel(ctx, 'Hero not found')
            return False

        creature_stats = await GemstoneStatsApi.get_api_response('stats/creature/' + quote(hero_name))

        if not creature_stats:
            await send_message_to_channel(ctx, 'Hero stats not available')
            return False

        embed = self._get_creature_embed(creature_stats, ctx)
        await send_message_to_channel(ctx, '', embed=embed)
Example #31
0
def center_profile(name):
    name = utils.unquote(name)
    pmode = True if session['role'] == 'patient' else False
    if not check_login():
        return redirect(url_for('login'))
    ct = center.Center(name)
    info = ct.info()
    pvd_list = ct.list_providers()
    for pvd in pvd_list:
        pvd['provider_email_quote'] = utils.quote(pvd['provider_email'])
        pvd['qs'] = utils.gen_query_string({
            'center': name,
            'provider': pvd['provider_email'],
            'time': pvd['provider_time']
        })
    if request.method == 'GET':
        return render_template('center_profile.html',
                               patient_mode=pmode,
                               success=False,
                               center_name_quote=utils.quote(info['name']),
                               center=info,
                               center_rate=ct.get_rate(),
                               email_quote=utils.quote(session['email']),
                               email=session['email'],
                               provider_list=pvd_list)
    else:
        rate = request.form["rate"]
        patient = session["email"]
        ct.set_rate(patient, rate)
        return render_template('center_profile.html',
                               patient_mode=pmode,
                               success=True,
                               center_name_quote=utils.quote(info['name']),
                               center=info,
                               center_rate=ct.get_rate(),
                               email_quote=utils.quote(session['email']),
                               email=session['email'],
                               provider_list=pvd_list)
Example #32
0
 def get(self):
     gets = self.request.GET
     symbol = gets.get('symbol', 'SPX')
     time, status = myutils.status()
     gae = datetime.datetime.now(GMT5()).replace(tzinfo=None)
     data = myutils.quote(symbol)
     template = jinja_environment.get_template('quote.html')
     template_values = {
         'head' : cst.head,
         'data' : data,
         'status' : time,
         'server' : gae,
         'responseDict': cst.responseDict,
     }
     self.response.out.write(template.render(template_values))
Example #33
0
def history():
    if not check_login():
        return redirect(url_for('login'))
    pvd = provider.Provider(session['email'])
    info = pvd.info()
    email = session['email']
    email_q = utils.quote(session['email'])

    history_list = pvd.book_history()
    for item in history_list:
        item['center_name_quote'] = utils.quote(item['center_name'])
        item['patient_email_quote'] = utils.quote(item['patient_email'])
        item['qs'] = utils.gen_query_string({
            'provider': session['email'],
            'center': item['center_name'],
            'patient': item['patient_email'],
            'time': item['service_time'],
            'comment': item['comment']
        })
    return render_template('history.html',
                           provider_email=email,
                           provider_email_quote=email_q,
                           provider_type=info['provider_type'],
                           history_list=history_list)
Example #34
0
    async def clan_members_ranking(self, ctx, *, guild_name: UserInputSanitizer):
        guild_id = await self.find_clan_id_by_name(ctx, guild_name)
        if not guild_id:
            return

        members = await GemstoneStatsApi.get_api_response('clans/' + quote(guild_id) + '/members')
        members.sort(key=lambda x: x.get('TeamPower', 0), reverse=True)
        message = []

        for place, member in enumerate(members, 1):
            name = member.get('username', '')
            team_power = member.get('TeamPower', 0)
            user_id = member.get('userId', 0)
            message.append(f"{place}. **{name}** `POWER:{team_power:,}` `ID:{user_id}`")

        await send_message_to_channel(ctx, '\n'.join(message))
Example #35
0
    async def player_stats(self, ctx, *, user_id: UserInputSanitizer):
        player = await GemstoneStatsApi.get_api_response('players/' +  quote(str(user_id)))

        if not player:
            await send_message_to_channel(ctx, 'Player not found')
            return

        stats = ["team_power", "clan_id"]
        message = ['**' + player.get('nick', '') + '**']

        for stat in stats:
            param = stat.replace('_', ' ').title()
            value = str(player.get(stat, ''))
            message.append(f"`{param}`: {value}")

        await send_message_to_channel(ctx, '\n'.join(message))
Example #36
0
def run_degrel(*args):
    if not args:
        args = utils.args()
    os.chdir(utils.APP_DIR)
    try:
        project_classes = glob.glob(
            app_path('target', 'scala-*', 'classes'))[-1]
    except:
        print('Project classes not found in targets/scala-*/classes',
              file=sys.stderr)
        sys.exit(-1)
    classpath = project_classes + PATH_ITEM_SEP + dependency_classpath()
    return run('java',
        '-cp',
        quote(classpath),
        MAIN_CLASS,
        *args)
Example #37
0
    def shares(self, path, root='app_folder'):
        parameters = self._oauth_parameter()

        if root not in ('app_folder', 'kuaipan'):
            root = 'app_folder'
        path = quote(path)

        base_url = SHARE_BASE_URL % (root, path)

        s = self._sig_request_url(base_url, parameters)

        rf = urllib.urlopen(s)
        status = rf.getcode()
        if status == 200:
            d = json.loads(rf.read())
            return to_string(d[u'url'])
        else:
            raise OpenAPIHTTPError(status, rf.read())
Example #38
0
    async def clan_stats(self, ctx, *, guild_name: UserInputSanitizer):
        guild_id = await self.find_clan_id_by_name(ctx, guild_name)
        if not guild_id:
            return

        clan = await GemstoneStatsApi.get_api_response('clans/' + quote(guild_id) + '/stats')

        if not isinstance(clan, dict):
            await send_message_to_channel(ctx, 'Guild stats not available')
            return

        stats = ["description", "members", "team_power", "created"]
        message = ['**' + clan.get('name', '') + '**']

        for stat in stats:
            param = stat.replace('_', ' ').title()
            value = str(clan.get(stat, ''))
            message.append(f"`{param}`: {value}")

        await send_message_to_channel(ctx, '\n'.join(message))
Example #39
0
    def __init__(self, format=default_format, root_path="", etree=None, filename=None):

        if etree and not isinstance(etree, ET.ElementTree):
            raise MetaconfError("etree param must be instance of ElementTree. %s passed" % (etree,))

        try:
            pvd_name = '%sFormatProvider' % format.capitalize()
            pvd_module = __import__('providers.%s_pvd' % format, globals(), locals(), [pvd_name], -1)
            self._provider = getattr(pvd_module, pvd_name)()
        except:
            raise MetaconfError('Unknown or broken format provider: %s' % format)
        #if not format_providers.has_key(format):
        #       raise MetaconfError("Unknown format: %s" % format)

        self._root_path = quote(root_path)
        self._format = format
        self.etree = etree
        self._config_count = 0
        if filename:
            self._read0(filename)
Example #40
0
    def outE(self,*args,**kwds):
        """
        Return the outgoing edges of the vertex.

        :arg classes: Zero or more classes to used for initializing the 
                        objects returned in the query results.

        :keyword label: Optional. The edge label. Defaults to None.
                        
        :keyword return_keys: Optional. A comman-separated list of
                              keys (DB properties) to return. If set to None, it
                              returns all properties. Defaults to None.

        :param raw: Optional keyword param. If set to True, it won't try to 
                    initialize data. Defaults to False. 

        """
        label, classes = self._parse_args(*args)
        script = "v.outE(%s)" % utils.quote(label)
        return self.gremlin(script,*classes,**kwds)
Example #41
0
    def create_database(self,
                        dbname,
                        overwrite=None,
                        reopen=None,
                        backend=None):
        """Create a database with the given name.

        """
        queryargs = {}
        if overwrite is not None:
            queryargs['overwrite'] = int(bool(overwrite))
        if reopen is not None:
            queryargs['reopen'] = int(bool(reopen))
        if backend is not None:
            queryargs['backend'] = backend
        if len(queryargs) == 0:
            queryargs = None
        return self.do_request('dbs/' + utils.quote(dbname),
                               'POST',
                               queryargs=queryargs)
Example #42
0
    def outE(self, *args, **kwds):
        """
        Return the outgoing edges of the vertex.

        :arg classes: Zero or more classes to used for initializing the 
                        objects returned in the query results.

        :keyword label: Optional. The edge label. Defaults to None.
                        
        :keyword return_keys: Optional. A comman-separated list of
                              keys (DB properties) to return. If set to None, it
                              returns all properties. Defaults to None.

        :param raw: Optional keyword param. If set to True, it won't try to 
                    initialize data. Defaults to False. 

        """
        label, classes = self._parse_args(*args)
        script = "v.outE(%s)" % utils.quote(label)
        return self.gremlin(script, *classes, **kwds)
Example #43
0
def entry():
    print(quote("Old School Helper", "==="))
    print("Available commands:")

    tasks = task_manager.task_manager()

    commands = [
        command("taska", "add new task", tasks.add_new_task),
        command("select", "select task", tasks.select_task),
        command("deselect", "deselect task", tasks.deselect_task),
        command("delete", "delete selected task", tasks.delete_task),
        command("geara", "add gear to task", tasks.add_gear_to_task),
        command("geardel", "remove gear from task",
                tasks.remove_gear_from_task),
        command("geardis", "display task gear", tasks.display_task_gear),
        command("rename", "rename selected task monster",
                tasks.rename_task_monster),
        command("save", "save data to disk", tasks.save),
        command("load", "load data from disk", tasks.load),
        command("DEBUG a", "", tasks.DEBUG_steel_dragon),
        command("help", "display available commands", None)
    ]

    for c in commands:
        if not c.name.startswith("DEBUG"):
            print(str(c))

    while True:
        print("Enter command:")
        command_input = input()
        selected_command = get_command_with_name(commands, command_input)
        if selected_command is None:
            print("That is not a valid command. Please try again.")
            continue
        if selected_command.name == "help":
            for c in commands:
                if not c.name.startswith("DEBUG"):
                    print(str(c))
            continue

        selected_command.func()
Example #44
0
    def inV(self,*args,**kwds):
        """
        Return the in-adjacent vertices of the vertex.

        :param classes: Zero or more classes to used for initializing the 
                        objects returned in the query results.

        :param kwds: name/value pairs of optional arguments:

        :param label: Optional keyword param. The edge label.
                        
        :param return_keys: Optional keyword param. A comman-separated list of
                            keys (DB properties) to return. If set to None, it
                            returns all properties. Defaults to None.

        :param raw: Optional keyword param. If set to True, it won't try to 
                     initialize data. Defaults to False. 
        """
        label, classes = self._parse_args(*args)
        script = "v.in(%s)" % utils.quote(label)
        return self.gremlin(script,*classes,**kwds)
Example #45
0
    def inV(self, *args, **kwds):
        """
        Return the in-adjacent vertices of the vertex.

        :param classes: Zero or more classes to used for initializing the 
                        objects returned in the query results.

        :param kwds: name/value pairs of optional arguments:

        :param label: Optional keyword param. The edge label.
                        
        :param return_keys: Optional keyword param. A comman-separated list of
                            keys (DB properties) to return. If set to None, it
                            returns all properties. Defaults to None.

        :param raw: Optional keyword param. If set to True, it won't try to 
                     initialize data. Defaults to False. 
        """
        label, classes = self._parse_args(*args)
        script = "v.in(%s)" % utils.quote(label)
        return self.gremlin(script, *classes, **kwds)
Example #46
0
 def test_quote_empty(self):
   """Tests that quoting the empty string returns a pair of quotes."""
   self.assertEqual(utils.quote(''), '\'\'')
Example #47
0
 def test_quote_with_space(self):
   """Tests quoting on strings containing spaces."""
   self.assertEqual(utils.quote('quote me'), '\'quote me\'')
   self.assertEqual(utils.quote('123 45$'), '\'123 45$\'')
Example #48
0
 def send(self, data):
   if self.readyState == SockPy.CONNECTING:
     raise Exception("INVALID_ACCESS_ERR")
   if self.readyState == SockPy.OPEN:
     self._transport.doSend(utils.quote('' + data))
   return True
Example #49
0
def encode_uri(v):
    return quote(dumps(v))
Example #50
0
 def test_quote_no_space(self):
   """Tests quoting on strings without spaces."""
   self.assertEqual(utils.quote('quote'), '\'quote\'')
   self.assertEqual(utils.quote('12345$'), '\'12345$\'')