Пример #1
0
 def get_path(self):
     try:
         
         if self.get_type() == "cue":
             return utils.get_path_from_uri(self.get("real_uri"))
         elif self.get_type() == "local":
             return utils.get_path_from_uri(self.get("uri"))
         elif self.get_type() == "cdda":
             uri = self.get("uri")
             return utils.unquote(uri[uri.find("#") + 1:])
         else:
             return utils.unquote(self.get("uri"))
     except:
         return ""
Пример #2
0
    def get_path(self):
        try:

            if self.get_type() == "cue":
                return utils.get_path_from_uri(self.get("real_uri"))
            elif self.get_type() == "local":
                return utils.get_path_from_uri(self.get("uri"))
            elif self.get_type() == "cdda":
                uri = self.get("uri")
                return utils.unquote(uri[uri.find("#") + 1:])
            else:
                return utils.unquote(self.get("uri"))
        except:
            return ""
Пример #3
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)
Пример #4
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)
Пример #5
0
def politeRole(semR, env, opts):
    traceSyntR("politeRole", semR)
    instance = unquote(semR.get_instance())
    if instance == "+":
        env.unshift(Q("Please"))
    elif instance == "-":
        env.unshift(Q("F..."))
    else:
        errorSyntR(":polite strange value:%s" % instance)
Пример #6
0
def wikiRole(semR, env, opts):
    traceSyntR("wikiRole", semR)
    name = semR.get_instance()
    if name == "-": return None
    ## uncomment the following line for adding links to Wikipedia
    #  it is now commented to ease comparisons...
    opts.add("tag", ("a", {
        "href": "https://en.wikipedia.org/wiki/" + unquote(name)
    }))
Пример #7
0
def havePolarity91(concept,roles,env,opts):
    if ":ARG2" in roles:
        pol=unquote(roles[":ARG2"].get_instance())
        if  pol=='-':
            env.push(AdvP(Adv("not")))
        elif pol =='+':
            env.push(AdvP(Adv("yes")))
        return addRoles(concept, roles, [":ARG2"], LexSem("polarity","SP",[],lambda:SP()), env, opts)
    return None
Пример #8
0
def instance2SyntR(semR):
    traceSyntR("instance2dsr", semR)
    instance = semR.instance
    if isinstance(instance, SemanticRep):
        myRole = semR.get_my_role()
        amrRef = instance
        refRole = amrRef.get_my_role()
        refConcept = amrRef.get_concept()
        #         print("myRole:%s  refRole:%s refConcept:%s"%(myRole,refRole,refConcept))
        if isNoun(refConcept) or specialConcept.isSpecialConcept(refConcept):
            if myRole == ":ARG0" and refRole != None:
                pronoun = Pro("I")
            elif myRole == ":ARG1":  # is object the same as the subject?
                parent = semR.get_parent()
                parentRoles = parent.get_roles()
                if ":ARG0" in parentRoles and (
                        parentRoles[":ARG0"] == amrRef
                        or instance == parentRoles[":ARG0"].instance):
                    pronoun = Pro("myself")
                else:
                    pronoun = Pro("I")
            else:
                pronoun = Pro("me")
            return pronoun.pe(3).g(gender[refConcept] if refConcept in
                                   gender else "n")
        elif isPronoun(refConcept):
            pronoun = Pro("I")
            return addOptions(pronoun, pronounOptions[refConcept]
                              ) if refConcept in pronounOptions else pronoun
        elif isVerb(refConcept):
            return VP(V(re.sub(r"-\d+$", "", refConcept)).t("b"))
        else:
            # clean the referenced concept and quote it
            return Q(generateConceptWord(refConcept))
    elif is_number(instance):
        return NO(unquote(instance))
    elif instance[0] == '"':
        return Q(unquote(instance))
    elif instance in ['-', '+']:
        return instance
    else:
        errorSyntR(instance + " :undefined instance")
        return Q(instance)
Пример #9
0
	def _get_cookies(self):
		if not hasattr(self,'_cookies'):
			cookies = {}
			cookie_str = self._environ.get('HTTP_COOKIE')
			if cookie_str:
				for c in cookie_str.split(';'):
					pos = c.find('=')
					if pos > 0:
						cookies[c[:pos].strip()] = utils.unquote(c[pos+1:])
			self._cookies = cookies
		return self._cookies
Пример #10
0
def liRole(semR, env, opts):
    traceSyntR("liRole", semR)
    semR_i = unquote(semR.get_instance())
    if semR_i == "-1":
        env.unshift(Adv("lastly"))
    elif semR_i == "1":
        env.unshift(Adv("first"))
    elif is_number(semR_i):
        env.unshift(Q("(" + str(semR_i) + ")"))
    elif semR_i[0] == '"':
        env.unshift(Q("(" + semR_i + ")"))
Пример #11
0
 def _get_cookies(self):
     if not hasattr(self, '_cookies'):
         cookies = {}
         cookie_str = self._environ.get('HTTP_COOKIE')
         if cookie_str:
             for c in cookie_str.split(';'):
                 pos = c.find('=')
                 if pos>0:
                     cookies[c[:pos].strip()] = unquote(c[pos+1:])
         self._cookies = cookies
     return self._cookies
Пример #12
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)
Пример #13
0
def polarityRole(semR, env, opts):
    traceSyntR("polarityRole", semR)
    if unquote(semR.get_instance()) == "-":
        parent_concept = semR.get_parent_concept()
        if isVerb(parent_concept):
            opts.add("typ", {"neg": True})
        elif isNoun(parent_concept):
            env.put(":D", Adv("no"))
        else:
            env.unshift(Adv("not"))
    elif semR.get_concept() == "amr-unknown":
        opts.add("typ", {"int": "yon"})
Пример #14
0
def streetAddress91(concept,roles,env,opts):
    traceSyntR("streetAddress91", concept)
    res=SP()
    for i in range(1,7):
        argi=":ARG"+str(i)
        if argi in roles:
            argi_role=roles[argi]
            if argi_role.get_concept()==None:
                res.add(Q(unquote(argi_role.get_instance())))
            else:
                res.add(makeSyntR(argi_role))
    return res
Пример #15
0
    def LIST_response(self, code, args):
        resp = scan_sexp(args)

        try:
            attributes = resp[0]
            hierarchy_delimiter = resp[1]
            name = resp[2]
        except:
            raise self.Error("Don't know how to parse the LIST response: %s" % args)

        # If the hierarchy_delimiter is NIL no hierarchy exists
        if hierarchy_delimiter != "NIL":
            hierarchy_delimiter = unquote(hierarchy_delimiter)
        else:
            hierarchy_delimiter = None

        self.sstatus["list_response"].append(parselist.Mailbox(name, attributes, hierarchy_delimiter))
Пример #16
0
    def _un_htmlify(self, text):
        def _handle_bad_html(s):
            pttn = re.compile('<|>')
            return pttn.sub(' ', s)

        soup = BeautifulSoup(text.strip())

        # get all of the text and any a/@href values
        texts = [_handle_bad_html(t.strip('"')) for t in soup.find_all(text=True)]
        if self.include_html_hrefs:
            texts += [unquote(a['href']) for a in soup.find_all('a') if 'href' in a.attrs]

        try:
            text = ' '.join(texts)
        except:
            raise
        return text
Пример #17
0
 def _signUnwrap (signWrappedDataStrQ, secret, maxExpiryInDays=30):   # Note: maxExpiryInDays=30 can be changed w/ each call.
     "Unwraps and reads signWrappedDataStr, using secret.";
     signWrappedDataStr = utils.unquote(signWrappedDataStrQ);
     signWrappedData = json.loads(signWrappedDataStr);               # Failure would raise json.decoder.JSONDecodeError
     # Unwrapping:
     data = signWrappedData["data"];                                 # Failure would raise KeyError
     msTs = signWrappedData["msTs"];
     sig = signWrappedData["sig"];
     # Validate signature:
     assert checkDetachedSign(sig, data, msTs, secret);              # Failure would raise AssertionError
     # ==> SIGNATURE FORMAT OK.
     msSinceSigned = ms_now() - msTs;
     #print("msSinceSigned = ", msSinceSigned);
     daysSinceSigned = ms_delta_toDays(msSinceSigned);
     #print("daysSinceSigned = ", daysSinceSigned);
     assert daysSinceSigned <= maxExpiryInDays;                       # Failure would raise AssertionError
     # ==> SIGNATURE EXPIRY OK.
     return dotsi.fy(data) if type(data) is dict else data;
Пример #18
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)
Пример #19
0
    def LIST_response(self, code, args):
        resp = scan_sexp(args)

        try:
            attributes = resp[0]
            hierarchy_delimiter = resp[1]
            name = resp[2]
        except:
            raise self.Error('Don\'t know how to parse the LIST response: %s' %\
                args )

        # If the hierarchy_delimiter is NIL no hierarchy exists
        if hierarchy_delimiter != 'NIL':
            hierarchy_delimiter = unquote(hierarchy_delimiter)
        else:
            hierarchy_delimiter = None

        self.sstatus['list_response'].append(
            parselist.Mailbox(name, attributes, hierarchy_delimiter))
Пример #20
0
async def show_news(msg, args):
    url = news["главное"]

    if args:
        category = args.pop()

        if category.lower() in ["помощь", "помощ", "помоги", "помог"]:
            return await msg.answer(f"{PREFIXES[0]}новости [тема], где тема - это одно из следующих слов:\n"
                                    f"{', '.join([k[0].upper() + k[1:] for k in news.keys()])}")

        if category.lower() in news:
            url = news[category]

    async with aiohttp.ClientSession() as sess:
        async with sess.get(url) as resp:
            xml = xmltodict.parse(await resp.text())
            items = xml["rss"]["channel"]["item"]
            item = unquote(choice(items))

            return await msg.answer(f'👉 {item["title"]}\n'
                                    f'👉 {item["description"]}')
Пример #21
0
    def _un_htmlify(self, text):
        def _handle_bad_html(s):
            pttn = re.compile('<|>')
            return pttn.sub(' ', s)

        soup = BeautifulSoup(text.strip())

        # get all of the text and any a/@href values
        texts = [
            _handle_bad_html(t.strip('"')) for t in soup.find_all(text=True)
        ]
        if self.include_html_hrefs:
            texts += [
                unquote(a['href']) for a in soup.find_all('a')
                if 'href' in a.attrs
            ]

        try:
            text = ' '.join(texts)
        except:
            raise
        return text
Пример #22
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)
Пример #23
0
        except:
            params = {}
        dataType = None
        utils.log('params = ' + str(params))
        for type in ['json', 'property', 'listitem']:
            try:
                data = params[type]
                dataType = type
                break
            except:
                pass

        hasChannels = False
        channelLST = ChannelList()
        channelLST.incHDHR = (utils.loadJson(
            utils.unquote(params.get('include_hdhr', '')))
                              or channelLST.incHDHR)
        channelLST.skinPath = ((utils.loadJson(
            utils.unquote(params.get('skin_path', ''))))
                               or channelLST.chkSkinPath())
        channelLST.mediaFolder = os.path.join(channelLST.skinPath, 'resources',
                                              'skins', 'default', 'media')
        channelLST.refreshPath = utils.loadJson(
            utils.unquote(params.get('refresh_path', '')) or utils.ADDON_ID)
        channelLST.refreshIntvl = int(
            utils.loadJson(utils.unquote(params.get('refresh_interval', '')))
            or '0')
        channelLST.skinFolder = os.path.join(
            channelLST.skinPath,
            'resources',
            'skins',
Пример #24
0
if __name__ == '__main__':
    if utils.getProperty('PseudoTVRunning') != "True":
        try: params = dict(arg.split('=') for arg in sys.argv[1].split('&'))
        except: params = {}
        dataType = None
        utils.log('params = ' + str(params))
        for type in ['json','property','listitem']:
            try:
                data = params[type]
                dataType = type
                break
            except: pass
            
        hasChannels= False
        channelLST = ChannelList()
        channelLST.incHDHR      = (utils.loadJson(utils.unquote(params.get('include_hdhr','')))          or channelLST.incHDHR)
        channelLST.skinPath     = ((utils.loadJson(utils.unquote(params.get('skin_path',''))))           or channelLST.chkSkinPath())
        channelLST.mediaFolder  = os.path.join(channelLST.skinPath,'resources','skins','default','media')
        channelLST.refreshPath  = utils.loadJson(utils.unquote(params.get('refresh_path',''))            or utils.ADDON_ID)
        channelLST.refreshIntvl = int(utils.loadJson(utils.unquote(params.get('refresh_interval','')))   or '0')
        channelLST.skinFolder   = os.path.join(channelLST.skinPath,'resources','skins','default','1080i',) if xbmcvfs.exists(os.path.join(channelLST.skinPath,'resources','skins','default','1080i','%s.guide.xml'%utils.ADDON_ID)) else os.path.join(channelLST.skinPath,'resources','skins','default','720p')
        utils.setProperty('uEPG.rowCount',utils.loadJson(utils.unquote(params.get('row_count',''))       or '9'))
        channelLST.pluginName, channelLST.pluginAuthor, channelLST.pluginIcon, channelLST.pluginFanart, channelLST.pluginPath = utils.getPluginMeta(channelLST.refreshPath)
        
        utils.log('dataType = '     + str(dataType))
        utils.log('skinPath = '     + str(channelLST.skinPath))
        utils.log('skinFolder = '   + str(channelLST.skinFolder))
        utils.log('rowCount = '     + utils.getProperty('uEPG.rowCount'))
        utils.log('refreshPath = '  + str(channelLST.refreshPath))
        utils.log('refreshIntvl = ' + str(channelLST.refreshIntvl))
        utils.setProperty('PluginName'   ,channelLST.pluginName)
Пример #25
0
def decrypt_videobam(url):
	download_link = ''
	cont = utils.get_content(url)
	download_link = unquote(utils.text_finder(cont, '","url":"', '"')).replace('\\/', '/')
	return download_link
Пример #26
0

#-------------

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

while True:
    conn, addr = s.accept()
    print('Got a connection from %s' % str(addr))
    request = str(conn.recv(2048))

    print(request)

    try:
        verb, path, rest = str(request).split(None, 2)
    except:
        print("ERR: Empty request")
        continue

    if verb[2:] == 'POST':
        headers, vars = rest[:-1].split(r'\r\n\r\n', 1)
        vars = dict([v.split('=') for v in vars.split('&')])
        for key, value in vars.items():
            vars[key] = unquote(value.replace('+', ' ')).decode('utf-8')
        print(vars)
        post(conn, path, vars)
    else:
        get(conn, path)
Пример #27
0
@author: lapalme
'''
import re
from utils import traceSyntR, setTraceSyntR, is_number, unquote, generateConceptWord, errorSyntR, predicate,\
                  relative, adverbFromAdjective, isArgOp, ensurePhrase, hasNegPolarity
from lexicalSemantics import Env, Options, LexSem
from jsRealBclass import N,A,Pro,D,Adv,V,C,P,DT,NO,Q,  NP,AP,AdvP,VP,CP,PP,S,SP,  Constituent, Terminal, Phrase
from amrDico import gender, getSyntR, makePoss, isPossessive, isPronoun, makePro, \
                    isNoun, makeN, isAdjective, makeA, isVerb, makeV,makeCP, nouns, verbs, getNominalization, getPOS
from amrDicoGen import verbalizations,morphVerbalizations,adjInfo,nounInfo

import SemR2SyntR,roleProcessing


quoteInfo= lambda string:LexSem(string,"Q",[],lambda:Q(unquote(string)))

## simplify notation because "from SemR2SyntR import makeSyntR"
#  makes the "recursive" import loop
def makeSyntR(semR,checkSpecial=True):
    return SemR2SyntR.makeSyntR(semR,checkSpecial)

##  add syntR for all roles except for the ignored ones at the end of syntR
def addRoles(concept,roles,ignored,dictInfo,env,opts):
    dictInfo=roleProcessing.processRoles(concept,roles,ignored,dictInfo,env,opts)
    syntR=dictInfo.apply(env,opts)
    return syntR

# create a Date using DT by first building a string for the Javascript Date object and the jsRealB dOpt
# monthNames=["*dummy*","January","February","March","April","May","June","July","August",
#             "September","October","November","December"]
Пример #28
0
        except:
            params = {}

        dataType = None
        utils.log('params = ' + str(params))
        for type in ['json', 'property', 'listitem']:
            try:
                data = params[type]
                dataType = type
                break
            except:
                pass

        channelLST = ChannelList()
        channelLST.skinPath = ((utils.loadJson(
            utils.unquote(params.get('skin_path', ''))))
                               or channelLST.chkSkinPath())
        channelLST.mediaFolder = os.path.join(channelLST.skinPath, 'resources',
                                              'skins', 'default', 'media')
        channelLST.refreshPath = utils.loadJson(
            utils.unquote(params.get('refresh_path', None) or None))
        channelLST.refreshIntvl = int(
            utils.loadJson(utils.unquote(params.get('refresh_interval', '0')))
            or '0')
        channelLST.skinFolder = os.path.join(
            channelLST.skinPath,
            'resources',
            'skins',
            'default',
            '1080i',
        ) if xbmcvfs.exists(
Пример #29
0
def initChannels(params, data, dataType):
    utils.log('initChannels, params = ' + str(params))
    with busy_dialog():
        hasChannels = False
        channelLST = ChannelList()
        channelLST.incHDHR = (
            params.get('include_hdhr', '')
            or utils.REAL_SETTINGS.getSetting('Enable_HDHR')) == 'true'
        channelLST.skinPath = (utils.unquote(params.get('skin_path', ''))
                               or channelLST.chkSkinPath())
        channelLST.mediaFolder = os.path.join(channelLST.skinPath, 'resources',
                                              'skins', 'default', 'media')
        channelLST.refreshPath = (utils.unquote(params.get('refresh_path', ''))
                                  or utils.ADDON_ID)
        channelLST.refreshIntvl = int(
            params.get('refresh_interval', '') or '0')
        channelLST.skinFolder = os.path.join(
            channelLST.skinPath,
            'resources',
            'skins',
            'default',
            '1080i',
        ) if xbmcvfs.exists(
            os.path.join(channelLST.skinPath, 'resources', 'skins', 'default',
                         '1080i', '%s.guide.xml' %
                         utils.ADDON_ID)) else os.path.join(
                             channelLST.skinPath, 'resources', 'skins',
                             'default', '720p')
        utils.setProperty('uEPG.rowCount',
                          (params.get('row_count', '') or '9'))
        channelLST.pluginName, channelLST.pluginAuthor, channelLST.pluginIcon, channelLST.pluginFanart, channelLST.pluginPath = utils.getPluginMeta(
            channelLST.refreshPath)

        utils.log('dataType = ' + str(dataType))
        utils.log('skinPath = ' + str(channelLST.skinPath))
        utils.log('skinFolder = ' + str(channelLST.skinFolder))
        utils.log('rowCount = ' + utils.getProperty('uEPG.rowCount'))
        utils.log('refreshPath = ' + str(channelLST.refreshPath))
        utils.log('refreshIntvl = ' + str(channelLST.refreshIntvl))
        utils.setProperty('PluginName', channelLST.pluginName)
        utils.setProperty('PluginIcon', channelLST.pluginIcon)
        utils.setProperty('PluginFanart', channelLST.pluginFanart)
        utils.setProperty('PluginAuthor', channelLST.pluginAuthor)
        utils.setProperty('pluginPath', channelLST.pluginPath)

        #show optional load screen
        # if channelLST.uEPGRunning == False and utils.getProperty('uEPGSplash') != 'True' and xbmcvfs.exists(os.path.join(channelLST.skinFolder,'%s.splash.xml'%utils.ADDON_ID)) == True:
        # mySplash   = epg.Splash('%s.splash.xml'%utils.ADDON_ID,channelLST.skinPath,'default')
        # mySplash.show()
        # xbmc.sleep(100)

        if utils.HDHR().hasHDHR():
            if utils.REAL_SETTINGS.getSetting(
                    'FirstTime_HDHR') == "true" and not channelLST.incHDHR:
                utils.REAL_SETTINGS.setSetting('FirstTime_HDHR', 'false')
                if utils.yesnoDialog(
                    (utils.LANGUAGE(30012) % (channelLST.pluginName)),
                        custom='Later'):
                    utils.REAL_SETTINGS.setSetting('Enable_HDHR', 'true')
                    channelLST.incHDHR = True
        utils.log('incHDHR = ' + str(channelLST.incHDHR))

    if dataType == 'wrap': hasChannels = channelLST.prepareJson(data)
    elif dataType == 'json':
        hasChannels = channelLST.prepareJson(
            utils.loadJson(utils.unquote(data)))
    elif dataType == 'property':
        hasChannels = channelLST.prepareJson(
            utils.loadJson(utils.unquote(utils.getProperty(data))))
    elif dataType == 'listitem':
        hasChannels = channelLST.prepareVFS(utils.unquote(data))

    if hasChannels == True:
        if utils.REAL_SETTINGS.getSetting('FirstTime_Run') == "true":
            utils.REAL_SETTINGS.setSetting('FirstTime_Run', 'false')
            utils.textViewer(
                utils.LANGUAGE(30008),
                '%s / %s' % (utils.ADDON_NAME, channelLST.pluginName))

        # if utils.getProperty('uEPGSplash') == 'True':
        # mySplash.close()
        # del mySplash
        # xbmc.sleep(100)

        if channelLST.refreshIntvl > 0 and channelLST.refreshPath is not None:
            channelLST.startRefreshTimer()
        if channelLST.uEPGRunning == False and utils.getProperty(
                'uEPGGuide') != 'True':
            channelLST.myEPG = epg.uEPG('%s.guide.xml' % utils.ADDON_ID,
                                        channelLST.skinPath, 'default')
            channelLST.myEPG.channelLST = channelLST
            channelLST.myEPG.doModal()
            del channelLST.myEPG
            xbmc.sleep(100)
    else:
        utils.log("invalid uEPG information", xbmc.LOGERROR)
        # utils.notificationDialog(utils.LANGUAGE(30002)%(channelLST.pluginName,channelLST.pluginAuthor),icon=channelLST.pluginIcon)
        # utils.REAL_SETTINGS.openSettings()
    del utils.KODI_MONITOR
Пример #30
0
def haveDegree91(concept,roles,env,opts):
    traceSyntR("haveDegree91",concept)
    subject=None
    attribute=None
    comp=""
    quant=None
    if ":ARG1" in roles:
        arg1=roles[":ARG1"]
#         print("haveDegree1:",arg1.instanceIsRef())
        if not arg1.instanceIsRef(): # do not follow link for subject
            subject=makeSyntR(arg1)
    if ":ARG2" in roles:
        concept=roles[":ARG2"].concept
        attribute=makeSyntR(roles[":ARG2"])
        # HACK: remove spurious pronouns created by starrole
        if isinstance(attribute, AP) and len(attribute.elements)>1 and isinstance(attribute.elements[1],Pro):
            del attribute.elements[1]
            if len(attribute.elements)==1:
                attribute=attribute.elements[0]
    else:
        errorSyntR("have-degree-91 without :ARG2:%s"%concept)
        return Q("degree-91")
    if ":mod" in roles:
        if isinstance(attribute,Terminal):
            attribute=AP(attribute)
        attribute.add(makeSyntR(roles[":mod"]))        
    if ":ARG3" in roles:
        rolesARG3=roles[":ARG3"]
        deg=rolesARG3.get_concept()
        moreRoles=rolesARG3.get_roles()
        if moreRoles!=None and len(moreRoles)>0:
            if ":quant" in moreRoles:
                quant=makeSyntR(moreRoles[":quant"])
            else:
                attribute.add(makeSyntR(moreRoles[0][1]))
        if deg=="more":
            attribute=attribute.f("co")
            if quant!=None:
                attribute=NP(quant,attribute)
                quant=None
            comp="co"
        elif deg=="most":
            if isinstance(attribute,A):
                attribute=AP(D("the"),attribute.f("su"))
            else:
                attribute=AP(attribute,D("the"),Adv("most"))
            comp="su"
        elif deg in ["too","so","less"]:
            attribute=AdvP(Adv(deg),attribute)
            if deg=="less":
                comp="co"
            elif quant!=None:
                attribute=AP(attribute,quant)
                quant=None
        elif deg=="equal":
            attribute=AdvP(Adv("as"),attribute,Adv("as"))
        elif deg=="times":
            if quant!=None:
                quant=NP(quant,N("time"))
                attribute=attribute.f("co")
            comp="co"
        else:
            attribute=AdvP(attribute,Adv(deg))
    if ":ARG4" in roles:
        syntR4=makeSyntR(roles[":ARG4"])
        if comp=="co":
            attribute=PP(attribute,P("than"),syntR4)
            if quant!=None:
                attribute.add(quant,0)
        elif comp=="su":
            attribute=AP(attribute,Adv("in"),syntR4)
        else:
            attribute.add(syntR4)
    if ":ARG5" in roles:
        attribute.add(makeSyntR(roles[":ARG5"]))
    if ":ARG6" in roles:
        attribute=NP(attribute,makeSyntR(roles[":ARG6"]))
#     print("have-degree-91:subject:",subject)
    while ":li" in roles:
        semR=roles[":li"]
        del roles[":li"]
        ## analogous to roleProcessing.lirole
        semR_i=unquote(semR.get_instance())
        if semR_i=="-1":
            attribute.add(Adv("lastly"),0)
        elif semR_i=="1":
            attribute.add(Adv("first"),0)
        elif is_number(semR_i):
            attribute.add(Q("("+str(semR_i)+")"),0)
        elif semR_i[0]=='"':
            attribute.add(Q("("+semR_i+")"),0)
    restRoles=addRoles(concept, roles, [":ARG1",":ARG2",":ARG3",":ARG4",":ARG5",":ARG6",":li",":mod",":polarity"], 
                       LexSem("degree","SP",[],lambda:SP()),env, opts)        
    if len(restRoles.elements)>0:
        attribute=ensurePhrase(attribute).add(restRoles)
    if subject!=None:
        attribute=predicate(subject,attribute)
        if hasNegPolarity(roles):
            return attribute.typ({"neg":True})
    else:
        if hasNegPolarity(roles):
            return AdvP(Adv("not"),attribute)
    return attribute
Пример #31
0
def dateEntity(concept,roles,env,opts):
    def zPad(s): #ensure a string of length 2 padded with a 0 
        if len(s)==2: return s
        if len(s)==1: return "0"+s
        if len(s)>2 : return s[0:2]
        return s
    
    def checkDateComp(date,rName,dOptField,length,default):
        if rName in roles:
            val=roles[rName].instance
            if is_number(val) and len(val)<=length:
                date+=val.rjust(length,"0")
                dOpt[dOptField]=True
            else:
                print("dateEntity: strange %s:%s"%(rName,val))
                date+=default
        else:
            date+=default
        return date
    
    traceSyntR("dateEntity",concept)
    if ":time" in roles and roles[":time"].get_concept()=="amr-unknown":
        return Q("what time is it ?")
    date="" # ISO format "YYYY-MM-DDTHH:mm:ss"
    dOpt={"year":False , "month":False , "date":False , "day":False , "hour":False , 
          "minute":False , "second":False , "nat":True, "det":False, "rtime":False}
    date=checkDateComp(date,":year","year",4,"2021")+"-"
    date=checkDateComp(date,":month", "month", 2, "01")+"-"
    date=checkDateComp(date,":day", "date", 2, "01")+"T"
    if ":time" in roles:
        timeS=roles[":time"].instance
        if isinstance(timeS,str) and ":" in timeS:
            time=unquote(timeS)
            tParts=time.split(":")
            if len(tParts)==2:
                tParts.append("00")
            if len(tParts)==3:
                date+=zPad(tParts[0])+":"+zPad(tParts[1])+":"+zPad(tParts[2])
                dOpt["hour"]=True
                dOpt["minute"]=True
                dOpt["second"]=True
    if not dOpt["hour"]:
        date+="00:00:00"
        dOpt["hour"]=False
        dOpt["minute"]=False
        dOpt["second"]=False
    sp=SP(DT(date+"-05:00").dOpt(dOpt))## HACK: force Montreal time zone  
    if ":timezone" in roles:
        sp.add(makeSyntR(roles[":timezone"]))
    if ":weekday" in roles:
        sp.add(Q(unquote(roles[":weekday"].get_concept()).capitalize()),0)
    if ":season" in roles:
        sp.add(Q(unquote(roles[":season"].get_concept())),0)
    if ":mod" in roles:
        sp.add(Q(unquote(roles[":mod"].get_concept())),0)
    if ":dayperiod" in roles:
        sp.add(Q(unquote(roles[":dayperiod"].get_concept())))
    if ":quarter" in roles:
        sp.add(NP(makeSyntR(roles[":quarter"]).dOpt({"ord":True}),N("quarter")))
    if ":year2" in roles:
        sp.add(makeSyntR(roles[":year2"]).dOpt({"raw":True}).b("-"))
    if ":era" in roles:
        sp.add(Q(unquote(roles[":era"].get_instance())))
    if ":calendar" in roles:
        sp.add(N("calendar").a(":"))
        sp.add(makeSyntR(roles[":calendar"]))
    if ":decade" in roles:
        sp.add(makeSyntR(roles[":decade"]))
        sp.add(Q("s"))
    return sp
Пример #32
0
 def extract_link(self) -> PartialPost:
     match = self.link_regex.search(self.element.html)
     if match:
         return {'link': utils.unquote(match.groups()[0])}
     return None
Пример #33
0
    async def method(self, key: str, data=None, user=False):
        """Выполняет метод API VK с дополнительными параметрами"""
        if key != "execute":
            task = RequestFuture(key, data, user)

            if not task.user and is_available_from_group(key):
                self.bot.queue_group.put_nowait(task)
            else:
                self.bot.queue_user.put_nowait(task)

            return await asyncio.wait_for(task, None)

        if data is None:
            data = {}
        else:
            for k, v in data.items():
                data[k] = quote(v)

        # Если мы работаем от имени группы
        if self.token and not user:
            # Если метод доступен от имени группы - используем API группы
            if is_available_from_group(key):
                api_method = self.group_api
            # Если метод доступен от паблик апи - используем его
            elif is_available_from_public(key):
                api_method = self.public_api
            elif self.user_api:
                api_method = self.user_api
            else:
                hues.warn(f'Метод {key} нельзя вызвать от имени сообщества!')
                return {}
        else:
            api_method = self.user_api
        try:
            return unquote(await api_method(key, **data))

        except (asyncio.TimeoutError, json.decoder.JSONDecodeError):
            # Пытаемся отправить запрос к API ещё раз
            return unquote(await api_method(key, **data))
        except aiovk.exceptions.VkAuthError:
            message = 'TOKEN' if self.token else 'LOGIN и PASSWORD'
            fatal("Произошла ошибка при авторизации API, "
                  f"проверьте значение {message} в settings.py!")
        except aiovk.exceptions.VkAPIError as ex:
            # Код 9 - Flood error - слишком много одинаковых сообщений
            if not ex.error_code == 9:
                hues.error("Произошла ошибка при вызове метода API "
                           f"{key} с значениями {data}:\n{ex}")
                return {}

            if 'message' not in data:
                return {}

            data['message'] += f'\n Анти-флуд (API): {self.anti_flood()}'
            try:
                # Пытаемся отправить сообщение ещё раз
                await self.method('messages.send', data)
            except aiovk.exceptions.VkAPIError:
                # Не знаю, может ли это случиться, или нет
                hues.error('Обход анти-флуда API не удался =(')
        return {}