rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
res1 = run_sql("SELECT id_%s,value FROM %sname WHERE ln='%s' and type='%s' and id_%s=%s" % (table, table, cdslang, rtype, table, ID))
res1 = run_sql("SELECT id_%s,value FROM %s%s WHERE ln='%s' and type='%s' and id_%s=%s" % (table, table, name, cdslang, rtype, table, ID))
def get_current_name(ID, ln, rtype, table): """Returns a list of the names, either with the name in the current language, the default language, or just the name from the given table ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn'""" #try: if 1==1: res = "" if ID: res = run_sql("SE...
res1 = run_sql("SELECT id_%s,value FROM %sname WHERE ln='%s' and type='%s'" % (table, table, cdslang, rtype))
res1 = run_sql("SELECT id_%s,value FROM %s%s WHERE ln='%s' and type='%s'" % (table, table, name, cdslang, rtype))
def get_current_name(ID, ln, rtype, table): """Returns a list of the names, either with the name in the current language, the default language, or just the name from the given table ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn'""" #try: if 1==1: res = "" if ID: res = run_sql("SE...
except StandardError, e: raise StandardError
def get_current_name(ID, ln, rtype, table): """Returns a list of the names, either with the name in the current language, the default language, or just the name from the given table ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn'""" #try: if 1==1: res = "" if ID: res = run_sql("SE...
try: res = run_sql("SELECT value FROM %sname where type='%s' and ln='%s' and id_%s=%s" % (table, rtype, ln, table, ID))
name = "name" if table == "rnkMETHOD": name = "NAME" try: res = run_sql("SELECT value FROM %s%s WHERE type='%s' and ln='%s' and id_%s=%s" % (table, name, rtype, ln, table, ID))
def get_name(ID, ln, rtype, table): """Returns the value from the table name based on arguments ID - id ln - a language supported by cdsware type - the type of value wanted, like 'ln', 'sn' table - tablename""" try: res = run_sql("SELECT value FROM %sname where type='%s' and ln='%s' and id_%s=%s" % (table, rtype, ln, ...
imagepath = "%s/getfile.py?docid=%s&name=%s&format=gif" % (weburl,existingIcon.getId(),existingIcon.getDocName())
imagepath = "%s/getfile.py?docid=%s&name=%s&format=gif" % (weburl,existingIcon.getId(),urllib.quote(existingIcon.getDocName()))
def display(self,version=""): t="" if version == "all": docfiles = self.listAllFiles() elif version != "": docfiles = self.listVersionFiles(version) else: docfiles = self.listLatestFiles() existingIcon = self.getIcon() if existingIcon != None: imagepath = "%s/getfile.py?docid=%s&name=%s&format=gif" % (weburl,existingIc...
return "<tr><td valign=top><small><a href=\"%s/getfile.py?docid=%s&name=%s&format=%s&version=%s\">%s%s</a></td><td valign=top><font size=-2 color=green>[%s&nbsp;B]</font></td></tr>\n""" % (weburl,self.bibdocid,re.sub("\&","%26",self.name),self.format,self.version,self.name,format,self.size)
return "<tr><td valign=top><small><a href=\"%s/getfile.py?docid=%s&name=%s&format=%s&version=%s\">%s%s</a></td><td valign=top><font size=-2 color=green>[%s&nbsp;B]</font></td></tr>\n""" % (weburl,self.bibdocid,urllib.quote(self.name),urllib.quote(self.format),self.version,self.name,format,self.size)
def display(self): if self.format != "": format = ".%s" % self.format else: format = "" return "<tr><td valign=top><small><a href=\"%s/getfile.py?docid=%s&name=%s&format=%s&version=%s\">%s%s</a></td><td valign=top><font size=-2 color=green>[%s&nbsp;B]</font></td></tr>\n""" % (weburl,self.bibdocid,re.sub("\&","%26",self...
if record_exists(irec)==1:
if record_exists(recIDs[irec])==1: req.write("""\n<div class="recordlastmodifiedbox">%s</div>""" % \ (msg_record_last_modified[ln] % (get_creation_date(recIDs[irec]),get_modification_date(recIDs[irec]))))
def print_records(req, recIDs, jrec=1, rg=10, format='hb', ot='', ln=cdslang, decompress=zlib.decompress): """Prints list of records 'recIDs' formatted accoding to 'format' in groups of 'rg' starting from 'jrec'. Assumes that the input list 'recIDs' is sorted in reverse order, so it counts records from tail to head. A ...
class functionError(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class functionStop(Exception): def __init__(self, value): self.value = value def __str__(self): return repr(self.value)
def Test_Reload(uid_email, doctype, act, access): res = run_sql("SELECT * FROM sbmSUBMISSIONS WHERE doctype=%s and action=%s and id=%s and email=%s and status='finished'", (doctype, act, access, uid_email,)) if len(res) > 0: return 1 else: return 0
'X_url_close': '</a>'}
'x_url_close': '</a>'}
def tmpl_create_guest_warning_box(self, ln=cdslang): """return html warning box for non registered users""" _ = gettext_set_language(ln) message = _("You are logged in as a guest user, so your baskets will disappear at the end of the current session.") + ' ' message += _("If you wish you can %(x_url_open)slogin or regi...
(reclist, hitset) = sort_record_relevance(recdict, rec_termcount, hitset, rank_limit_relevance, verbose)
if len(recdict) == 0 or len(lwords) == 0: return (None, "Could not find any similar documents, possibly because of error in ranking data.", "", voutput) else: (reclist, hitset) = sort_record_relevance(recdict, rec_termcount, hitset, rank_limit_relevance, verbose)
def find_similar(rank_method_code, recID, hitset, rank_limit_relevance,verbose): """Finding terms to use for calculating similarity. Terms are taken from the recid given, returns a list of recids's and relevance, input: rank_method_code - the code of the method, from the name field in rnkMETHOD recID - records to use f...
recdict[j] = math.log(recdict[j] * rec_termcount[j])
if recdict[j] > 0: recdict[j] = math.log(recdict[j] * rec_termcount[j])
def sort_record_relevance(recdict, rec_termcount, hitset, rank_limit_relevance, verbose): """Sorts the dictionary and returns records with a relevance higher than the given value. recdict - {recid: value} unsorted rank_limit_relevance - a value > 0 usually verbose - verbose value""" startCreate = time.time() global vo...
command = '%s/bibharvest -v ListRecords -p %s ' % (bindir, prefix)
command = '%s/bibharvest -o %s -v ListRecords -p %s ' % (bindir, harvestpath, prefix)
def call_bibharvest(prefix, baseurl, harvestpath, fro="", until=""): """ A method that calls bibharvest and writes harvested output to disk """ try: command = '%s/bibharvest -v ListRecords -p %s ' % (bindir, prefix) if fro!="": command += '-f %s ' % fro if until!="": command += '-u %s ' % until command += baseurl (stdi...
(stdin, harvesttext, stderr) = os.popen3(command) harvestread = harvesttext.read() ftmp = open(harvestpath, 'w') ftmp.write(harvestread) ftmp.close()
print "Start harvesting" ret = os.system(command) print "Harvesting finished, merging files" harvestdir, filename = os.path.split(harvestpath) files = os.listdir(harvestdir) files.sort() hf = file(harvestpath, 'w') for f in files: if f[:len(filename)] == filename: print "processing file %s"%f rf = file(os.path.join...
def call_bibharvest(prefix, baseurl, harvestpath, fro="", until=""): """ A method that calls bibharvest and writes harvested output to disk """ try: command = '%s/bibharvest -v ListRecords -p %s ' % (bindir, prefix) if fro!="": command += '-f %s ' % fro if until!="": command += '-u %s ' % until command += baseurl (stdi...
return stdout
return 0
def call_bibconvert(config, harvestpath, convertpath): """ A method that reads from a file and converts according to a BibConvert Configuration file. Converted output is returned """ command = """%s/bibconvert -c %s < %s > %s """ % (bindir, config, harvestpath, convertpath) stdout = os.popen(command) return stdout
if of.startswith("xm"): req.write("""<collection xmlns="http://www.loc.gov/MARC21/slim">\n""") else: req.write("""<collection>\n""")
def page_start(req, of, cc, as, ln, uid, title_message=None, description='', keywords=''): "Start page according to given output format." _ = gettext_set_language(ln) if not title_message: title_message = _("Search Results") if not req: return # we were called from CLI content_type = get_output_format_content_type(...
elif of.startswith('x'): req.write("""</collection>\n""")
def page_end(req, of="hb", ln=cdslang): "End page according to given output format: e.g. close XML tags, add HTML footer, etc." if of == "id": return [] # empty recID list if not req: return # we were called from CLI if of.startswith('h'): req.write(websearch_templates.tmpl_search_pageend(ln = ln)) # pagebody end req.w...
for irec in range(irec_max, irec_min, -1): req.write(print_record(recIDs[irec], format, ot, ln, search_pattern=search_pattern, uid=uid))
if format.startswith('xm'): format_prologue = websearch_templates.tmpl_xml_marc_prologue() format_epilogue = websearch_templates.tmpl_xml_marc_epilogue() elif format.startswith('xn'): format_prologue = websearch_templates.tmpl_xml_nlm_prologue() format_epilogue = websearch_templates.tmpl_xml_nlm_epilogue() elif format....
def print_records(req, recIDs, jrec=1, rg=10, format='hb', ot='', ln=cdslang, relevances=[], relevances_prologue="(", relevances_epilogue="%%)", decompress=zlib.decompress, search_pattern=''): """Prints list of records 'recIDs' formatted accoding to 'format' in groups of 'rg' starting from 'jrec'. Assumes that the inpu...
expr = sre.compile( r"\"(http://[\w]+\.+[\w]+[^\"'><]*\.)(" + \
expr = sre.compile( r"\"(http://[\w]+\.+[\w]+[^\"'><]*\." + \
def get_fulltext_urls_from_html_page(htmlpagebody): """Parses htmlpagebody data looking for url_directs referring to probable fulltexts. Returns an array of (ext,url_direct) to fulltexts. Note: it looks for file format extensions as defined by global 'conv_programs'structure. """ out = [] for ext in conv_programs.keys(...
out.append([ext,match.group()])
out.append([ext,match.group(1)])
def get_fulltext_urls_from_html_page(htmlpagebody): """Parses htmlpagebody data looking for url_directs referring to probable fulltexts. Returns an array of (ext,url_direct) to fulltexts. Note: it looks for file format extensions as defined by global 'conv_programs'structure. """ out = [] for ext in conv_programs.keys(...
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
def get_words_from_fulltext(url_direct_or_indirect, separators="[^\w]", split=string.split, force_file_extension=None): """Returns all the words contained in the document specified by URL_DIRECT_OR_INDIRECT with the words being split by SEPARATORS. If FORCE_FILE_EXTENSION is set (e.g. to "pdf", then treat URL_DIRECT_O...
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
write_message("... reading fulltext files from %s started" % url_indirect) url_direct = None
write_message("... reading fulltext files from %s started" % url_direct_or_indirect)
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
url_indirect_ext = lower(split(url_indirect,".")[-1]) if url_indirect_ext in conv_programs.keys(): fulltext_urls = [(url_indirect_ext,url_indirect)] if not fulltext_urls: try: htmlpagebody = urllib.urlopen(url_indirect).read() except: sys.stderr.write("Error: Cannot read %s.\n" % url_indirect) return [] fulltext_ur...
if not force_file_extension: url_direct = None fulltext_urls = None url_direct_or_indirect_ext = lower(split(url_direct_or_indirect,".")[-1]) if url_direct_or_indirect_ext in conv_programs.keys(): fulltext_urls = [(url_direct_or_indirect_ext,url_direct_or_indirect)] if not fulltext_urls: try: htmlpagebody = urllib...
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
url = urllib.urlopen(url_direct[1:-1])
url = urllib.urlopen(url_direct)
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
sys.stderr.write("Error: Cannot read %s.\n" % url_direct[1:-1])
sys.stderr.write("Error: Cannot read %s.\n" % url_direct)
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
write_message("... reading fulltext files from %s ended" % url_indirect)
write_message("... reading fulltext files from %s ended" % url_direct_or_indirect)
def get_words_from_fulltext(url_indirect,separators="[^\w]",split=string.split): """Returns all the words contained in the fulltext whose url is contained in the document pointed to in phrase. Please note the double indirection. url_indirect returns a document that has to be parsed to get the actual urls.""" if cfg_bib...
new_words = get_words_function(phrase)
if tag == "8564_u": filename = get_associated_subfield_value(recID,'8564_u', phrase, 'y') filename_extension = lower(split(filename, ".")[-1]) if filename_extension in conv_programs.keys(): new_words = get_words_function(phrase, force_file_extension=filename_extension) else: new_words = get_words_function(phr...
def add_recID_range(self, recID1, recID2): empty_list_string = serialize_via_marshal([]) wlist = {} self.recIDs_in_mem.append([recID1,recID2]) # secondly fetch all needed tags: for tag in self.fields_to_index: if tag in tagToWordsFunctions.keys(): get_words_function = tagToWordsFunctions[ tag ] else: get_words_function...
txt.append(arr[6])
def interface(req,c=cdsname,ln=cdslang, doctype="", act="", startPg=1, indir="", access="",mainmenu="",fromdir="",file="",nextPg="",nbPg="",curpage=1): ln = wash_language(ln) sys.stdout = req # get user ID: try: uid = getUid(req) uid_email = get_email(uid) except MySQLdb.Error, e: return errorMsg(e.value,req) # variabl...
rw = RequestWrapper( request )
rw = RequestWrapper.getWrapper( request )
def get_session (self, request): """Proxy method to SessionManager get_session. It converts the mod_python request objects in a SessionManager compatible one and executes the parent implementation passing the compatible object """ rw = RequestWrapper( request ) s = SessionManager.get_session( self, rw ) rw.setSession(...
rw = RequestWrapper( request )
rw = RequestWrapper.getWrapper( request )
def maintain_session (self, request, session): """Proxy method to SessionManager maintain_session. It converts the mod_python request objects in a SessionManager compatible one and executes the parent implementation passing the compatible object """ rw = RequestWrapper( request ) SessionManager.maintain_session( self, ...
rw = RequestWrapper( request )
rw = RequestWrapper.getWrapper( request )
def has_session_cookie (self, request, must_exist=0): """Proxy method to SessionManager has_session_cookie. It converts the mod_python request objects in a SessionManager compatible one and executes the parent implementation passing the compatible object """ rw = RequestWrapper( request ) return SessionManager.has_sess...
rw = RequestWrapper( request )
rw = RequestWrapper.getWrapper( request )
def expire_session (self, request): """Proxy method to SessionManager expire_session. It converts the mod_python request objects in a SessionManager compatible one and executes the parent implementation passing the compatible object """ rw = RequestWrapper( request ) SessionManager.expire_session(self, rw )
def create_session (self, request): """Proxy method to SessionManager create_session. It converts the mod_python request objects in a SessionManager compatible one and executes the parent implementation passing the compatible object """ rw = RequestWrapper( request ) return SessionManager._create_session(self,rw) def ...
def revoke_session_cookie (self, request):
def create_session (self, request):
rw = RequestWrapper( request)
rw = RequestWrapper.getWrapper( request)
def revoke_session_cookie(self, request):
"""Constructor of the class. Initialises the necessesary values.
"""Constructor of the class. Initialises the necessesary values. It should never be used, use getWrapper method instead.
def __init__(self, request): """Constructor of the class. Initialises the necessesary values. """ self.__request = request try: self.cookies = parse_cookie(self.__request.headers_in[ "Cookie" ]) except KeyError, e: self.cookies = {} self.environ = {} self.environ["REMOTE_ADDR"] = self.__request.get_remote_host(apache.R...
{'query': query, 'text_in': _('in'), 'name': _(engine.name), 'url': url})
{'url': url, 'query': cgi.escape(query), 'text_in': _('in'), 'name': _(engine.name)})
def build_seealso_links(basic_search_units, seealso_engines, lang, query): """Build the links for the see also box.""" _ = gettext_set_language(lang) links = [] for engine in seealso_engines: url = engine.build_search_url(basic_search_units, lang) if url: links.append('<a href="%(url)s">%(query)s %(text_in)s %(name)s<...
body += _("You may want to start browsing from &s") % link
body += _("You may want to start browsing from %s") % link
def tmpl_record_not_found(self, status='missing', recID="", ln=cdslang): """ Displays a page when bad or missing record ID was given. @param status: 'missing' : no recID was given 'inexistant': recID doesn't have an entry in the database 'nan' : recID is not a number 'invalid' : recID is an error code, i.e. ...
elif os.path.exists("%s/RTdata/RTdata" % cachedir) and argd['verb'] not in ["Identify", "ListMetadataFormats"]:
if os.path.exists("%s/RTdata/RTdata" % cachedir) and (argd['verb'] not in ["Identify", "ListMetadataFormats"]):
def __call__(self, req, form): "OAI repository interface"
"""Returns MySQL's recID for ALEPH sysno passed in the argument (e.g. "2209836CERCER").
"""Returns MySQL's recID for ALEPH sysno passed in the argument (e.g. "002379334CER").
def get_mysql_recid_from_aleph_sysno(sysno): """Returns MySQL's recID for ALEPH sysno passed in the argument (e.g. "2209836CERCER"). Returns None in case of failure.""" out = None query = "SELECT bb.id_bibrec FROM bibrec_bib90x AS bb, bib97x AS b WHERE b.value='%s' AND b.tag='970__a' AND bb.id_bibxxx=b.id" %\ (escape_s...
query = "SELECT bb.id_bibrec FROM bibrec_bib90x AS bb, bib97x AS b WHERE b.value='%s' AND b.tag='970__a' AND bb.id_bibxxx=b.id" %\
query = "SELECT bb.id_bibrec FROM bibrec_bib97x AS bb, bib97x AS b WHERE b.value='%s' AND b.tag='970__a' AND bb.id_bibxxx=b.id" %\
def get_mysql_recid_from_aleph_sysno(sysno): """Returns MySQL's recID for ALEPH sysno passed in the argument (e.g. "2209836CERCER"). Returns None in case of failure.""" out = None query = "SELECT bb.id_bibrec FROM bibrec_bib90x AS bb, bib97x AS b WHERE b.value='%s' AND b.tag='970__a' AND bb.id_bibxxx=b.id" %\ (escape_s...
alephsysnos = get_fieldvalues(recID, "909C0o")
alephsysnos = get_fieldvalues(recID, "970__a")
def print_record(recID, format='hb', ot='', decompress=zlib.decompress): "Prints record 'recID' formatted accoding to 'format'." out = "" # sanity check: if not record_exists(recID): return out # print record opening tags, if needed: if format == "marcxml" or format == "oai_dc": out += " <record>\n" out += " <head...
stemmer = Stemmer.Stemmer(languages[[methods[rnkMETHOD]["stem_lang"]]]) else:
stemmer = Stemmer.Stemmer(languages[methods[rnkMETHOD]["stem_lang"]]) else:
def get_config(rnkMETHOD): #needs some work """Load common data into memory""" global stopwords global stemmer global chars_alphanumericseparators global col_size global rnkWORD_table languages = {'fr': 'french', 'en': 'porter', 'no':'norwegian', 'se':'swedish', 'de': 'german', 'it':'italian', 'pt':'portugese'} try: i...
except Exception:
except Exception, e:
def get_config(rnkMETHOD): #needs some work """Load common data into memory""" global stopwords global stemmer global chars_alphanumericseparators global col_size global rnkWORD_table languages = {'fr': 'french', 'en': 'porter', 'no':'norwegian', 'se':'swedish', 'de': 'german', 'it':'italian', 'pt':'portugese'} try: i...
stat(reclist, col_size, query_terms_old)
stat(reclist, query_terms)
def find_similar(recID, lrecIDs, min_relevance=10,verbose=0): """Finding terms to use for calculating similarity. Terms are taken from the recid given, returns a list of recids's and relevance, [[23,34], [344,24], [1,01]] recID - record to use for find similar min_relevance - find all similar document above given perce...
if terms != term:
if lwords_old[i] != term:
def word_frequency(lwords, lrecIDs, min_relevance,verbose=0): """input: list of words, ['ellis', 'muon'] optional list of recIDs output: sorted list of recIDs by summary word frequencies, e.g. [[23,34], [344,24], [1,01]] if not possible (e.g. all stopwords), then return empty list""" startCreate = time.time() query_te...
stat(reclist, query_terms, col_size, lwords)
print query_terms print col_size stat(reclist, query_terms)
def word_frequency(lwords, lrecIDs, min_relevance,verbose=0): """input: list of words, ['ellis', 'muon'] optional list of recIDs output: sorted list of recIDs by summary word frequencies, e.g. [[23,34], [344,24], [1,01]] if not possible (e.g. all stopwords), then return empty list""" startCreate = time.time() query_te...
def stat(reclist, col_size, lwords):
def stat(reclist, lwords):
def stat(reclist, col_size, lwords): """Shows some statistics about the searchresult.""" if len(reclist) > 20: j = 20 else: j = len(reclist) for i in range(1, j): print i,reclist[len(reclist) - i] res = run_sql("SELECT termlist FROM %sR WHERE id_bibrec=%s" % (rnkWORD_table[:-1],reclist[len(reclist) - i][0])) try: ter...
print "-"*11, "-"*8, "-"*6, "-"*6, "-"*8, "-"*12, "-"*11
print " ", "-"*11, "-"*8, "-"*6, "-"*6, "-"*8, "-"*12, "-"*11
def main(srcdir): """Run kwalitee estimation for each CDS Invenio module and print the results on stdout. """ # init kwalitee measurement structure: kwalitee = {} kwalitee['TOTAL'] = ['TOTAL', 0, 0, 0, 0, 0] # detect CDS Invenio modules: modulenames = get_invenio_modulenames(srcdir) if "websearch" not in modulenames: p...
uid = getUid(req)
def print_records(req, recIDs, jrec=1, rg=10, format='hb', ot='', ln=cdslang, relevances=[], relevances_prologue="(", relevances_epilogue="%%)", decompress=zlib.decompress, search_pattern=''): """Prints list of records 'recIDs' formatted accoding to 'format' in groups of 'rg' starting from 'jrec'. Assumes that the inpu...
except MySQLdb.Error, e: return error_page(req)
except Error: return page(title=_("Internal Error"), body = create_error_box(req, verbose=0, ln=ln), description="%s - Internal Error" % cdsname, keywords="%s, CDS Invenio, Internal Error" % cdsname, language=ln, req=req)
def index(req, ln=cdslang): """ Shows status of migration and options to continue migration """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = getnavtrail() try: uid = getUid(req) except MySQLdb.Error, e: return error_page(req) (auth_code, auth_msg) = check_user(uid, 'cfgbibformat') if ...
except MySQLdb.Error, e: return error_page(req)
except Error: return page(title=_("Internal Error"), body = create_error_box(req, verbose=0, ln=ln), description="%s - Internal Error" % cdsname, keywords="%s, CDS Invenio, Internal Error" % cdsname, language=ln, req=req)
def migrate_kb(req, ln=cdslang): """ Migrate kbs and tell users the result of migration """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = getnavtrail(' &gt; <a class=navtrail href="%s/admin/bibformat/bibformat_migration_kit_assistant.py">Migration Kit</a>'%weburl) try: uid = getUid(req)...
except MySQLdb.Error, e: return error_page(req)
except Error: return page(title=_("Internal Error"), body = create_error_box(req, verbose=0, ln=ln), description="%s - Internal Error" % cdsname, keywords="%s, CDS Invenio, Internal Error" % cdsname, language=ln, req=req)
def migrate_behaviours(req, ln=cdslang): """ Migrate behaviours and tell users the result of migration """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = getnavtrail(' &gt; <a class=navtrail href="%s/admin/bibformat/bibformat_migration_kit_assistant.py">Migration Kit</a>'%weburl) try: ui...
except MySQLdb.Error, e: return error_page(req)
except Error: return page(title=_("Internal Error"), body = create_error_box(req, verbose=0, ln=ln), description="%s - Internal Error" % cdsname, keywords="%s, CDS Invenio, Internal Error" % cdsname, language=ln, req=req)
def migrate_formats(req, ln=cdslang): """ Shows the interface for migrating formats to format templates and format elements """ ln = wash_language(ln) _ = gettext_set_language(ln) navtrail_previous_links = getnavtrail(' &gt; <a class=navtrail href="%s/admin/bibformat/bibformat_migration_kit_assistant.py">Migration Kit<...
(collection, weburl, weburl, urllib.quote_plus(collection), as, collection)
(urllib.quote(collection), weburl, weburl, urllib.quote_plus(collection), as, collection)
def print_search_info(p, f, sf, so, sp, of, ot, collection=cdsname, nb_found=-1, jrec=1, rg=10, as=0, p1="", p2="", p3="", f1="", f2="", f3="", m1="", m2="", m3="", op1="", op2="", d1y="", d1m="", d1d="", d2y="", d2m="", d2d="", cpu_time=-1, middle_only=0): """Prints stripe with the information on 'collection' and 'nb_...
fullname_last_dot_postition = fullname.rfind(".")
if fullname.endswith(".gz"): fullname_last_dot_postition = fullname[:-3].rfind(".") else: fullname_last_dot_postition = fullname.rfind(".")
def BuildFileList(self): """lists all files attached to the bibdoc""" self.docfiles = [] if os.path.exists(self.basedir): for fil in os.listdir(self.basedir): if fil != ".recid" and fil != ".docid" and fil != "." and fil != "..": filepath = "%s/%s" % (self.basedir,fil) fileversion = re.sub(".*;","",fil) fullname = fil....
mess = _("Supplied email address %s already exists in the database.") % args['p_email']
mess = _("Supplied email address %s already exists in the database.") % args['email']
def change(self, req, form): args = wash_urlargd(form, { 'nickname': (str, None), 'email': (str, None), 'password': (str, None), 'password2': (str, None), 'login_method': (str, "") }) uid = webuser.getUid(req)
You may want to <A href="../"> start a new search</A>
def perform_display_account(req,data,bask,aler,sear): uid = getUid(req) #your account if isGuestUser(uid): user ="guest" accBody = """You are logged in as guest. You may want to <A href="../youraccount.py/login">login</A> as a regular user <BR><BR> You may want to <A href="../"> start a new search</A> """ bask=aler="""...
accBody ="""You are logged in as %s. You may want to <A href="../youraccount.py/logout">logout</A><BR><BR> You may want to <A href="../"> start a new search</A> """%user
accBody ="""You are logged in as %s. You may want to a) <A href="../youraccount.py/logout">logout</A>; b) edit your <A href="../youraccount.py/set">email address or password.<BR><BR> """%user
def perform_display_account(req,data,bask,aler,sear): uid = getUid(req) #your account if isGuestUser(uid): user ="guest" accBody = """You are logged in as guest. You may want to <A href="../youraccount.py/login">login</A> as a regular user <BR><BR> You may want to <A href="../"> start a new search</A> """ bask=aler="""...
def print_record_list_for_similarity_boxen(req, title, recID_score_list, ln=cdslang, search_pattern=''): """Print list of records in the "hs" (HTML Similarity) format for similarity boxes. FIXME: templatize. """ uid = getUid(req) recID_score_list_to_be_printed = [] nb_records_to_be_printed = 0 nb_records_seen = 0 wh...
def print_record_list_for_similarity_boxen(req, title, recID_score_list, ln=cdslang, search_pattern=''): """Print list of records in the "hs" (HTML Similarity) format for similarity boxes. FIXME: templatize. """ # get user id (for formatting based on priviledge) uid = getUid(req) recID_score_list_to_be_printed = [] # ...
low = get_date(limits[0])
low = get_datetime(limits[0])
def get_date_range(var): "Returns the two dates contained as a low,high tuple" limits = string.split(var, ",") if len(limits)==1: low = get_date(limits[0]) return low,None if len(limits)==2: low = get_date(limits[0]) high = get_date(limits[1]) return low,high
low = get_date(limits[0]) high = get_date(limits[1])
low = get_datetime(limits[0]) high = get_datetime(limits[1])
def get_date_range(var): "Returns the two dates contained as a low,high tuple" limits = string.split(var, ",") if len(limits)==1: low = get_date(limits[0]) return low,None if len(limits)==2: low = get_date(limits[0]) high = get_date(limits[1]) return low,high
'p' is assumed already being a ``basic search unit'' so that it is search as such and is not broken up in any way. Only
'p' is assumed to be already a ``basic search unit'' so that it is searched as such and is not broken up in any way. Only
def search_unit(p, f=None, m=None): """Search for basic search unit defined by pattern 'p' and field 'f' and matching type 'm'. Return hitset of recIDs. All the parameters are assumed to have been previously washed. 'p' is assumed already being a ``basic search unit'' so that it is search as such and is not broken up...
for coll in results_final.keys(): if results_final[coll]._nbhits:
colls_to_search.extend(results_final.keys()) for coll in colls_to_search: if results_final.has_key(coll) and results_final[coll]._nbhits:
def perform_request_search(req=None, cc=cdsname, c=None, p="", f="", rg="10", sf="", so="d", sp="", of="id", ot="", as="0", p1="", f1="", m1="", op1="", p2="", f2="", m2="", op2="", p3="", f3="", m3="", sc="0", jrec="0", recid="-1", recidb="-1", sysno="", id="-1", idb="-1", sysnb="", action="SEARCH", d1y="", d1m="", d1...
print files_for_pylinting
def generate_kwalitee_stats_for_some_files(filenames): """Run kwalitee checks on FILENAMES and print results.""" # init kwalitee measurement structure: kwalitee = {} kwalitee['TOTAL'] = {'nb_loc': 0, 'nb_missing_docstrings': 0, 'nb_pychecker_warnings': 0, 'avg_pylint_score': 0, } # print header: print "%(filename)50s %...
idtext = """<a href="submit/sub/access=%(id)s@%(action)s%(doctype)s">%(id)s</a>
idtext = """<a href="submit/sub?access=%(id)s@%(action)s%(doctype)s">%(id)s</a>
def tmpl_yoursubmissions(self, ln, images, weburl, order, doctypes, submissions): """ Displays the list of the user's submissions.
if string.find(p, ":") > 0:
if not f and string.find(p, ":") > 0:
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
browsed_phrases_above = {} browsed_phrases_exact = {} browsed_phrases_below = {}
browsed_phrases = {} browsed_phrases[p] = 1
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
% (bx, escape_string(p), t, n_above)
% (bx, escape_string(p), t, n_fetch)
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
browsed_phrases_above[row[0]] = 1
browsed_phrases[row[0]] = 1
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
query = "SELECT bx.value FROM %s AS bx WHERE bx.value='%s' AND bx.tag LIKE '%s%%' ORDER BY bx.value ASC" \ % (bx, escape_string(p), t) else: query = "SELECT bx.value FROM %s AS bx WHERE bx.value='%s' AND bx.tag='%s' ORDER BY bx.value ASC" \ % (bx, escape_string(p), t)
query = "SELECT bx.value FROM %s AS bx WHERE bx.value>='%s' AND bx.tag LIKE '%s%%' ORDER BY bx.value ASC LIMIT %d" \ % (bx, escape_string(p), t, n_fetch) else: query = "SELECT bx.value FROM %s AS bx WHERE bx.value>='%s' AND bx.tag='%s' ORDER BY bx.value ASC LIMIT %d" \ % (bx, escape_string(p), t, n_fetch)
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
browsed_phrases_exact[row[0]] = 1 if len(t) != 6 or t[-1:]=='%': query = "SELECT bx.value FROM %s AS bx WHERE bx.value>'%s' AND bx.tag LIKE '%s%%' ORDER BY bx.value ASC LIMIT %d" \ % (bx, escape_string(p), t, n_below) else: query = "SELECT bx.value FROM %s AS bx WHERE bx.value>'%s' AND bx.tag='%s' ORDER BY bx.value AS...
browsed_phrases[row[0]] = 1
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
l1 = browsed_phrases_above.keys() l1.sort() l1.reverse() l1 = l1[:n_above] l1.reverse() l2 = browsed_phrases_below.keys() l2.sort() out = [] for phrase in l1[:n_above]: out.append(phrase) if len(browsed_phrases_exact)>0: for phrase in browsed_phrases_exact.keys(): out.append(phrase) else: out.append(p) for phrase in l2...
phrases_out = browsed_phrases.keys() phrases_out.sort(lambda x, y: cmp(string.lower(strip_accents(x)), string.lower(strip_accents(y)))) try: idx_p = phrases_out.index(p) except: idx_p = len(phrases_out)/2 return phrases_out[max(0,idx_p-n_above):idx_p+n_below]
def get_nearest_terms_in_bibxxx(p, f, n_below, n_above): """Browse (-n_above, +n_below) closest bibliographic phrases for the given pattern p in the given field f, regardless of collection. Return list of [phrase1, phrase2, ... , phrase_n].""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':...
if string.find(p, ":") > 0:
if not f and string.find(p, ":") > 0:
def get_nbhits_in_bibxxx(p, f): """Return number of hits for word 'word' inside words index for field 'f'.""" ## determine browse field: if string.find(p, ":") > 0: # does 'p' contain ':'? f, p = split(p, ":", 1) ## wash 'p' argument: p = re_quotes.sub("", p) ## construct 'tl' which defines the tag list (MARC tags) to ...
y = unicode(x, "utf-8")
try: y = unicode(x, "utf-8") except: return x
def strip_accents(x): """Strip accents in the input phrase X by replacing UTF-8 accented characters by their unaccented cousins. For exmple, replace é by e.""" y = unicode(x, "utf-8") # asciify lowercase: y = sre.sub(unicode(r"(?u)[áàäâã]", "utf-8"), "a", y) y = sre.sub(unicode(r"(?u)[éèëê]", "utf-8"), "e", y) y = sre...
urlargs = string.replace(req.args, "action=%s","action=%s" % (msg_search[ln], msg_browse[ln])) req.write(create_nearest_terms_box(urlargs, p, f, 'w', ln=ln))
urlargs = string.replace(req.args, "action=%s" % msg_search[ln],"action=%s" % msg_browse[ln]) req.write(create_nearest_terms_box(urlargs, p, f, 'w', ln=ln, intro_text_p=0))
def browse_in_bibwords(req, p, f, ln=cdslang): """Browse inside words indexes.""" if not p: return req.write("<p>Words nearest to <em>%s</em> " % p) if f: req.write(" inside <em>%s</em> " % f) req.write(" in any collection are:<br>") urlargs = string.replace(req.args, "action=%s","action=%s" % (msg_search[ln], msg_brow...
def create_nearest_terms_box(urlargs, p, f, t='w', n=5, ln=cdslang):
def create_nearest_terms_box(urlargs, p, f, t='w', n=5, ln=cdslang, intro_text_p=1):
def create_nearest_terms_box(urlargs, p, f, t='w', n=5, ln=cdslang): """Return text box containing list of 'n' nearest terms above/below 'p' for the field 'f' for matching type 't' (words/phrases) in language 'ln'. Propose new searches according to `urlargs' with the new words. """ out = "" nearest_terms = [] if not p:...
return "%s%s%s.%s" % (prologue, msg_no_words_index_available[ln], f, epilogue)
return "%s%s." % (msg_no_words_index_available[ln], f)
def create_nearest_terms_box(urlargs, p, f, t='w', n=5, ln=cdslang): """Return text box containing list of 'n' nearest terms above/below 'p' for the field 'f' for matching type 't' (words/phrases) in language 'ln'. Propose new searches according to `urlargs' with the new words. """ out = "" nearest_terms = [] if not p:...
return "%s%s %s.%s" % (prologue, msg_no_phrase_index_available[ln], f, epilogue)
return "%s %s." % (msg_no_phrase_index_available[ln], f)
def create_nearest_terms_box(urlargs, p, f, t='w', n=5, ln=cdslang): """Return text box containing list of 'n' nearest terms above/below 'p' for the field 'f' for matching type 't' (words/phrases) in language 'ln'. Propose new searches according to `urlargs' with the new words. """ out = "" nearest_terms = [] if not p:...
intro = msg_search_term[ln] % p if f: intro += " " + msg_inside_index[ln] % f intro += " " + msg_did_not_match[ln]
intro = "" if intro_text_p: intro = msg_search_term[ln] % p if f: intro += " " + msg_inside_index[ln] % f intro += " " + msg_did_not_match[ln]
def create_nearest_terms_box(urlargs, p, f, t='w', n=5, ln=cdslang): """Return text box containing list of 'n' nearest terms above/below 'p' for the field 'f' for matching type 't' (words/phrases) in language 'ln'. Propose new searches according to `urlargs' with the new words. """ out = "" nearest_terms = [] if not p:...
return escape_string(compress(dumps(obj)))
return escape_string(compress(marshal.dumps(obj)))
def serialize_via_marshal(obj): """Serialize Python object via marshal into a compressed string.""" return escape_string(compress(dumps(obj)))
return loads(decompress(string))
return marshal.loads(decompress(string))
def deserialize_via_marshal(string): """Decompress and deserialize string into a Python object via marshal.""" return loads(decompress(string))
error = record_add_field(record, '001', '', '', rec_id)
error = record_add_field(record, '001', '', '', rec_id, [], 0)
def bibupload(record): """Main function: process a record and fit it in the tables bibfmt, bibrec, bibrec_bibxxx, bibxxx with proper record metadata. Return (error_code, recID) of the processed record. """ error = None #If there are special tags to proceed check if it exists in the record if options['tag'] != None and...
query = """SHOW TABLES like %s""" params = (table_name,) try: res = run_sql(query, params) except Error, error: write_message(" Error during the insert_record_bibxxx function : %s " % error, verbose=1, stream=sys.stderr) if len(res): pass else: if options['verbose'] >= 1: print 'create table'
def insert_record_bibxxx(tag, value): """Insert the record into bibxxx""" #determine into which table one should insert the record table_name = 'bib'+tag[0:2]+'x' #check if the table exists in the database query = """SHOW TABLES like %s""" params = (table_name,) try: res = run_sql(query, params) except Error, error: w...
query = """SHOW TABLES like '%s'""" params = (full_table_name) try: res = run_sql(query % params) except Error, error: write_message(" Error during the insert_record_bibrec_bibxxx function 1st query: %s " % error, verbose=1, stream=sys.stderr) if len(res): pass else: print 'create table', full_table_name
def insert_record_bibrec_bibxxx(table_name, id_bibxxx, field_number, id_bibrec): """Insert the record into bibrec_bibxxx""" #determine into which table one should insert the record full_table_name = 'bibrec_'+ table_name #check if the table exists in the database query = """SHOW TABLES like '%s'""" params = (full_tabl...
if tag in CFG_BIBUPLOAD_CONTROLFIELD_TAGS and tag != "001":
if tag in CFG_BIBUPLOAD_SPECIAL_TAGS: pass elif tag in CFG_BIBUPLOAD_CONTROLFIELD_TAGS and tag != "001":
def update_database_with_metadata(record, rec_id): """Update the database tables with the record and the record id given in parameter""" for tag in record.keys(): # check if tag is not a control field : tag not in CFG_BIBUPLOAD_CONTROLFIELD_TAGS and if tag not in CFG_BIBUPLOAD_SPECIAL_TAGS: # for each tag there is a li...
table_name = 'bibrec_bib'+tag[0:2]+'x' query = """DELETE FROM `%s` where id_bibrec = %s""" params = (table_name, id_bibrec) try: run_sql(query % params) except Error, error: write_message(" Error during the delete_bibrec_bibxxx function : %s " % error, verbose=1, stream=sys.stderr)
if tag not in CFG_BIBUPLOAD_SPECIAL_TAGS: table_name = 'bibrec_bib'+tag[0:2]+'x' query = """DELETE FROM `%s` where id_bibrec = %s""" params = (table_name, id_bibrec) try: run_sql(query % params) except Error, error: write_message(" Error during the delete_bibrec_bibxxx function : %s " % error, verbose=1, stream=sys...
def delete_bibrec_bibxxx(record, id_bibrec): """Delete the database record from the table bibxxx given in parameters""" # we clear all the rows from bibrec_bibxxx from the old record for tag in record.keys(): # for each name construct the bibrec_bibxxx table name table_name = 'bibrec_bib'+tag[0:2]+'x' # delete all the ...
return run_sql("UPDATE schTASK SET progress=%s where id=%s", (msg, options["task"]))
return run_sql("UPDATE schTASK SET progress=%s WHERE id=%s", (msg, options["task"]))
def task_update_progress(msg): """Updates progress information in the BibSched task table.""" global options if options["verbose"] >= 9: write_message("Updating task progress to %s." % msg) return run_sql("UPDATE schTASK SET progress=%s where id=%s", (msg, options["task"]))
return run_sql("UPDATE schTASK SET status=%s where id=%s", (val, options["task"]))
return run_sql("UPDATE schTASK SET status=%s WHERE id=%s", (val, options["task"]))
def task_update_status(val): """Updates status information in the BibSched task table.""" global options if options["verbose"] >= 9: write_message("Updating task status to %s." % val) return run_sql("UPDATE schTASK SET status=%s where id=%s", (val, options["task"]))
error = update_bibfmt_format(rec_id, rec_xml_new, 'xm')
if options['mode'] != 'format': error = update_bibfmt_format(rec_id, rec_xml_new, 'xm')
def bibupload(record): """Main function: process a record and fit it in the tables bibfmt, bibrec, bibrec_bibxxx, bibxxx with proper record metadata. Return (error_code, recID) of the processed record. """ error = None #If there are special tags to proceed check if it exists in the record if options['tag'] != None and...
print """Receive a MARC XML file and update the appropriate database tables according to options
print """Receive MARC XML file and update appropriate database tables according to options.
def usage(): """Print help""" print """Receive a MARC XML file and update the appropriate database tables according to options Usage: bibupload [options] input.xml Examples: $ bibupload -i input.xml Options: Input: -a --append : new fields are appended to the existing record -c --correct : fields are replaced by ...
Input: -a --append : new fields are appended to the existing record -c --correct : fields are replaced by the new ones in the existing record -f --format : takes only the FMT fields into account. Does not update -i --insert : insert the new record in the database -r --replace : the existing record is entirely repla...
-a, --append new fields are appended to the existing record -c, --correct fields are replaced by the new ones in the existing record -f, --format takes only the FMT fields into account. Does not update -i, --insert insert the new record in the database -r, --replace ...
def usage(): """Print help""" print """Receive a MARC XML file and update the appropriate database tables according to options Usage: bibupload [options] input.xml Examples: $ bibupload -i input.xml Options: Input: -a --append : new fields are appended to the existing record -c --correct : fields are replaced by ...
-h, --help print this help and exit -v, --verbose=LEVEL verbose level (from 0 to 9, default 1) -n --notimechange : do not change record last modification date when updating -V --version : print the script version
-h, --help print this help and exit -v, --verbose=LEVEL verbose level (from 0 to 9, default 1) -V --version print the script version
def usage(): """Print help""" print """Receive a MARC XML file and update the appropriate database tables according to options Usage: bibupload [options] input.xml Examples: $ bibupload -i input.xml Options: Input: -a --append : new fields are appended to the existing record -c --correct : fields are replaced by ...
query = """SELECT id FROM bibrec where id = %s"""
query = """SELECT id FROM bibrec WHERE id = %s"""
def find_record_bibrec(rec_id): """ receives the record ID and returns if this record exist in bibrec """ query = """SELECT id FROM bibrec where id = %s""" params = (rec_id,) try: res = run_sql(query, params) except Error, error: write_message(" Error during find_record_bibrec function : %s " % error, verbose=1, stre...
query = """SELECT count(id) FROM bibfmt where id_bibrec = %s and format = %s"""
out = 0 query = """SELECT COUNT(id) FROM bibfmt WHERE id_bibrec=%s AND format=%s"""
def find_record_format(rec_id, format): """ receives the record ID and returns if this record exist in bibrec """ query = """SELECT count(id) FROM bibfmt where id_bibrec = %s and format = %s""" params = (rec_id, format) try: res = run_sql(query, params) except Error, error: write_message(" Error during find_record_fo...
if len(res): return res[0] else: return None
return out
def find_record_format(rec_id, format): """ receives the record ID and returns if this record exist in bibrec """ query = """SELECT count(id) FROM bibfmt where id_bibrec = %s and format = %s""" params = (rec_id, format) try: res = run_sql(query, params) except Error, error: write_message(" Error during find_record_fo...
query = """SELECT id_bibrec FROM bibfmt where value = %s"""
query = """SELECT id_bibrec FROM bibfmt WHERE value = %s"""
def find_record_bibfmt(marc): """ receives the xmlmarc containing a record and returns the id in bibrec if the record exists in bibfmt""" # compress the marc value pickled_marc = MySQLdb.escape_string(compress(marc)) query = """SELECT id_bibrec FROM bibfmt where value = %s""" # format for marc xml is xm params = (pick...
query = """SELECT DISTINCT id FROM `%s` where value = '%s'"""
query = """SELECT DISTINCT id FROM `%s` WHERE value = '%s'"""
def find_record_from_sysno(sysno): """receive the sysno number and return the record id""" table_name = 'bib'+cfg_bibupload_external_sysno_tag[0:2]+'x' query = """SELECT DISTINCT id FROM `%s` where value = '%s'""" params = (table_name, sysno) try: res = run_sql(query % params) except Error, error: write_message(" Err...
query = """SELECT DISTINCT id_bibrec FROM `%s` where id_bibxxx = '%s'"""
query = """SELECT DISTINCT id_bibrec FROM `%s` WHERE id_bibxxx = '%s'"""
def find_record_from_sysno(sysno): """receive the sysno number and return the record id""" table_name = 'bib'+cfg_bibupload_external_sysno_tag[0:2]+'x' query = """SELECT DISTINCT id FROM `%s` where value = '%s'""" params = (table_name, sysno) try: res = run_sql(query % params) except Error, error: write_message(" Err...
for tag in record.keys(): if tag == tag_number: return record[tag]
return record.get(tag_number, None)
def extract_tag_from_record(record, tag_number): """ Extract the recordId """ # first step verify if the record is not already in the database if record: for tag in record.keys(): #Check the recordId if tag == tag_number: return record[tag] return None
query = """SELECT id FROM %s """ % table_name query += """ WHERE tag = %s and value = %s"""
query = """SELECT id FROM %s """ % table_name query += """ WHERE tag=%s AND value=%s"""
def insert_record_bibxxx(tag, value): """Insert the record into bibxxx""" #determine into which table one should insert the record table_name = 'bib'+tag[0:2]+'x' #check if the table exists in the database query = """SHOW TABLES like %s""" params = (table_name,) try: res = run_sql(query, params) except Error, error: w...
tuple_list = None tuple_list = extract_tag_from_record(record, 'FMT') if tuple_list != None: for single_tuple in tuple_list: f_value = single_tuple[0][0][1] g_value = single_tuple[0][1][1]
fmt_fields = record_get_field_instances(record, 'FMT') if fmt_fields: for fmt_field in fmt_fields: try: f_value = field_get_subfield_values(fmt_field, "f")[0] except IndexError: f_value = "" try: g_value = field_get_subfield_values(fmt_field, "g")[0] except IndexError: g_value = ""
def insert_fmt_tags(record, rec_id): """Process and insert FMT tags""" tuple_list = None tuple_list = extract_tag_from_record(record, 'FMT') #If there is a FMT TAG :) if tuple_list != None: for single_tuple in tuple_list: # Get the inside of the FMT file f_value = single_tuple[0][0][1] g_value = single_tuple[0][1][1] ...