rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
_task_params = {key : value}
_TASK_PARAMS = {key : value}
def task_set_task_param(key, value): """Set the value corresponding to the particular task param""" global _task_params try: _task_params[key] = value except NameError: _task_params = {key : value}
(msg, _task_params["task_id"]))
(msg, _TASK_PARAMS["task_id"]))
def task_update_progress(msg): """Updates progress information in the BibSched task table.""" write_message("Updating task progress to %s." % msg, verbose=9) return run_sql("UPDATE schTASK SET progress=%s where id=%s", (msg, _task_params["task_id"]))
(val, _task_params["task_id"]))
(val, _TASK_PARAMS["task_id"]))
def task_update_status(val): """Updates status information in the BibSched task table.""" write_message("Updating task status to %s." % val, verbose=9) return run_sql("UPDATE schTASK SET status=%s where id=%s", (val, _task_params["task_id"]))
(_task_params['task_id'],), 1)
(_TASK_PARAMS['task_id'],), 1)
def task_read_status(): """Read status information in the BibSched task table.""" res = run_sql("SELECT status FROM schTASK where id=%s", (_task_params['task_id'],), 1) try: out = res[0][0] except: out = 'UNKNOWN' return out
if msg and _task_params['verbose'] >= verbose:
if msg and _TASK_PARAMS['verbose'] >= verbose:
def write_message(msg, stream=sys.stdout, verbose=1): """Write message and flush output stream (may be sys.stdout or sys.stderr). Useful for debugging stuff.""" if msg and _task_params['verbose'] >= verbose: if stream == sys.stdout: logging.info(msg) elif stream == sys.stderr: logging.error(msg) else: sys.stderr.write(...
_task_params['user'] = authenticate(_task_params["user"], authorization_action, authorization_msg)
_TASK_PARAMS['user'] = authenticate(_TASK_PARAMS["user"], authorization_action, authorization_msg)
def _task_submit(argv, authorization_action, authorization_msg): """Submits task to the BibSched task queue. This is what people will be invoking via command line.""" ## check as whom we want to submit? check_running_process_user() ## sanity check: remove eventual "task" option: ## authenticate user: _task_params['...
if _task_params['task_specific_name']: task_name = '%s:%s' % (_task_params['task_name'], _task_params['task_specific_name'])
if _TASK_PARAMS['task_specific_name']: task_name = '%s:%s' % (_TASK_PARAMS['task_name'], _TASK_PARAMS['task_specific_name'])
def _task_submit(argv, authorization_action, authorization_msg): """Submits task to the BibSched task queue. This is what people will be invoking via command line.""" ## check as whom we want to submit? check_running_process_user() ## sanity check: remove eventual "task" option: ## authenticate user: _task_params['...
task_name = _task_params['task_name']
task_name = _TASK_PARAMS['task_name']
def _task_submit(argv, authorization_action, authorization_msg): """Submits task to the BibSched task queue. This is what people will be invoking via command line.""" ## check as whom we want to submit? check_running_process_user() ## sanity check: remove eventual "task" option: ## authenticate user: _task_params['...
_task_params['task_id'] = run_sql("""INSERT INTO schTASK (proc,user,
_TASK_PARAMS['task_id'] = run_sql("""INSERT INTO schTASK (proc,user,
def _task_submit(argv, authorization_action, authorization_msg): """Submits task to the BibSched task queue. This is what people will be invoking via command line.""" ## check as whom we want to submit? check_running_process_user() ## sanity check: remove eventual "task" option: ## authenticate user: _task_params['...
(task_name, _task_params['user'], _task_params["runtime"], _task_params["sleeptime"], marshal.dumps(argv), _task_params['priority']))
(task_name, _TASK_PARAMS['user'], _TASK_PARAMS["runtime"], _TASK_PARAMS["sleeptime"], marshal.dumps(argv), _TASK_PARAMS['priority']))
def _task_submit(argv, authorization_action, authorization_msg): """Submits task to the BibSched task queue. This is what people will be invoking via command line.""" ## check as whom we want to submit? check_running_process_user() ## sanity check: remove eventual "task" option: ## authenticate user: _task_params['...
write_message("Task return _task_params['task_id']
write_message("Task return _TASK_PARAMS['task_id']
def _task_submit(argv, authorization_action, authorization_msg): """Submits task to the BibSched task queue. This is what people will be invoking via command line.""" ## check as whom we want to submit? check_running_process_user() ## sanity check: remove eventual "task" option: ## authenticate user: _task_params['...
'bibsched_task_%d.pid' % _task_params['task_id'])
'bibsched_task_%d.pid' % _TASK_PARAMS['task_id'])
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
(_task_params['task_id'], task_status), sys.stderr)
(_TASK_PARAMS['task_id'], task_status), sys.stderr)
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
if _task_params['runtime_limit'] is not None and os.environ.get('BIBSCHED_MODE', 'manual') != 'manual': if not _task_params['runtime_limit'][0][0] <= time_now <= _task_params['runtime_limit'][0][1]: if time_now <= _task_params['runtime_limit'][0][0]: new_runtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_task...
if _TASK_PARAMS['runtime_limit'] is not None and os.environ.get('BIBSCHED_MODE', 'manual') != 'manual': if not _TASK_PARAMS['runtime_limit'][0][0] <= time_now <= _TASK_PARAMS['runtime_limit'][0][1]: if time_now <= _TASK_PARAMS['runtime_limit'][0][0]: new_runtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_TASK...
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
new_runtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_task_params['runtime_limit'][1][0])) progress = run_sql("SELECT progress FROM schTASK WHERE id=%s", (_task_params['task_id'], ))
new_runtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(_TASK_PARAMS['runtime_limit'][1][0])) progress = run_sql("SELECT progress FROM schTASK WHERE id=%s", (_TASK_PARAMS['task_id'], ))
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
run_sql("UPDATE schTASK SET runtime=%s, status='WAITING', progress=%s WHERE id=%s", (new_runtime, 'Postponed %d time(s)' % (postponed_times + 1), _task_params['task_id'])) write_message("Task
run_sql("UPDATE schTASK SET runtime=%s, status='WAITING', progress=%s WHERE id=%s", (new_runtime, 'Postponed %d time(s)' % (postponed_times + 1), _TASK_PARAMS['task_id'])) write_message("Task
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
_task_params['task_starting_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) sleeptime = _task_params['sleeptime']
_TASK_PARAMS['task_starting_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) sleeptime = _TASK_PARAMS['sleeptime']
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
run_sql("UPDATE schTASK SET runtime=%s, status='WAITING', progress='' WHERE id=%s", (new_runtime, _task_params['task_id'])) write_message("Task
run_sql("UPDATE schTASK SET runtime=%s, status='WAITING', progress='' WHERE id=%s", (new_runtime, _TASK_PARAMS['task_id'])) write_message("Task
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
run_sql("UPDATE schTASK SET status='WAITING', progress='' WHERE id=%s", (_task_params['task_id'], )) write_message("Task
run_sql("UPDATE schTASK SET status='WAITING', progress='' WHERE id=%s", (_TASK_PARAMS['task_id'], )) write_message("Task
def _task_run(task_run_fnc): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. @param task_run_fnc: will be called as the main core function. Must return...
if self.status: (auth_code, auth_message) = acc_authorize_action(req, 'viewrestrdoc', status=self.status)
if os.path.exists(self.fullpath): if random.random() < CFG_BIBDOCFILE_MD5_CHECK_PROBABILITY and calculate_md5(self.fullpath) != self.checksum: raise InvenioWebSubmitFileError, "File %s, version %i, for record %s is corrupted!" % (self.fullname, self.version, self.recid) stream_file(req, self.fullpath, "%s%s" % (self.na...
def stream(self, req): """Stream the file.""" if self.status: (auth_code, auth_message) = acc_authorize_action(req, 'viewrestrdoc', status=self.status) else: auth_code = 0 if auth_code == 0: if os.path.exists(self.fullpath): if random.random() < CFG_BIBDOCFILE_MD5_CHECK_PROBABILITY and calculate_md5(self.fullpath) != s...
auth_code = 0 if auth_code == 0: if os.path.exists(self.fullpath): if random.random() < CFG_BIBDOCFILE_MD5_CHECK_PROBABILITY and calculate_md5(self.fullpath) != self.checksum: raise InvenioWebSubmitFileError, "File %s, version %i, for record %s is corrupted!" % (self.fullname, self.version, self.recid) stream_file(req,...
req.status = apache.HTTP_NOT_FOUND raise InvenioWebSubmitFileError, "%s does not exists!" % self.fullpath
def stream(self, req): """Stream the file.""" if self.status: (auth_code, auth_message) = acc_authorize_action(req, 'viewrestrdoc', status=self.status) else: auth_code = 0 if auth_code == 0: if os.path.exists(self.fullpath): if random.random() < CFG_BIBDOCFILE_MD5_CHECK_PROBABILITY and calculate_md5(self.fullpath) != s...
my_new_bibdoc.add_icon( CFG_PREFIX + '/lib/webtest/invenio/icon-test.gif', basename=None, format=None)
my_new_bibdoc.add_icon( CFG_PREFIX + '/lib/webtest/invenio/icon-test.gif')
def test_BibDocs(self): """bibdocfile - BibDocs functions""" #add file my_bibrecdoc = BibRecDocs(2) my_bibrecdoc.add_new_file(CFG_PREFIX + '/lib/webtest/invenio/test.jpg', 'Main', 'img_test', False, 'test add new file', 'test', '.jpg') my_new_bibdoc = my_bibrecdoc.get_bibdoc("img_test") value = my_bibrecdoc.list_bibdoc...
out += "\n"
def filter_hidden_fields(recxml, user_info=None, filter_tags=CFG_BIBFORMAT_HIDDEN_TAGS, force_filtering=False): """ Filter out tags specified by filter_tags from MARCXML. If the user is allowed to run bibedit, then filter nothing, unless force_filtering is set to True. @param recxml: marcxml presentation of the record...
error_msg = _("The user '%s' is not authorized to modify collection '%s'" % (user_info['nickname'], filename_tag980_value))
error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \ {'x_user': user_info['nickname'], 'x_coll': filename_tag980_value}
def _check_client_can_submit_file(client_ip="", metafile="", req=None, webupload=0, ln=CFG_SITE_LANG): """ Is this client able to upload such a FILENAME? check 980 $a values and collection tags in the file to see if they are among the permitted ones as specified by CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS and ACC_AUTHORIZE_A...
error_msg = _("The user '%s' is not authorized to modify collection '%s'" % (user_info['nickname'], filename_rec_id_collection))
error_msg = _("The user '%(x_user)s' is not authorized to modify collection '%(x_coll)s'") % \ {'x_user': user_info['nickname'], 'x_coll': filename_rec_id_collection}
def _check_client_can_submit_file(client_ip="", metafile="", req=None, webupload=0, ln=CFG_SITE_LANG): """ Is this client able to upload such a FILENAME? check 980 $a values and collection tags in the file to see if they are among the permitted ones as specified by CFG_BATCHUPLOADER_WEB_ROBOT_RIGHTS and ACC_AUTHORIZE_A...
out += "</td>"
out += "</td><td>"
def tmpl_action_page(self, ln, uid, guest, pid, now, doctype, description, docfulldesc, snameCateg, lnameCateg, actionShortDesc, indir, statustext): """ Recursive function that produces a catalog's HTML display
out += "<script>checked=1;</script>" out += """<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
out += '<td><script type="text/javascript">checked=1;</script>' out += """&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
def tmpl_action_page(self, ln, uid, guest, pid, now, doctype, description, docfulldesc, snameCateg, lnameCateg, actionShortDesc, indir, statustext): """ Recursive function that produces a catalog's HTML display
except ValueError, e:
except ValueError:
def remove_auto_cites(dic): """Remove auto-cites and dedupe.""" for key in dic.keys(): new_list = dic.fromkeys(dic[key]).keys() try: new_list.remove(key) except ValueError, e: pass dic[key] = new_list return dic
date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
def del_recids(rank_method_code, range_rec): """Delete some records from the rank method""" id = run_sql("SELECT id from rnkMETHOD where name=%s", (rank_method_code, )) res = run_sql("SELECT relevance_data FROM rnkMETHODDATA WHERE id_rnkMETHOD=%s", (id[0][0], )) if res: rec_dict = deserialize_via_marshal(res[0][0]) wri...
sets = {}
def bibrank_engine(run): """Run the indexing task. Return 1 in case of success and 0 in case of failure. """ try: import psyco psyco.bind(single_tag_rank) psyco.bind(single_tag_rank_method_exec) psyco.bind(serialize_via_marshal) psyco.bind(deserialize_via_marshal) except StandardError, e: pass startCreate = time.time...
except Exception, e:
except Exception:
def add_recIDs_by_date(rank_method_code, dates=""): """Return recID range from records modified between DATES[0] and DATES[1]. If DATES is not set, then add records modified since the last run of the ranking method RANK_METHOD_CODE. """ if not dates: try: dates = (get_lastupdated(rank_method_code), '') except Exception...
except Exception, e:
except Exception:
def getName(rank_method_code, ln=CFG_SITE_LANG, type='ln'): """Returns the name of the method if it exists""" try: rnkid = run_sql("SELECT id FROM rnkMETHOD where name=%s", (rank_method_code, )) if rnkid: rnkid = str(rnkid[0][0]) res = run_sql("SELECT value FROM rnkMETHODNAME where type=%s and ln=%s and id_rnkMETHOD=%...
def format(bfo, indico_seminar_xml="http://indico.cern.ch/tools/export.py?fid=1l7&amp;date=today&amp;days=1&amp;of=xml"):
def format(bfo, indico_seminar_xml="http://indico.cern.ch/tools/export.py?fid=1l7&date=today&days=1&of=xml"):
def format(bfo, indico_seminar_xml="http://indico.cern.ch/tools/export.py?fid=1l7&amp;date=today&amp;days=1&amp;of=xml"): """ Display the list of seminar from the given Indico XML URL @param indico_seminar_xml: the URL to the XML generated by an Indico instance """ args = parse_url_string(bfo.user_info['uri']) journal...
recids1 = search_pattern(p=oaiId, f=CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG, m='e').tolist() repnumber = oaiId.split(":")[-1] recids2 = search_pattern(p = repnumber, f = "reportnumber", m = 'e' ).tolist() repnumber = "arXiv:" + oaiId.split(":")[-1] recids3 = search_pattern(p = repnumber, f = "reportnumber", m = 'e' ).toli...
if oaiId: recids = search_pattern(p=oaiId, f=CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG, m='e') repnumber = oaiId.split(":")[-1] if repnumber: recids |= search_pattern(p = repnumber, f = "reportnumber", m = 'e' ) repnumber = "arXiv:" + oaiId.split(":")[-1] recids |= search_pattern(p = repnumber, f = "reportnumber", m = 'e'...
def find_record_ids_by_oai_id(oaiId): """ A method finding the records identifier provided the oai identifier returns a list of identifiers matching a given oai identifier """ # Is this record already in invenio (matching by oaiid) recids1 = search_pattern(p=oaiId, f=CFG_BIBUPLOAD_EXTERNAL_OAIID_TAG, m='e').tolist() # ...
assert(_add_new_format(bibdoc, url, format, docname, description, doctype, newname, description, comment, flags))
assert(_add_new_format(bibdoc, url, format, docname, doctype, newname, description, comment, flags))
def _update_description_and_comment(bibdoc, docname, format, description, comment, flags): """Directly update comments and descriptions.""" write_message('Just updating description and comment for %s with format %s with description %s, comment %s and flags %s' % (docname, format, description, comment, flags), verbose=9...
assert(_add_new_format(bibdoc, url, format, docname, doctype, newname, description, comment))
assert(_add_new_format(bibdoc, url, format, docname, doctype, newname, description, comment, flags))
def _update_description_and_comment(bibdoc, docname, format, description, comment, flags): """Directly update comments and descriptions.""" write_message('Just updating description and comment for %s with format %s with description %s, comment %s and flags %s' % (docname, format, description, comment, flags), verbose=9...
print " <controlfield tag=\"%s\">%s</controlfield>" % (tag,instance_to_print)
if not (tag == "001" and int(self.sysno) == int(instance_to_print)): print " <controlfield tag=\"%s\">%s</controlfield>" % (tag,instance_to_print)
def display(self, filehandle): "Displays record in the xml format."
elif opt[0] in ("-r", "--latex-template-var"):
elif opt[0] in ("-c", "--latex-template-var"):
def get_cli_options(): """From the options and arguments supplied by the user via the CLI, build a dictionary of options to drive websubmit-file-stamper. For reference, the CLI options available to the user are as follows: -h, --help -> Display help/usage message and exit; -V, --version ->...
re.compile(r'^(\s*\.?,?\s*:?\s\<cds\.VOL\>(\d+)\<\/cds\.VOL> \<cds\.YR\>\(([1-2]\d\d\d)\)\<\/cds\.YR\> \<cds\.PG\>([RL]?\d+[c]?)\<\/cds\.PG\>)', re.UNICODE)
re.compile(r'^(\s*\.?,?\s*:?\s\<cds\.VOL\>(\d+|(?:\d+\-\d+))\<\/cds\.VOL> \<cds\.YR\>\(([1-2]\d\d\d)\)\<\/cds\.YR\> \<cds\.PG\>([RL]?\d+[c]?)\<\/cds\.PG\>)', re.UNICODE)
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
^((\s*;\s*|\s+and\s+):?\s \<cds\.VOL\>(\d+)\<\/cds\.VOL>\s \<cds\.YR\>\(([12]\d{3})\)\<\/cds\.YR\>\s \<cds\.PG\>([RL]?\d+[c]?)\<\/cds\.PG\>)
^((\s*;\s*|\s+and\s+):?\s \<cds\.VOL\>(\d+|(?:\d+\-\d+))\<\/cds\.VOL>\s \<cds\.YR\>\(([12]\d{3})\)\<\/cds\.YR\>\s \<cds\.PG\>([RL]?\d+[c]?)\<\/cds\.PG\>)
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
(\b[Vv]o?l?\.?|\b[Nn]o\.?)?\s?(\d+)
(\b[Vv]o?l?\.?|\b[Nn]o\.?)?\s?(\d+|(?:\d+\-\d+))
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
(\b[Vv]o?l?\.?|\b[Nn]o\.?)?\s?(?<!(?:\/|\d))(\d+)\s?
(\b[Vv]o?l?\.?|\b[Nn]o\.?)?\s?(?<!(?:\/|\d))(\d+|(?:\d+\-\d+))\s?
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
([Vv]o?l?\.?|[Nn]o\.?)?\s?(?<!(?:\/|\d))(\d+)\s?
([Vv]o?l?\.?|[Nn]o\.?)?\s?(?<!(?:\/|\d))(\d+|(?:\d+\-\d+))\s?
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
(\b|\()(1\d\d\d|20\d\d)\)?(,\s?|\s) ([Vv]o?l?\.?|[Nn]o\.?)?\s?(\d+)[,:\s]\s? [pP]?[p]?\.?\s?
(\b|\()(1\d\d\d|20\d\d)\)?(,\s?|\s) ([Vv]o?l?\.?|[Nn]o\.?)?\s?(\d+|(?:\d+\-\d+))[,:\s]\s? [pP]?[p]?\.?\s?
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
def make_auth_regex_str(author=None):
def make_auth_regex_str(author=None,first_author=None):
def get_bad_char_replacements(): """When a document is converted to plain-text from PDF, certain characters may result in the plain-text, that are either unwanted, or broken. These characters need to be corrected or removed. Examples are, certain control characters that would be illegal in XML and must be removed; TeX ...
author = """
author = u"""
def make_auth_regex_str(author=None): if not author:
([A-Z]((\.\s?)|(\.?\s+))){1,9} ((([A-Z]\w\s)\w+[\-\’'\`]?\w*)|([A-Z]\w+[\-\’'\`]?\w*)) (([,\.]\s*)|([,\.]?\s+))
([A-Z]((\’\s?)|(\.\s?)|(\.?\s+)|(\.?\s?\-))){1,9} ([A-Za-z]\w{1,2}\s)?[A-Z]\w+[\-’'\`]?\w* (([,\.]\s*)|([,\.]?\s+))
def make_auth_regex_str(author=None): if not author:
(^|\s+) (?P<badand> (([Aa][Nn]([Dd]|[Ss])|\&)\s+)
(^|\s+|\() (?P<es> (((eds?|edited|editors?)((\.\s?)|(\.?\s))) |((eds?|edited|editions?)((\.\s?)|(\.?\s))by(\s|([:,]\s))) |(\(\s?(eds?|edited|editors?)((\.\s?)|(\.?\s))?\)))
def make_auth_regex_str(author=None): if not author:
(?P<es> (((ed|edited|editor)((\.\s?)|(\.?\s))) |((ed|edited)((\.\s?)|(\.?\s))by(\s|([:,]\s))) |(\(\s?(ed|edited|editor)((\.\s?)|(\.?\s))?\))) )? %s+
%s (%s)*
def make_auth_regex_str(author=None): if not author:
(?P<ee> (((ed|edited|editor)((\.?\s)|(\.\s?))) |(\((ed|edited|editor)((\.\s)|(\.))?\)))
(?P<et> [Ee][Tt](((,|\.)\s*)|((,|\.)?\s+))[Aa][Ll][,\.]?[,\.]?\s*
def make_auth_regex_str(author=None): if not author:
(?P<et> \s?[Ee][Tt](((,|\.)\s*)|((,|\.)?\s+))[Aa][Ll][,\.]?[,\.]?
(?P<ee> (((eds?|edited|editors?)((\.?\s)|(\.\s?))) |(\((eds?|edited|editors?)((\.\s)|(\.))?\)))
def make_auth_regex_str(author=None): if not author:
""" % (author,author)
\)? """ % (first_author,author,author)
def make_auth_regex_str(author=None): if not author:
(([A-Z]((\.\s?)|(\.?\s+))){1,9}
(([A-Z]((\.\s?)|(\.?\s+)|(\-))){1,9}
def make_auth_regex_str(author=None): if not author:
re_auth_near_miss = (re.compile(make_auth_regex_str(weaker_author),re.VERBOSE|re.UNICODE))
re_auth_near_miss = (re.compile(make_auth_regex_str(weaker_author,weaker_author),re.VERBOSE|re.UNICODE)) bad_etal_before_auth_matches = (' et al.,',' et. al.,',' et. al.',' et.al.,',' et al.',' et al') re_arxiv_notation = re.compile(""" (arxiv)|(e[\-\s]?print:?\s*arxiv) """, re.VERBOSE)
def make_auth_regex_str(author=None): if not author:
"""Given a reference line, attepmt to locate instances of citation
"""Given a reference line, attempt to locate instances of citation
def standardize_and_markup_numeration_of_citations_in_line(line): """Given a reference line, attepmt to locate instances of citation 'numeration' in the line. Upon finding some numeration, re-arrange it into a standard order, and mark it up with tags. Will process numeration in the following order: Delete the colon and...
will be record, and they will be replaced in the working-line
will be recorded, and they will be replaced in the working-line
def identify_preprint_report_numbers(line, preprint_repnum_search_kb, preprint_repnum_standardised_categs): """Attempt to identify all preprint report numbers in a reference line. Report numbers will be identified, their information (location in line, length in line, and standardised replacement version) will be record...
def identify_and_tag_doi(line):
def identify_and_tag_DOI(line):
def identify_and_tag_doi(line): """takes a single citation line and attempts to locate any DOI references. DOI references are recognised in both http (url) format and also the standard DOI notation (DOI: ...) @param line: (string) the reference line in which to search for DOI's. @return: the tagged line and a list of D...
'bad_and' : match.group('badand'),
def identify_and_tag_authors(line): """Given a reference, look for a GROUP of author names, leave a tag in place, and return a list of authors GROUPS found in the line. """ output_line = line tmp_line = line ## Firstly, go through and change JUST THE TITLES to underscores ## so that title tag content won't be tagged a...
if m['bad_and']:
lower_text_before = m['text_before'].strip().lower() for e in bad_etal_before_auth_matches: if lower_text_before.endswith(e): dump_in_misc = True break if not dump_in_misc and (lower_text_before.endswith(' and') or lower_text_before.endswith(' ans')):
def identify_and_tag_authors(line): """Given a reference, look for a GROUP of author names, leave a tag in place, and return a list of authors GROUPS found in the line. """ output_line = line tmp_line = line ## Firstly, go through and change JUST THE TITLES to underscores ## so that title tag content won't be tagged a...
if element['misc_txt'].strip(" .,") == ";":
if ((element['misc_txt'].strip(" .,") == ";") or \ ((len(re.sub(re_arxiv_notation,"",lower_stripped_misc)) == 0) and \ (element['type'] == 'REPORTNUMBER'))):
def build_formatted_xml_citation(citation_elements,line_marker): """ Create the MARC-XML string of the found reference information which was taken from a tagged reference line. @param citation_elements: (list) an ordered list of dictionary elements, with each element corresponding to a found piece of information from a...
if "R" in past_elements and (len(element['misc_txt'].lower().replace("arxiv", "").strip(".,:;- []")) > 0):
if "R" in past_elements and \ (len(re.sub(re_arxiv_notation,"",(element['misc_txt'].lower().strip(".,:;- []")))) > 0):
def build_formatted_xml_citation(citation_elements,line_marker): """ Create the MARC-XML string of the found reference information which was taken from a tagged reference line. @param citation_elements: (list) an ordered list of dictionary elements, with each element corresponding to a found piece of information from a...
if "T" in past_elements and (len(element['misc_txt'].lower().replace("arxiv", "").strip(".,:;- []")) > 0):
if "T" in past_elements and \ (len(re.sub(re_arxiv_notation,"",(element['misc_txt'].lower().strip(".,:;- []")))) > 0):
def build_formatted_xml_citation(citation_elements,line_marker): """ Create the MARC-XML string of the found reference information which was taken from a tagged reference line. @param citation_elements: (list) an ordered list of dictionary elements, with each element corresponding to a found piece of information from a...
(working_line1, identified_dois) = identify_and_tag_doi(working_line1)
(working_line1, identified_dois) = identify_and_tag_DOI(working_line1)
def create_marc_xml_reference_section(ref_sect, preprint_repnum_search_kb, preprint_repnum_standardised_categs, periodical_title_search_kb, standardised_periodical_titles, periodical_title_search_keys): """Passed a complete reference section, process each line and attempt to ## identify and standardise individual citat...
"""[42] M. Gell-Mann, P. Ramon ans R. Slansky, in Supergravity, P. van Niewenhuizen and D. Freedman (North-Holland 1979); T. Yanagida, in Proceedings of the Workshop on the Unified Thoery and the Baryon Number in teh Universe, ed. O. Sawaga and A. Sugamoto (Tsukuba 1979); R.N. Mohapatra and G. Senjanovic, Phys. Rev. Le...
"""[42] M. Gell-Mann, P. Ramon ans R. Slansky, in Supergravity, P. van Niewenhuizen and D. Freedman (North-Holland 1979); T. Yanagida, in Proceedings of the Workshop on the Unified Thoery and the Baryon Number in teh Universe, ed. O. Sawaga and A. Sugamoto (Tsukuba 1979); R.N. Mohapatra and G. Senjanovic’, Phys. Rev. L...
def test_get_reference_lines(): """Returns some test reference lines. @return: (list) of strings - the test reference lines. Each string in the list is a reference line that should be processed. """ ## new addition: include two references containing a standard DOI and a DOI embedded in an http link (last two references...
' -collection:"DELETED" -collection:"DUMMY"')
' -980__:"DELETED" -980__:"DUMMY"')
def calculate_reclist(self): """Calculate, set and return the (reclist, reclist_with_nonpublic_subcolls) tuple for given collection.""" if self.calculate_reclist_run_already or str(self.dbquery).startswith("hostedcollection:"): # do we have to recalculate? return (self.reclist, self.reclist_with_nonpublic_subcolls) wri...
reclist = search_pattern(None, self.dbquery + ' -collection:"DELETED"')
reclist = search_pattern(None, self.dbquery + ' -980__:"DELETED"')
def calculate_reclist(self): """Calculate, set and return the (reclist, reclist_with_nonpublic_subcolls) tuple for given collection.""" if self.calculate_reclist_run_already or str(self.dbquery).startswith("hostedcollection:"): # do we have to recalculate? return (self.reclist, self.reclist_with_nonpublic_subcolls) wri...
def highlight(text, keywords=None, prefix_tag='<strong>', suffix_tag="</strong>"): """ Returns text with all words highlighted with given tags (this function places 'prefix_tag' and 'suffix_tag' before and after words from 'keywords' in 'text'). for example set prefix_tag='<b style="color: black; background-color: rgb...
def highlight_matches(text, compiled_pattern, \ prefix_tag='<strong>', suffix_tag="</strong>"): """ Highlight words in 'text' matching the 'compiled_pattern' """
def highlight(text, keywords=None, prefix_tag='<strong>', suffix_tag="</strong>"): """ Returns text with all words highlighted with given tags (this function places 'prefix_tag' and 'suffix_tag' before and after words from 'keywords' in 'text'). for example set prefix_tag='<b style="color: black; background-color: rgb...
pattern = '|'.join(keywords) compiled_pattern = re.compile(pattern, re.IGNORECASE)
def replace_highlight(match): """ replace match.group() by prefix_tag + match.group() + suffix_tag""" return prefix_tag + match.group() + suffix_tag
out = get_text_snippets(text_path, stemmed_patterns, nb_words_around, max_snippets)
out = get_text_snippets(text_path, stemmed_patterns, nb_words_around, max_snippets, False)
def get_pdf_snippets(recID, patterns, nb_words_around=CFG_WEBSEARCH_FULLTEXT_SNIPPETS_WORDS, max_snippets=CFG_WEBSEARCH_FULLTEXT_SNIPPETS): """ Extract text snippets around 'patterns' from the newest PDF file of 'recID' The search is case-insensitive. The snippets are meant to look like in the results of the popular se...
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets):
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets, \ right_boundary = True):
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets): """ Extract text snippets around 'patterns' from file found at 'textfile_path' The snippets are meant to look like in the results of the popular search engine: using " ... " between snippets. For empty patterns it returns "" The idea is to f...
%s | grep -i -A%s -B%s -m%s"
%s | grep -i -E -A%s -B%s -m%s"
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets): """ Extract text snippets around 'patterns' from file found at 'textfile_path' The snippets are meant to look like in the results of the popular search engine: using " ... " between snippets. For empty patterns it returns "" The idea is to f...
for p in patterns: cmd += " -e %s"
for p in escaped_keywords: cmd += " -e \"(\\b|\\s)\"%s" if right_boundary: cmd += "\"(\\b|\\s)\""
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets): """ Extract text snippets around 'patterns' from file found at 'textfile_path' The snippets are meant to look like in the results of the popular search engine: using " ... " between snippets. For empty patterns it returns "" The idea is to f...
small_snippet = cut_out_snippet(s, patterns, nb_words_around, words_left)
small_snippet = cut_out_snippet(s, escaped_keywords, nb_words_around, \ words_left, right_boundary)
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets): """ Extract text snippets around 'patterns' from file found at 'textfile_path' The snippets are meant to look like in the results of the popular search engine: using " ... " between snippets. For empty patterns it returns "" The idea is to f...
out += "..." + highlight(snippet, patterns) + "..."
out += "..." + snippet + "..."
def get_text_snippets(textfile_path, patterns, nb_words_around, max_snippets): """ Extract text snippets around 'patterns' from file found at 'textfile_path' The snippets are meant to look like in the results of the popular search engine: using " ... " between snippets. For empty patterns it returns "" The idea is to f...
def starts_with_any(word, patterns): ret = False lower_case = word.lower() for p in patterns: if lower_case.startswith(str(p).lower()): ret = True break return ret
def matches_any(w1): if compiled_pattern.search(' ' + w1 + ' '): return True else: return False if right_boundary: pattern = '(\\b|\\s)(' + '|'.join(patterns) + ')(\\b|\\s)' else: pattern = '(\\b|\\s)(' + '|'.join(patterns) + ')' compiled_pattern = re.compile(pattern, re.IGNORECASE | re.UNICODE)
def starts_with_any(word, patterns): # Check whether the word's beginning matches any of the patterns. # The second argument is an array of patterns to match.
if starts_with_any(words[i], patterns):
if matches_any(words[i]):
def starts_with_any(word, patterns): # Check whether the word's beginning matches any of the patterns. # The second argument is an array of patterns to match.
if starts_with_any(words[i+j], patterns):
if matches_any(words[i+j]):
def starts_with_any(word, patterns): # Check whether the word's beginning matches any of the patterns. # The second argument is an array of patterns to match.
def __init__(self, index_id, fields_to_index, table_name_pattern, default_get_words_fnc, tag_to_words_fnc_map, wash_index_terms=True, is_fulltext_index=False):
def __init__(self, index_id, fields_to_index, table_name_pattern, default_get_words_fnc, tag_to_words_fnc_map, wash_index_terms=50, is_fulltext_index=False):
def __init__(self, index_id, fields_to_index, table_name_pattern, default_get_words_fnc, tag_to_words_fnc_map, wash_index_terms=True, is_fulltext_index=False): """Creates words table instance. @param index_id: the index integer identificator @param fields_to_index: a list of fields to index @param table_name_pattern: i...
extract words from particular metdata (such as 8564_u)
extract words from particular metdata (such as 8564_u) @param wash_index_terms: do we wash index terms, and if yes (when >0), how many characters do we keep in the index terms; see max_char_length parameter of wash_index_term()
def __init__(self, index_id, fields_to_index, table_name_pattern, default_get_words_fnc, tag_to_words_fnc_map, wash_index_terms=True, is_fulltext_index=False): """Creates words table instance. @param index_id: the index integer identificator @param fields_to_index: a list of fields to index @param table_name_pattern: i...
word = wash_index_term(word)
word = wash_index_term(word, self.wash_index_terms)
def put(self, recID, word, sign): """Adds/deletes a word to the word list.""" try: if self.wash_index_terms: word = wash_index_term(word) if self.value.has_key(word): # the word 'word' exist already: update sign self.value[word][recID] = sign else: self.value[word] = {recID: sign} except: write_message("Error: Cannot p...
wordTable = WordTable(index_id, index_tags, 'idxWORD%02dF', fnc_get_words_from_phrase, {'8564_u': get_words_from_fulltext})
wordTable = WordTable(index_id=index_id, fields_to_index=index_tags, table_name_pattern='idxWORD%02dF', default_get_words_fnc=fnc_get_words_from_phrase, tag_to_words_fnc_map={'8564_u': get_words_from_fulltext}, wash_index_terms=50)
def task_run_core(): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. Return 1 in case of success and 0 in case of failure.""" global _last_word_table ...
wordTable = WordTable(index_id, index_tags, 'idxPAIR%02dF', get_pairs_from_phrase, {'8564_u': get_nothing_from_phrase}, False)
wordTable = WordTable(index_id=index_id, fields_to_index=index_tags, table_name_pattern='idxPAIR%02dF', default_get_words_fnc=get_pairs_from_phrase, tag_to_words_fnc_map={'8564_u': get_nothing_from_phrase}, wash_index_terms=100)
def task_run_core(): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. Return 1 in case of success and 0 in case of failure.""" global _last_word_table ...
wordTable = WordTable(index_id, index_tags, 'idxPHRASE%02dF', fnc_get_phrases_from_phrase, {'8564_u': get_nothing_from_phrase}, False)
wordTable = WordTable(index_id=index_id, fields_to_index=index_tags, table_name_pattern='idxPHRASE%02dF', default_get_words_fnc=fnc_get_phrases_from_phrase, tag_to_words_fnc_map={'8564_u': get_nothing_from_phrase}, wash_index_terms=0)
def task_run_core(): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. Return 1 in case of success and 0 in case of failure.""" global _last_word_table ...
wordTable = WordTable(index_id, index_tags, reindex_prefix + 'idxWORD%02dF', fnc_get_words_from_phrase, {'8564_u': get_words_from_fulltext}, is_fulltext_index=is_fulltext_index)
wordTable = WordTable(index_id=index_id, fields_to_index=index_tags, table_name_pattern=reindex_prefix + 'idxWORD%02dF', default_get_words_fnc=fnc_get_words_from_phrase, tag_to_words_fnc_map={'8564_u': get_words_from_fulltext}, is_fulltext_index=is_fulltext_index, wash_index_terms=50)
def task_run_core(): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. Return 1 in case of success and 0 in case of failure.""" global _last_word_table ...
wordTable = WordTable(index_id, index_tags, reindex_prefix + 'idxPAIR%02dF', get_pairs_from_phrase, {'8564_u': get_nothing_from_phrase}, False)
wordTable = WordTable(index_id=index_id, fields_to_index=index_tags, table_name_pattern=reindex_prefix + 'idxPAIR%02dF', default_get_words_fnc=get_pairs_from_phrase, tag_to_words_fnc_map={'8564_u': get_nothing_from_phrase}, wash_index_terms=100)
def task_run_core(): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. Return 1 in case of success and 0 in case of failure.""" global _last_word_table ...
wordTable = WordTable(index_id, index_tags, reindex_prefix + 'idxPHRASE%02dF', fnc_get_phrases_from_phrase, {'8564_u': get_nothing_from_phrase}, False)
wordTable = WordTable(index_id=index_id, fields_to_index=index_tags, table_name_pattern=reindex_prefix + 'idxPHRASE%02dF', default_get_words_fnc=fnc_get_phrases_from_phrase, tag_to_words_fnc_map={'8564_u': get_nothing_from_phrase}, wash_index_terms=0)
def task_run_core(): """Runs the task by fetching arguments from the BibSched task queue. This is what BibSched will be invoking via daemon call. The task prints Fibonacci numbers for up to NUM on the stdout, and some messages on stderr. Return 1 in case of success and 0 in case of failure.""" global _last_word_table ...
if lower_case.startswith(str(p)):
if lower_case.startswith(str(p).lower()):
def starts_with_any(word, patterns): # Check whether the word's beginning matches any of the patterns. # The second argument is an array of patterns to match.
later_datestamp = sample_datestamp later_datestamp = sample_datestamp[0:3] + str(int(sample_datestamp[3]) + 1) + sample_datestamp[4:]
sample_datestamp_year = int(sample_datestamp[0:4]) sample_datestamp_rest = sample_datestamp[4:] later_datestamp = str(sample_datestamp_year + 1) + sample_datestamp_rest
def test_from_and_until(self): """bibharvest oai repository - testing selective harvesting with 'from' and 'until' parameters"""
earlier_datestamp = sample_datestamp[0:3] + str(int(sample_datestamp[3]) - 1) + sample_datestamp[4:]
earlier_datestamp = str(sample_datestamp_year - 1) + sample_datestamp_rest
def test_from_and_until(self): """bibharvest oai repository - testing selective harvesting with 'from' and 'until' parameters"""
self.fail(merge_error_messages(error_messages))
self.failUnless("HTTP Error 401: Unauthorized" in merge_error_messages(error_messages))
def test_restricted_pictures_hyde(self): """websearch - restricted pictures not available to Mr. Hyde"""
url = field_get_subfield_values(field, 'u') if not bibdocfile_url_p(url):
urls = field_get_subfield_values(field, 'u') if urls and not bibdocfile_url_p(urls[0]):
def get_xml_8564(self): """ Return a snippet of I{MARCXML} representing the I{8564} fields corresponding to the current state.
try: phrase = lower_index_term(phrase) except UnicodeDecodeError: phrase = phrase.lower()
phrase = wash_for_utf8(phrase) phrase = lower_index_term(phrase)
def get_words_from_phrase(phrase, stemming_language=None): """Return list of words found in PHRASE. Note that the phrase is split into groups depending on the alphanumeric characters and punctuation characters definition present in the config file. """ words = {} formulas = [] if CFG_BIBINDEX_REMOVE_HTML_MARKUP and ph...
try: phrase = lower_index_term(phrase) except UnicodeDecodeError: phrase = phrase.lower()
phrase = wash_for_utf8(phrase) phrase = lower_index_term(phrase)
def get_pairs_from_phrase(phrase, stemming_language=None): """Return list of words found in PHRASE. Note that the phrase is split into groups depending on the alphanumeric characters and punctuation characters definition present in the config file. """ words = {} if CFG_BIBINDEX_REMOVE_HTML_MARKUP and phrase.find("</"...
return bal.add_new_copy_step1(req, ln)
return bal.add_new_copy_step1(req)
def add_new_copy_step1(req, ln=CFG_SITE_LANG): """ http://cdsweb.cern.ch/admin/bibcirculation/bibcirculationadmin.py/add_new_copy_step1 """ return bal.add_new_copy_step1(req, ln)
""" % (CFG_SITE_URL, _("The item <strong>%s</strong>, with barcode <strong>%s</strong>, has been returned with success." % (book_title_from_MARC(recid), barcode)))
""" % (CFG_SITE_URL, _("The item %(x_title)s with barcode %(x_barcode)s has been returned with success." % \ {'x_title': book_title_from_MARC(recid), 'x_barcode': barcode}))
def tmpl_loan_return_confirm(self, borrower_name, borrower_id, recid, barcode, return_date, result, ln=CFG_SITE_LANG): """ @param borrower_name: person who returned the book @param id_bibrec: book's recid @param barcode: book's barcode @param ln: language """ _ = gettext_set_language(ln)
raise Exception("Method must be overriden in child class")
raise Exception("Method must be overridden in child class")
def __init__(self, file_loc, mode, allow_clobber=False): """ Overided child methods must set class properties: self._fh self._filename self._file_loc self._mode """ self._mode = None self._ext = None self._filename = None self._fh = None
self._re_search_term_pattern_match = re.compile(r'\b(?P<combine_operator>find|and|or|not)\s+(?P<search_term>title:|keyword:)(?P<search_content>.*?\b)(?= and | or | not |$)', re.IGNORECASE)
self._re_search_term_pattern_match = re.compile(r'\b(?P<combine_operator>find|and|or|not)\s+(?P<search_term>title:|keyword:)(?P<search_content>.*?(\b|\'|\"|\/))(?= and | or | not |$)', re.IGNORECASE)
def _compile_regular_expressions(self): """Compiles some of the regular expressions that are used in the class for higher performance."""
author: ellis or title:THESE or title:THREE or title:WORDS. For a combining operator is used the operator befor the search term
author:ellis or (title: THESE and title:THREE...) For a combining operator "and" is used though FIXME this is not correct, it should really be calculated by boolean expansion of parens.
def _expand_search_patterns(self, query): """Expands search queries.
for word in self._re_split_pattern.split(search_content): if combine_operator.lower() == 'find': result = 'find ' + search_term + word combine_operator = 'and' else: result = result + ' ' + combine_operator + ' ' + search_term + word
search_content = self._re_pattern_single_quotes.sub(lambda x: "'"+string.replace(x.group(1), ' ', '__SPACE__')+"'", search_content) search_content = self._re_pattern_double_quotes.sub(lambda x: "\""+string.replace(x.group(1), ' ', '__SPACE__')+"\"", search_content) search_content = self._re_pattern_regexp_quotes.sub(la...
def create_replacement_pattern(match): result = '' search_term = match.group('search_term') combine_operator = match.group('combine_operator') search_content = match.group('search_content').strip()
query = self._replace_keyword(query, spires_keyword, invenio_keyword)
query = self._replace_keyword(query, spires_keyword,\ invenio_keyword)
def _replace_all_spires_keywords_in_string(self, query): """Replaces all SPIRES keywords in the string with their corresponding Invenio keywords"""