code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
from . import LocalFile if os.path.isdir(filename) and self.source is None: raise ValueError("Cannot write this object to " "directory %s without an explicit filename." % filename) target = get_target_path(filename, self.source) if (encoding is not None) and (encoding != self.encoded_with): raise ValueError('%s is already encoded as "%s"' % self, self.encoded_with) with self.open('rb') as infile, open(target, 'wb') as outfile: for line in infile: outfile.write(line) return LocalFile(target)
def put(self, filename, encoding=None)
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
4.689109
4.602537
1.01881
access_type = self._get_access_type(mode) if access_type == 't' and encoding is not None and encoding != self.encoded_with: warnings.warn('Attempting to decode %s as "%s", but encoding is declared as "%s"' % (self, encoding, self.encoded_with)) if encoding is None: encoding = self.encoded_with buffer = io.BytesIO(self._contents) if access_type == 'b': return buffer else: return io.TextIOWrapper(buffer, encoding=encoding)
def open(self, mode='r', encoding=None)
Return file-like object Args: mode (str): access mode (only reading modes are supported) encoding (str): text decoding method for text access (default: system default) Returns: io.BytesIO OR io.TextIOWrapper: buffer accessing the file as bytes or characters
3.422565
3.386127
1.010761
if os.path.exists(destination): if not os.path.isdir(destination): raise OSError('Cannot write to requested destination %s - file exists' % destination) return os.path.join(destination, os.path.basename(origname)) else: destdir = os.path.abspath(os.path.join(destination, os.path.pardir)) if not os.path.isdir(destdir): raise OSError( 'Cannot write to requested destination %s - parent directory does not exist' % destination) return os.path.join(destination)
def get_target_path(destination, origname)
Implements the directory/path semantics of linux mv/cp etc. Examples: >>> import os >>> os.makedirs('./a') >>> get_target_path('./a', '/tmp/myfile') './myfile' >>> get_target_path('./a/b', '/tmp/myfile') './a/b' Raises: OSError: if neither destination NOR destination's parent exists OR it already exists
2.199093
2.380827
0.923667
from . import LocalFile target = get_target_path(filename, self.source) with self.open('rb') as infile, open(target, 'wb') as outfile: shutil.copyfileobj(infile, outfile) return LocalFile(target)
def put(self, filename)
Write the file to the given path Args: filename(str): path to write this file to Returns: LocalFile: reference to the copy of the file stored at ``filename``
4.237209
4.595626
0.922009
access_type = None for char in mode: # figure out whether it's binary or text access if char in 'bt': if access_type is not None: raise IOError('File mode "%s" contains contradictory flags' % mode) access_type = char elif char not in 'rbt': raise NotImplementedError( '%s objects are read-only; unsupported mode "%s"'% (type(self), mode)) if access_type is None: access_type = 't' return access_type
def _get_access_type(self, mode)
Make sure mode is appropriate; return 'b' for binary access and 't' for text
5.098997
4.182472
1.219135
if inspect.ismethod(func): func = func.__func__ elif not inspect.isroutine(func): raise TypeError("'{!r}' is not a Python function".format(func)) # AMVMOD: deal with python 2 builtins that don't define these code = getattr(func, '__code__', None) closure = getattr(func, '__closure__', None) co_names = getattr(code, 'co_names', ()) glb = getattr(func, '__globals__', {}) # Nonlocal references are named in co_freevars and resolved # by looking them up in __closure__ by positional index if closure is None: nonlocal_vars = {} else: nonlocal_vars = {var: cell.cell_contents for var, cell in zip(code.co_freevars, func.__closure__)} # Global and builtin references are named in co_names and resolved # by looking them up in __globals__ or __builtins__ global_ns = glb builtin_ns = global_ns.get("__builtins__", builtins.__dict__) if inspect.ismodule(builtin_ns): builtin_ns = builtin_ns.__dict__ global_vars = {} builtin_vars = {} unbound_names = set() for name in co_names: if name in ("None", "True", "False"): # Because these used to be builtins instead of keywords, they # may still show up as name references. We ignore them. continue try: global_vars[name] = global_ns[name] except KeyError: try: builtin_vars[name] = builtin_ns[name] except KeyError: unbound_names.add(name) return {'nonlocal': nonlocal_vars, 'global': global_vars, 'builtin': builtin_vars, 'unbound': unbound_names}
def getclosurevars(func)
Get the mapping of free variables to their current values. Returns a named tuple of dicts mapping the current nonlocal, global and builtin references as seen by the body of the function. A final set of unbound names that could not be resolved is also provided. Note: Modified function from the Python 3.5 inspect standard library module Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017 Python Software Foundation; All Rights Reserved" See also py-cloud-compute-cannon/NOTICES.
3.071491
2.944212
1.04323
target = get_target_path(destination, self.localpath) shutil.copytree(self.localpath, target)
def put(self, destination)
Copy the referenced directory to this path The semantics of this command are similar to unix ``cp``: if ``destination`` already exists, the copied directory will be put at ``[destination] // [basename(localpath)]``. If it does not already exist, the directory will be renamed to this path (the parent directory must exist). Args: destination (str): path to put this directory
5.516479
8.102945
0.680799
target = get_target_path(destination, self.dirname) valid_paths = (self.dirname, './%s' % self.dirname) with tarfile.open(self.archive_path, 'r:*') as tf: members = [] for tarinfo in tf: # Get only files under the directory `self.dirname` pathsplit = os.path.normpath(tarinfo.path).split(os.sep) if pathsplit[0] not in valid_paths: print('WARNING: skipped file "%s" in archive; not in directory "%s"' % (tarinfo.path, self.dirname)) continue if len(pathsplit) == 1: continue tarinfo.name = os.path.join(*pathsplit[1:]) members.append(tarinfo) if not members: raise ValueError("No files under path directory '%s' in this tarfile") tf.extractall(target, members)
def put(self, destination)
Copy the referenced directory to this path Note: This ignores anything not in the desired directory, given by ``self.dirname``. Args: destination (str): path to put this directory (which must NOT already exist) References: https://stackoverflow.com/a/8261083/1958900
3.562063
3.56863
0.99816
if not self._fetched: self._fetch() DirectoryArchive.put(self, destination)
def put(self, destination)
Copy the referenced directory to this path Args: destination (str): path to put this directory (which must NOT already exist)
11.104877
13.915688
0.798011
from pathlib import Path root = Path(native_str(target)) for outputpath, outputfile in job.get_output().items(): path = Path(native_str(outputpath)) # redirect absolute paths into the appropriate subdirectory if path.is_absolute(): if abspaths: path = Path(native_str(abspaths), *path.parts[1:]) else: continue dest = root / path if not dest.parent.is_dir(): dest.parent.mkdir(parents=True) if dest.is_file(): dest.unlink() try: outputfile.put(str(dest)) except IsADirectoryError: if not dest.is_dir(): dest.mkdir(parents=True)
def dump_all_outputs(self, job, target, abspaths=None)
Default dumping strategy - potentially slow for large numbers of files Subclasses should offer faster implementations, if available
3.280457
3.363811
0.97522
if isinstance(command, PythonCall): return PythonJob(self, image, command, **kwargs) else: return Job(self, image, command, **kwargs)
def launch(self, image, command, **kwargs)
Create a job on this engine Args: image (str): name of the docker image to launch command (str): shell command to run
4.147234
5.116932
0.810492
if ord(char) < 128: return 1 elif unicodedata.east_asian_width(char) in ('F', 'W'): return 2 elif unicodedata.category(char) in ('Mn',): return 0 else: return 1
def char_width(char)
Get the display length of a unicode character.
2.179101
2.317898
0.940119
text = unicodedata.normalize('NFD', text) return sum(char_width(char) for char in text)
def display_len(text)
Get the display length of a string. This can differ from the character length if the string contains wide characters.
4.799141
5.256269
0.913032
return tuple(name for name in names if regex.search(name) is not None)
def filter_regex(names, regex)
Return a tuple of strings that match the regular expression pattern.
5.13544
4.209638
1.219925
return tuple(name for name in names if fnmatch.fnmatch(name, pattern))
def filter_wildcard(names, pattern)
Return a tuple of strings that match a shell-style wildcard pattern.
4.438235
3.860858
1.149546
if '__doc__' in attrs: lstrip = getattr(obj.__doc__, 'lstrip', False) return lstrip and any(lstrip())
def match(self, obj, attrs)
Only match if the object contains a non-empty docstring.
9.142226
6.651422
1.374477
to_run = self.prepare_namespace(func) result = to_run(*self.args, **self.kwargs) return result
def run(self, func=None)
Evaluates the packaged function as func(*self.args,**self.kwargs) If func is a method of an object, it's accessed as getattr(self.obj,__name__). If it's a user-defined function, it needs to be passed in here because it can't be serialized. Returns: object: function's return value
6.089868
5.910115
1.030414
if self.is_imethod: to_run = getattr(self.obj, self.imethod_name) else: to_run = func for varname, modulename in self.global_modules.items(): to_run.__globals__[varname] = __import__(modulename) if self.global_closure: to_run.__globals__.update(self.global_closure) if self.global_functions: to_run.__globals__.update(self.global_functions) return to_run
def prepare_namespace(self, func)
Prepares the function to be run after deserializing it. Re-associates any previously bound variables and modules from the closure Returns: callable: ready-to-call function
3.390342
3.183789
1.064876
results = [] add = results.append add('.. list-table:: %s' % title) add(' :header-rows: 1') if columns: add(' :widths: %s' % (','.join(str(c) for c in columns))) add('') add(' - * %s' % headers[0]) for h in headers[1:]: add(' * %s' % h) for row in data: add(' - * %s' % row[0]) for r in row[1:]: add(' * %s' % r) add('') return '\n'.join(results)
def make_list_table(headers, data, title='', columns=None)
Build a list-table directive. :param headers: List of header values. :param data: Iterable of row data, yielding lists or tuples with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the columns.
1.818259
1.844312
0.985874
header_names = [h[0] for h in headers] header_keys = [h[1] for h in headers] row_data = ( [d.get(k) for k in header_keys] for d in data ) return make_list_table(header_names, row_data, title, columns)
def make_list_table_from_mappings(headers, data, title, columns=None)
Build a list-table directive. :param headers: List of tuples containing header title and key value. :param data: Iterable of row data, yielding mappings with rows. :param title: Optional text to show as the table title. :param columns: Optional widths for the columns.
2.534463
2.540297
0.997703
'Format a decimal.Decimal like to 2 decimal places.' if not isinstance(value, Decimal): value = Decimal(str(value)) return value.quantize(TWOPLACES)
def decimal_format(value, TWOPLACES=Decimal(100) ** -2)
Format a decimal.Decimal like to 2 decimal places.
4.395307
2.704621
1.62511
'''Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True. ''' default_alert_value = True if not profile: alerts_on = True else: notifications = profile.get('notifications', {}) alerts_on = notifications.get(obj_type, default_alert_value) return dict(alerts_on=alerts_on, obj_type=obj_type)
def notification_preference(obj_type, profile)
Display two radio buttons for turning notifications on or off. The default value is is have alerts_on = True.
5.587654
2.838047
1.968838
'''If the committee id no longer exists in mongo for some reason, this function returns None. ''' if 'committee_id' in self: _id = self['committee_id'] return self.document._old_roles_committees.get(_id) else: return self
def committee_object(self)
If the committee id no longer exists in mongo for some reason, this function returns None.
9.660376
4.501205
2.146175
'''Return old roles, grouped first by term, then by chamber, then by type.''' wrapper = self._old_role_wrapper chamber_getter = operator.methodcaller('get', 'chamber') for term, roles in self.get('old_roles', {}).items(): chamber_roles = defaultdict(lambda: defaultdict(list)) for chamber, roles in itertools.groupby(roles, chamber_getter): for role in roles: role = wrapper(role) typeslug = role['type'].lower().replace(' ', '_') chamber_roles[chamber][typeslug].append(role) yield term, chamber_roles
def old_roles_manager(self)
Return old roles, grouped first by term, then by chamber, then by type.
4.447371
3.054967
1.455784
name = re.sub( r'^(Senator|Representative|Sen\.?|Rep\.?|' 'Hon\.?|Right Hon\.?|Mr\.?|Mrs\.?|Ms\.?|L\'hon\.?|' 'Assembly(member|man|woman)) ', '', name) return name.strip().lower().replace('.', '')
def _normalize(self, name)
Normalizes a legislator name by stripping titles from the front, converting to lowercase and removing punctuation.
10.195889
8.413989
1.211778
name, obj = legislator, legislator['_id'] if (legislator['roles'] and legislator['roles'][0]['term'] == self._term and legislator['roles'][0]['type'] == 'member'): chamber = legislator['roles'][0]['chamber'] else: try: chamber = legislator['old_roles'][self._term][0].get('chamber') except KeyError: raise ValueError("no role in legislator %s [%s] for term %s" % (legislator['full_name'], legislator['_id'], self._term)) if '_code' in name: code = name['_code'] if code in self._codes[chamber] or code in self._codes[None]: raise ValueError("non-unique legislator code [%s] for %s" % (code, name['full_name'])) self._codes[chamber][code] = obj self._codes[None][code] = obj # We throw possible forms of this name into a set because we # don't want to try to add the same form twice for the same # name forms = set() def add_form(form): forms.add(self._normalize(form)) add_form(name['full_name']) add_form(name['_scraped_name']) add_form(name['last_name']) if name['first_name']: add_form("%s, %s" % (name['last_name'], name['first_name'])) add_form("%s %s" % (name['first_name'], name['last_name'])) add_form("%s, %s" % (name['last_name'], name['first_name'][0])) add_form("%s (%s)" % (name['last_name'], name['first_name'])) add_form("%s %s" % (name['first_name'][0], name['last_name'])) add_form("%s (%s)" % (name['last_name'], name['first_name'][0])) if name['middle_name']: add_form("%s, %s %s" % (name['last_name'], name['first_name'], name['middle_name'])) add_form("%s, %s %s" % (name['last_name'], name['first_name'][0], name['middle_name'])) add_form("%s %s %s" % (name['first_name'], name['middle_name'], name['last_name'])) add_form("%s, %s %s" % (name['last_name'], name['first_name'][0], name['middle_name'][0])) add_form("%s %s %s" % (name['first_name'], name['middle_name'][0], name['last_name'])) add_form("%s, %s %s" % (name['last_name'], name['first_name'], name['middle_name'][0])) add_form("%s, %s.%s." % (name['last_name'], name['first_name'][0], name['middle_name'][0])) for form in forms: form = self._normalize(form) if form in self._names[chamber]: self._names[chamber][form] = None else: self._names[chamber][form] = obj if form in self._names[None]: self._names[None][form] = None else: self._names[None][form] = obj
def _learn(self, legislator)
Expects a dictionary with full_name, first_name, last_name and middle_name elements as key. While this can grow quickly, we should never be dealing with more than a few hundred legislators at a time so don't worry about it.
1.972569
1.962679
1.005039
try: return self._manual[chamber][name] except KeyError: pass if chamber == 'joint': chamber = None try: return self._codes[chamber][name] except KeyError: pass if chamber not in self._names: logger.warning("Chamber %s is invalid for a legislator." % ( chamber )) return None name = self._normalize(name) return self._names[chamber].get(name, None)
def match(self, name, chamber=None)
If this matcher has uniquely seen a matching name, return its value. Otherwise, return None. If chamber is set then the search will be limited to legislators with matching chamber. If chamber is None then the search will be cross-chamber.
3.539885
3.428743
1.032415
# act of importing puts it into the registry try: module = importlib.import_module(mod_path) except ImportError as e: raise ScrapeError("could not import %s" % mod_path, e) # now find the class within the module ScraperClass = None for k, v in module.__dict__.items(): if k.startswith('_'): continue if getattr(v, 'scraper_type', None) == scraper_type: if ScraperClass: raise ScrapeError("two %s scrapers found in module %s: %s %s" % (scraper_type, mod_path, ScraperClass, k)) ScraperClass = v if not ScraperClass: raise ScrapeError("no %s scraper found in module %s" % ( scraper_type, mod_path)) return ScraperClass
def get_scraper(mod_path, scraper_type)
import a scraper from the scraper registry
2.565239
2.497861
1.026975
types = ('bill', 'committee', 'person', 'vote', 'event') for type in types: schema_path = os.path.join(os.path.split(__file__)[0], '../schemas/%s.json' % type) self._schema[type] = json.load(open(schema_path)) self._schema[type]['properties'][settings.LEVEL_FIELD] = { 'minLength': 2, 'type': 'string'} # bills & votes self._schema['bill']['properties']['session']['enum'] = \ self.all_sessions() self._schema['vote']['properties']['session']['enum'] = \ self.all_sessions() # legislators terms = [t['name'] for t in self.metadata['terms']] # ugly break here b/c this line is nearly impossible to split self._schema['person']['properties']['roles'][ 'items']['properties']['term']['enum'] = terms
def _load_schemas(self)
load all schemas into schema dict
4.149538
3.977555
1.043238
if latest_only: if session != self.metadata['terms'][-1]['sessions'][-1]: raise NoDataForPeriod(session) for t in self.metadata['terms']: if session in t['sessions']: return True raise NoDataForPeriod(session)
def validate_session(self, session, latest_only=False)
Check that a session is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if session is invalid :param session: string representing session to check
5.129236
3.700078
1.386251
if latest_only: if term == self.metadata['terms'][-1]['name']: return True else: raise NoDataForPeriod(term) for t in self.metadata['terms']: if term == t['name']: return True raise NoDataForPeriod(term)
def validate_term(self, term, latest_only=False)
Check that a term is present in the metadata dictionary. raises :exc:`~billy.scrape.NoDataForPeriod` if term is invalid :param term: string representing term to check :param latest_only: if True, will raise exception if term is not the current term (default: False)
3.408191
2.403957
1.417742
self['sources'].append(dict(url=url, **kwargs))
def add_source(self, url, **kwargs)
Add a source URL from which data related to this object was scraped. :param url: the location of the source
5.530247
9.435826
0.58609
'''Guess where the ends of the columns lie. ''' ends = collections.Counter() for line in self.text.splitlines(): for matchobj in re.finditer('\s{2,}', line.lstrip()): ends[matchobj.end()] += 1 return ends
def _get_column_ends(self)
Guess where the ends of the columns lie.
5.275315
4.105668
1.284886
'''Use the guessed ends to guess the boundaries of the plain text columns. ''' # Try to figure out the most common column boundaries. ends = self._get_column_ends() if not ends: # If there aren't even any nontrivial sequences of whitespace # dividing text, there may be just one column. In which case, # Return a single span, effectively the whole line. return [slice(None, None)] most_common = [] threshold = self.threshold for k, v in collections.Counter(ends.values()).most_common(): if k >= threshold: most_common.append(k) if most_common: boundaries = [] for k, v in ends.items(): if v in most_common: boundaries.append(k) else: # Here there weren't enough boundaries to guess the most common # ones, so just use the apparent boundaries. In other words, we # have only 1 row. Potentially a source of inaccuracy. boundaries = ends.keys() # Convert the boundaries into a list of span slices. boundaries.sort() last_boundary = boundaries[-1] boundaries = zip([0] + boundaries, boundaries) boundaries = list(itertools.starmap(slice, boundaries)) # And get from the last boundary to the line ending. boundaries.append(slice(last_boundary, None)) return boundaries
def _get_column_boundaries(self)
Use the guessed ends to guess the boundaries of the plain text columns.
5.770529
4.87815
1.182934
'''Using self.boundaries, extract cells from the given line. ''' for boundary in self.boundaries: cell = line.lstrip()[boundary].strip() if cell: for cell in re.split('\s{3,}', cell): yield cell else: yield None
def getcells(self, line)
Using self.boundaries, extract cells from the given line.
6.46312
3.791417
1.704671
'''Returns an iterator of row tuples. ''' for line in self.text.splitlines(): yield tuple(self.getcells(line))
def rows(self)
Returns an iterator of row tuples.
8.664966
5.827564
1.486893
'''Returns an interator of all cells in the table. ''' for line in self.text.splitlines(): for cell in self.getcells(line): yield cell
def cells(self)
Returns an interator of all cells in the table.
6.859457
4.023094
1.705021
'A generator of previous page integers.' skip = self.skip if skip == 0: return 0 count, remainder = divmod(skip, self.limit) return count
def _previous_pages_count(self)
A generator of previous page integers.
8.64642
6.398818
1.351253
'A generator of previous page integers.' count = self._previous_pages_count() + 1 for i in reversed(range(1, count)): yield i
def previous_pages_numbers(self)
A generator of previous page integers.
8.558461
5.937204
1.441497
'''"Showing 40 - 50 of 234 results ^ ''' count = self.count range_end = self.range_start + self.limit - 1 if count < range_end: range_end = count return range_end
def range_end(self)
"Showing 40 - 50 of 234 results ^
8.746703
3.340226
2.618596
'''Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clickable or not. ''' div, mod = divmod(max_number_of_links, 2) if not mod == 1: msg = 'Max number of links must be odd, was %r.' raise ValueError(msg % max_number_of_links) midpoint = (max_number_of_links - 1) / 2 current_page = self.current_page last_page = self.last_page if current_page > last_page: raise Http404('invalid page number') current_page = last_page show_link_firstpage = midpoint < current_page show_link_previouspage = 1 < current_page show_link_lastpage = current_page < (self.last_page - midpoint) show_link_nextpage = current_page < last_page extra_room_previous = midpoint - current_page if extra_room_previous < 0: extra_room_previous = 0 if not show_link_firstpage: extra_room_previous += 1 if not show_link_previouspage: extra_room_previous += 1 extra_room_subsequent = current_page - last_page + midpoint extra_room_subsequent = max([extra_room_subsequent, 0]) if not show_link_nextpage: extra_room_subsequent += 1 if not show_link_lastpage: extra_room_subsequent += 1 if self.current_page == 1: yield PageLink(string=1, page_number=1, clickable=False) else: # The "first page" link. if show_link_firstpage: #[<<] [<] [7] [8] [9] 10 [11] ...' # ^ yield PageLink(string=u"\u00AB", page_number=1, clickable=True) if show_link_previouspage: # The "previous page" link. #[<<] [<] [7] [8] [9] 10 [11] ...' # ^ yield PageLink(string=u"\u2039", page_number=self.previous_page, clickable=True) # Up to `midpoint + extra_room_subsequent` previous page numbers. previous = itertools.islice(self.previous_pages_numbers(), midpoint + extra_room_subsequent) previous = list(previous)[::-1] for page_number in previous: yield PageLink(string=page_number, page_number=page_number, clickable=True) # The current page, clickable. if current_page != 1: yield PageLink(string=current_page, page_number=current_page, clickable=False) # Up to `midpoint + extra_room_previous` subsequent page numbers. subsequent_count = midpoint + extra_room_previous _subsequent_pages_count = self._subsequent_pages_count if _subsequent_pages_count < subsequent_count: subsequent_count = _subsequent_pages_count for page_number in itertools.islice(self.subsequent_pages_numbers(), subsequent_count): yield PageLink(string=page_number, page_number=page_number, clickable=True) if show_link_nextpage: yield PageLink(string=u"\u203A", page_number=current_page + 1, clickable=True) if show_link_lastpage: yield PageLink(string=u"\u00BB", page_number=last_page, clickable=True)
def pagination_data(self, max_number_of_links=7)
Returns a generator of tuples (string, page_number, clickable), where `string` is the text of the html link, `page_number` is the number of the page the link points to, and `clickable` is a boolean indicating whether the link is clickable or not.
2.332299
2.142844
1.088413
_clear_scraped_data(options.output_dir, scraper_type) scraper = _get_configured_scraper(scraper_type, options, metadata) ua_email = os.environ.get('BILLY_UA_EMAIL') if ua_email and scraper: scraper.user_agent += ' ({})'.format(ua_email) if not scraper: return [{ "type": scraper_type, "start_time": dt.datetime.utcnow(), "noscraper": True, "end_time": dt.datetime.utcnow() }] runs = [] # Removed from the inner loop due to non-bicameral scrapers scrape = { "type": scraper_type } scrape['start_time'] = dt.datetime.utcnow() if scraper_type in ('bills', 'votes', 'events'): times = options.sessions for time in times: scraper.validate_session(time, scraper.latest_only) elif scraper_type in ('committees', 'legislators'): times = options.terms for time in times: scraper.validate_term(time, scraper.latest_only) # run scraper against year/session/term for time in times: # old style chambers = options.chambers if scraper_type == 'events' and len(options.chambers) == 2: chambers.append('other') if _is_old_scrape(scraper.scrape): for chamber in chambers: scraper.scrape(chamber, time) else: scraper.scrape(time, chambers=chambers) # error out if events or votes don't scrape anything if not scraper.object_count and scraper_type not in ('events', 'votes'): raise ScrapeError("%s scraper didn't save any objects" % scraper_type) scrape['end_time'] = dt.datetime.utcnow() runs.append(scrape) return runs
def _run_scraper(scraper_type, options, metadata)
scraper_type: bills, legislators, committees, votes
3.827433
3.700697
1.034246
meta = db.metadata.find_one({'_id': abbr}) current_term = meta['terms'][-1] current_session = current_term['sessions'][-1] for bill in db.bills.find({settings.LEVEL_FIELD: abbr}): if bill['session'] == current_session: bill['_current_session'] = True else: bill['_current_session'] = False if bill['session'] in current_term['sessions']: bill['_current_term'] = True else: bill['_current_term'] = False db.bills.save(bill, safe=True)
def populate_current_fields(abbr)
Set/update _current_term and _current_session fields on all bills for a given location.
2.777827
2.281077
1.21777
self._reset_sequence() for item in item_list: key = self.nondup_key_for_item(item) self.ids[key] = item[self.id_key]
def learn_ids(self, item_list)
read in already set ids on objects
5.772347
5.170711
1.116355
self._reset_sequence() for item in item_list: key = self.nondup_key_for_item(item) item[self.id_key] = self.ids.get(key) or self._get_next_id()
def set_ids(self, item_list)
set ids on an object, using internal mapping then new ids
5.264282
4.485559
1.173607
# for all current legislators for legislator in db.legislators.find({'roles': {'$elemMatch': { 'term': current_term, settings.LEVEL_FIELD: abbr}}}): # for all committee roles for role in legislator['roles']: if (role['type'] == 'committee member' and 'committee_id' not in role): spec = {settings.LEVEL_FIELD: abbr, 'chamber': role['chamber'], 'committee': role['committee']} if 'subcommittee' in role: spec['subcommittee'] = role['subcommittee'] committee = db.committees.find_one(spec) if not committee: committee = spec committee['_type'] = 'committee' # copy LEVEL_FIELD from legislator to committee committee[settings.LEVEL_FIELD] = \ legislator[settings.LEVEL_FIELD] committee['members'] = [] committee['sources'] = [] if 'subcommittee' not in committee: committee['subcommittee'] = None insert_with_id(committee) for member in committee['members']: if member['leg_id'] == legislator['leg_id']: break else: committee['members'].append( {'name': legislator['full_name'], 'leg_id': legislator['leg_id'], 'role': role.get('position') or 'member'}) for source in legislator['sources']: if source not in committee['sources']: committee['sources'].append(source) db.committees.save(committee, safe=True) role['committee_id'] = committee['_id'] db.legislators.save(legislator, safe=True)
def import_committees_from_legislators(current_term, abbr)
create committees from legislators that have committee roles
2.493239
2.481833
1.004596
self['sponsors'].append(dict(type=type, name=name, **kwargs))
def add_sponsor(self, type, name, **kwargs)
Associate a sponsor with this bill. :param type: the type of sponsorship, e.g. 'primary', 'cosponsor' :param name: the name of the sponsor as provided by the official source
3.803767
5.705123
0.666728
if not mimetype: raise ValueError('mimetype parameter to add_version is required') if on_duplicate != 'ignore': if url in self._seen_versions: if on_duplicate == 'error': raise ValueError('duplicate version url %s' % url) elif on_duplicate == 'use_new': # delete the old version self['versions'] = [v for v in self['versions'] if v['url'] != url] elif on_duplicate == 'use_old': return # do nothing self._seen_versions.add(url) d = dict(name=name, url=url, mimetype=mimetype, **kwargs) self['versions'].append(d)
def add_version(self, name, url, mimetype=None, on_duplicate='error', **kwargs)
Add a version of the text of this bill. :param name: a name given to this version of the text, e.g. 'As Introduced', 'Version 2', 'As amended', 'Enrolled' :param url: the location of this version on the legislative website. :param mimetype: MIME type of the document :param on_duplicate: What to do if a duplicate is seen: error - default option, raises a ValueError ignore - add the document twice (rarely the right choice) use_new - use the new name, removing the old document use_old - use the old name, not adding the new document If multiple formats are provided, a good rule of thumb is to prefer text, followed by html, followed by pdf/word/etc.
2.479247
2.336777
1.060969
def _cleanup_list(obj, default): if not obj: obj = default elif isinstance(obj, string_types): obj = [obj] elif not isinstance(obj, list): obj = list(obj) return obj type = _cleanup_list(type, ['other']) committees = _cleanup_list(committees, []) legislators = _cleanup_list(legislators, []) if 'committee' in kwargs: raise ValueError("invalid param 'committee' passed to add_action, " "must use committees") if isinstance(committees, string_types): committees = [committees] related_entities = [] # OK, let's work some magic. for committee in committees: related_entities.append({ "type": "committee", "name": committee }) for legislator in legislators: related_entities.append({ "type": "legislator", "name": legislator }) self['actions'].append(dict(actor=actor, action=action, date=date, type=type, related_entities=related_entities, **kwargs))
def add_action(self, actor, action, date, type=None, committees=None, legislators=None, **kwargs)
Add an action that was performed on this bill. :param actor: a string representing who performed the action. If the action is associated with one of the chambers this should be 'upper' or 'lower'. Alternatively, this could be the name of a committee, a specific legislator, or an outside actor such as 'Governor'. :param action: a string representing the action performed, e.g. 'Introduced', 'Signed by the Governor', 'Amended' :param date: the date/time this action was performed. :param type: a type classification for this action ;param committees: a committee or list of committees to associate with this action
2.534014
2.582878
0.981082
companion = {'bill_id': bill_id, 'session': session or self['session'], 'chamber': chamber} self['companions'].append(companion)
def add_companion(self, bill_id, session=None, chamber=None)
Associate another bill with this one. If session isn't set it will be set to self['session'].
2.935997
2.589039
1.13401
''' Context: all_metadata Templates: - billy/web/public/homepage.html ''' all_metadata = db.metadata.find() return render(request, templatename('homepage'), dict(all_metadata=all_metadata))
def homepage(request)
Context: all_metadata Templates: - billy/web/public/homepage.html
8.74686
4.044984
2.162396
''' Context: - all_metadata Templates: - billy/web/public/downloads.html ''' all_metadata = sorted(db.metadata.find(), key=lambda x: x['name']) return render(request, 'billy/web/public/downloads.html', {'all_metadata': all_metadata})
def downloads(request)
Context: - all_metadata Templates: - billy/web/public/downloads.html
4.137932
2.462642
1.680282
''' Context: - request - lat - long - located - legislators Templates: - billy/web/public/find_your_legislator_table.html ''' # check if lat/lon are set # if leg_search is set, they most likely don't have ECMAScript enabled. # XXX: fallback behavior here for alpha. get = request.GET context = {} template = 'find_your_legislator' context['request'] = "" if "q" in get: context['request'] = get['q'] if "lat" in get and "lon" in get: # We've got a passed lat/lon. Let's build off it. lat = get['lat'] lon = get['lon'] context['lat'] = lat context['lon'] = lon context['located'] = True qurl = "%slegislators/geo/?long=%s&lat=%s&apikey=%s" % ( billy_settings.API_BASE_URL, lon, lat, getattr(billy_settings, 'API_KEY', '') ) leg_resp = json.load(urllib2.urlopen(qurl, timeout=0.5)) # allow limiting lookup to region for region map views if 'abbr' in get: leg_resp = [leg for leg in leg_resp if leg[billy_settings.LEVEL_FIELD] == get['abbr']] context['abbr'] = get['abbr'] # Also, allow filtering by chamber if 'chamber' in get: leg_resp = [leg for leg in leg_resp if leg['chamber'] == get['chamber']] context['chamber'] = get['chamber'] if "boundary" in get: return HttpResponse(json.dumps([])) context['legislators'] = map(Legislator, leg_resp) template = 'find_your_legislator_table' return render(request, templatename(template), context)
def find_your_legislator(request)
Context: - request - lat - long - located - legislators Templates: - billy/web/public/find_your_legislator_table.html
4.287927
3.665498
1.169807
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)
def activate_legislators(current_term, abbr)
Sets the 'active' flag on legislators and populates top-level district/chamber/party fields for currently serving legislators.
2.496595
2.380281
1.048866
self['roles'].append(dict(role=role, term=term, start_date=start_date, end_date=end_date, **kwargs))
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')
2.580604
2.692213
0.958544
office_dict = dict(type=type, address=address, name=name, phone=phone, fax=fax, email=email, **kwargs) self['offices'].append(office_dict)
def add_office(self, type, name, address=None, phone=None, fax=None, email=None, **kwargs)
Allowed office types: capitol district
2.362842
2.617931
0.902561
# 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
def metadata(abbr, __metadata=__metadata)
Grab the metadata for the given two-letter abbreviation.
5.464816
5.380319
1.015705
'''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)
def cd(path)
Creates the path if it doesn't exist
2.630539
2.648121
0.993361
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
def _get_property_dict(schema)
given a schema object produce a nested dictionary of fields
2.887828
2.765154
1.044364
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
def insert_with_id(obj)
Generates a unique ID for the supplied legislator/committee/bill and inserts it into the appropriate collection.
2.462316
2.354392
1.045839
# 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
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
2.990915
3.107806
0.962388
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
def convert_timestamps(obj)
Convert unix timestamps in the scraper output to python datetimes so that they will be saved properly as Mongo datetimes.
3.6569
3.636091
1.005723
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
def split_name(obj)
If the supplied legislator/person object is missing 'first_name' or 'last_name' then use name_tools to split.
4.918297
3.251404
1.512669
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
def _make_plus_helper(obj, fields)
add a + prefix to any fields in obj that aren't in fields
4.518397
4.173007
1.082767
fields = standard_fields.get(obj['_type'], dict()) return _make_plus_helper(obj, 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
10.442364
5.368358
1.945169
''' 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)
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.
10.038347
2.609489
3.846863
'''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
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.
5.681371
3.695935
1.537194
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
def extract_fields(d, fields, delimiter='|')
get values out of an object ``d`` for saving to a csv
2.187695
2.2952
0.953161
''' 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'))
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
3.370725
2.512445
1.341611
''' 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'))
def vote(request, abbr, vote_id)
Context: - abbr - metadata - bill - vote - nav_active Templates: - vote.html
4.880312
3.407379
1.432277
''' 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'))
def document(request, abbr, session, bill_id, doc_id)
Context: - abbr - session - bill - version - metadata - nav_active Templates: - billy/web/public/document.html
3.508482
2.891928
1.213198
''' 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
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.
4.830171
2.912208
1.658594
''' 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
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.
3.122077
2.501278
1.248192
'''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)
def region_selection(request)
Handle submission of the region selection form in the base template.
5.565551
3.928937
1.416554
''' 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'))
def region(request, abbr)
Context: - abbr - metadata - sessions - chambers - joint_committee_count - geo_bounds - nav_active Templates: - bill/web/public/region.html
3.457251
2.962106
1.16716
''' 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))
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
3.679022
2.796678
1.315497
self['members'].append(dict(name=legislator, role=role, **kwargs))
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'
5.11222
6.282513
0.813722
'''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
def action_display(self)
The action text, with any hyperlinked related entities.
5.4669
4.450986
1.228245
'''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
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.
7.307325
2.886072
2.531927
'''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)
def _ratio(self, key)
Return the yes/total ratio as a percetage string suitable for use as as css attribute.
9.193559
3.226848
2.849083
'''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
def _legislator_objects(self)
A cache of dereferenced legislator objects.
5.313708
4.599016
1.155401
'''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
def legislator_vote_value(self)
If this vote was accessed through the legislator.votes_manager, return the value of this legislator's vote.
4.995534
3.148642
1.586568
'''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
def _vote_legislators(self, yes_no_other)
Return all legislators who votes yes/no/other on this bill.
3.378619
2.732435
1.236487
'''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
def is_probably_a_voice_vote(self)
Guess whether this vote is a "voice vote".
5.1814
4.17481
1.24111
'''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}})
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.
7.925017
2.251347
3.520123
'''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']
def host(self)
Return the host committee.
6.98492
5.759465
1.212772
'''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
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'.
11.957579
3.004342
3.980099
'''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
def host_members(self)
Return the members of the host committee.
9.79312
6.39202
1.532085
''' 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'))
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
2.714303
2.008759
1.351234
''' 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'))
def committee(request, abbr, committee_id)
Context: - committee - abbr - metadata - sources - nav_active Tempaltes: - billy/web/public/committee.html
4.840606
2.771881
1.746325
# 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
def update_common(obj, report)
do updated_at checks
3.106766
2.776273
1.119042
''' 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'))
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
2.478692
2.001465
1.238439
''' 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'))
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
3.287383
2.556863
1.28571
''' 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'))
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
3.508042
2.161082
1.62328
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')
def normalize_rank(rank)
Normalize a rank in order to be schema-compliant.
2.607869
2.51619
1.036436
if not isinstance(ref_obj, dict): return None url = ref_obj.get('$ref', '') return maybe_int(url.split('/')[-1])
def get_recid_from_ref(ref_obj)
Retrieve recid from jsonref reference object. If no recid can be parsed, returns None.
4.867442
4.294826
1.133327
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)
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``.
3.243785
2.420137
1.340331
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
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``.
3.066522
2.011533
1.52447
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
def strip_empty_values(obj)
Recursively strips empty values.
1.553715
1.530027
1.015482
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
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
2.134476
2.24753
0.949699