repository_name
stringlengths 5
67
| func_path_in_repository
stringlengths 4
234
| func_name
stringlengths 0
314
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 6
values | func_code_string
stringlengths 52
3.87M
| func_documentation_string
stringlengths 1
47.2k
| func_code_url
stringlengths 85
339
|
---|---|---|---|---|---|---|---|
openstates/billy | billy/importers/legislators.py | activate_legislators | def activate_legislators(current_term, abbr):
"""
Sets the 'active' flag on legislators and populates top-level
district/chamber/party fields for currently serving legislators.
"""
for legislator in db.legislators.find(
{'roles': {'$elemMatch':
{settings.LEVEL_FIELD: abbr, 'term': current_term}}}):
active_role = legislator['roles'][0]
if not active_role.get('end_date') and active_role['type'] == 'member':
legislator['active'] = True
legislator['party'] = active_role.get('party', None)
legislator['district'] = active_role.get('district', None)
legislator['chamber'] = active_role.get('chamber', None)
legislator['updated_at'] = datetime.datetime.utcnow()
db.legislators.save(legislator, safe=True) | python | def activate_legislators(current_term, abbr):
"""
Sets the 'active' flag on legislators and populates top-level
district/chamber/party fields for currently serving legislators.
"""
for legislator in db.legislators.find(
{'roles': {'$elemMatch':
{settings.LEVEL_FIELD: abbr, 'term': current_term}}}):
active_role = legislator['roles'][0]
if not active_role.get('end_date') and active_role['type'] == 'member':
legislator['active'] = True
legislator['party'] = active_role.get('party', None)
legislator['district'] = active_role.get('district', None)
legislator['chamber'] = active_role.get('chamber', None)
legislator['updated_at'] = datetime.datetime.utcnow()
db.legislators.save(legislator, safe=True) | Sets the 'active' flag on legislators and populates top-level
district/chamber/party fields for currently serving legislators. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/legislators.py#L45-L62 |
openstates/billy | billy/scrape/legislators.py | Person.add_role | def add_role(self, role, term, start_date=None, end_date=None,
**kwargs):
"""
Examples:
leg.add_role('member', term='2009', chamber='upper',
party='Republican', district='10th')
"""
self['roles'].append(dict(role=role, term=term,
start_date=start_date,
end_date=end_date, **kwargs)) | python | def add_role(self, role, term, start_date=None, end_date=None,
**kwargs):
"""
Examples:
leg.add_role('member', term='2009', chamber='upper',
party='Republican', district='10th')
"""
self['roles'].append(dict(role=role, term=term,
start_date=start_date,
end_date=end_date, **kwargs)) | Examples:
leg.add_role('member', term='2009', chamber='upper',
party='Republican', district='10th') | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/legislators.py#L46-L56 |
openstates/billy | billy/scrape/legislators.py | Person.add_office | def add_office(self, type, name, address=None, phone=None, fax=None,
email=None, **kwargs):
"""
Allowed office types:
capitol
district
"""
office_dict = dict(type=type, address=address, name=name, phone=phone,
fax=fax, email=email, **kwargs)
self['offices'].append(office_dict) | python | def add_office(self, type, name, address=None, phone=None, fax=None,
email=None, **kwargs):
"""
Allowed office types:
capitol
district
"""
office_dict = dict(type=type, address=address, name=name, phone=phone,
fax=fax, email=email, **kwargs)
self['offices'].append(office_dict) | Allowed office types:
capitol
district | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/legislators.py#L58-L67 |
openstates/billy | billy/utils/__init__.py | metadata | def metadata(abbr, __metadata=__metadata):
"""
Grab the metadata for the given two-letter abbreviation.
"""
# This data should change very rarely and is queried very often so
# cache it here
abbr = abbr.lower()
if abbr in __metadata:
return __metadata[abbr]
rv = db.metadata.find_one({'_id': abbr})
__metadata[abbr] = rv
return rv | python | def metadata(abbr, __metadata=__metadata):
"""
Grab the metadata for the given two-letter abbreviation.
"""
# This data should change very rarely and is queried very often so
# cache it here
abbr = abbr.lower()
if abbr in __metadata:
return __metadata[abbr]
rv = db.metadata.find_one({'_id': abbr})
__metadata[abbr] = rv
return rv | Grab the metadata for the given two-letter abbreviation. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/utils/__init__.py#L22-L34 |
openstates/billy | billy/utils/__init__.py | cd | def cd(path):
'''Creates the path if it doesn't exist'''
old_dir = os.getcwd()
try:
os.makedirs(path)
except OSError:
pass
os.chdir(path)
try:
yield
finally:
os.chdir(old_dir) | python | def cd(path):
'''Creates the path if it doesn't exist'''
old_dir = os.getcwd()
try:
os.makedirs(path)
except OSError:
pass
os.chdir(path)
try:
yield
finally:
os.chdir(old_dir) | Creates the path if it doesn't exist | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/utils/__init__.py#L147-L158 |
openstates/billy | billy/importers/utils.py | _get_property_dict | def _get_property_dict(schema):
""" given a schema object produce a nested dictionary of fields """
pdict = {}
for k, v in schema['properties'].items():
pdict[k] = {}
if 'items' in v and 'properties' in v['items']:
pdict[k] = _get_property_dict(v['items'])
pdict[settings.LEVEL_FIELD] = {}
return pdict | python | def _get_property_dict(schema):
""" given a schema object produce a nested dictionary of fields """
pdict = {}
for k, v in schema['properties'].items():
pdict[k] = {}
if 'items' in v and 'properties' in v['items']:
pdict[k] = _get_property_dict(v['items'])
pdict[settings.LEVEL_FIELD] = {}
return pdict | given a schema object produce a nested dictionary of fields | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L16-L24 |
openstates/billy | billy/importers/utils.py | insert_with_id | def insert_with_id(obj):
"""
Generates a unique ID for the supplied legislator/committee/bill
and inserts it into the appropriate collection.
"""
if '_id' in obj:
raise ValueError("object already has '_id' field")
# add created_at/updated_at on insert
obj['created_at'] = datetime.datetime.utcnow()
obj['updated_at'] = obj['created_at']
if obj['_type'] == 'person' or obj['_type'] == 'legislator':
collection = db.legislators
id_type = 'L'
elif obj['_type'] == 'committee':
collection = db.committees
id_type = 'C'
elif obj['_type'] == 'bill':
collection = db.bills
id_type = 'B'
else:
raise ValueError("unknown _type for object")
# get abbr
abbr = obj[settings.LEVEL_FIELD].upper()
id_reg = re.compile('^%s%s' % (abbr, id_type))
# Find the next available _id and insert
id_prefix = '%s%s' % (abbr, id_type)
cursor = collection.find({'_id': id_reg}).sort('_id', -1).limit(1)
try:
new_id = int(next(cursor)['_id'][len(abbr) + 1:]) + 1
except StopIteration:
new_id = 1
while True:
if obj['_type'] == 'bill':
obj['_id'] = '%s%08d' % (id_prefix, new_id)
else:
obj['_id'] = '%s%06d' % (id_prefix, new_id)
obj['_all_ids'] = [obj['_id']]
if obj['_type'] in ['person', 'legislator']:
obj['leg_id'] = obj['_id']
try:
return collection.insert(obj, safe=True)
except pymongo.errors.DuplicateKeyError:
new_id += 1 | python | def insert_with_id(obj):
"""
Generates a unique ID for the supplied legislator/committee/bill
and inserts it into the appropriate collection.
"""
if '_id' in obj:
raise ValueError("object already has '_id' field")
# add created_at/updated_at on insert
obj['created_at'] = datetime.datetime.utcnow()
obj['updated_at'] = obj['created_at']
if obj['_type'] == 'person' or obj['_type'] == 'legislator':
collection = db.legislators
id_type = 'L'
elif obj['_type'] == 'committee':
collection = db.committees
id_type = 'C'
elif obj['_type'] == 'bill':
collection = db.bills
id_type = 'B'
else:
raise ValueError("unknown _type for object")
# get abbr
abbr = obj[settings.LEVEL_FIELD].upper()
id_reg = re.compile('^%s%s' % (abbr, id_type))
# Find the next available _id and insert
id_prefix = '%s%s' % (abbr, id_type)
cursor = collection.find({'_id': id_reg}).sort('_id', -1).limit(1)
try:
new_id = int(next(cursor)['_id'][len(abbr) + 1:]) + 1
except StopIteration:
new_id = 1
while True:
if obj['_type'] == 'bill':
obj['_id'] = '%s%08d' % (id_prefix, new_id)
else:
obj['_id'] = '%s%06d' % (id_prefix, new_id)
obj['_all_ids'] = [obj['_id']]
if obj['_type'] in ['person', 'legislator']:
obj['leg_id'] = obj['_id']
try:
return collection.insert(obj, safe=True)
except pymongo.errors.DuplicateKeyError:
new_id += 1 | Generates a unique ID for the supplied legislator/committee/bill
and inserts it into the appropriate collection. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L37-L88 |
openstates/billy | billy/importers/utils.py | update | def update(old, new, collection, sneaky_update_filter=None):
"""
update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
collection to save changed object to
sneaky_update_filter
a filter for updates to object that should be ignored
format is a dict mapping field names to a comparison function
that returns True iff there is a change
"""
# need_save = something has changed
need_save = False
locked_fields = old.get('_locked_fields', [])
for key, value in new.items():
# don't update locked fields
if key in locked_fields:
continue
if old.get(key) != value:
if sneaky_update_filter and key in sneaky_update_filter:
if sneaky_update_filter[key](old[key], value):
old[key] = value
need_save = True
else:
old[key] = value
need_save = True
# remove old +key field if this field no longer has a +
plus_key = '+%s' % key
if plus_key in old:
del old[plus_key]
need_save = True
if need_save:
old['updated_at'] = datetime.datetime.utcnow()
collection.save(old, safe=True)
return need_save | python | def update(old, new, collection, sneaky_update_filter=None):
"""
update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
collection to save changed object to
sneaky_update_filter
a filter for updates to object that should be ignored
format is a dict mapping field names to a comparison function
that returns True iff there is a change
"""
# need_save = something has changed
need_save = False
locked_fields = old.get('_locked_fields', [])
for key, value in new.items():
# don't update locked fields
if key in locked_fields:
continue
if old.get(key) != value:
if sneaky_update_filter and key in sneaky_update_filter:
if sneaky_update_filter[key](old[key], value):
old[key] = value
need_save = True
else:
old[key] = value
need_save = True
# remove old +key field if this field no longer has a +
plus_key = '+%s' % key
if plus_key in old:
del old[plus_key]
need_save = True
if need_save:
old['updated_at'] = datetime.datetime.utcnow()
collection.save(old, safe=True)
return need_save | update an existing object with a new one, only saving it and
setting updated_at if something has changed
old
old object
new
new object
collection
collection to save changed object to
sneaky_update_filter
a filter for updates to object that should be ignored
format is a dict mapping field names to a comparison function
that returns True iff there is a change | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L130-L176 |
openstates/billy | billy/importers/utils.py | convert_timestamps | def convert_timestamps(obj):
"""
Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes.
"""
for key in ('date', 'when', 'end', 'start_date', 'end_date'):
value = obj.get(key)
if value:
try:
obj[key] = _timestamp_to_dt(value)
except TypeError:
raise TypeError("expected float for %s, got %s" % (key, value))
for key in ('sources', 'actions', 'votes', 'roles'):
for child in obj.get(key, []):
convert_timestamps(child)
return obj | python | def convert_timestamps(obj):
"""
Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes.
"""
for key in ('date', 'when', 'end', 'start_date', 'end_date'):
value = obj.get(key)
if value:
try:
obj[key] = _timestamp_to_dt(value)
except TypeError:
raise TypeError("expected float for %s, got %s" % (key, value))
for key in ('sources', 'actions', 'votes', 'roles'):
for child in obj.get(key, []):
convert_timestamps(child)
return obj | Convert unix timestamps in the scraper output to python datetimes
so that they will be saved properly as Mongo datetimes. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L179-L196 |
openstates/billy | billy/importers/utils.py | split_name | def split_name(obj):
"""
If the supplied legislator/person object is missing 'first_name'
or 'last_name' then use name_tools to split.
"""
if obj['_type'] in ('person', 'legislator'):
for key in ('first_name', 'last_name'):
if key not in obj or not obj[key]:
# Need to split
(obj['first_name'], obj['last_name'],
obj['suffixes']) = name_tools.split(obj['full_name'])[1:]
break
return obj | python | def split_name(obj):
"""
If the supplied legislator/person object is missing 'first_name'
or 'last_name' then use name_tools to split.
"""
if obj['_type'] in ('person', 'legislator'):
for key in ('first_name', 'last_name'):
if key not in obj or not obj[key]:
# Need to split
(obj['first_name'], obj['last_name'],
obj['suffixes']) = name_tools.split(obj['full_name'])[1:]
break
return obj | If the supplied legislator/person object is missing 'first_name'
or 'last_name' then use name_tools to split. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L199-L212 |
openstates/billy | billy/importers/utils.py | _make_plus_helper | def _make_plus_helper(obj, fields):
""" add a + prefix to any fields in obj that aren't in fields """
new_obj = {}
for key, value in obj.items():
if key in fields or key.startswith('_'):
# if there's a subschema apply it to a list or subdict
if fields.get(key):
if isinstance(value, list):
value = [_make_plus_helper(item, fields[key])
for item in value]
# assign the value (modified potentially) to the new_obj
new_obj[key] = value
else:
# values not in the fields dict get a +
new_obj['+%s' % key] = value
return new_obj | python | def _make_plus_helper(obj, fields):
""" add a + prefix to any fields in obj that aren't in fields """
new_obj = {}
for key, value in obj.items():
if key in fields or key.startswith('_'):
# if there's a subschema apply it to a list or subdict
if fields.get(key):
if isinstance(value, list):
value = [_make_plus_helper(item, fields[key])
for item in value]
# assign the value (modified potentially) to the new_obj
new_obj[key] = value
else:
# values not in the fields dict get a +
new_obj['+%s' % key] = value
return new_obj | add a + prefix to any fields in obj that aren't in fields | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L215-L232 |
openstates/billy | billy/importers/utils.py | make_plus_fields | def make_plus_fields(obj):
"""
Add a '+' to the key of non-standard fields.
dispatch to recursive _make_plus_helper based on _type field
"""
fields = standard_fields.get(obj['_type'], dict())
return _make_plus_helper(obj, fields) | python | def make_plus_fields(obj):
"""
Add a '+' to the key of non-standard fields.
dispatch to recursive _make_plus_helper based on _type field
"""
fields = standard_fields.get(obj['_type'], dict())
return _make_plus_helper(obj, fields) | Add a '+' to the key of non-standard fields.
dispatch to recursive _make_plus_helper based on _type field | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/importers/utils.py#L235-L242 |
openstates/billy | billy/models/metadata.py | Metadata.get_object | def get_object(cls, abbr):
'''
This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects.
'''
obj = get_metadata(abbr)
if obj is None:
msg = 'No metadata found for abbreviation %r' % abbr
raise DoesNotExist(msg)
return cls(obj) | python | def get_object(cls, abbr):
'''
This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects.
'''
obj = get_metadata(abbr)
if obj is None:
msg = 'No metadata found for abbreviation %r' % abbr
raise DoesNotExist(msg)
return cls(obj) | This particular model needs its own constructor in order to take
advantage of the metadata cache in billy.util, which would otherwise
return unwrapped objects. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/metadata.py#L88-L98 |
openstates/billy | billy/models/metadata.py | Metadata.committees_legislators | def committees_legislators(self, *args, **kwargs):
'''Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members.
'''
committees = list(self.committees(*args, **kwargs))
legislators = self.legislators({'active': True},
fields=['full_name',
settings.LEVEL_FIELD])
_legislators = {}
# This will be a cache of legislator objects used in
# the committees.html template. Includes ids in each
# legislator's _all_ids field (if it exists.)
for obj in legislators:
if 'all_ids' in obj:
for _id in obj['_all_ids']:
_legislators[_id] = obj
else:
_legislators[obj['_id']] = obj
del legislators
for com in committees:
com._legislators = _legislators
return committees | python | def committees_legislators(self, *args, **kwargs):
'''Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members.
'''
committees = list(self.committees(*args, **kwargs))
legislators = self.legislators({'active': True},
fields=['full_name',
settings.LEVEL_FIELD])
_legislators = {}
# This will be a cache of legislator objects used in
# the committees.html template. Includes ids in each
# legislator's _all_ids field (if it exists.)
for obj in legislators:
if 'all_ids' in obj:
for _id in obj['_all_ids']:
_legislators[_id] = obj
else:
_legislators[obj['_id']] = obj
del legislators
for com in committees:
com._legislators = _legislators
return committees | Return an iterable of committees with all the
legislators cached for reference in the Committee model.
So do a "select_related" operation on committee members. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/metadata.py#L168-L191 |
openstates/billy | billy/bin/commands/dump.py | extract_fields | def extract_fields(d, fields, delimiter='|'):
""" get values out of an object ``d`` for saving to a csv """
rd = {}
for f in fields:
v = d.get(f, None)
if isinstance(v, (str, unicode)):
v = v.encode('utf8')
elif isinstance(v, list):
v = delimiter.join(v)
rd[f] = v
return rd | python | def extract_fields(d, fields, delimiter='|'):
""" get values out of an object ``d`` for saving to a csv """
rd = {}
for f in fields:
v = d.get(f, None)
if isinstance(v, (str, unicode)):
v = v.encode('utf8')
elif isinstance(v, list):
v = delimiter.join(v)
rd[f] = v
return rd | get values out of an object ``d`` for saving to a csv | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/bin/commands/dump.py#L46-L56 |
openstates/billy | billy/web/public/views/bills.py | bill | def bill(request, abbr, session, bill_id):
'''
Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html
'''
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if fixed_bill_id.replace(' ', '') != bill_id:
return redirect('bill', abbr=abbr, session=session, bill_id=fixed_bill_id.replace(' ', ''))
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session,
'bill_id': fixed_bill_id})
if bill is None:
raise Http404(u'no bill found {0} {1} {2}'.format(abbr, session, bill_id))
show_all_sponsors = request.GET.get('show_all_sponsors')
if show_all_sponsors:
sponsors = bill.sponsors_manager
else:
sponsors = bill.sponsors_manager.first_fifteen
return render(
request, templatename('bill'),
dict(vote_preview_row_template=templatename('vote_preview_row'),
abbr=abbr,
metadata=Metadata.get_object(abbr),
bill=bill,
show_all_sponsors=show_all_sponsors,
sponsors=sponsors,
sources=bill['sources'],
nav_active='bills')) | python | def bill(request, abbr, session, bill_id):
'''
Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html
'''
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if fixed_bill_id.replace(' ', '') != bill_id:
return redirect('bill', abbr=abbr, session=session, bill_id=fixed_bill_id.replace(' ', ''))
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session,
'bill_id': fixed_bill_id})
if bill is None:
raise Http404(u'no bill found {0} {1} {2}'.format(abbr, session, bill_id))
show_all_sponsors = request.GET.get('show_all_sponsors')
if show_all_sponsors:
sponsors = bill.sponsors_manager
else:
sponsors = bill.sponsors_manager.first_fifteen
return render(
request, templatename('bill'),
dict(vote_preview_row_template=templatename('vote_preview_row'),
abbr=abbr,
metadata=Metadata.get_object(abbr),
bill=bill,
show_all_sponsors=show_all_sponsors,
sponsors=sponsors,
sources=bill['sources'],
nav_active='bills')) | Context:
- vote_preview_row_template
- abbr
- metadata
- bill
- show_all_sponsors
- sponsors
- sources
- nav_active
Templates:
- billy/web/public/bill.html
- billy/web/public/vote_preview_row.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/bills.py#L360-L401 |
openstates/billy | billy/web/public/views/bills.py | vote | def vote(request, abbr, vote_id):
'''
Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html
'''
vote = db.votes.find_one(vote_id)
if vote is None:
raise Http404('no such vote: {0}'.format(vote_id))
bill = vote.bill()
return render(request, templatename('vote'),
dict(abbr=abbr, metadata=Metadata.get_object(abbr),
bill=bill,
vote=vote,
nav_active='bills')) | python | def vote(request, abbr, vote_id):
'''
Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html
'''
vote = db.votes.find_one(vote_id)
if vote is None:
raise Http404('no such vote: {0}'.format(vote_id))
bill = vote.bill()
return render(request, templatename('vote'),
dict(abbr=abbr, metadata=Metadata.get_object(abbr),
bill=bill,
vote=vote,
nav_active='bills')) | Context:
- abbr
- metadata
- bill
- vote
- nav_active
Templates:
- vote.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/bills.py#L404-L425 |
openstates/billy | billy/web/public/views/bills.py | document | def document(request, abbr, session, bill_id, doc_id):
'''
Context:
- abbr
- session
- bill
- version
- metadata
- nav_active
Templates:
- billy/web/public/document.html
'''
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if fixed_bill_id.replace(' ', '') != bill_id:
return redirect('document', abbr=abbr, session=session,
bill_id=fixed_bill_id.replace(' ', ''), doc_id=doc_id)
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session,
'bill_id': fixed_bill_id})
if not bill:
raise Http404('No such bill.')
for version in bill['versions']:
if version['doc_id'] == doc_id:
break
else:
raise Http404('No such document.')
if not settings.ENABLE_DOCUMENT_VIEW.get(abbr, False):
return redirect(version['url'])
return render(request, templatename('document'),
dict(abbr=abbr, session=session, bill=bill, version=version,
metadata=bill.metadata, nav_active='bills')) | python | def document(request, abbr, session, bill_id, doc_id):
'''
Context:
- abbr
- session
- bill
- version
- metadata
- nav_active
Templates:
- billy/web/public/document.html
'''
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if fixed_bill_id.replace(' ', '') != bill_id:
return redirect('document', abbr=abbr, session=session,
bill_id=fixed_bill_id.replace(' ', ''), doc_id=doc_id)
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr, 'session': session,
'bill_id': fixed_bill_id})
if not bill:
raise Http404('No such bill.')
for version in bill['versions']:
if version['doc_id'] == doc_id:
break
else:
raise Http404('No such document.')
if not settings.ENABLE_DOCUMENT_VIEW.get(abbr, False):
return redirect(version['url'])
return render(request, templatename('document'),
dict(abbr=abbr, session=session, bill=bill, version=version,
metadata=bill.metadata, nav_active='bills')) | Context:
- abbr
- session
- bill
- version
- metadata
- nav_active
Templates:
- billy/web/public/document.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/bills.py#L428-L465 |
openstates/billy | billy/web/public/views/bills.py | show_all | def show_all(key):
'''
Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc.
'''
def func(request, abbr, session, bill_id, key):
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if fixed_bill_id.replace(' ', '') != bill_id:
return redirect('bill', abbr=abbr, session=session,
bill_id=fixed_bill_id.replace(' ', ''))
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr,
'session': session,
'bill_id': fixed_bill_id})
if bill is None:
raise Http404('no bill found {0} {1} {2}'.format(abbr, session,
bill_id))
return render(request, templatename('bill_all_%s' % key),
dict(abbr=abbr, metadata=Metadata.get_object(abbr),
bill=bill, sources=bill['sources'],
nav_active='bills'))
return func | python | def show_all(key):
'''
Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc.
'''
def func(request, abbr, session, bill_id, key):
# get fixed version
fixed_bill_id = fix_bill_id(bill_id)
# redirect if URL's id isn't fixed id without spaces
if fixed_bill_id.replace(' ', '') != bill_id:
return redirect('bill', abbr=abbr, session=session,
bill_id=fixed_bill_id.replace(' ', ''))
bill = db.bills.find_one({settings.LEVEL_FIELD: abbr,
'session': session,
'bill_id': fixed_bill_id})
if bill is None:
raise Http404('no bill found {0} {1} {2}'.format(abbr, session,
bill_id))
return render(request, templatename('bill_all_%s' % key),
dict(abbr=abbr, metadata=Metadata.get_object(abbr),
bill=bill, sources=bill['sources'],
nav_active='bills'))
return func | Context:
- abbr
- metadata
- bill
- sources
- nav_active
Templates:
- billy/web/public/bill_all_{key}.html
- where key is passed in, like "actions", etc. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/bills.py#L473-L503 |
openstates/billy | billy/web/public/views/bills.py | RelatedBillsList.get_context_data | def get_context_data(self, *args, **kwargs):
'''
Context:
If GET parameters are given:
- search_text
- form (FilterBillsForm)
- long_description
- description
- get_params
Otherwise, the only context item is an unbound FilterBillsForm.
Templates:
- Are specified in subclasses.
'''
context = super(RelatedBillsList, self).get_context_data(*args,
**kwargs)
metadata = context['metadata']
FilterBillsForm = get_filter_bills_form(metadata)
if self.request.GET:
form = FilterBillsForm(self.request.GET)
search_text = form.data.get('search_text')
context.update(search_text=search_text)
context.update(form=FilterBillsForm(self.request.GET))
# human readable description of search
description = []
if metadata:
description.append(metadata['name'])
else:
description = ['Search All']
long_description = []
chamber = form.data.get('chamber')
session = form.data.get('session')
type = form.data.get('type')
status = form.data.getlist('status')
subjects = form.data.getlist('subjects')
sponsor = form.data.get('sponsor__leg_id')
if chamber:
if metadata:
description.append(metadata['chambers'][chamber]['name']
)
else:
description.extend([chamber.title(), 'Chamber'])
description.append((type or 'Bill') + 's')
if session:
description.append(
'(%s)' %
metadata['session_details'][session]['display_name']
)
if 'signed' in status:
long_description.append('which have been signed into law')
elif 'passed_upper' in status and 'passed_lower' in status:
long_description.append('which have passed both chambers')
elif 'passed_lower' in status:
chamber_name = (metadata['chambers']['lower']['name']
if metadata else 'lower chamber')
long_description.append('which have passed the ' +
chamber_name)
elif 'passed_upper' in status:
chamber_name = (metadata['chambers']['upper']['name']
if metadata else 'upper chamber')
long_description.append('which have passed the ' +
chamber_name)
if sponsor:
leg = db.legislators.find_one({'_all_ids': sponsor},
fields=('full_name', '_id'))
leg = leg['full_name']
long_description.append('sponsored by ' + leg)
if subjects:
long_description.append('related to ' + ', '.join(subjects))
if search_text:
long_description.append(u'containing the term "{0}"'.format(
search_text))
context.update(long_description=long_description)
else:
if metadata:
description = [metadata['name'], 'Bills']
else:
description = ['All Bills']
context.update(form=FilterBillsForm())
context.update(description=' '.join(description))
# Add the correct path to paginated links.
params = list(self.request.GET.lists())
for k, v in params[:]:
if k == 'page':
params.remove((k, v))
get_params = urllib.urlencode(params, doseq=True)
context['get_params'] = get_params
# Add the abbr.
context['abbr'] = self.kwargs['abbr']
return context | python | def get_context_data(self, *args, **kwargs):
'''
Context:
If GET parameters are given:
- search_text
- form (FilterBillsForm)
- long_description
- description
- get_params
Otherwise, the only context item is an unbound FilterBillsForm.
Templates:
- Are specified in subclasses.
'''
context = super(RelatedBillsList, self).get_context_data(*args,
**kwargs)
metadata = context['metadata']
FilterBillsForm = get_filter_bills_form(metadata)
if self.request.GET:
form = FilterBillsForm(self.request.GET)
search_text = form.data.get('search_text')
context.update(search_text=search_text)
context.update(form=FilterBillsForm(self.request.GET))
# human readable description of search
description = []
if metadata:
description.append(metadata['name'])
else:
description = ['Search All']
long_description = []
chamber = form.data.get('chamber')
session = form.data.get('session')
type = form.data.get('type')
status = form.data.getlist('status')
subjects = form.data.getlist('subjects')
sponsor = form.data.get('sponsor__leg_id')
if chamber:
if metadata:
description.append(metadata['chambers'][chamber]['name']
)
else:
description.extend([chamber.title(), 'Chamber'])
description.append((type or 'Bill') + 's')
if session:
description.append(
'(%s)' %
metadata['session_details'][session]['display_name']
)
if 'signed' in status:
long_description.append('which have been signed into law')
elif 'passed_upper' in status and 'passed_lower' in status:
long_description.append('which have passed both chambers')
elif 'passed_lower' in status:
chamber_name = (metadata['chambers']['lower']['name']
if metadata else 'lower chamber')
long_description.append('which have passed the ' +
chamber_name)
elif 'passed_upper' in status:
chamber_name = (metadata['chambers']['upper']['name']
if metadata else 'upper chamber')
long_description.append('which have passed the ' +
chamber_name)
if sponsor:
leg = db.legislators.find_one({'_all_ids': sponsor},
fields=('full_name', '_id'))
leg = leg['full_name']
long_description.append('sponsored by ' + leg)
if subjects:
long_description.append('related to ' + ', '.join(subjects))
if search_text:
long_description.append(u'containing the term "{0}"'.format(
search_text))
context.update(long_description=long_description)
else:
if metadata:
description = [metadata['name'], 'Bills']
else:
description = ['All Bills']
context.update(form=FilterBillsForm())
context.update(description=' '.join(description))
# Add the correct path to paginated links.
params = list(self.request.GET.lists())
for k, v in params[:]:
if k == 'page':
params.remove((k, v))
get_params = urllib.urlencode(params, doseq=True)
context['get_params'] = get_params
# Add the abbr.
context['abbr'] = self.kwargs['abbr']
return context | Context:
If GET parameters are given:
- search_text
- form (FilterBillsForm)
- long_description
- description
- get_params
Otherwise, the only context item is an unbound FilterBillsForm.
Templates:
- Are specified in subclasses. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/bills.py#L29-L123 |
openstates/billy | billy/web/public/views/region.py | region_selection | def region_selection(request):
'''Handle submission of the region selection form in the base template. '''
form = get_region_select_form(request.GET)
abbr = form.data.get('abbr')
if not abbr or len(abbr) != 2:
return redirect('homepage')
return redirect('region', abbr=abbr) | python | def region_selection(request):
'''Handle submission of the region selection form in the base template. '''
form = get_region_select_form(request.GET)
abbr = form.data.get('abbr')
if not abbr or len(abbr) != 2:
return redirect('homepage')
return redirect('region', abbr=abbr) | Handle submission of the region selection form in the base template. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/region.py#L17-L23 |
openstates/billy | billy/web/public/views/region.py | region | def region(request, abbr):
'''
Context:
- abbr
- metadata
- sessions
- chambers
- joint_committee_count
- geo_bounds
- nav_active
Templates:
- bill/web/public/region.html
'''
report = db.reports.find_one({'_id': abbr})
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
fallback_bounds = GEO_BOUNDS['US']
geo_bounds = GEO_BOUNDS.get(abbr.upper(), fallback_bounds)
# count legislators
legislators = meta.legislators({'active': True}, {'party': True,
'chamber': True})
# Maybe later, mapreduce instead?
party_counts = defaultdict(lambda: defaultdict(int))
for leg in legislators:
if 'chamber' in leg: # exclude lt. governors
party_counts[leg['chamber']][leg['party']] += 1
chambers = []
for chamber_type, chamber in meta['chambers'].items():
res = {}
# chamber metadata
res['type'] = chamber_type
res['title'] = chamber['title']
res['name'] = chamber['name']
# legislators
res['legislators'] = {
'count': sum(party_counts[chamber_type].values()),
'party_counts': dict(party_counts[chamber_type]),
}
# committees
res['committees_count'] = meta.committees({'chamber': chamber_type}
).count()
res['latest_bills'] = meta.bills({'chamber': chamber_type}).sort(
[('action_dates.first', -1)]).limit(2)
res['passed_bills'] = meta.bills({'chamber': chamber_type}).sort(
[('action_dates.passed_' + chamber_type, -1)]).limit(2)
chambers.append(res)
joint_committee_count = meta.committees({'chamber': 'joint'}).count()
# add bill counts to session listing
sessions = meta.sessions()
for s in sessions:
try:
s['bill_count'] = (
report['bills']['sessions'][s['id']]['upper_count']
+ report['bills']['sessions'][s['id']]['lower_count'])
except KeyError:
# there's a chance that the session had no bills
s['bill_count'] = 0
return render(request, templatename('region'),
dict(abbr=abbr, metadata=meta, sessions=sessions,
chambers=chambers,
joint_committee_count=joint_committee_count,
geo_bounds=geo_bounds,
nav_active='home')) | python | def region(request, abbr):
'''
Context:
- abbr
- metadata
- sessions
- chambers
- joint_committee_count
- geo_bounds
- nav_active
Templates:
- bill/web/public/region.html
'''
report = db.reports.find_one({'_id': abbr})
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
fallback_bounds = GEO_BOUNDS['US']
geo_bounds = GEO_BOUNDS.get(abbr.upper(), fallback_bounds)
# count legislators
legislators = meta.legislators({'active': True}, {'party': True,
'chamber': True})
# Maybe later, mapreduce instead?
party_counts = defaultdict(lambda: defaultdict(int))
for leg in legislators:
if 'chamber' in leg: # exclude lt. governors
party_counts[leg['chamber']][leg['party']] += 1
chambers = []
for chamber_type, chamber in meta['chambers'].items():
res = {}
# chamber metadata
res['type'] = chamber_type
res['title'] = chamber['title']
res['name'] = chamber['name']
# legislators
res['legislators'] = {
'count': sum(party_counts[chamber_type].values()),
'party_counts': dict(party_counts[chamber_type]),
}
# committees
res['committees_count'] = meta.committees({'chamber': chamber_type}
).count()
res['latest_bills'] = meta.bills({'chamber': chamber_type}).sort(
[('action_dates.first', -1)]).limit(2)
res['passed_bills'] = meta.bills({'chamber': chamber_type}).sort(
[('action_dates.passed_' + chamber_type, -1)]).limit(2)
chambers.append(res)
joint_committee_count = meta.committees({'chamber': 'joint'}).count()
# add bill counts to session listing
sessions = meta.sessions()
for s in sessions:
try:
s['bill_count'] = (
report['bills']['sessions'][s['id']]['upper_count']
+ report['bills']['sessions'][s['id']]['lower_count'])
except KeyError:
# there's a chance that the session had no bills
s['bill_count'] = 0
return render(request, templatename('region'),
dict(abbr=abbr, metadata=meta, sessions=sessions,
chambers=chambers,
joint_committee_count=joint_committee_count,
geo_bounds=geo_bounds,
nav_active='home')) | Context:
- abbr
- metadata
- sessions
- chambers
- joint_committee_count
- geo_bounds
- nav_active
Templates:
- bill/web/public/region.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/region.py#L26-L103 |
openstates/billy | billy/web/public/views/region.py | search | def search(request, abbr):
'''
Context:
- search_text
- abbr
- metadata
- found_by_id
- bill_results
- more_bills_available
- legislators_list
- nav_active
Tempaltes:
- billy/web/public/search_results_no_query.html
- billy/web/public/search_results_bills_legislators.html
- billy/web/public/bills_list_row_with_abbr_and_session.html
'''
if not request.GET:
return render(request, templatename('search_results_no_query'),
{'abbr': abbr})
search_text = unicode(request.GET['search_text']).encode('utf8')
# First try to get by bill_id.
if re.search(r'\d', search_text):
url = '/%s/bills?' % abbr
url += urllib.urlencode([('search_text', search_text)])
return redirect(url)
else:
found_by_id = False
kwargs = {}
if abbr != 'all':
kwargs['abbr'] = abbr
bill_results = Bill.search(search_text, sort='last', **kwargs)
# Limit the bills if it's a search.
bill_result_count = len(bill_results)
more_bills_available = (bill_result_count > 5)
bill_results = bill_results[:5]
# See if any legislator names match. First split up name to avoid
# the Richard S. Madaleno problem. See Jira issue OS-32.
textbits = search_text.split()
textbits = filter(lambda s: 2 < len(s), textbits)
textbits = filter(lambda s: '.' not in s, textbits)
andspec = []
for text in textbits:
andspec.append({'full_name': {'$regex': text, '$options': 'i'}})
if andspec:
spec = {'$and': andspec}
else:
spec = {'full_name': {'$regex': search_text, '$options': 'i'}}
# Run the query.
if abbr != 'all':
spec[settings.LEVEL_FIELD] = abbr
legislator_results = list(db.legislators.find(spec).sort(
[('active', -1)]))
if abbr != 'all':
metadata = Metadata.get_object(abbr)
else:
metadata = None
return render(
request, templatename('search_results_bills_legislators'),
dict(search_text=search_text,
abbr=abbr,
metadata=metadata,
found_by_id=found_by_id,
bill_results=bill_results,
bill_result_count=bill_result_count,
more_bills_available=more_bills_available,
legislators_list=legislator_results,
column_headers_tmplname=None, # not used
rowtemplate_name=templatename('bills_list_row_with'
'_abbr_and_session'),
show_chamber_column=True,
nav_active=None)) | python | def search(request, abbr):
'''
Context:
- search_text
- abbr
- metadata
- found_by_id
- bill_results
- more_bills_available
- legislators_list
- nav_active
Tempaltes:
- billy/web/public/search_results_no_query.html
- billy/web/public/search_results_bills_legislators.html
- billy/web/public/bills_list_row_with_abbr_and_session.html
'''
if not request.GET:
return render(request, templatename('search_results_no_query'),
{'abbr': abbr})
search_text = unicode(request.GET['search_text']).encode('utf8')
# First try to get by bill_id.
if re.search(r'\d', search_text):
url = '/%s/bills?' % abbr
url += urllib.urlencode([('search_text', search_text)])
return redirect(url)
else:
found_by_id = False
kwargs = {}
if abbr != 'all':
kwargs['abbr'] = abbr
bill_results = Bill.search(search_text, sort='last', **kwargs)
# Limit the bills if it's a search.
bill_result_count = len(bill_results)
more_bills_available = (bill_result_count > 5)
bill_results = bill_results[:5]
# See if any legislator names match. First split up name to avoid
# the Richard S. Madaleno problem. See Jira issue OS-32.
textbits = search_text.split()
textbits = filter(lambda s: 2 < len(s), textbits)
textbits = filter(lambda s: '.' not in s, textbits)
andspec = []
for text in textbits:
andspec.append({'full_name': {'$regex': text, '$options': 'i'}})
if andspec:
spec = {'$and': andspec}
else:
spec = {'full_name': {'$regex': search_text, '$options': 'i'}}
# Run the query.
if abbr != 'all':
spec[settings.LEVEL_FIELD] = abbr
legislator_results = list(db.legislators.find(spec).sort(
[('active', -1)]))
if abbr != 'all':
metadata = Metadata.get_object(abbr)
else:
metadata = None
return render(
request, templatename('search_results_bills_legislators'),
dict(search_text=search_text,
abbr=abbr,
metadata=metadata,
found_by_id=found_by_id,
bill_results=bill_results,
bill_result_count=bill_result_count,
more_bills_available=more_bills_available,
legislators_list=legislator_results,
column_headers_tmplname=None, # not used
rowtemplate_name=templatename('bills_list_row_with'
'_abbr_and_session'),
show_chamber_column=True,
nav_active=None)) | Context:
- search_text
- abbr
- metadata
- found_by_id
- bill_results
- more_bills_available
- legislators_list
- nav_active
Tempaltes:
- billy/web/public/search_results_no_query.html
- billy/web/public/search_results_bills_legislators.html
- billy/web/public/bills_list_row_with_abbr_and_session.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/region.py#L106-L185 |
openstates/billy | billy/scrape/committees.py | Committee.add_member | def add_member(self, legislator, role='member', **kwargs):
"""
Add a member to the committee object.
:param legislator: name of the legislator
:param role: role that legislator holds in the committee
(eg. chairman) default: 'member'
"""
self['members'].append(dict(name=legislator, role=role,
**kwargs)) | python | def add_member(self, legislator, role='member', **kwargs):
"""
Add a member to the committee object.
:param legislator: name of the legislator
:param role: role that legislator holds in the committee
(eg. chairman) default: 'member'
"""
self['members'].append(dict(name=legislator, role=role,
**kwargs)) | Add a member to the committee object.
:param legislator: name of the legislator
:param role: role that legislator holds in the committee
(eg. chairman) default: 'member' | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/scrape/committees.py#L32-L41 |
openstates/billy | billy/models/bills.py | Action.action_display | def action_display(self):
'''The action text, with any hyperlinked related entities.'''
action = self['action']
annotations = []
abbr = self.bill[settings.LEVEL_FIELD]
if 'related_entities' in self:
for entity in self['related_entities']:
name = entity['name']
_id = entity['id']
# If the importer couldn't ID the entity,
# skip.
if _id is None:
continue
url = mongoid_2_url(abbr, _id)
link = '<a href="%s">%s</a>' % (url, name)
if name in action:
action = action.replace(entity['name'], link)
else:
annotations.append(link)
if annotations:
action += ' (%s)' % ', '.join(annotations)
return action | python | def action_display(self):
'''The action text, with any hyperlinked related entities.'''
action = self['action']
annotations = []
abbr = self.bill[settings.LEVEL_FIELD]
if 'related_entities' in self:
for entity in self['related_entities']:
name = entity['name']
_id = entity['id']
# If the importer couldn't ID the entity,
# skip.
if _id is None:
continue
url = mongoid_2_url(abbr, _id)
link = '<a href="%s">%s</a>' % (url, name)
if name in action:
action = action.replace(entity['name'], link)
else:
annotations.append(link)
if annotations:
action += ' (%s)' % ', '.join(annotations)
return action | The action text, with any hyperlinked related entities. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L129-L151 |
openstates/billy | billy/models/bills.py | ActionsManager._bytype | def _bytype(self, action_type, action_spec=None):
'''Return the most recent date on which action_type occurred.
Action spec is a dictionary of key-value attrs to match.'''
for action in reversed(self.bill['actions']):
if action_type in action['type']:
for k, v in action_spec.items():
if action[k] == v:
yield action | python | def _bytype(self, action_type, action_spec=None):
'''Return the most recent date on which action_type occurred.
Action spec is a dictionary of key-value attrs to match.'''
for action in reversed(self.bill['actions']):
if action_type in action['type']:
for k, v in action_spec.items():
if action[k] == v:
yield action | Return the most recent date on which action_type occurred.
Action spec is a dictionary of key-value attrs to match. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L161-L168 |
openstates/billy | billy/models/bills.py | BillVote._ratio | def _ratio(self, key):
'''Return the yes/total ratio as a percetage string
suitable for use as as css attribute.'''
total = float(self._total_votes())
try:
return math.floor(self[key] / total * 100)
except ZeroDivisionError:
return float(0) | python | def _ratio(self, key):
'''Return the yes/total ratio as a percetage string
suitable for use as as css attribute.'''
total = float(self._total_votes())
try:
return math.floor(self[key] / total * 100)
except ZeroDivisionError:
return float(0) | Return the yes/total ratio as a percetage string
suitable for use as as css attribute. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L199-L206 |
openstates/billy | billy/models/bills.py | BillVote._legislator_objects | def _legislator_objects(self):
'''A cache of dereferenced legislator objects.
'''
kwargs = {}
id_getter = operator.itemgetter('leg_id')
ids = []
for k in ('yes', 'no', 'other'):
ids.extend(map(id_getter, self[k + '_votes']))
objs = db.legislators.find({'_all_ids': {'$in': ids}}, **kwargs)
# Handy to keep a reference to the vote on each legislator.
objs = list(objs)
id_cache = {}
for obj in objs:
obj.vote = self
for _id in obj['_all_ids']:
id_cache[_id] = obj
return id_cache | python | def _legislator_objects(self):
'''A cache of dereferenced legislator objects.
'''
kwargs = {}
id_getter = operator.itemgetter('leg_id')
ids = []
for k in ('yes', 'no', 'other'):
ids.extend(map(id_getter, self[k + '_votes']))
objs = db.legislators.find({'_all_ids': {'$in': ids}}, **kwargs)
# Handy to keep a reference to the vote on each legislator.
objs = list(objs)
id_cache = {}
for obj in objs:
obj.vote = self
for _id in obj['_all_ids']:
id_cache[_id] = obj
return id_cache | A cache of dereferenced legislator objects. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L226-L245 |
openstates/billy | billy/models/bills.py | BillVote.legislator_vote_value | def legislator_vote_value(self):
'''If this vote was accessed through the legislator.votes_manager,
return the value of this legislator's vote.
'''
if not hasattr(self, 'legislator'):
msg = ('legislator_vote_value can only be called '
'from a vote accessed by legislator.votes_manager.')
raise ValueError(msg)
leg_id = self.legislator.id
for k in ('yes', 'no', 'other'):
for leg in self[k + '_votes']:
if leg['leg_id'] == leg_id:
return k | python | def legislator_vote_value(self):
'''If this vote was accessed through the legislator.votes_manager,
return the value of this legislator's vote.
'''
if not hasattr(self, 'legislator'):
msg = ('legislator_vote_value can only be called '
'from a vote accessed by legislator.votes_manager.')
raise ValueError(msg)
leg_id = self.legislator.id
for k in ('yes', 'no', 'other'):
for leg in self[k + '_votes']:
if leg['leg_id'] == leg_id:
return k | If this vote was accessed through the legislator.votes_manager,
return the value of this legislator's vote. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L248-L260 |
openstates/billy | billy/models/bills.py | BillVote._vote_legislators | def _vote_legislators(self, yes_no_other):
'''Return all legislators who votes yes/no/other on this bill.
'''
#id_getter = operator.itemgetter('leg_id')
#ids = map(id_getter, self['%s_votes' % yes_no_other])
#return map(self._legislator_objects.get, ids)
result = []
for voter in self[yes_no_other + '_votes']:
if voter['leg_id']:
result.append(self._legislator_objects.get(voter['leg_id']))
else:
result.append(voter)
return result | python | def _vote_legislators(self, yes_no_other):
'''Return all legislators who votes yes/no/other on this bill.
'''
#id_getter = operator.itemgetter('leg_id')
#ids = map(id_getter, self['%s_votes' % yes_no_other])
#return map(self._legislator_objects.get, ids)
result = []
for voter in self[yes_no_other + '_votes']:
if voter['leg_id']:
result.append(self._legislator_objects.get(voter['leg_id']))
else:
result.append(voter)
return result | Return all legislators who votes yes/no/other on this bill. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L262-L274 |
openstates/billy | billy/models/bills.py | BillVote.is_probably_a_voice_vote | def is_probably_a_voice_vote(self):
'''Guess whether this vote is a "voice vote".'''
if '+voice_vote' in self:
return True
if '+vote_type' in self:
if self['+vote_type'] == 'Voice':
return True
if 'voice vote' in self['motion'].lower():
return True
return False | python | def is_probably_a_voice_vote(self):
'''Guess whether this vote is a "voice vote".'''
if '+voice_vote' in self:
return True
if '+vote_type' in self:
if self['+vote_type'] == 'Voice':
return True
if 'voice vote' in self['motion'].lower():
return True
return False | Guess whether this vote is a "voice vote". | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/bills.py#L291-L300 |
openstates/billy | billy/models/events.py | Event.bill_objects | def bill_objects(self):
'''Returns a cursor of full bill objects for any bills that have
ids. Not in use anyware as of 12/18/12, but handy to have around.
'''
bills = []
for bill in self['related_bills']:
if 'id' in bill:
bills.append(bill['id'])
return db.bills.find({"_id": {"$in": bills}}) | python | def bill_objects(self):
'''Returns a cursor of full bill objects for any bills that have
ids. Not in use anyware as of 12/18/12, but handy to have around.
'''
bills = []
for bill in self['related_bills']:
if 'id' in bill:
bills.append(bill['id'])
return db.bills.find({"_id": {"$in": bills}}) | Returns a cursor of full bill objects for any bills that have
ids. Not in use anyware as of 12/18/12, but handy to have around. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/events.py#L22-L30 |
openstates/billy | billy/models/events.py | Event.host | def host(self):
'''Return the host committee.
'''
_id = None
for participant in self['participants']:
if participant['type'] == 'host':
if set(['participant_type', 'id']) < set(participant):
# This event uses the id keyname "id".
if participant['participant_type'] == 'committee':
_id = participant['id']
if _id is None:
continue
return self.committees_dict.get(_id)
else:
return participant['participant'] | python | def host(self):
'''Return the host committee.
'''
_id = None
for participant in self['participants']:
if participant['type'] == 'host':
if set(['participant_type', 'id']) < set(participant):
# This event uses the id keyname "id".
if participant['participant_type'] == 'committee':
_id = participant['id']
if _id is None:
continue
return self.committees_dict.get(_id)
else:
return participant['participant'] | Return the host committee. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/events.py#L62-L76 |
openstates/billy | billy/models/events.py | Event.host_chairs | def host_chairs(self):
'''Returns a list of members that chair the host committee,
including "co-chair" and "chairperson." This could concievalby
yield a false positive if the person's title is 'dunce chair'.
'''
chairs = []
# Host is guaranteed to be a committe or none.
host = self.host()
if host is None:
return
for member, full_member in host.members_objects:
if 'chair' in member.get('role', '').lower():
chairs.append((member, full_member))
return chairs | python | def host_chairs(self):
'''Returns a list of members that chair the host committee,
including "co-chair" and "chairperson." This could concievalby
yield a false positive if the person's title is 'dunce chair'.
'''
chairs = []
# Host is guaranteed to be a committe or none.
host = self.host()
if host is None:
return
for member, full_member in host.members_objects:
if 'chair' in member.get('role', '').lower():
chairs.append((member, full_member))
return chairs | Returns a list of members that chair the host committee,
including "co-chair" and "chairperson." This could concievalby
yield a false positive if the person's title is 'dunce chair'. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/events.py#L83-L96 |
openstates/billy | billy/models/events.py | Event.host_members | def host_members(self):
'''Return the members of the host committee.
'''
host = self.host()
if host is None:
return
for member, full_member in host.members_objects:
yield full_member | python | def host_members(self):
'''Return the members of the host committee.
'''
host = self.host()
if host is None:
return
for member, full_member in host.members_objects:
yield full_member | Return the members of the host committee. | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/models/events.py#L103-L110 |
openstates/billy | billy/web/public/views/committees.py | committees | def committees(request, abbr):
'''
Context:
chamber
committees
abbr
metadata
chamber_name
chamber_select_template
chamber_select_collection
chamber_select_chambers
committees_table_template
show_chamber_column
sort_order
nav_active
Templates:
- billy/web/public/committees.html
- billy/web/public/committees-pjax.html
- billy/web/public/chamber_select_form.html
- billy/web/public/committees_table.html
'''
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
chamber = request.GET.get('chamber', 'both')
if chamber in ('upper', 'lower'):
chamber_name = meta['chambers'][chamber]['name']
spec = {'chamber': chamber}
show_chamber_column = False
elif chamber == 'joint':
chamber_name = 'Joint'
spec = {'chamber': 'joint'}
show_chamber_column = False
else:
chamber = 'both'
spec = {}
show_chamber_column = True
chamber_name = ''
chambers = dict((k, v['name']) for k, v in meta['chambers'].items())
if meta.committees({'chamber': 'joint'}).count():
chambers['joint'] = 'Joint'
fields = mongo_fields('committee', 'subcommittee', 'members',
settings.LEVEL_FIELD, 'chamber')
sort_key = request.GET.get('key', 'committee')
sort_order = int(request.GET.get('order', 1))
committees = meta.committees_legislators(spec, fields=fields,
sort=[(sort_key, sort_order)])
sort_order = -sort_order
return TemplateResponse(
request, templatename('committees'),
dict(chamber=chamber, committees=committees, abbr=abbr, metadata=meta,
chamber_name=chamber_name,
chamber_select_template=templatename('chamber_select_form'),
chamber_select_collection='committees',
chamber_select_chambers=chambers,
committees_table_template=templatename('committees_table'),
show_chamber_column=show_chamber_column, sort_order=sort_order,
nav_active='committees')) | python | def committees(request, abbr):
'''
Context:
chamber
committees
abbr
metadata
chamber_name
chamber_select_template
chamber_select_collection
chamber_select_chambers
committees_table_template
show_chamber_column
sort_order
nav_active
Templates:
- billy/web/public/committees.html
- billy/web/public/committees-pjax.html
- billy/web/public/chamber_select_form.html
- billy/web/public/committees_table.html
'''
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
chamber = request.GET.get('chamber', 'both')
if chamber in ('upper', 'lower'):
chamber_name = meta['chambers'][chamber]['name']
spec = {'chamber': chamber}
show_chamber_column = False
elif chamber == 'joint':
chamber_name = 'Joint'
spec = {'chamber': 'joint'}
show_chamber_column = False
else:
chamber = 'both'
spec = {}
show_chamber_column = True
chamber_name = ''
chambers = dict((k, v['name']) for k, v in meta['chambers'].items())
if meta.committees({'chamber': 'joint'}).count():
chambers['joint'] = 'Joint'
fields = mongo_fields('committee', 'subcommittee', 'members',
settings.LEVEL_FIELD, 'chamber')
sort_key = request.GET.get('key', 'committee')
sort_order = int(request.GET.get('order', 1))
committees = meta.committees_legislators(spec, fields=fields,
sort=[(sort_key, sort_order)])
sort_order = -sort_order
return TemplateResponse(
request, templatename('committees'),
dict(chamber=chamber, committees=committees, abbr=abbr, metadata=meta,
chamber_name=chamber_name,
chamber_select_template=templatename('chamber_select_form'),
chamber_select_collection='committees',
chamber_select_chambers=chambers,
committees_table_template=templatename('committees_table'),
show_chamber_column=show_chamber_column, sort_order=sort_order,
nav_active='committees')) | Context:
chamber
committees
abbr
metadata
chamber_name
chamber_select_template
chamber_select_collection
chamber_select_chambers
committees_table_template
show_chamber_column
sort_order
nav_active
Templates:
- billy/web/public/committees.html
- billy/web/public/committees-pjax.html
- billy/web/public/chamber_select_form.html
- billy/web/public/committees_table.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/committees.py#L19-L85 |
openstates/billy | billy/web/public/views/committees.py | committee | def committee(request, abbr, committee_id):
'''
Context:
- committee
- abbr
- metadata
- sources
- nav_active
Tempaltes:
- billy/web/public/committee.html
'''
committee = db.committees.find_one({'_id': committee_id})
if committee is None:
raise Http404
return render(request, templatename('committee'),
dict(committee=committee, abbr=abbr,
metadata=Metadata.get_object(abbr),
sources=committee['sources'],
nav_active='committees')) | python | def committee(request, abbr, committee_id):
'''
Context:
- committee
- abbr
- metadata
- sources
- nav_active
Tempaltes:
- billy/web/public/committee.html
'''
committee = db.committees.find_one({'_id': committee_id})
if committee is None:
raise Http404
return render(request, templatename('committee'),
dict(committee=committee, abbr=abbr,
metadata=Metadata.get_object(abbr),
sources=committee['sources'],
nav_active='committees')) | Context:
- committee
- abbr
- metadata
- sources
- nav_active
Tempaltes:
- billy/web/public/committee.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/committees.py#L89-L109 |
openstates/billy | billy/reports/utils.py | update_common | def update_common(obj, report):
""" do updated_at checks """
# updated checks
if obj['updated_at'] >= yesterday:
report['_updated_today_count'] += 1
if obj['updated_at'] >= last_month:
report['_updated_this_month_count'] += 1
if obj['updated_at'] >= last_year:
report['_updated_this_year_count'] += 1 | python | def update_common(obj, report):
""" do updated_at checks """
# updated checks
if obj['updated_at'] >= yesterday:
report['_updated_today_count'] += 1
if obj['updated_at'] >= last_month:
report['_updated_this_month_count'] += 1
if obj['updated_at'] >= last_year:
report['_updated_this_year_count'] += 1 | do updated_at checks | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/reports/utils.py#L11-L19 |
openstates/billy | billy/web/public/views/legislators.py | legislators | def legislators(request, abbr):
'''
Context:
- metadata
- chamber
- chamber_title
- chamber_select_template
- chamber_select_collection
- chamber_select_chambers
- show_chamber_column
- abbr
- legislators
- sort_order
- sort_key
- legislator_table
- nav_active
Templates:
- billy/web/public/legislators.html
- billy/web/public/chamber_select_form.html
- billy/web/public/legislator_table.html
'''
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
spec = {'active': True, 'district': {'$exists': True}}
chambers = dict((k, v['name']) for k, v in meta['chambers'].items())
chamber = request.GET.get('chamber', 'both')
if chamber in chambers:
spec['chamber'] = chamber
chamber_title = meta['chambers'][chamber]['title'] + 's'
else:
chamber = 'both'
chamber_title = 'Legislators'
fields = mongo_fields('leg_id', 'full_name', 'photo_url', 'district',
'party', 'first_name', 'last_name', 'chamber',
billy_settings.LEVEL_FIELD, 'last_name')
sort_key = 'district'
sort_order = 1
if request.GET:
sort_key = request.GET.get('key', sort_key)
sort_order = int(request.GET.get('order', sort_order))
legislators = meta.legislators(extra_spec=spec, fields=fields)
def sort_by_district(obj):
matchobj = re.search(r'\d+', obj.get('district', '') or '')
if matchobj:
return int(matchobj.group())
else:
return obj.get('district', '')
legislators = sorted(legislators, key=sort_by_district)
if sort_key != 'district':
legislators = sorted(legislators, key=operator.itemgetter(sort_key),
reverse=(sort_order == -1))
else:
legislators = sorted(legislators, key=sort_by_district,
reverse=bool(0 > sort_order))
sort_order = {1: -1, -1: 1}[sort_order]
legislators = list(legislators)
return TemplateResponse(
request, templatename('legislators'),
dict(metadata=meta, chamber=chamber,
chamber_title=chamber_title,
chamber_select_template=templatename('chamber_select_form'),
chamber_select_collection='legislators',
chamber_select_chambers=chambers, show_chamber_column=True,
abbr=abbr, legislators=legislators, sort_order=sort_order,
sort_key=sort_key,
legislator_table=templatename('legislator_table'),
nav_active='legislators')) | python | def legislators(request, abbr):
'''
Context:
- metadata
- chamber
- chamber_title
- chamber_select_template
- chamber_select_collection
- chamber_select_chambers
- show_chamber_column
- abbr
- legislators
- sort_order
- sort_key
- legislator_table
- nav_active
Templates:
- billy/web/public/legislators.html
- billy/web/public/chamber_select_form.html
- billy/web/public/legislator_table.html
'''
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
spec = {'active': True, 'district': {'$exists': True}}
chambers = dict((k, v['name']) for k, v in meta['chambers'].items())
chamber = request.GET.get('chamber', 'both')
if chamber in chambers:
spec['chamber'] = chamber
chamber_title = meta['chambers'][chamber]['title'] + 's'
else:
chamber = 'both'
chamber_title = 'Legislators'
fields = mongo_fields('leg_id', 'full_name', 'photo_url', 'district',
'party', 'first_name', 'last_name', 'chamber',
billy_settings.LEVEL_FIELD, 'last_name')
sort_key = 'district'
sort_order = 1
if request.GET:
sort_key = request.GET.get('key', sort_key)
sort_order = int(request.GET.get('order', sort_order))
legislators = meta.legislators(extra_spec=spec, fields=fields)
def sort_by_district(obj):
matchobj = re.search(r'\d+', obj.get('district', '') or '')
if matchobj:
return int(matchobj.group())
else:
return obj.get('district', '')
legislators = sorted(legislators, key=sort_by_district)
if sort_key != 'district':
legislators = sorted(legislators, key=operator.itemgetter(sort_key),
reverse=(sort_order == -1))
else:
legislators = sorted(legislators, key=sort_by_district,
reverse=bool(0 > sort_order))
sort_order = {1: -1, -1: 1}[sort_order]
legislators = list(legislators)
return TemplateResponse(
request, templatename('legislators'),
dict(metadata=meta, chamber=chamber,
chamber_title=chamber_title,
chamber_select_template=templatename('chamber_select_form'),
chamber_select_collection='legislators',
chamber_select_chambers=chambers, show_chamber_column=True,
abbr=abbr, legislators=legislators, sort_order=sort_order,
sort_key=sort_key,
legislator_table=templatename('legislator_table'),
nav_active='legislators')) | Context:
- metadata
- chamber
- chamber_title
- chamber_select_template
- chamber_select_collection
- chamber_select_chambers
- show_chamber_column
- abbr
- legislators
- sort_order
- sort_key
- legislator_table
- nav_active
Templates:
- billy/web/public/legislators.html
- billy/web/public/chamber_select_form.html
- billy/web/public/legislator_table.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/legislators.py#L25-L106 |
openstates/billy | billy/web/public/views/legislators.py | legislator | def legislator(request, abbr, _id, slug=None):
'''
Context:
- vote_preview_row_template
- roles
- abbr
- district_id
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vote_preview_row.html
'''
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
legislator = db.legislators.find_one({'_id': _id})
if legislator is None:
spec = {'_all_ids': _id}
cursor = db.legislators.find(spec)
msg = 'Two legislators returned for spec %r' % spec
assert cursor.count() < 2, msg
try:
legislator = next(cursor)
except StopIteration:
raise Http404('No legislator was found with leg_id = %r' % _id)
else:
return redirect(legislator.get_absolute_url(), permanent=True)
if not legislator['active']:
return legislator_inactive(request, abbr, legislator)
district = db.districts.find({'abbr': abbr, 'chamber': legislator['chamber'],
'name': legislator['district']})
if district:
district_id = district[0]['division_id']
else:
district_id = None
sponsored_bills = legislator.sponsored_bills(
limit=6, sort=[('action_dates.first', pymongo.DESCENDING)])
# Note to self: Another slow query
legislator_votes = legislator.votes_6_sorted()
has_votes = bool(legislator_votes)
return render(
request, templatename('legislator'),
dict(vote_preview_row_template=templatename('vote_preview_row'),
roles=legislator.roles_manager, abbr=abbr,
district_id=district_id, metadata=meta, legislator=legislator,
sources=legislator['sources'],
sponsored_bills=list(sponsored_bills),
legislator_votes=list(legislator_votes),
has_votes=has_votes,
nav_active='legislators')) | python | def legislator(request, abbr, _id, slug=None):
'''
Context:
- vote_preview_row_template
- roles
- abbr
- district_id
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vote_preview_row.html
'''
try:
meta = Metadata.get_object(abbr)
except DoesNotExist:
raise Http404
legislator = db.legislators.find_one({'_id': _id})
if legislator is None:
spec = {'_all_ids': _id}
cursor = db.legislators.find(spec)
msg = 'Two legislators returned for spec %r' % spec
assert cursor.count() < 2, msg
try:
legislator = next(cursor)
except StopIteration:
raise Http404('No legislator was found with leg_id = %r' % _id)
else:
return redirect(legislator.get_absolute_url(), permanent=True)
if not legislator['active']:
return legislator_inactive(request, abbr, legislator)
district = db.districts.find({'abbr': abbr, 'chamber': legislator['chamber'],
'name': legislator['district']})
if district:
district_id = district[0]['division_id']
else:
district_id = None
sponsored_bills = legislator.sponsored_bills(
limit=6, sort=[('action_dates.first', pymongo.DESCENDING)])
# Note to self: Another slow query
legislator_votes = legislator.votes_6_sorted()
has_votes = bool(legislator_votes)
return render(
request, templatename('legislator'),
dict(vote_preview_row_template=templatename('vote_preview_row'),
roles=legislator.roles_manager, abbr=abbr,
district_id=district_id, metadata=meta, legislator=legislator,
sources=legislator['sources'],
sponsored_bills=list(sponsored_bills),
legislator_votes=list(legislator_votes),
has_votes=has_votes,
nav_active='legislators')) | Context:
- vote_preview_row_template
- roles
- abbr
- district_id
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vote_preview_row.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/legislators.py#L110-L173 |
openstates/billy | billy/web/public/views/legislators.py | legislator_inactive | def legislator_inactive(request, abbr, legislator):
'''
Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vote_preview_row.html
'''
sponsored_bills = legislator.sponsored_bills(
limit=6, sort=[('action_dates.first', pymongo.DESCENDING)])
legislator_votes = list(legislator.votes_6_sorted())
has_votes = bool(legislator_votes)
return render(
request, templatename('legislator'),
dict(vote_preview_row_template=templatename('vote_preview_row'),
old_roles=legislator.old_roles_manager,
abbr=abbr,
metadata=legislator.metadata,
legislator=legislator,
sources=legislator['sources'],
sponsored_bills=list(sponsored_bills),
legislator_votes=legislator_votes,
has_votes=has_votes,
nav_active='legislators')) | python | def legislator_inactive(request, abbr, legislator):
'''
Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vote_preview_row.html
'''
sponsored_bills = legislator.sponsored_bills(
limit=6, sort=[('action_dates.first', pymongo.DESCENDING)])
legislator_votes = list(legislator.votes_6_sorted())
has_votes = bool(legislator_votes)
return render(
request, templatename('legislator'),
dict(vote_preview_row_template=templatename('vote_preview_row'),
old_roles=legislator.old_roles_manager,
abbr=abbr,
metadata=legislator.metadata,
legislator=legislator,
sources=legislator['sources'],
sponsored_bills=list(sponsored_bills),
legislator_votes=legislator_votes,
has_votes=has_votes,
nav_active='legislators')) | Context:
- vote_preview_row_template
- old_roles
- abbr
- metadata
- legislator
- sources
- sponsored_bills
- legislator_votes
- has_votes
- nav_active
Templates:
- billy/web/public/legislator.html
- billy/web/public/vote_preview_row.html | https://github.com/openstates/billy/blob/5fc795347f12a949e410a8cfad0c911ea6bced67/billy/web/public/views/legislators.py#L176-L211 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | normalize_rank | def normalize_rank(rank):
"""Normalize a rank in order to be schema-compliant."""
normalized_ranks = {
'BA': 'UNDERGRADUATE',
'BACHELOR': 'UNDERGRADUATE',
'BS': 'UNDERGRADUATE',
'BSC': 'UNDERGRADUATE',
'JUNIOR': 'JUNIOR',
'MAS': 'MASTER',
'MASTER': 'MASTER',
'MS': 'MASTER',
'MSC': 'MASTER',
'PD': 'POSTDOC',
'PHD': 'PHD',
'POSTDOC': 'POSTDOC',
'SENIOR': 'SENIOR',
'STAFF': 'STAFF',
'STUDENT': 'PHD',
'UG': 'UNDERGRADUATE',
'UNDERGRADUATE': 'UNDERGRADUATE',
'VISITING SCIENTIST': 'VISITOR',
'VISITOR': 'VISITOR',
}
if not rank:
return None
rank = rank.upper().replace('.', '')
return normalized_ranks.get(rank, 'OTHER') | python | def normalize_rank(rank):
"""Normalize a rank in order to be schema-compliant."""
normalized_ranks = {
'BA': 'UNDERGRADUATE',
'BACHELOR': 'UNDERGRADUATE',
'BS': 'UNDERGRADUATE',
'BSC': 'UNDERGRADUATE',
'JUNIOR': 'JUNIOR',
'MAS': 'MASTER',
'MASTER': 'MASTER',
'MS': 'MASTER',
'MSC': 'MASTER',
'PD': 'POSTDOC',
'PHD': 'PHD',
'POSTDOC': 'POSTDOC',
'SENIOR': 'SENIOR',
'STAFF': 'STAFF',
'STUDENT': 'PHD',
'UG': 'UNDERGRADUATE',
'UNDERGRADUATE': 'UNDERGRADUATE',
'VISITING SCIENTIST': 'VISITOR',
'VISITOR': 'VISITOR',
}
if not rank:
return None
rank = rank.upper().replace('.', '')
return normalized_ranks.get(rank, 'OTHER') | Normalize a rank in order to be schema-compliant. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L50-L76 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | get_recid_from_ref | def get_recid_from_ref(ref_obj):
"""Retrieve recid from jsonref reference object.
If no recid can be parsed, returns None.
"""
if not isinstance(ref_obj, dict):
return None
url = ref_obj.get('$ref', '')
return maybe_int(url.split('/')[-1]) | python | def get_recid_from_ref(ref_obj):
"""Retrieve recid from jsonref reference object.
If no recid can be parsed, returns None.
"""
if not isinstance(ref_obj, dict):
return None
url = ref_obj.get('$ref', '')
return maybe_int(url.split('/')[-1]) | Retrieve recid from jsonref reference object.
If no recid can be parsed, returns None. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L87-L95 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | absolute_url | def absolute_url(relative_url):
"""Returns an absolute URL from a URL relative to the server root.
The base URL is taken from the Flask app config if present, otherwise it
falls back to ``http://inspirehep.net``.
"""
default_server = 'http://inspirehep.net'
server = current_app.config.get('SERVER_NAME', default_server)
if not re.match('^https?://', server):
server = u'http://{}'.format(server)
return urllib.parse.urljoin(server, relative_url) | python | def absolute_url(relative_url):
"""Returns an absolute URL from a URL relative to the server root.
The base URL is taken from the Flask app config if present, otherwise it
falls back to ``http://inspirehep.net``.
"""
default_server = 'http://inspirehep.net'
server = current_app.config.get('SERVER_NAME', default_server)
if not re.match('^https?://', server):
server = u'http://{}'.format(server)
return urllib.parse.urljoin(server, relative_url) | Returns an absolute URL from a URL relative to the server root.
The base URL is taken from the Flask app config if present, otherwise it
falls back to ``http://inspirehep.net``. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L98-L108 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | afs_url | def afs_url(file_path):
"""Convert a file path to a URL pointing to its path on AFS.
If ``file_path`` doesn't start with ``/opt/cds-invenio/``, and hence is not on
AFS, it returns it unchanged.
The base AFS path is taken from the Flask app config if present, otherwise
it falls back to ``/afs/cern.ch/project/inspire/PROD``.
"""
default_afs_path = '/afs/cern.ch/project/inspire/PROD'
afs_path = current_app.config.get('LEGACY_AFS_PATH', default_afs_path)
if file_path is None:
return
if file_path.startswith('/opt/cds-invenio/'):
file_path = os.path.relpath(file_path, '/opt/cds-invenio/')
file_path = os.path.join(afs_path, file_path)
return urllib.parse.urljoin('file://', urllib.request.pathname2url(file_path.encode('utf-8')))
return file_path | python | def afs_url(file_path):
"""Convert a file path to a URL pointing to its path on AFS.
If ``file_path`` doesn't start with ``/opt/cds-invenio/``, and hence is not on
AFS, it returns it unchanged.
The base AFS path is taken from the Flask app config if present, otherwise
it falls back to ``/afs/cern.ch/project/inspire/PROD``.
"""
default_afs_path = '/afs/cern.ch/project/inspire/PROD'
afs_path = current_app.config.get('LEGACY_AFS_PATH', default_afs_path)
if file_path is None:
return
if file_path.startswith('/opt/cds-invenio/'):
file_path = os.path.relpath(file_path, '/opt/cds-invenio/')
file_path = os.path.join(afs_path, file_path)
return urllib.parse.urljoin('file://', urllib.request.pathname2url(file_path.encode('utf-8')))
return file_path | Convert a file path to a URL pointing to its path on AFS.
If ``file_path`` doesn't start with ``/opt/cds-invenio/``, and hence is not on
AFS, it returns it unchanged.
The base AFS path is taken from the Flask app config if present, otherwise
it falls back to ``/afs/cern.ch/project/inspire/PROD``. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L111-L131 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | strip_empty_values | def strip_empty_values(obj):
"""Recursively strips empty values."""
if isinstance(obj, dict):
new_obj = {}
for key, val in obj.items():
new_val = strip_empty_values(val)
if new_val is not None:
new_obj[key] = new_val
return new_obj or None
elif isinstance(obj, (list, tuple, set)):
new_obj = []
for val in obj:
new_val = strip_empty_values(val)
if new_val is not None:
new_obj.append(new_val)
return type(obj)(new_obj) or None
elif obj or obj is False or obj == 0:
return obj
else:
return None | python | def strip_empty_values(obj):
"""Recursively strips empty values."""
if isinstance(obj, dict):
new_obj = {}
for key, val in obj.items():
new_val = strip_empty_values(val)
if new_val is not None:
new_obj[key] = new_val
return new_obj or None
elif isinstance(obj, (list, tuple, set)):
new_obj = []
for val in obj:
new_val = strip_empty_values(val)
if new_val is not None:
new_obj.append(new_val)
return type(obj)(new_obj) or None
elif obj or obj is False or obj == 0:
return obj
else:
return None | Recursively strips empty values. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L145-L164 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | dedupe_all_lists | def dedupe_all_lists(obj, exclude_keys=()):
"""Recursively remove duplucates from all lists.
Args:
obj: collection to deduplicate
exclude_keys (Container[str]): key names to ignore for deduplication
"""
squared_dedupe_len = 10
if isinstance(obj, dict):
new_obj = {}
for key, value in obj.items():
if key in exclude_keys:
new_obj[key] = value
else:
new_obj[key] = dedupe_all_lists(value)
return new_obj
elif isinstance(obj, (list, tuple, set)):
new_elements = [dedupe_all_lists(v) for v in obj]
if len(new_elements) < squared_dedupe_len:
new_obj = dedupe_list(new_elements)
else:
new_obj = dedupe_list_of_dicts(new_elements)
return type(obj)(new_obj)
else:
return obj | python | def dedupe_all_lists(obj, exclude_keys=()):
"""Recursively remove duplucates from all lists.
Args:
obj: collection to deduplicate
exclude_keys (Container[str]): key names to ignore for deduplication
"""
squared_dedupe_len = 10
if isinstance(obj, dict):
new_obj = {}
for key, value in obj.items():
if key in exclude_keys:
new_obj[key] = value
else:
new_obj[key] = dedupe_all_lists(value)
return new_obj
elif isinstance(obj, (list, tuple, set)):
new_elements = [dedupe_all_lists(v) for v in obj]
if len(new_elements) < squared_dedupe_len:
new_obj = dedupe_list(new_elements)
else:
new_obj = dedupe_list_of_dicts(new_elements)
return type(obj)(new_obj)
else:
return obj | Recursively remove duplucates from all lists.
Args:
obj: collection to deduplicate
exclude_keys (Container[str]): key names to ignore for deduplication | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L167-L191 |
inspirehep/inspire-dojson | inspire_dojson/utils/__init__.py | normalize_date_aggressively | def normalize_date_aggressively(date):
"""Normalize date, stripping date parts until a valid date is obtained."""
def _strip_last_part(date):
parts = date.split('-')
return '-'.join(parts[:-1])
fake_dates = {'0000', '9999'}
if date in fake_dates:
return None
try:
return normalize_date(date)
except ValueError:
if '-' not in date:
raise
else:
new_date = _strip_last_part(date)
return normalize_date_aggressively(new_date) | python | def normalize_date_aggressively(date):
"""Normalize date, stripping date parts until a valid date is obtained."""
def _strip_last_part(date):
parts = date.split('-')
return '-'.join(parts[:-1])
fake_dates = {'0000', '9999'}
if date in fake_dates:
return None
try:
return normalize_date(date)
except ValueError:
if '-' not in date:
raise
else:
new_date = _strip_last_part(date)
return normalize_date_aggressively(new_date) | Normalize date, stripping date parts until a valid date is obtained. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/__init__.py#L194-L210 |
inspirehep/inspire-dojson | inspire_dojson/utils/geo.py | match_country_name_to_its_code | def match_country_name_to_its_code(country_name, city=''):
"""Try to match country name with its code.
Name of the city helps when country_name is "Korea".
"""
if country_name:
country_name = country_name.upper().replace('.', '').strip()
if country_to_iso_code.get(country_name):
return country_to_iso_code.get(country_name)
elif country_name == 'KOREA':
if city.upper() in south_korean_cities:
return 'KR'
else:
for c_code, spellings in countries_alternative_spellings.items():
for spelling in spellings:
if country_name == spelling:
return c_code
return None | python | def match_country_name_to_its_code(country_name, city=''):
"""Try to match country name with its code.
Name of the city helps when country_name is "Korea".
"""
if country_name:
country_name = country_name.upper().replace('.', '').strip()
if country_to_iso_code.get(country_name):
return country_to_iso_code.get(country_name)
elif country_name == 'KOREA':
if city.upper() in south_korean_cities:
return 'KR'
else:
for c_code, spellings in countries_alternative_spellings.items():
for spelling in spellings:
if country_name == spelling:
return c_code
return None | Try to match country name with its code.
Name of the city helps when country_name is "Korea". | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/geo.py#L469-L488 |
inspirehep/inspire-dojson | inspire_dojson/utils/geo.py | match_us_state | def match_us_state(state_string):
"""Try to match a string with one of the states in the US."""
if state_string:
state_string = state_string.upper().replace('.', '').strip()
if us_state_to_iso_code.get(state_string):
return us_state_to_iso_code.get(state_string)
else:
for code, state_spellings in us_states_alternative_spellings.items():
for spelling in state_spellings:
if state_string == spelling:
return code
return None | python | def match_us_state(state_string):
"""Try to match a string with one of the states in the US."""
if state_string:
state_string = state_string.upper().replace('.', '').strip()
if us_state_to_iso_code.get(state_string):
return us_state_to_iso_code.get(state_string)
else:
for code, state_spellings in us_states_alternative_spellings.items():
for spelling in state_spellings:
if state_string == spelling:
return code
return None | Try to match a string with one of the states in the US. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/geo.py#L491-L502 |
inspirehep/inspire-dojson | inspire_dojson/utils/geo.py | parse_conference_address | def parse_conference_address(address_string):
"""Parse a conference address.
This is a pretty dummy address parser. It only extracts country
and state (for US) and should be replaced with something better,
like Google Geocoding.
"""
geo_elements = address_string.split(',')
city = geo_elements[0]
country_name = geo_elements[-1].upper().replace('.', '').strip()
us_state = None
state = None
country_code = None
# Try to match the country
country_code = match_country_name_to_its_code(country_name, city)
if country_code == 'US' and len(geo_elements) > 1:
us_state = match_us_state(geo_elements[-2].upper().strip()
.replace('.', ''))
if not country_code:
# Sometimes the country name stores info about U.S. state
us_state = match_us_state(country_name)
if us_state:
state = us_state
country_code = 'US'
return {
'cities': [
city,
],
'country_code': country_code,
'postal_code': None,
'state': state,
} | python | def parse_conference_address(address_string):
"""Parse a conference address.
This is a pretty dummy address parser. It only extracts country
and state (for US) and should be replaced with something better,
like Google Geocoding.
"""
geo_elements = address_string.split(',')
city = geo_elements[0]
country_name = geo_elements[-1].upper().replace('.', '').strip()
us_state = None
state = None
country_code = None
# Try to match the country
country_code = match_country_name_to_its_code(country_name, city)
if country_code == 'US' and len(geo_elements) > 1:
us_state = match_us_state(geo_elements[-2].upper().strip()
.replace('.', ''))
if not country_code:
# Sometimes the country name stores info about U.S. state
us_state = match_us_state(country_name)
if us_state:
state = us_state
country_code = 'US'
return {
'cities': [
city,
],
'country_code': country_code,
'postal_code': None,
'state': state,
} | Parse a conference address.
This is a pretty dummy address parser. It only extracts country
and state (for US) and should be replaced with something better,
like Google Geocoding. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/geo.py#L505-L542 |
inspirehep/inspire-dojson | inspire_dojson/utils/geo.py | parse_institution_address | def parse_institution_address(address, city, state_province,
country, postal_code, country_code):
"""Parse an institution address."""
address_list = force_list(address)
state_province = match_us_state(state_province) or state_province
postal_code = force_list(postal_code)
country = force_list(country)
country_code = match_country_code(country_code)
if isinstance(postal_code, (tuple, list)):
postal_code = ', '.join(postal_code)
if isinstance(country, (tuple, list)):
country = ', '.join(set(country))
if not country_code and country:
country_code = match_country_name_to_its_code(country)
if not country_code and state_province and state_province in us_state_to_iso_code.values():
country_code = 'US'
return {
'cities': force_list(city),
'country_code': country_code,
'postal_address': address_list,
'postal_code': postal_code,
'state': state_province,
} | python | def parse_institution_address(address, city, state_province,
country, postal_code, country_code):
"""Parse an institution address."""
address_list = force_list(address)
state_province = match_us_state(state_province) or state_province
postal_code = force_list(postal_code)
country = force_list(country)
country_code = match_country_code(country_code)
if isinstance(postal_code, (tuple, list)):
postal_code = ', '.join(postal_code)
if isinstance(country, (tuple, list)):
country = ', '.join(set(country))
if not country_code and country:
country_code = match_country_name_to_its_code(country)
if not country_code and state_province and state_province in us_state_to_iso_code.values():
country_code = 'US'
return {
'cities': force_list(city),
'country_code': country_code,
'postal_address': address_list,
'postal_code': postal_code,
'state': state_province,
} | Parse an institution address. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/utils/geo.py#L545-L573 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | ids2marc | def ids2marc(self, key, value):
"""Populate the ``035`` MARC field.
Also populates the ``8564`` and ``970`` MARC field through side effects.
"""
def _is_schema_inspire_bai(id_, schema):
return schema == 'INSPIRE BAI'
def _is_schema_inspire_id(id_, schema):
return schema == 'INSPIRE ID'
def _is_schema_spires(id_, schema):
return schema == 'SPIRES'
def _is_schema_linkedin(id, schema):
return schema == 'LINKEDIN'
def _is_schema_twitter(id, schema):
return schema == 'TWITTER'
id_ = value.get('value')
schema = value.get('schema')
if _is_schema_spires(id_, schema):
self.setdefault('970', []).append({'a': id_})
elif _is_schema_linkedin(id_, schema):
self.setdefault('8564', []).append(
{
'u': u'https://www.linkedin.com/in/{id}'.format(id=quote_url(id_)),
'y': 'LINKEDIN',
}
)
elif _is_schema_twitter(id_, schema):
self.setdefault('8564', []).append(
{
'u': u'https://twitter.com/{id}'.format(id=id_),
'y': 'TWITTER',
}
)
elif _is_schema_inspire_id(id_, schema):
return {
'a': id_,
'9': 'INSPIRE',
}
elif _is_schema_inspire_bai(id_, schema):
return {
'a': id_,
'9': 'BAI',
}
else:
return {
'a': id_,
'9': schema,
} | python | def ids2marc(self, key, value):
"""Populate the ``035`` MARC field.
Also populates the ``8564`` and ``970`` MARC field through side effects.
"""
def _is_schema_inspire_bai(id_, schema):
return schema == 'INSPIRE BAI'
def _is_schema_inspire_id(id_, schema):
return schema == 'INSPIRE ID'
def _is_schema_spires(id_, schema):
return schema == 'SPIRES'
def _is_schema_linkedin(id, schema):
return schema == 'LINKEDIN'
def _is_schema_twitter(id, schema):
return schema == 'TWITTER'
id_ = value.get('value')
schema = value.get('schema')
if _is_schema_spires(id_, schema):
self.setdefault('970', []).append({'a': id_})
elif _is_schema_linkedin(id_, schema):
self.setdefault('8564', []).append(
{
'u': u'https://www.linkedin.com/in/{id}'.format(id=quote_url(id_)),
'y': 'LINKEDIN',
}
)
elif _is_schema_twitter(id_, schema):
self.setdefault('8564', []).append(
{
'u': u'https://twitter.com/{id}'.format(id=id_),
'y': 'TWITTER',
}
)
elif _is_schema_inspire_id(id_, schema):
return {
'a': id_,
'9': 'INSPIRE',
}
elif _is_schema_inspire_bai(id_, schema):
return {
'a': id_,
'9': 'BAI',
}
else:
return {
'a': id_,
'9': schema,
} | Populate the ``035`` MARC field.
Also populates the ``8564`` and ``970`` MARC field through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L119-L172 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | name | def name(self, key, value):
"""Populate the ``name`` key.
Also populates the ``status``, ``birth_date`` and ``death_date`` keys through side effects.
"""
def _get_title(value):
c_value = force_single_element(value.get('c', ''))
if c_value != 'title (e.g. Sir)':
return c_value
def _get_value(value):
a_value = force_single_element(value.get('a', ''))
q_value = force_single_element(value.get('q', ''))
return a_value or normalize_name(q_value)
if value.get('d'):
dates = value['d']
try:
self['death_date'] = normalize_date(dates)
except ValueError:
dates = dates.split(' - ')
if len(dates) == 1:
dates = dates[0].split('-')
self['birth_date'] = normalize_date(dates[0])
self['death_date'] = normalize_date(dates[1])
self['status'] = force_single_element(value.get('g', '')).lower()
return {
'numeration': force_single_element(value.get('b', '')),
'preferred_name': force_single_element(value.get('q', '')),
'title': _get_title(value),
'value': _get_value(value),
} | python | def name(self, key, value):
"""Populate the ``name`` key.
Also populates the ``status``, ``birth_date`` and ``death_date`` keys through side effects.
"""
def _get_title(value):
c_value = force_single_element(value.get('c', ''))
if c_value != 'title (e.g. Sir)':
return c_value
def _get_value(value):
a_value = force_single_element(value.get('a', ''))
q_value = force_single_element(value.get('q', ''))
return a_value or normalize_name(q_value)
if value.get('d'):
dates = value['d']
try:
self['death_date'] = normalize_date(dates)
except ValueError:
dates = dates.split(' - ')
if len(dates) == 1:
dates = dates[0].split('-')
self['birth_date'] = normalize_date(dates[0])
self['death_date'] = normalize_date(dates[1])
self['status'] = force_single_element(value.get('g', '')).lower()
return {
'numeration': force_single_element(value.get('b', '')),
'preferred_name': force_single_element(value.get('q', '')),
'title': _get_title(value),
'value': _get_value(value),
} | Populate the ``name`` key.
Also populates the ``status``, ``birth_date`` and ``death_date`` keys through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L176-L209 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | name2marc | def name2marc(self, key, value):
"""Populates the ``100`` field.
Also populates the ``400``, ``880``, and ``667`` fields through side
effects.
"""
result = self.get('100', {})
result['a'] = value.get('value')
result['b'] = value.get('numeration')
result['c'] = value.get('title')
result['q'] = value.get('preferred_name')
if 'name_variants' in value:
self['400'] = [{'a': el} for el in value['name_variants']]
if 'native_names' in value:
self['880'] = [{'a': el} for el in value['native_names']]
if 'previous_names' in value:
prev_names = [
{'a': u'Formerly {}'.format(prev_name)}
for prev_name in value['previous_names']
]
self['667'] = prev_names
return result | python | def name2marc(self, key, value):
"""Populates the ``100`` field.
Also populates the ``400``, ``880``, and ``667`` fields through side
effects.
"""
result = self.get('100', {})
result['a'] = value.get('value')
result['b'] = value.get('numeration')
result['c'] = value.get('title')
result['q'] = value.get('preferred_name')
if 'name_variants' in value:
self['400'] = [{'a': el} for el in value['name_variants']]
if 'native_names' in value:
self['880'] = [{'a': el} for el in value['native_names']]
if 'previous_names' in value:
prev_names = [
{'a': u'Formerly {}'.format(prev_name)}
for prev_name in value['previous_names']
]
self['667'] = prev_names
return result | Populates the ``100`` field.
Also populates the ``400``, ``880``, and ``667`` fields through side
effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L213-L237 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | positions | def positions(self, key, value):
"""Populate the positions field.
Also populates the email_addresses field by side effect.
"""
email_addresses = self.get("email_addresses", [])
current = None
record = None
recid_or_status = force_list(value.get('z'))
for el in recid_or_status:
if el.lower() == 'current':
current = True if value.get('a') else None
else:
record = get_record_ref(maybe_int(el), 'institutions')
rank = normalize_rank(value.get('r'))
current_email_addresses = force_list(value.get('m'))
non_current_email_addresses = force_list(value.get('o'))
email_addresses.extend({
'value': address,
'current': True,
} for address in current_email_addresses)
email_addresses.extend({
'value': address,
'current': False,
} for address in non_current_email_addresses)
self['email_addresses'] = email_addresses
if 'a' not in value:
return None
return {
'institution': value['a'],
'record': record,
'curated_relation': True if record is not None else None,
'rank': rank,
'start_date': normalize_date(value.get('s')),
'end_date': normalize_date(value.get('t')),
'current': current,
} | python | def positions(self, key, value):
"""Populate the positions field.
Also populates the email_addresses field by side effect.
"""
email_addresses = self.get("email_addresses", [])
current = None
record = None
recid_or_status = force_list(value.get('z'))
for el in recid_or_status:
if el.lower() == 'current':
current = True if value.get('a') else None
else:
record = get_record_ref(maybe_int(el), 'institutions')
rank = normalize_rank(value.get('r'))
current_email_addresses = force_list(value.get('m'))
non_current_email_addresses = force_list(value.get('o'))
email_addresses.extend({
'value': address,
'current': True,
} for address in current_email_addresses)
email_addresses.extend({
'value': address,
'current': False,
} for address in non_current_email_addresses)
self['email_addresses'] = email_addresses
if 'a' not in value:
return None
return {
'institution': value['a'],
'record': record,
'curated_relation': True if record is not None else None,
'rank': rank,
'start_date': normalize_date(value.get('s')),
'end_date': normalize_date(value.get('t')),
'current': current,
} | Populate the positions field.
Also populates the email_addresses field by side effect. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L251-L294 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | email_addresses2marc | def email_addresses2marc(self, key, value):
"""Populate the 595 MARCXML field.
Also populates the 371 field as a side effect.
"""
m_or_o = 'm' if value.get('current') else 'o'
element = {
m_or_o: value.get('value')
}
if value.get('hidden'):
return element
else:
self.setdefault('371', []).append(element)
return None | python | def email_addresses2marc(self, key, value):
"""Populate the 595 MARCXML field.
Also populates the 371 field as a side effect.
"""
m_or_o = 'm' if value.get('current') else 'o'
element = {
m_or_o: value.get('value')
}
if value.get('hidden'):
return element
else:
self.setdefault('371', []).append(element)
return None | Populate the 595 MARCXML field.
Also populates the 371 field as a side effect. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L327-L341 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | email_addresses595 | def email_addresses595(self, key, value):
"""Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect.
"""
emails = self.get('email_addresses', [])
if value.get('o'):
emails.append({
'value': value.get('o'),
'current': False,
'hidden': True,
})
if value.get('m'):
emails.append({
'value': value.get('m'),
'current': True,
'hidden': True,
})
notes = self.get('_private_notes', [])
new_note = (
{
'source': value.get('9'),
'value': _private_note,
} for _private_note in force_list(value.get('a'))
)
notes.extend(new_note)
self['_private_notes'] = notes
return emails | python | def email_addresses595(self, key, value):
"""Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect.
"""
emails = self.get('email_addresses', [])
if value.get('o'):
emails.append({
'value': value.get('o'),
'current': False,
'hidden': True,
})
if value.get('m'):
emails.append({
'value': value.get('m'),
'current': True,
'hidden': True,
})
notes = self.get('_private_notes', [])
new_note = (
{
'source': value.get('9'),
'value': _private_note,
} for _private_note in force_list(value.get('a'))
)
notes.extend(new_note)
self['_private_notes'] = notes
return emails | Populates the ``email_addresses`` field using the 595 MARCXML field.
Also populates ``_private_notes`` as a side effect. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L345-L376 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | arxiv_categories | def arxiv_categories(self, key, value):
"""Populate the ``arxiv_categories`` key.
Also populates the ``inspire_categories`` key through side effects.
"""
def _is_arxiv(category):
return category in valid_arxiv_categories()
def _is_inspire(category):
schema = load_schema('elements/inspire_field')
valid_inspire_categories = schema['properties']['term']['enum']
return category in valid_inspire_categories
def _normalize(a_value):
for category in valid_arxiv_categories():
if a_value.lower() == category.lower():
return normalize_arxiv_category(category)
schema = load_schema('elements/inspire_field')
valid_inspire_categories = schema['properties']['term']['enum']
for category in valid_inspire_categories:
if a_value.lower() == category.lower():
return category
field_codes_to_inspire_categories = {
'a': 'Astrophysics',
'b': 'Accelerators',
'c': 'Computing',
'e': 'Experiment-HEP',
'g': 'Gravitation and Cosmology',
'i': 'Instrumentation',
'l': 'Lattice',
'm': 'Math and Math Physics',
'n': 'Theory-Nucl',
'o': 'Other',
'p': 'Phenomenology-HEP',
'q': 'General Physics',
't': 'Theory-HEP',
'x': 'Experiment-Nucl',
}
return field_codes_to_inspire_categories.get(a_value.lower())
arxiv_categories = self.get('arxiv_categories', [])
inspire_categories = self.get('inspire_categories', [])
for value in force_list(value):
for a_value in force_list(value.get('a')):
normalized_a_value = _normalize(a_value)
if _is_arxiv(normalized_a_value):
arxiv_categories.append(normalized_a_value)
elif _is_inspire(normalized_a_value):
inspire_categories.append({'term': normalized_a_value})
self['inspire_categories'] = inspire_categories
return arxiv_categories | python | def arxiv_categories(self, key, value):
"""Populate the ``arxiv_categories`` key.
Also populates the ``inspire_categories`` key through side effects.
"""
def _is_arxiv(category):
return category in valid_arxiv_categories()
def _is_inspire(category):
schema = load_schema('elements/inspire_field')
valid_inspire_categories = schema['properties']['term']['enum']
return category in valid_inspire_categories
def _normalize(a_value):
for category in valid_arxiv_categories():
if a_value.lower() == category.lower():
return normalize_arxiv_category(category)
schema = load_schema('elements/inspire_field')
valid_inspire_categories = schema['properties']['term']['enum']
for category in valid_inspire_categories:
if a_value.lower() == category.lower():
return category
field_codes_to_inspire_categories = {
'a': 'Astrophysics',
'b': 'Accelerators',
'c': 'Computing',
'e': 'Experiment-HEP',
'g': 'Gravitation and Cosmology',
'i': 'Instrumentation',
'l': 'Lattice',
'm': 'Math and Math Physics',
'n': 'Theory-Nucl',
'o': 'Other',
'p': 'Phenomenology-HEP',
'q': 'General Physics',
't': 'Theory-HEP',
'x': 'Experiment-Nucl',
}
return field_codes_to_inspire_categories.get(a_value.lower())
arxiv_categories = self.get('arxiv_categories', [])
inspire_categories = self.get('inspire_categories', [])
for value in force_list(value):
for a_value in force_list(value.get('a')):
normalized_a_value = _normalize(a_value)
if _is_arxiv(normalized_a_value):
arxiv_categories.append(normalized_a_value)
elif _is_inspire(normalized_a_value):
inspire_categories.append({'term': normalized_a_value})
self['inspire_categories'] = inspire_categories
return arxiv_categories | Populate the ``arxiv_categories`` key.
Also populates the ``inspire_categories`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L392-L450 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | birth_and_death_date2marc | def birth_and_death_date2marc(self, key, value):
"""Populate the ``100__d`` MARC field, which includes the birth and the death date.
By not using the decorator ```for_each_value```, the values of the fields
```birth_date``` and ```death_date``` are both added to ```values``` as a list.
"""
name_field = self.get('100', {})
if 'd' in name_field:
if int(name_field['d'].split('-')[0]) > int(value.split('-')[0]):
dates_field = ' - '.join([value, name_field['d']])
else:
dates_field = ' - '.join([name_field['d'], value])
else:
dates_field = value
name_field['d'] = dates_field
return name_field | python | def birth_and_death_date2marc(self, key, value):
"""Populate the ``100__d`` MARC field, which includes the birth and the death date.
By not using the decorator ```for_each_value```, the values of the fields
```birth_date``` and ```death_date``` are both added to ```values``` as a list.
"""
name_field = self.get('100', {})
if 'd' in name_field:
if int(name_field['d'].split('-')[0]) > int(value.split('-')[0]):
dates_field = ' - '.join([value, name_field['d']])
else:
dates_field = ' - '.join([name_field['d'], value])
else:
dates_field = value
name_field['d'] = dates_field
return name_field | Populate the ``100__d`` MARC field, which includes the birth and the death date.
By not using the decorator ```for_each_value```, the values of the fields
```birth_date``` and ```death_date``` are both added to ```values``` as a list. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L497-L515 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | urls | def urls(self, key, value):
"""Populate the ``url`` key.
Also populates the ``ids`` key through side effects.
"""
description = force_single_element(value.get('y'))
url = value.get('u')
linkedin_match = LINKEDIN_URL.match(url)
twitter_match = TWITTER_URL.match(url)
wikipedia_match = WIKIPEDIA_URL.match(url)
if linkedin_match:
self.setdefault('ids', []).append(
{
'schema': 'LINKEDIN',
'value': unquote_url(linkedin_match.group('page')),
}
)
elif twitter_match:
self.setdefault('ids', []).append(
{
'schema': 'TWITTER',
'value': twitter_match.group('handle'),
}
)
elif wikipedia_match:
lang = wikipedia_match.group('lang')
page = unquote_url(wikipedia_match.group('page'))
if lang != 'en':
page = ':'.join([lang, page])
self.setdefault('ids', []).append(
{
'schema': 'WIKIPEDIA',
'value': page,
}
)
else:
return {
'description': description,
'value': url,
} | python | def urls(self, key, value):
"""Populate the ``url`` key.
Also populates the ``ids`` key through side effects.
"""
description = force_single_element(value.get('y'))
url = value.get('u')
linkedin_match = LINKEDIN_URL.match(url)
twitter_match = TWITTER_URL.match(url)
wikipedia_match = WIKIPEDIA_URL.match(url)
if linkedin_match:
self.setdefault('ids', []).append(
{
'schema': 'LINKEDIN',
'value': unquote_url(linkedin_match.group('page')),
}
)
elif twitter_match:
self.setdefault('ids', []).append(
{
'schema': 'TWITTER',
'value': twitter_match.group('handle'),
}
)
elif wikipedia_match:
lang = wikipedia_match.group('lang')
page = unquote_url(wikipedia_match.group('page'))
if lang != 'en':
page = ':'.join([lang, page])
self.setdefault('ids', []).append(
{
'schema': 'WIKIPEDIA',
'value': page,
}
)
else:
return {
'description': description,
'value': url,
} | Populate the ``url`` key.
Also populates the ``ids`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L656-L696 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | new_record | def new_record(self, key, value):
"""Populate the ``new_record`` key.
Also populates the ``ids`` key through side effects.
"""
new_record = self.get('new_record', {})
ids = self.get('ids', [])
for value in force_list(value):
for id_ in force_list(value.get('a')):
ids.append({
'schema': 'SPIRES',
'value': id_,
})
new_recid = force_single_element(value.get('d', ''))
if new_recid:
new_record = get_record_ref(new_recid, 'authors')
self['ids'] = ids
return new_record | python | def new_record(self, key, value):
"""Populate the ``new_record`` key.
Also populates the ``ids`` key through side effects.
"""
new_record = self.get('new_record', {})
ids = self.get('ids', [])
for value in force_list(value):
for id_ in force_list(value.get('a')):
ids.append({
'schema': 'SPIRES',
'value': id_,
})
new_recid = force_single_element(value.get('d', ''))
if new_recid:
new_record = get_record_ref(new_recid, 'authors')
self['ids'] = ids
return new_record | Populate the ``new_record`` key.
Also populates the ``ids`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L707-L727 |
inspirehep/inspire-dojson | inspire_dojson/hepnames/rules.py | deleted | def deleted(self, key, value):
"""Populate the ``deleted`` key.
Also populates the ``stub`` key through side effects.
"""
def _is_deleted(value):
return force_single_element(value.get('c', '')).upper() == 'DELETED'
def _is_stub(value):
return not (force_single_element(value.get('a', '')).upper() == 'USEFUL')
deleted = self.get('deleted')
stub = self.get('stub')
for value in force_list(value):
deleted = not deleted and _is_deleted(value)
stub = not stub and _is_stub(value)
self['stub'] = stub
return deleted | python | def deleted(self, key, value):
"""Populate the ``deleted`` key.
Also populates the ``stub`` key through side effects.
"""
def _is_deleted(value):
return force_single_element(value.get('c', '')).upper() == 'DELETED'
def _is_stub(value):
return not (force_single_element(value.get('a', '')).upper() == 'USEFUL')
deleted = self.get('deleted')
stub = self.get('stub')
for value in force_list(value):
deleted = not deleted and _is_deleted(value)
stub = not stub and _is_stub(value)
self['stub'] = stub
return deleted | Populate the ``deleted`` key.
Also populates the ``stub`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hepnames/rules.py#L731-L750 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd1xx.py | authors2marc | def authors2marc(self, key, value):
"""Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects.
"""
value = force_list(value)
def _get_ids(value):
ids = {
'i': [],
'j': [],
}
if value.get('ids'):
for _id in value.get('ids'):
if _id.get('schema') == 'INSPIRE ID':
ids['i'].append(_id.get('value'))
elif _id.get('schema') == 'ORCID':
ids['j'].append('ORCID:' + _id.get('value'))
elif _id.get('schema') == 'JACOW':
ids['j'].append(_id.get('value'))
elif _id.get('schema') == 'CERN':
ids['j'].append('CCID-' + _id.get('value')[5:])
return ids
def _get_affiliations(value):
return [
aff.get('value') for aff in value.get('affiliations', [])
]
def _get_affiliations_identifiers(value):
return [
u'{}:{}'.format(aff.get('schema'), aff.get('value')) for aff in value.get('affiliations_identifiers', [])
]
def _get_inspire_roles(value):
values = force_list(value.get('inspire_roles'))
return ['ed.' for role in values if role == 'editor']
def _get_raw_affiliations(value):
return [
aff.get('value') for aff in value.get('raw_affiliations', [])
]
def get_value_100_700(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'e': _get_inspire_roles(value),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'm': value.get('emails'),
't': _get_affiliations_identifiers(value),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
def get_value_701(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
if len(value) > 1:
self["700"] = []
self["701"] = []
for author in value[1:]:
is_supervisor = 'supervisor' in author.get('inspire_roles', [])
if is_supervisor:
self["701"].append(get_value_701(author))
else:
self["700"].append(get_value_100_700(author))
return get_value_100_700(value[0]) | python | def authors2marc(self, key, value):
"""Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects.
"""
value = force_list(value)
def _get_ids(value):
ids = {
'i': [],
'j': [],
}
if value.get('ids'):
for _id in value.get('ids'):
if _id.get('schema') == 'INSPIRE ID':
ids['i'].append(_id.get('value'))
elif _id.get('schema') == 'ORCID':
ids['j'].append('ORCID:' + _id.get('value'))
elif _id.get('schema') == 'JACOW':
ids['j'].append(_id.get('value'))
elif _id.get('schema') == 'CERN':
ids['j'].append('CCID-' + _id.get('value')[5:])
return ids
def _get_affiliations(value):
return [
aff.get('value') for aff in value.get('affiliations', [])
]
def _get_affiliations_identifiers(value):
return [
u'{}:{}'.format(aff.get('schema'), aff.get('value')) for aff in value.get('affiliations_identifiers', [])
]
def _get_inspire_roles(value):
values = force_list(value.get('inspire_roles'))
return ['ed.' for role in values if role == 'editor']
def _get_raw_affiliations(value):
return [
aff.get('value') for aff in value.get('raw_affiliations', [])
]
def get_value_100_700(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'e': _get_inspire_roles(value),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'm': value.get('emails'),
't': _get_affiliations_identifiers(value),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
def get_value_701(value):
ids = _get_ids(value)
return {
'a': value.get('full_name'),
'q': value.get('alternative_names'),
'i': ids.get('i'),
'j': ids.get('j'),
'u': _get_affiliations(value),
'v': _get_raw_affiliations(value),
}
if len(value) > 1:
self["700"] = []
self["701"] = []
for author in value[1:]:
is_supervisor = 'supervisor' in author.get('inspire_roles', [])
if is_supervisor:
self["701"].append(get_value_701(author))
else:
self["700"].append(get_value_100_700(author))
return get_value_100_700(value[0]) | Populate the ``100`` MARC field.
Also populates the ``700`` and the ``701`` MARC fields through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd1xx.py#L196-L274 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | isbns | def isbns(self, key, value):
"""Populate the ``isbns`` key."""
def _get_medium(value):
def _normalize(medium):
schema = load_schema('hep')
valid_media = schema['properties']['isbns']['items']['properties']['medium']['enum']
medium = medium.lower().replace('-', '').replace(' ', '')
if medium in valid_media:
return medium
elif medium == 'ebook':
return 'online'
elif medium == 'paperback':
return 'softcover'
return ''
medium = force_single_element(value.get('b', ''))
normalized_medium = _normalize(medium)
return normalized_medium
def _get_isbn(value):
a_value = force_single_element(value.get('a', ''))
normalized_a_value = a_value.replace('.', '')
if normalized_a_value:
return normalize_isbn(normalized_a_value)
return {
'medium': _get_medium(value),
'value': _get_isbn(value),
} | python | def isbns(self, key, value):
"""Populate the ``isbns`` key."""
def _get_medium(value):
def _normalize(medium):
schema = load_schema('hep')
valid_media = schema['properties']['isbns']['items']['properties']['medium']['enum']
medium = medium.lower().replace('-', '').replace(' ', '')
if medium in valid_media:
return medium
elif medium == 'ebook':
return 'online'
elif medium == 'paperback':
return 'softcover'
return ''
medium = force_single_element(value.get('b', ''))
normalized_medium = _normalize(medium)
return normalized_medium
def _get_isbn(value):
a_value = force_single_element(value.get('a', ''))
normalized_a_value = a_value.replace('.', '')
if normalized_a_value:
return normalize_isbn(normalized_a_value)
return {
'medium': _get_medium(value),
'value': _get_isbn(value),
} | Populate the ``isbns`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L48-L79 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | dois | def dois(self, key, value):
"""Populate the ``dois`` key.
Also populates the ``persistent_identifiers`` key through side effects.
"""
def _get_first_non_curator_source(sources):
sources_without_curator = [el for el in sources if el.upper() != 'CURATOR']
return force_single_element(sources_without_curator)
def _get_material(value):
MATERIAL_MAP = {
'ebook': 'publication',
}
q_value = force_single_element(value.get('q', ''))
normalized_q_value = q_value.lower()
return MATERIAL_MAP.get(normalized_q_value, normalized_q_value)
def _is_doi(id_, type_):
return (not type_ or type_.upper() == 'DOI') and is_doi(id_)
def _is_handle(id_, type_):
return (not type_ or type_.upper() == 'HDL') and is_handle(id_)
dois = self.get('dois', [])
persistent_identifiers = self.get('persistent_identifiers', [])
values = force_list(value)
for value in values:
id_ = force_single_element(value.get('a', ''))
material = _get_material(value)
schema = force_single_element(value.get('2', ''))
sources = force_list(value.get('9'))
source = _get_first_non_curator_source(sources)
if _is_doi(id_, schema):
dois.append({
'material': material,
'source': source,
'value': normalize_doi(id_),
})
else:
schema = 'HDL' if _is_handle(id_, schema) else schema
persistent_identifiers.append({
'material': material,
'schema': schema,
'source': source,
'value': id_,
})
self['persistent_identifiers'] = persistent_identifiers
return dois | python | def dois(self, key, value):
"""Populate the ``dois`` key.
Also populates the ``persistent_identifiers`` key through side effects.
"""
def _get_first_non_curator_source(sources):
sources_without_curator = [el for el in sources if el.upper() != 'CURATOR']
return force_single_element(sources_without_curator)
def _get_material(value):
MATERIAL_MAP = {
'ebook': 'publication',
}
q_value = force_single_element(value.get('q', ''))
normalized_q_value = q_value.lower()
return MATERIAL_MAP.get(normalized_q_value, normalized_q_value)
def _is_doi(id_, type_):
return (not type_ or type_.upper() == 'DOI') and is_doi(id_)
def _is_handle(id_, type_):
return (not type_ or type_.upper() == 'HDL') and is_handle(id_)
dois = self.get('dois', [])
persistent_identifiers = self.get('persistent_identifiers', [])
values = force_list(value)
for value in values:
id_ = force_single_element(value.get('a', ''))
material = _get_material(value)
schema = force_single_element(value.get('2', ''))
sources = force_list(value.get('9'))
source = _get_first_non_curator_source(sources)
if _is_doi(id_, schema):
dois.append({
'material': material,
'source': source,
'value': normalize_doi(id_),
})
else:
schema = 'HDL' if _is_handle(id_, schema) else schema
persistent_identifiers.append({
'material': material,
'schema': schema,
'source': source,
'value': id_,
})
self['persistent_identifiers'] = persistent_identifiers
return dois | Populate the ``dois`` key.
Also populates the ``persistent_identifiers`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L93-L146 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | dois2marc | def dois2marc(self, key, value):
"""Populate the ``0247`` MARC field."""
return {
'2': 'DOI',
'9': value.get('source'),
'a': value.get('value'),
'q': value.get('material'),
} | python | def dois2marc(self, key, value):
"""Populate the ``0247`` MARC field."""
return {
'2': 'DOI',
'9': value.get('source'),
'a': value.get('value'),
'q': value.get('material'),
} | Populate the ``0247`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L151-L158 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | persistent_identifiers2marc | def persistent_identifiers2marc(self, key, value):
"""Populate the ``0247`` MARC field."""
return {
'2': value.get('schema'),
'9': value.get('source'),
'a': value.get('value'),
'q': value.get('material'),
} | python | def persistent_identifiers2marc(self, key, value):
"""Populate the ``0247`` MARC field."""
return {
'2': value.get('schema'),
'9': value.get('source'),
'a': value.get('value'),
'q': value.get('material'),
} | Populate the ``0247`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L163-L170 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | texkeys | def texkeys(self, key, value):
"""Populate the ``texkeys`` key.
Also populates the ``external_system_identifiers`` and ``_desy_bookkeeping`` keys through side effects.
"""
def _is_oai(id_, schema):
return id_.startswith('oai:')
def _is_desy(id_, schema):
return id_ and schema in ('DESY',)
def _is_texkey(id_, schema):
return id_ and schema in ('INSPIRETeX', 'SPIRESTeX')
texkeys = self.get('texkeys', [])
external_system_identifiers = self.get('external_system_identifiers', [])
_desy_bookkeeping = self.get('_desy_bookkeeping', [])
values = force_list(value)
for value in values:
ids = force_list(value.get('a', ''))
other_ids = force_list(value.get('z', ''))
schema = force_single_element(value.get('9', ''))
for id_ in ids:
id_ = id_.strip()
if not id_:
continue
if _is_texkey(id_, schema):
texkeys.insert(0, id_)
elif _is_oai(id_, schema):
continue # XXX: ignored.
elif _is_desy(id_, schema):
_desy_bookkeeping.append({'identifier': id_})
else:
external_system_identifiers.insert(0, {
'schema': schema,
'value': id_,
})
for id_ in other_ids:
id_ = id_.strip()
if not id_:
continue
if _is_texkey(id_, schema):
texkeys.append(id_)
elif _is_oai(id_, schema):
continue # XXX: ignored.
elif _is_desy(id_, schema):
_desy_bookkeeping.append({'identifier': id_})
else:
external_system_identifiers.append({
'schema': schema,
'value': id_,
})
self['external_system_identifiers'] = external_system_identifiers
self['_desy_bookkeeping'] = _desy_bookkeeping
return texkeys | python | def texkeys(self, key, value):
"""Populate the ``texkeys`` key.
Also populates the ``external_system_identifiers`` and ``_desy_bookkeeping`` keys through side effects.
"""
def _is_oai(id_, schema):
return id_.startswith('oai:')
def _is_desy(id_, schema):
return id_ and schema in ('DESY',)
def _is_texkey(id_, schema):
return id_ and schema in ('INSPIRETeX', 'SPIRESTeX')
texkeys = self.get('texkeys', [])
external_system_identifiers = self.get('external_system_identifiers', [])
_desy_bookkeeping = self.get('_desy_bookkeeping', [])
values = force_list(value)
for value in values:
ids = force_list(value.get('a', ''))
other_ids = force_list(value.get('z', ''))
schema = force_single_element(value.get('9', ''))
for id_ in ids:
id_ = id_.strip()
if not id_:
continue
if _is_texkey(id_, schema):
texkeys.insert(0, id_)
elif _is_oai(id_, schema):
continue # XXX: ignored.
elif _is_desy(id_, schema):
_desy_bookkeeping.append({'identifier': id_})
else:
external_system_identifiers.insert(0, {
'schema': schema,
'value': id_,
})
for id_ in other_ids:
id_ = id_.strip()
if not id_:
continue
if _is_texkey(id_, schema):
texkeys.append(id_)
elif _is_oai(id_, schema):
continue # XXX: ignored.
elif _is_desy(id_, schema):
_desy_bookkeeping.append({'identifier': id_})
else:
external_system_identifiers.append({
'schema': schema,
'value': id_,
})
self['external_system_identifiers'] = external_system_identifiers
self['_desy_bookkeeping'] = _desy_bookkeeping
return texkeys | Populate the ``texkeys`` key.
Also populates the ``external_system_identifiers`` and ``_desy_bookkeeping`` keys through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L174-L234 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | texkeys2marc | def texkeys2marc(self, key, value):
"""Populate the ``035`` MARC field."""
result = []
values = force_list(value)
if values:
value = values[0]
result.append({
'9': 'INSPIRETeX',
'a': value,
})
for value in values[1:]:
result.append({
'9': 'INSPIRETeX',
'z': value,
})
return result | python | def texkeys2marc(self, key, value):
"""Populate the ``035`` MARC field."""
result = []
values = force_list(value)
if values:
value = values[0]
result.append({
'9': 'INSPIRETeX',
'a': value,
})
for value in values[1:]:
result.append({
'9': 'INSPIRETeX',
'z': value,
})
return result | Populate the ``035`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L238-L256 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | external_system_identifiers2marc | def external_system_identifiers2marc(self, key, value):
"""Populate the ``035`` MARC field.
Also populates the ``970`` MARC field through side effects and an extra
``id_dict`` dictionary that holds potentially duplicate IDs that are
post-processed in a filter.
"""
def _is_scheme_cernkey(id_, schema):
return schema == 'CERNKEY'
def _is_scheme_spires(id_, schema):
return schema == 'SPIRES'
result_035 = self.get('035', [])
id_dict = self.get('id_dict', defaultdict(list))
result_970 = self.get('970', [])
values = force_list(value)
for value in values:
id_ = value.get('value')
schema = value.get('schema')
if _is_scheme_spires(id_, schema):
result_970.append({
'a': id_,
})
elif _is_scheme_cernkey(id_, schema):
result_035.append({
'9': 'CERNKEY',
'z': id_,
})
else:
id_dict[schema].append(id_)
self['970'] = result_970
self['id_dict'] = id_dict
return result_035 | python | def external_system_identifiers2marc(self, key, value):
"""Populate the ``035`` MARC field.
Also populates the ``970`` MARC field through side effects and an extra
``id_dict`` dictionary that holds potentially duplicate IDs that are
post-processed in a filter.
"""
def _is_scheme_cernkey(id_, schema):
return schema == 'CERNKEY'
def _is_scheme_spires(id_, schema):
return schema == 'SPIRES'
result_035 = self.get('035', [])
id_dict = self.get('id_dict', defaultdict(list))
result_970 = self.get('970', [])
values = force_list(value)
for value in values:
id_ = value.get('value')
schema = value.get('schema')
if _is_scheme_spires(id_, schema):
result_970.append({
'a': id_,
})
elif _is_scheme_cernkey(id_, schema):
result_035.append({
'9': 'CERNKEY',
'z': id_,
})
else:
id_dict[schema].append(id_)
self['970'] = result_970
self['id_dict'] = id_dict
return result_035 | Populate the ``035`` MARC field.
Also populates the ``970`` MARC field through side effects and an extra
``id_dict`` dictionary that holds potentially duplicate IDs that are
post-processed in a filter. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L260-L296 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | arxiv_eprints | def arxiv_eprints(self, key, value):
"""Populate the ``arxiv_eprints`` key.
Also populates the ``report_numbers`` key through side effects.
"""
def _get_clean_arxiv_eprint(id_):
return id_.split(':')[-1]
def _is_arxiv_eprint(id_, source):
return source.lower() == 'arxiv'
def _is_hidden_report_number(other_id, source):
return other_id
def _get_clean_source(source):
if source == 'arXiv:reportnumber':
return 'arXiv'
return source
arxiv_eprints = self.get('arxiv_eprints', [])
report_numbers = self.get('report_numbers', [])
values = force_list(value)
for value in values:
id_ = force_single_element(value.get('a', ''))
other_id = force_single_element(value.get('z', ''))
categories = [normalize_arxiv_category(category) for category
in force_list(value.get('c'))]
source = force_single_element(value.get('9', ''))
if _is_arxiv_eprint(id_, source):
arxiv_eprints.append({
'categories': categories,
'value': _get_clean_arxiv_eprint(id_),
})
elif _is_hidden_report_number(other_id, source):
report_numbers.append({
'hidden': True,
'source': _get_clean_source(source),
'value': other_id,
})
else:
report_numbers.append({
'source': _get_clean_source(source),
'value': id_,
})
self['report_numbers'] = report_numbers
return arxiv_eprints | python | def arxiv_eprints(self, key, value):
"""Populate the ``arxiv_eprints`` key.
Also populates the ``report_numbers`` key through side effects.
"""
def _get_clean_arxiv_eprint(id_):
return id_.split(':')[-1]
def _is_arxiv_eprint(id_, source):
return source.lower() == 'arxiv'
def _is_hidden_report_number(other_id, source):
return other_id
def _get_clean_source(source):
if source == 'arXiv:reportnumber':
return 'arXiv'
return source
arxiv_eprints = self.get('arxiv_eprints', [])
report_numbers = self.get('report_numbers', [])
values = force_list(value)
for value in values:
id_ = force_single_element(value.get('a', ''))
other_id = force_single_element(value.get('z', ''))
categories = [normalize_arxiv_category(category) for category
in force_list(value.get('c'))]
source = force_single_element(value.get('9', ''))
if _is_arxiv_eprint(id_, source):
arxiv_eprints.append({
'categories': categories,
'value': _get_clean_arxiv_eprint(id_),
})
elif _is_hidden_report_number(other_id, source):
report_numbers.append({
'hidden': True,
'source': _get_clean_source(source),
'value': other_id,
})
else:
report_numbers.append({
'source': _get_clean_source(source),
'value': id_,
})
self['report_numbers'] = report_numbers
return arxiv_eprints | Populate the ``arxiv_eprints`` key.
Also populates the ``report_numbers`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L300-L348 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | arxiv_eprints2marc | def arxiv_eprints2marc(self, key, values):
"""Populate the ``037`` MARC field.
Also populates the ``035`` and the ``65017`` MARC fields through side effects.
"""
result_037 = self.get('037', [])
result_035 = self.get('035', [])
result_65017 = self.get('65017', [])
for value in values:
arxiv_id = value.get('value')
arxiv_id = 'arXiv:' + arxiv_id if is_arxiv_post_2007(arxiv_id) else arxiv_id
result_037.append({
'9': 'arXiv',
'a': arxiv_id,
'c': force_single_element(value.get('categories')),
})
result_035.append({
'9': 'arXiv',
'a': 'oai:arXiv.org:' + value.get('value'),
})
categories = force_list(value.get('categories'))
for category in categories:
result_65017.append({
'2': 'arXiv',
'a': category,
})
self['65017'] = result_65017
self['035'] = result_035
return result_037 | python | def arxiv_eprints2marc(self, key, values):
"""Populate the ``037`` MARC field.
Also populates the ``035`` and the ``65017`` MARC fields through side effects.
"""
result_037 = self.get('037', [])
result_035 = self.get('035', [])
result_65017 = self.get('65017', [])
for value in values:
arxiv_id = value.get('value')
arxiv_id = 'arXiv:' + arxiv_id if is_arxiv_post_2007(arxiv_id) else arxiv_id
result_037.append({
'9': 'arXiv',
'a': arxiv_id,
'c': force_single_element(value.get('categories')),
})
result_035.append({
'9': 'arXiv',
'a': 'oai:arXiv.org:' + value.get('value'),
})
categories = force_list(value.get('categories'))
for category in categories:
result_65017.append({
'2': 'arXiv',
'a': category,
})
self['65017'] = result_65017
self['035'] = result_035
return result_037 | Populate the ``037`` MARC field.
Also populates the ``035`` and the ``65017`` MARC fields through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L352-L384 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | report_numbers2marc | def report_numbers2marc(self, key, value):
"""Populate the ``037`` MARC field."""
def _get_mangled_source(source):
if source == 'arXiv':
return 'arXiv:reportnumber'
return source
source = _get_mangled_source(value.get('source'))
if value.get('hidden'):
return {
'9': source,
'z': value.get('value'),
}
return {
'9': source,
'a': value.get('value'),
} | python | def report_numbers2marc(self, key, value):
"""Populate the ``037`` MARC field."""
def _get_mangled_source(source):
if source == 'arXiv':
return 'arXiv:reportnumber'
return source
source = _get_mangled_source(value.get('source'))
if value.get('hidden'):
return {
'9': source,
'z': value.get('value'),
}
return {
'9': source,
'a': value.get('value'),
} | Populate the ``037`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L389-L407 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | languages | def languages(self, key, value):
"""Populate the ``languages`` key."""
languages = self.get('languages', [])
values = force_list(value.get('a'))
for value in values:
for language in RE_LANGUAGE.split(value):
try:
name = language.strip().capitalize()
languages.append(pycountry.languages.get(name=name).alpha_2)
except KeyError:
pass
return languages | python | def languages(self, key, value):
"""Populate the ``languages`` key."""
languages = self.get('languages', [])
values = force_list(value.get('a'))
for value in values:
for language in RE_LANGUAGE.split(value):
try:
name = language.strip().capitalize()
languages.append(pycountry.languages.get(name=name).alpha_2)
except KeyError:
pass
return languages | Populate the ``languages`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L411-L424 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd0xx.py | languages2marc | def languages2marc(self, key, value):
"""Populate the ``041`` MARC field."""
return {'a': pycountry.languages.get(alpha_2=value).name.lower()} | python | def languages2marc(self, key, value):
"""Populate the ``041`` MARC field."""
return {'a': pycountry.languages.get(alpha_2=value).name.lower()} | Populate the ``041`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd0xx.py#L429-L431 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd9xx.py | record_affiliations | def record_affiliations(self, key, value):
"""Populate the ``record_affiliations`` key."""
record = get_record_ref(value.get('z'), 'institutions')
return {
'curated_relation': record is not None,
'record': record,
'value': value.get('a'),
} | python | def record_affiliations(self, key, value):
"""Populate the ``record_affiliations`` key."""
record = get_record_ref(value.get('z'), 'institutions')
return {
'curated_relation': record is not None,
'record': record,
'value': value.get('a'),
} | Populate the ``record_affiliations`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd9xx.py#L121-L129 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd9xx.py | document_type | def document_type(self, key, value):
"""Populate the ``document_type`` key.
Also populates the ``_collections``, ``citeable``, ``core``, ``deleted``,
``refereed``, ``publication_type``, and ``withdrawn`` keys through side
effects.
"""
schema = load_schema('hep')
publication_type_schema = schema['properties']['publication_type']
valid_publication_types = publication_type_schema['items']['enum']
document_type = self.get('document_type', [])
publication_type = self.get('publication_type', [])
a_values = force_list(value.get('a'))
for a_value in a_values:
normalized_a_value = a_value.strip().lower()
if normalized_a_value == 'arxiv':
continue # XXX: ignored.
elif normalized_a_value == 'citeable':
self['citeable'] = True
elif normalized_a_value == 'core':
self['core'] = True
elif normalized_a_value == 'noncore':
self['core'] = False
elif normalized_a_value == 'published':
self['refereed'] = True
elif normalized_a_value == 'withdrawn':
self['withdrawn'] = True
elif normalized_a_value == 'deleted':
self['deleted'] = True
elif normalized_a_value in COLLECTIONS_MAP:
self.setdefault('_collections', []).append(COLLECTIONS_MAP[normalized_a_value])
elif normalized_a_value in DOCUMENT_TYPE_MAP:
document_type.append(DOCUMENT_TYPE_MAP[normalized_a_value])
elif normalized_a_value in valid_publication_types:
publication_type.append(normalized_a_value)
c_value = force_single_element(value.get('c', ''))
normalized_c_value = c_value.strip().lower()
if normalized_c_value == 'deleted':
self['deleted'] = True
self['publication_type'] = publication_type
return document_type | python | def document_type(self, key, value):
"""Populate the ``document_type`` key.
Also populates the ``_collections``, ``citeable``, ``core``, ``deleted``,
``refereed``, ``publication_type``, and ``withdrawn`` keys through side
effects.
"""
schema = load_schema('hep')
publication_type_schema = schema['properties']['publication_type']
valid_publication_types = publication_type_schema['items']['enum']
document_type = self.get('document_type', [])
publication_type = self.get('publication_type', [])
a_values = force_list(value.get('a'))
for a_value in a_values:
normalized_a_value = a_value.strip().lower()
if normalized_a_value == 'arxiv':
continue # XXX: ignored.
elif normalized_a_value == 'citeable':
self['citeable'] = True
elif normalized_a_value == 'core':
self['core'] = True
elif normalized_a_value == 'noncore':
self['core'] = False
elif normalized_a_value == 'published':
self['refereed'] = True
elif normalized_a_value == 'withdrawn':
self['withdrawn'] = True
elif normalized_a_value == 'deleted':
self['deleted'] = True
elif normalized_a_value in COLLECTIONS_MAP:
self.setdefault('_collections', []).append(COLLECTIONS_MAP[normalized_a_value])
elif normalized_a_value in DOCUMENT_TYPE_MAP:
document_type.append(DOCUMENT_TYPE_MAP[normalized_a_value])
elif normalized_a_value in valid_publication_types:
publication_type.append(normalized_a_value)
c_value = force_single_element(value.get('c', ''))
normalized_c_value = c_value.strip().lower()
if normalized_c_value == 'deleted':
self['deleted'] = True
self['publication_type'] = publication_type
return document_type | Populate the ``document_type`` key.
Also populates the ``_collections``, ``citeable``, ``core``, ``deleted``,
``refereed``, ``publication_type``, and ``withdrawn`` keys through side
effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd9xx.py#L140-L186 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd9xx.py | document_type2marc | def document_type2marc(self, key, value):
"""Populate the ``980`` MARC field."""
if value in DOCUMENT_TYPE_REVERSE_MAP and DOCUMENT_TYPE_REVERSE_MAP[value]:
return {'a': DOCUMENT_TYPE_REVERSE_MAP[value]} | python | def document_type2marc(self, key, value):
"""Populate the ``980`` MARC field."""
if value in DOCUMENT_TYPE_REVERSE_MAP and DOCUMENT_TYPE_REVERSE_MAP[value]:
return {'a': DOCUMENT_TYPE_REVERSE_MAP[value]} | Populate the ``980`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd9xx.py#L241-L244 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd9xx.py | references | def references(self, key, value):
"""Populate the ``references`` key."""
def _has_curator_flag(value):
normalized_nine_values = [el.upper() for el in force_list(value.get('9'))]
return 'CURATOR' in normalized_nine_values
def _is_curated(value):
return force_single_element(value.get('z')) == '1' and _has_curator_flag(value)
def _set_record(el):
recid = maybe_int(el)
record = get_record_ref(recid, 'literature')
rb.set_record(record)
rb = ReferenceBuilder()
mapping = [
('0', _set_record),
('a', rb.add_uid),
('b', rb.add_uid),
('c', rb.add_collaboration),
('e', partial(rb.add_author, role='ed.')),
('h', rb.add_refextract_authors_str),
('i', rb.add_uid),
('k', rb.set_texkey),
('m', rb.add_misc),
('o', rb.set_label),
('p', rb.set_publisher),
('q', rb.add_parent_title),
('r', rb.add_report_number),
('s', rb.set_pubnote),
('t', rb.add_title),
('x', rb.add_raw_reference),
('y', rb.set_year),
]
for field, method in mapping:
for el in force_list(value.get(field)):
if el:
method(el)
for el in dedupe_list(force_list(value.get('u'))):
if el:
rb.add_url(el)
if _is_curated(value):
rb.curate()
if _has_curator_flag(value):
rb.obj['legacy_curated'] = True
return rb.obj | python | def references(self, key, value):
"""Populate the ``references`` key."""
def _has_curator_flag(value):
normalized_nine_values = [el.upper() for el in force_list(value.get('9'))]
return 'CURATOR' in normalized_nine_values
def _is_curated(value):
return force_single_element(value.get('z')) == '1' and _has_curator_flag(value)
def _set_record(el):
recid = maybe_int(el)
record = get_record_ref(recid, 'literature')
rb.set_record(record)
rb = ReferenceBuilder()
mapping = [
('0', _set_record),
('a', rb.add_uid),
('b', rb.add_uid),
('c', rb.add_collaboration),
('e', partial(rb.add_author, role='ed.')),
('h', rb.add_refextract_authors_str),
('i', rb.add_uid),
('k', rb.set_texkey),
('m', rb.add_misc),
('o', rb.set_label),
('p', rb.set_publisher),
('q', rb.add_parent_title),
('r', rb.add_report_number),
('s', rb.set_pubnote),
('t', rb.add_title),
('x', rb.add_raw_reference),
('y', rb.set_year),
]
for field, method in mapping:
for el in force_list(value.get(field)):
if el:
method(el)
for el in dedupe_list(force_list(value.get('u'))):
if el:
rb.add_url(el)
if _is_curated(value):
rb.curate()
if _has_curator_flag(value):
rb.obj['legacy_curated'] = True
return rb.obj | Populate the ``references`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd9xx.py#L256-L306 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd9xx.py | references2marc | def references2marc(self, key, value):
"""Populate the ``999C5`` MARC field."""
reference = value.get('reference', {})
pids = force_list(reference.get('persistent_identifiers'))
a_values = ['doi:' + el for el in force_list(reference.get('dois'))]
a_values.extend(['hdl:' + el['value'] for el in pids if el.get('schema') == 'HDL'])
a_values.extend(['urn:' + el['value'] for el in pids if el.get('schema') == 'URN'])
external_ids = force_list(reference.get('external_system_identifiers'))
u_values = force_list(get_value(reference, 'urls.value'))
u_values.extend(CDS_RECORD_FORMAT.format(el['value']) for el in external_ids if el.get('schema') == 'CDS')
u_values.extend(ADS_RECORD_FORMAT.format(el['value']) for el in external_ids if el.get('schema') == 'ADS')
authors = force_list(reference.get('authors'))
e_values = [el['full_name'] for el in authors if el.get('inspire_role') == 'editor']
h_values = [el['full_name'] for el in authors if el.get('inspire_role') != 'editor']
r_values = force_list(reference.get('report_numbers'))
if reference.get('arxiv_eprint'):
arxiv_eprint = reference['arxiv_eprint']
r_values.append('arXiv:' + arxiv_eprint if is_arxiv_post_2007(arxiv_eprint) else arxiv_eprint)
if reference.get('publication_info'):
reference['publication_info'] = convert_new_publication_info_to_old([reference['publication_info']])[0]
journal_title = get_value(reference, 'publication_info.journal_title')
journal_volume = get_value(reference, 'publication_info.journal_volume')
page_start = get_value(reference, 'publication_info.page_start')
page_end = get_value(reference, 'publication_info.page_end')
artid = get_value(reference, 'publication_info.artid')
s_value = build_pubnote(journal_title, journal_volume, page_start, page_end, artid)
m_value = ' / '.join(force_list(reference.get('misc')))
return {
'0': get_recid_from_ref(value.get('record')),
'9': 'CURATOR' if value.get('legacy_curated') else None,
'a': a_values,
'b': get_value(reference, 'publication_info.cnum'),
'c': reference.get('collaborations'),
'e': e_values,
'h': h_values,
'i': reference.get('isbn'),
'k': reference.get('texkey'),
'm': m_value,
'o': reference.get('label'),
'p': get_value(reference, 'imprint.publisher'),
'q': get_value(reference, 'publication_info.parent_title'),
'r': r_values,
's': s_value,
't': get_value(reference, 'title.title'),
'u': u_values,
'x': get_value(value, 'raw_refs.value'),
'y': get_value(reference, 'publication_info.year'),
'z': 1 if value.get('curated_relation') else 0,
} | python | def references2marc(self, key, value):
"""Populate the ``999C5`` MARC field."""
reference = value.get('reference', {})
pids = force_list(reference.get('persistent_identifiers'))
a_values = ['doi:' + el for el in force_list(reference.get('dois'))]
a_values.extend(['hdl:' + el['value'] for el in pids if el.get('schema') == 'HDL'])
a_values.extend(['urn:' + el['value'] for el in pids if el.get('schema') == 'URN'])
external_ids = force_list(reference.get('external_system_identifiers'))
u_values = force_list(get_value(reference, 'urls.value'))
u_values.extend(CDS_RECORD_FORMAT.format(el['value']) for el in external_ids if el.get('schema') == 'CDS')
u_values.extend(ADS_RECORD_FORMAT.format(el['value']) for el in external_ids if el.get('schema') == 'ADS')
authors = force_list(reference.get('authors'))
e_values = [el['full_name'] for el in authors if el.get('inspire_role') == 'editor']
h_values = [el['full_name'] for el in authors if el.get('inspire_role') != 'editor']
r_values = force_list(reference.get('report_numbers'))
if reference.get('arxiv_eprint'):
arxiv_eprint = reference['arxiv_eprint']
r_values.append('arXiv:' + arxiv_eprint if is_arxiv_post_2007(arxiv_eprint) else arxiv_eprint)
if reference.get('publication_info'):
reference['publication_info'] = convert_new_publication_info_to_old([reference['publication_info']])[0]
journal_title = get_value(reference, 'publication_info.journal_title')
journal_volume = get_value(reference, 'publication_info.journal_volume')
page_start = get_value(reference, 'publication_info.page_start')
page_end = get_value(reference, 'publication_info.page_end')
artid = get_value(reference, 'publication_info.artid')
s_value = build_pubnote(journal_title, journal_volume, page_start, page_end, artid)
m_value = ' / '.join(force_list(reference.get('misc')))
return {
'0': get_recid_from_ref(value.get('record')),
'9': 'CURATOR' if value.get('legacy_curated') else None,
'a': a_values,
'b': get_value(reference, 'publication_info.cnum'),
'c': reference.get('collaborations'),
'e': e_values,
'h': h_values,
'i': reference.get('isbn'),
'k': reference.get('texkey'),
'm': m_value,
'o': reference.get('label'),
'p': get_value(reference, 'imprint.publisher'),
'q': get_value(reference, 'publication_info.parent_title'),
'r': r_values,
's': s_value,
't': get_value(reference, 'title.title'),
'u': u_values,
'x': get_value(value, 'raw_refs.value'),
'y': get_value(reference, 'publication_info.year'),
'z': 1 if value.get('curated_relation') else 0,
} | Populate the ``999C5`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd9xx.py#L311-L366 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bdFFT.py | documents | def documents(self, key, value):
"""Populate the ``documents`` key.
Also populates the ``figures`` key through side effects.
"""
def _is_hidden(value):
return 'HIDDEN' in [val.upper() for val in value] or None
def _is_figure(value):
figures_extensions = ['.png']
return value.get('f') in figures_extensions
def _is_fulltext(value):
return value.get('d', '').lower() == 'fulltext' or None
def _get_index_and_caption(value):
match = re.compile(r'(^\d{5})?\s*(.*)').match(value)
if match:
return match.group(1), match.group(2)
def _get_key(value):
fname = value.get('n', 'document')
extension = value.get('f', '')
if fname.endswith(extension):
return fname
return fname + extension
def _get_source(value):
source = value.get('t', '')
if source in ('INSPIRE-PUBLIC', 'Main'):
source = None
elif source.lower() == 'arxiv':
return 'arxiv'
return source
figures = self.get('figures', [])
is_context = value.get('f', '').endswith('context')
if is_context:
return
if _is_figure(value):
index, caption = _get_index_and_caption(value.get('d', ''))
figures.append({
'key': _get_key(value),
'caption': caption,
'url': afs_url(value.get('a')),
'order': index,
'source': 'arxiv', # XXX: we don't have any other figures on legacy
})
self['figures'] = figures
else:
return {
'description': value.get('d') if not _is_fulltext(value) else None,
'key': _get_key(value),
'fulltext': _is_fulltext(value),
'hidden': _is_hidden(force_list(value.get('o'))),
'url': afs_url(value.get('a')),
'source': _get_source(value),
} | python | def documents(self, key, value):
"""Populate the ``documents`` key.
Also populates the ``figures`` key through side effects.
"""
def _is_hidden(value):
return 'HIDDEN' in [val.upper() for val in value] or None
def _is_figure(value):
figures_extensions = ['.png']
return value.get('f') in figures_extensions
def _is_fulltext(value):
return value.get('d', '').lower() == 'fulltext' or None
def _get_index_and_caption(value):
match = re.compile(r'(^\d{5})?\s*(.*)').match(value)
if match:
return match.group(1), match.group(2)
def _get_key(value):
fname = value.get('n', 'document')
extension = value.get('f', '')
if fname.endswith(extension):
return fname
return fname + extension
def _get_source(value):
source = value.get('t', '')
if source in ('INSPIRE-PUBLIC', 'Main'):
source = None
elif source.lower() == 'arxiv':
return 'arxiv'
return source
figures = self.get('figures', [])
is_context = value.get('f', '').endswith('context')
if is_context:
return
if _is_figure(value):
index, caption = _get_index_and_caption(value.get('d', ''))
figures.append({
'key': _get_key(value),
'caption': caption,
'url': afs_url(value.get('a')),
'order': index,
'source': 'arxiv', # XXX: we don't have any other figures on legacy
})
self['figures'] = figures
else:
return {
'description': value.get('d') if not _is_fulltext(value) else None,
'key': _get_key(value),
'fulltext': _is_fulltext(value),
'hidden': _is_hidden(force_list(value.get('o'))),
'url': afs_url(value.get('a')),
'source': _get_source(value),
} | Populate the ``documents`` key.
Also populates the ``figures`` key through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bdFFT.py#L40-L101 |
inspirehep/inspire-dojson | inspire_dojson/api.py | marcxml2record | def marcxml2record(marcxml):
"""Convert a MARCXML string to a JSON record.
Tries to guess which set of rules to use by inspecting the contents
of the ``980__a`` MARC field, but falls back to HEP in case nothing
matches, because records belonging to special collections logically
belong to the Literature collection but don't have ``980__a:HEP``.
Args:
marcxml(str): a string containing MARCXML.
Returns:
dict: a JSON record converted from the string.
"""
marcjson = create_record(marcxml, keep_singletons=False)
collections = _get_collections(marcjson)
if 'conferences' in collections:
return conferences.do(marcjson)
elif 'data' in collections:
return data.do(marcjson)
elif 'experiment' in collections:
return experiments.do(marcjson)
elif 'hepnames' in collections:
return hepnames.do(marcjson)
elif 'institution' in collections:
return institutions.do(marcjson)
elif 'job' in collections or 'jobhidden' in collections:
return jobs.do(marcjson)
elif 'journals' in collections or 'journalsnew' in collections:
return journals.do(marcjson)
return hep.do(marcjson) | python | def marcxml2record(marcxml):
"""Convert a MARCXML string to a JSON record.
Tries to guess which set of rules to use by inspecting the contents
of the ``980__a`` MARC field, but falls back to HEP in case nothing
matches, because records belonging to special collections logically
belong to the Literature collection but don't have ``980__a:HEP``.
Args:
marcxml(str): a string containing MARCXML.
Returns:
dict: a JSON record converted from the string.
"""
marcjson = create_record(marcxml, keep_singletons=False)
collections = _get_collections(marcjson)
if 'conferences' in collections:
return conferences.do(marcjson)
elif 'data' in collections:
return data.do(marcjson)
elif 'experiment' in collections:
return experiments.do(marcjson)
elif 'hepnames' in collections:
return hepnames.do(marcjson)
elif 'institution' in collections:
return institutions.do(marcjson)
elif 'job' in collections or 'jobhidden' in collections:
return jobs.do(marcjson)
elif 'journals' in collections or 'journalsnew' in collections:
return journals.do(marcjson)
return hep.do(marcjson) | Convert a MARCXML string to a JSON record.
Tries to guess which set of rules to use by inspecting the contents
of the ``980__a`` MARC field, but falls back to HEP in case nothing
matches, because records belonging to special collections logically
belong to the Literature collection but don't have ``980__a:HEP``.
Args:
marcxml(str): a string containing MARCXML.
Returns:
dict: a JSON record converted from the string. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/api.py#L66-L98 |
inspirehep/inspire-dojson | inspire_dojson/api.py | record2marcxml | def record2marcxml(record):
"""Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from the record.
"""
schema_name = _get_schema_name(record)
if schema_name == 'hep':
marcjson = hep2marc.do(record)
elif schema_name == 'authors':
marcjson = hepnames2marc.do(record)
else:
raise NotImplementedError(u'JSON -> MARC rules missing for "{}"'.format(schema_name))
record = RECORD()
for key, values in sorted(iteritems(marcjson)):
tag, ind1, ind2 = _parse_key(key)
if _is_controlfield(tag, ind1, ind2):
value = force_single_element(values)
if not isinstance(value, text_type):
value = text_type(value)
record.append(CONTROLFIELD(_strip_invalid_chars_for_xml(value), {'tag': tag}))
else:
for value in force_list(values):
datafield = DATAFIELD({'tag': tag, 'ind1': ind1, 'ind2': ind2})
for code, els in sorted(iteritems(value)):
for el in force_list(els):
if not isinstance(el, text_type):
el = text_type(el)
datafield.append(SUBFIELD(_strip_invalid_chars_for_xml(el), {'code': code}))
record.append(datafield)
return tostring(record, encoding='utf8', pretty_print=True) | python | def record2marcxml(record):
"""Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from the record.
"""
schema_name = _get_schema_name(record)
if schema_name == 'hep':
marcjson = hep2marc.do(record)
elif schema_name == 'authors':
marcjson = hepnames2marc.do(record)
else:
raise NotImplementedError(u'JSON -> MARC rules missing for "{}"'.format(schema_name))
record = RECORD()
for key, values in sorted(iteritems(marcjson)):
tag, ind1, ind2 = _parse_key(key)
if _is_controlfield(tag, ind1, ind2):
value = force_single_element(values)
if not isinstance(value, text_type):
value = text_type(value)
record.append(CONTROLFIELD(_strip_invalid_chars_for_xml(value), {'tag': tag}))
else:
for value in force_list(values):
datafield = DATAFIELD({'tag': tag, 'ind1': ind1, 'ind2': ind2})
for code, els in sorted(iteritems(value)):
for el in force_list(els):
if not isinstance(el, text_type):
el = text_type(el)
datafield.append(SUBFIELD(_strip_invalid_chars_for_xml(el), {'code': code}))
record.append(datafield)
return tostring(record, encoding='utf8', pretty_print=True) | Convert a JSON record to a MARCXML string.
Deduces which set of rules to use by parsing the ``$schema`` key, as
it unequivocally determines which kind of record we have.
Args:
record(dict): a JSON record.
Returns:
str: a MARCXML string converted from the record. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/api.py#L101-L142 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd3xx.py | number_of_pages | def number_of_pages(self, key, value):
"""Populate the ``number_of_pages`` key."""
result = maybe_int(force_single_element(value.get('a', '')))
if result and result > 0:
return result | python | def number_of_pages(self, key, value):
"""Populate the ``number_of_pages`` key."""
result = maybe_int(force_single_element(value.get('a', '')))
if result and result > 0:
return result | Populate the ``number_of_pages`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd3xx.py#L34-L38 |
inspirehep/inspire-dojson | inspire_dojson/cds/rules.py | secondary_report_numbers | def secondary_report_numbers(self, key, value):
"""Populate the ``037`` MARC field.
Also populates the ``500``, ``595`` and ``980`` MARC field through side effects.
"""
preliminary_results_prefixes = ['ATLAS-CONF-', 'CMS-PAS-', 'CMS-DP-', 'LHCB-CONF-']
note_prefixes = ['ALICE-INT-', 'ATL-', 'ATLAS-CONF-', 'CMS-DP-', 'CMS-PAS-', 'LHCB-CONF-', 'LHCB-PUB-']
result_037 = self.get('037__', [])
result_500 = self.get('500__', [])
result_595 = self.get('595__', [])
result_980 = self.get('980__', [])
report = force_single_element(value.get('a', ''))
hidden_report = force_single_element(value.get('9') or value.get('z', ''))
source = 'CDS' if not is_arxiv(report) else 'arXiv'
if any(report.upper().startswith(prefix) for prefix in note_prefixes):
result_980.append({'a': 'NOTE'})
if any(report.upper().startswith(prefix) for prefix in preliminary_results_prefixes):
result_500.append({'9': 'CDS', 'a': 'Preliminary results'})
is_barcode = hidden_report.startswith('P0') or hidden_report.startswith('CM-P0')
if not report.startswith('SIS-') and not is_barcode:
result_037.append({
'9': source,
'a': report,
'c': value.get('c'),
'z': hidden_report if source == 'CDS' else None,
})
self['500__'] = result_500
self['595__'] = result_595
self['980__'] = result_980
return result_037 | python | def secondary_report_numbers(self, key, value):
"""Populate the ``037`` MARC field.
Also populates the ``500``, ``595`` and ``980`` MARC field through side effects.
"""
preliminary_results_prefixes = ['ATLAS-CONF-', 'CMS-PAS-', 'CMS-DP-', 'LHCB-CONF-']
note_prefixes = ['ALICE-INT-', 'ATL-', 'ATLAS-CONF-', 'CMS-DP-', 'CMS-PAS-', 'LHCB-CONF-', 'LHCB-PUB-']
result_037 = self.get('037__', [])
result_500 = self.get('500__', [])
result_595 = self.get('595__', [])
result_980 = self.get('980__', [])
report = force_single_element(value.get('a', ''))
hidden_report = force_single_element(value.get('9') or value.get('z', ''))
source = 'CDS' if not is_arxiv(report) else 'arXiv'
if any(report.upper().startswith(prefix) for prefix in note_prefixes):
result_980.append({'a': 'NOTE'})
if any(report.upper().startswith(prefix) for prefix in preliminary_results_prefixes):
result_500.append({'9': 'CDS', 'a': 'Preliminary results'})
is_barcode = hidden_report.startswith('P0') or hidden_report.startswith('CM-P0')
if not report.startswith('SIS-') and not is_barcode:
result_037.append({
'9': source,
'a': report,
'c': value.get('c'),
'z': hidden_report if source == 'CDS' else None,
})
self['500__'] = result_500
self['595__'] = result_595
self['980__'] = result_980
return result_037 | Populate the ``037`` MARC field.
Also populates the ``500``, ``595`` and ``980`` MARC field through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/cds/rules.py#L143-L178 |
inspirehep/inspire-dojson | inspire_dojson/cds/rules.py | nonfirst_authors | def nonfirst_authors(self, key, value):
"""Populate ``700`` MARC field.
Also populates the ``701`` MARC field through side-effects.
"""
field_700 = self.get('700__', [])
field_701 = self.get('701__', [])
is_supervisor = any(el.lower().startswith('dir') for el in force_list(value.get('e', '')))
if is_supervisor:
field_701.append(_converted_author(value))
else:
field_700.append(_converted_author(value))
self['701__'] = field_701
return field_700 | python | def nonfirst_authors(self, key, value):
"""Populate ``700`` MARC field.
Also populates the ``701`` MARC field through side-effects.
"""
field_700 = self.get('700__', [])
field_701 = self.get('701__', [])
is_supervisor = any(el.lower().startswith('dir') for el in force_list(value.get('e', '')))
if is_supervisor:
field_701.append(_converted_author(value))
else:
field_700.append(_converted_author(value))
self['701__'] = field_701
return field_700 | Populate ``700`` MARC field.
Also populates the ``701`` MARC field through side-effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/cds/rules.py#L254-L269 |
inspirehep/inspire-dojson | inspire_dojson/cds/rules.py | urls | def urls(self, key, value):
"""Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects.
"""
def _is_preprint(value):
return value.get('y', '').lower() == 'preprint'
def _is_fulltext(value):
return value['u'].endswith('.pdf') and value['u'].startswith('http://cds.cern.ch')
def _is_local_copy(value):
return 'local copy' in value.get('y', '')
def _is_ignored_domain(value):
ignored_domains = ['http://cdsweb.cern.ch', 'http://cms.cern.ch',
'http://cmsdoc.cern.ch', 'http://documents.cern.ch',
'http://preprints.cern.ch', 'http://cds.cern.ch',
'http://arxiv.org']
return any(value['u'].startswith(domain) for domain in ignored_domains)
field_8564 = self.get('8564_', [])
field_FFT = self.get('FFT__', [])
if 'u' not in value:
return field_8564
url = escape_url(value['u'])
if _is_fulltext(value) and not _is_preprint(value):
if _is_local_copy(value):
description = value.get('y', '').replace('local copy', 'on CERN Document Server')
field_8564.append({
'u': url,
'y': description,
})
else:
_, file_name = os.path.split(urllib.parse.urlparse(value['u']).path)
_, extension = os.path.splitext(file_name)
field_FFT.append({
't': 'CDS',
'a': url,
'd': value.get('y', ''),
'n': file_name,
'f': extension,
})
elif not _is_ignored_domain(value):
field_8564.append({
'u': url,
'y': value.get('y'),
})
self['FFT__'] = field_FFT
return field_8564 | python | def urls(self, key, value):
"""Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects.
"""
def _is_preprint(value):
return value.get('y', '').lower() == 'preprint'
def _is_fulltext(value):
return value['u'].endswith('.pdf') and value['u'].startswith('http://cds.cern.ch')
def _is_local_copy(value):
return 'local copy' in value.get('y', '')
def _is_ignored_domain(value):
ignored_domains = ['http://cdsweb.cern.ch', 'http://cms.cern.ch',
'http://cmsdoc.cern.ch', 'http://documents.cern.ch',
'http://preprints.cern.ch', 'http://cds.cern.ch',
'http://arxiv.org']
return any(value['u'].startswith(domain) for domain in ignored_domains)
field_8564 = self.get('8564_', [])
field_FFT = self.get('FFT__', [])
if 'u' not in value:
return field_8564
url = escape_url(value['u'])
if _is_fulltext(value) and not _is_preprint(value):
if _is_local_copy(value):
description = value.get('y', '').replace('local copy', 'on CERN Document Server')
field_8564.append({
'u': url,
'y': description,
})
else:
_, file_name = os.path.split(urllib.parse.urlparse(value['u']).path)
_, extension = os.path.splitext(file_name)
field_FFT.append({
't': 'CDS',
'a': url,
'd': value.get('y', ''),
'n': file_name,
'f': extension,
})
elif not _is_ignored_domain(value):
field_8564.append({
'u': url,
'y': value.get('y'),
})
self['FFT__'] = field_FFT
return field_8564 | Populate the ``8564`` MARC field.
Also populate the ``FFT`` field through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/cds/rules.py#L400-L453 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd2xx.py | titles | def titles(self, key, value):
"""Populate the ``titles`` key."""
if not key.startswith('245'):
return {
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
}
self.setdefault('titles', []).insert(0, {
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
}) | python | def titles(self, key, value):
"""Populate the ``titles`` key."""
if not key.startswith('245'):
return {
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
}
self.setdefault('titles', []).insert(0, {
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
}) | Populate the ``titles`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd2xx.py#L39-L52 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd2xx.py | title_translations | def title_translations(self, key, value):
"""Populate the ``title_translations`` key."""
return {
'language': langdetect.detect(value.get('a')),
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
} | python | def title_translations(self, key, value):
"""Populate the ``title_translations`` key."""
return {
'language': langdetect.detect(value.get('a')),
'source': value.get('9'),
'subtitle': value.get('b'),
'title': value.get('a'),
} | Populate the ``title_translations`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd2xx.py#L57-L64 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd2xx.py | titles2marc | def titles2marc(self, key, values):
"""Populate the ``246`` MARC field.
Also populates the ``245`` MARC field through side effects.
"""
first, rest = values[0], values[1:]
self.setdefault('245', []).append({
'a': first.get('title'),
'b': first.get('subtitle'),
'9': first.get('source'),
})
return [
{
'a': value.get('title'),
'b': value.get('subtitle'),
'9': value.get('source'),
} for value in rest
] | python | def titles2marc(self, key, values):
"""Populate the ``246`` MARC field.
Also populates the ``245`` MARC field through side effects.
"""
first, rest = values[0], values[1:]
self.setdefault('245', []).append({
'a': first.get('title'),
'b': first.get('subtitle'),
'9': first.get('source'),
})
return [
{
'a': value.get('title'),
'b': value.get('subtitle'),
'9': value.get('source'),
} for value in rest
] | Populate the ``246`` MARC field.
Also populates the ``245`` MARC field through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd2xx.py#L68-L87 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd2xx.py | title_translations2marc | def title_translations2marc(self, key, value):
"""Populate the ``242`` MARC field."""
return {
'a': value.get('title'),
'b': value.get('subtitle'),
'9': value.get('source'),
} | python | def title_translations2marc(self, key, value):
"""Populate the ``242`` MARC field."""
return {
'a': value.get('title'),
'b': value.get('subtitle'),
'9': value.get('source'),
} | Populate the ``242`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd2xx.py#L92-L98 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd2xx.py | imprints | def imprints(self, key, value):
"""Populate the ``imprints`` key."""
return {
'place': value.get('a'),
'publisher': value.get('b'),
'date': normalize_date_aggressively(value.get('c')),
} | python | def imprints(self, key, value):
"""Populate the ``imprints`` key."""
return {
'place': value.get('a'),
'publisher': value.get('b'),
'date': normalize_date_aggressively(value.get('c')),
} | Populate the ``imprints`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd2xx.py#L118-L124 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd2xx.py | imprints2marc | def imprints2marc(self, key, value):
"""Populate the ``260`` MARC field."""
return {
'a': value.get('place'),
'b': value.get('publisher'),
'c': value.get('date'),
} | python | def imprints2marc(self, key, value):
"""Populate the ``260`` MARC field."""
return {
'a': value.get('place'),
'b': value.get('publisher'),
'c': value.get('date'),
} | Populate the ``260`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd2xx.py#L129-L135 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | public_notes | def public_notes(self, key, value):
"""Populate the ``public_notes`` key.
Also populates the ``curated`` and ``thesis_info`` keys through side effects.
"""
def _means_not_curated(public_note):
return public_note in [
'*Brief entry*',
'* Brief entry *',
'*Temporary entry*',
'* Temporary entry *',
'*Temporary record*',
'* Temporary record *',
]
public_notes = self.get('public_notes', [])
thesis_info = self.get('thesis_info', {})
source = force_single_element(value.get('9', ''))
for value in force_list(value):
for public_note in force_list(value.get('a')):
match = IS_DEFENSE_DATE.match(public_note)
if match:
try:
thesis_info['defense_date'] = normalize_date(match.group('defense_date'))
except ValueError:
public_notes.append({
'source': source,
'value': public_note,
})
elif _means_not_curated(public_note):
self['curated'] = False
else:
public_notes.append({
'source': source,
'value': public_note,
})
self['thesis_info'] = thesis_info
return public_notes | python | def public_notes(self, key, value):
"""Populate the ``public_notes`` key.
Also populates the ``curated`` and ``thesis_info`` keys through side effects.
"""
def _means_not_curated(public_note):
return public_note in [
'*Brief entry*',
'* Brief entry *',
'*Temporary entry*',
'* Temporary entry *',
'*Temporary record*',
'* Temporary record *',
]
public_notes = self.get('public_notes', [])
thesis_info = self.get('thesis_info', {})
source = force_single_element(value.get('9', ''))
for value in force_list(value):
for public_note in force_list(value.get('a')):
match = IS_DEFENSE_DATE.match(public_note)
if match:
try:
thesis_info['defense_date'] = normalize_date(match.group('defense_date'))
except ValueError:
public_notes.append({
'source': source,
'value': public_note,
})
elif _means_not_curated(public_note):
self['curated'] = False
else:
public_notes.append({
'source': source,
'value': public_note,
})
self['thesis_info'] = thesis_info
return public_notes | Populate the ``public_notes`` key.
Also populates the ``curated`` and ``thesis_info`` keys through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L42-L81 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | thesis_info | def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'laurea',
'MASTER': 'master',
'THESIS': 'other',
'PHD': 'phd',
'PDF': 'phd',
'PH.D. THESIS': 'phd',
'HABILITATION': 'habilitation',
}
b_value = force_single_element(value.get('b', ''))
if b_value:
return DEGREE_TYPES_MAP.get(b_value.upper(), 'other')
def _get_institutions(value):
c_values = force_list(value.get('c'))
z_values = force_list(value.get('z'))
# XXX: we zip only when they have the same length, otherwise
# we might match a value with the wrong recid.
if len(c_values) != len(z_values):
return [{'name': c_value} for c_value in c_values]
else:
return [{
'curated_relation': True,
'name': c_value,
'record': get_record_ref(z_value, 'institutions'),
} for c_value, z_value in zip(c_values, z_values)]
thesis_info = self.get('thesis_info', {})
thesis_info['date'] = normalize_date(force_single_element(value.get('d')))
thesis_info['degree_type'] = _get_degree_type(value)
thesis_info['institutions'] = _get_institutions(value)
return thesis_info | python | def thesis_info(self, key, value):
"""Populate the ``thesis_info`` key."""
def _get_degree_type(value):
DEGREE_TYPES_MAP = {
'RAPPORT DE STAGE': 'other',
'INTERNSHIP REPORT': 'other',
'DIPLOMA': 'diploma',
'BACHELOR': 'bachelor',
'LAUREA': 'laurea',
'MASTER': 'master',
'THESIS': 'other',
'PHD': 'phd',
'PDF': 'phd',
'PH.D. THESIS': 'phd',
'HABILITATION': 'habilitation',
}
b_value = force_single_element(value.get('b', ''))
if b_value:
return DEGREE_TYPES_MAP.get(b_value.upper(), 'other')
def _get_institutions(value):
c_values = force_list(value.get('c'))
z_values = force_list(value.get('z'))
# XXX: we zip only when they have the same length, otherwise
# we might match a value with the wrong recid.
if len(c_values) != len(z_values):
return [{'name': c_value} for c_value in c_values]
else:
return [{
'curated_relation': True,
'name': c_value,
'record': get_record_ref(z_value, 'institutions'),
} for c_value, z_value in zip(c_values, z_values)]
thesis_info = self.get('thesis_info', {})
thesis_info['date'] = normalize_date(force_single_element(value.get('d')))
thesis_info['degree_type'] = _get_degree_type(value)
thesis_info['institutions'] = _get_institutions(value)
return thesis_info | Populate the ``thesis_info`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L85-L127 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | thesis_info2marc | def thesis_info2marc(self, key, value):
"""Populate the ``502`` MARC field.
Also populates the ``500`` MARC field through side effects.
"""
def _get_b_value(value):
DEGREE_TYPES_MAP = {
'bachelor': 'Bachelor',
'diploma': 'Diploma',
'habilitation': 'Habilitation',
'laurea': 'Laurea',
'master': 'Master',
'other': 'Thesis',
'phd': 'PhD',
}
degree_type = value.get('degree_type')
if degree_type:
return DEGREE_TYPES_MAP.get(degree_type)
result_500 = self.get('500', [])
result_502 = self.get('502', {})
if value.get('defense_date'):
result_500.append({
'a': u'Presented on {}'.format(value.get('defense_date')),
})
result_502 = {
'b': _get_b_value(value),
'c': [el['name'] for el in force_list(value.get('institutions'))],
'd': value.get('date'),
}
self['500'] = result_500
return result_502 | python | def thesis_info2marc(self, key, value):
"""Populate the ``502`` MARC field.
Also populates the ``500`` MARC field through side effects.
"""
def _get_b_value(value):
DEGREE_TYPES_MAP = {
'bachelor': 'Bachelor',
'diploma': 'Diploma',
'habilitation': 'Habilitation',
'laurea': 'Laurea',
'master': 'Master',
'other': 'Thesis',
'phd': 'PhD',
}
degree_type = value.get('degree_type')
if degree_type:
return DEGREE_TYPES_MAP.get(degree_type)
result_500 = self.get('500', [])
result_502 = self.get('502', {})
if value.get('defense_date'):
result_500.append({
'a': u'Presented on {}'.format(value.get('defense_date')),
})
result_502 = {
'b': _get_b_value(value),
'c': [el['name'] for el in force_list(value.get('institutions'))],
'd': value.get('date'),
}
self['500'] = result_500
return result_502 | Populate the ``502`` MARC field.
Also populates the ``500`` MARC field through side effects. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L131-L166 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | abstracts | def abstracts(self, key, value):
"""Populate the ``abstracts`` key."""
result = []
source = force_single_element(value.get('9'))
for a_value in force_list(value.get('a')):
result.append({
'source': source,
'value': a_value,
})
return result | python | def abstracts(self, key, value):
"""Populate the ``abstracts`` key."""
result = []
source = force_single_element(value.get('9'))
for a_value in force_list(value.get('a')):
result.append({
'source': source,
'value': a_value,
})
return result | Populate the ``abstracts`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L172-L184 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | funding_info | def funding_info(self, key, value):
"""Populate the ``funding_info`` key."""
return {
'agency': value.get('a'),
'grant_number': value.get('c'),
'project_number': value.get('f'),
} | python | def funding_info(self, key, value):
"""Populate the ``funding_info`` key."""
return {
'agency': value.get('a'),
'grant_number': value.get('c'),
'project_number': value.get('f'),
} | Populate the ``funding_info`` key. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L199-L205 |
inspirehep/inspire-dojson | inspire_dojson/hep/rules/bd5xx.py | funding_info2marc | def funding_info2marc(self, key, value):
"""Populate the ``536`` MARC field."""
return {
'a': value.get('agency'),
'c': value.get('grant_number'),
'f': value.get('project_number'),
} | python | def funding_info2marc(self, key, value):
"""Populate the ``536`` MARC field."""
return {
'a': value.get('agency'),
'c': value.get('grant_number'),
'f': value.get('project_number'),
} | Populate the ``536`` MARC field. | https://github.com/inspirehep/inspire-dojson/blob/17f3789cd3d5ae58efa1190dc0eea9efb9c8ca59/inspire_dojson/hep/rules/bd5xx.py#L210-L216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.