Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Predict the next line after this snippet: <|code_start|>__author__ = 'Stuart Gordon Reid' __email__ = 'stuartgordonreid@gmail.com' __website__ = 'http://www.stuartreid.co.za' """ File description """ <|code_end|> using the current file's imports: import random import profile from Optimizers.Solution import Soluti...
class BrownianSolution(Solution):
Predict the next line after this snippet: <|code_start|>__website__ = 'http://www.stuartreid.co.za' """ File description """ class BrownianSolution(Solution): def __init__(self, solution, problem, parameters=None): """ :param solution: the initial solution :param parameters: [0] num att...
problem = Cigar(50, 25, -25)
Based on the snippet: <|code_start|> self.parent.title(self.title) self.content_grid = Frame(self.parent) self.parent.geometry("%dx%d" % (self.width, self.height)) def pack_window(self): """ This method just 'packs' the window with the different components """ ...
assert isinstance(element, GridElement)
Predict the next line for this snippet: <|code_start|> :param columns: the number of columns to create """ one_width = (self.width * padding) / columns one_height = (self.height * padding) / rows for element in grid_elements: assert isinstance(element, GridElement) ...
grid_elements = [FormGridElement(0, 0, 2, 1, 'grey'),
Based on the snippet: <|code_start|>__author__ = 'stuartreid' def investing_example(): """ This method creates a set of regression analyses based on fundamental trading (revenues) """ # b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white statsmodels_args_inv = Regression...
regressions_inv = [RegressionAnalysis(QuandlDownloader("DMDRN/GOOG_REV_LAST", quandl_args_inv),
Given the code snippet: <|code_start|>__author__ = 'stuartreid' def investing_example(): """ This method creates a set of regression analyses based on fundamental trading (revenues) """ # b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white statsmodels_args_inv = Regressi...
quandl_args_inv = QuandlSettings(5, 1, "yearly")
Here is a snippet: <|code_start|>__author__ = 'stuartreid' def investing_example(): """ This method creates a set of regression analyses based on fundamental trading (revenues) """ # b: blue, g: green, r: red, c: cyan, m: magenta, y: yellow, k: black, w: white statsmodels_args_inv = RegressionSet...
SimplePlotter.plot_regression_line(regressions_inv)
Here is a snippet: <|code_start|>__author__ = 'Stuart Gordon Reid' __email__ = 'stuartgordonreid@gmail.com' __website__ = 'http://www.stuartreid.co.za' """ File description """ <|code_end|> . Write the next line using the current file imports: from Optimizers.Optimizer import Optimizer and context from other file...
class SimulatedAnnealing(Optimizer):
Given the following code snippet before the placeholder: <|code_start|> FILEONLY = 'fileonly' class Artefacts(FunctionType): """ Will return a list of artefacts (relative path) inside directories starting with ! If fileonly == True is passed in then only filenames will be listed """ def __init__(s...
'and does not need to be specified' % striptoclassname(type(obj)))
Next line prediction: <|code_start|> return metaDef expr = p.OneOrMore(p.Group(aggregatorIdParser() + p.OneOrMore(aggregatorMetas()))) match = expr.parseString(configstring) _retlist = [] for m in match: _retdict = {} _retdict['id'] = m[0] for k, v in m.items(): ...
return AttrSelector() # 'ATTRTYPE'
Continue the code snippet: <|code_start|> match = expr.parseString(configstring) _retlist = [] for m in match: _retdict = {} _retdict['id'] = m[0] for k, v in m.items(): _retdict[k] = v _retlist.append(_retdict) return _retlist def parseSelector(selectorst...
return FullPathSelector() #'FULLPATH'
Based on the snippet: <|code_start|> _retlist = [] for m in match: _retdict = {} _retdict['id'] = m[0] for k, v in m.items(): _retdict[k] = v _retlist.append(_retdict) return _retlist def parseSelector(selectorstring): # *select = @attr1 | /tf1/@attr | @attr...
return AttrByObjectSelector() #'ATTRBYOBJECT'
Predict the next line for this snippet: <|code_start|> class Slice(FunctionType): """ Truncates a single string. Will return None if the attributes in the config string is missing. Does not work with multiple value attributes or attributes that are dynamic objects. Example strings are: '@text1[:5] ...
'a %s instead' % striptoclassname(type(self.targetobject)))
Given snippet: <|code_start|> if self.config is None or len(self.config) < 1 or not isinstance(self.config, str): raise ValueError('Cvssv2 plugin function requires an attribute be specified such as "@vector"') def compute(self): def getname(obj, name): _val = None ...
'only works on singleton attributes' % striptoclassname(type(self.targetobject)))
Predict the next line after this snippet: <|code_start|> return trailers def get_movie_data(tmdb_id, lang): tmdb = get_tmdb(lang=lang) return tmdb.Movies(tmdb_id) movie_data_en = get_movie_data(tmdb_id, "en") movie_info_en = movie_data_en.info() # We have to get all info in engl...
raise MovieNotInDb(tmdb_id)
Predict the next line after this snippet: <|code_start|> if search_type == "actor": movies = filter_movies_only(person.cast) else: movies = filter_movies_only(person.crew) movies = [m for m in movies if m["job"] == "Director"] return movies ...
"poster": get_poster_url("small", poster),
Continue the code snippet: <|code_start|> class SearchView(TemplateAnonymousView): template_name = "search.html" class SearchMovieView(AjaxAnonymousView): def get(self, request): AVAILABLE_SEARCH_TYPES = [ "actor", "movie", "director", ] try: ...
class AddToListFromDbView(AjaxView):
Continue the code snippet: <|code_start|> options = json.loads(GET["options"]) type_ = GET["type"] if type_ not in AVAILABLE_SEARCH_TYPES: raise NotAvailableSearchType except (KeyError, NotAvailableSearchType): return self.render_bad_request_respons...
add_movie_to_list(movie_id, list_id, user)
Given the following code snippet before the placeholder: <|code_start|> def logout_view(request): logout(request) return redirect("/") @method_decorator(login_required, name="dispatch") class PreferencesView(FormView): template_name = "user/preferences.html" form_class = UserForm def get_form_...
class LoginErrorView(TemplateAnonymousView):
Next line prediction: <|code_start|> @register(Movie) class MovieTranslationOptions(TranslationOptions): fields = ("title", "poster", "description", "trailers") <|code_end|> . Use current file imports: (from modeltranslation.translator import TranslationOptions, register from .models import Action, List, Movie...
@register(Action)
Next line prediction: <|code_start|> @register(Movie) class MovieTranslationOptions(TranslationOptions): fields = ("title", "poster", "description", "trailers") @register(Action) class ActionTranslationOptions(TranslationOptions): fields = ("name",) <|code_end|> . Use current file imports: (from modeltra...
@register(List)
Given the code snippet: <|code_start|> ).save() record.rating = rating record.save() return self.success() class AddToListView(AjaxView): def post(self, request, **kwargs): try: movie_id = int(kwargs["id"]) list_id = int(request.POST["...
class SaveSettingsView(AjaxAnonymousView):
Next line prediction: <|code_start|> record.watched_in_theatre = options["theatre"] record.watched_in_4k = options["4k"] record.watched_in_hd = options["hd"] record.watched_in_full_hd = options["fullHd"] record.save() return self.success() class SaveCommentView(AjaxView)...
class ListView(TemplateAnonymousView):
Continue the code snippet: <|code_start|> if username and session["recommendation"]: records = self._filter_records_for_recommendation(records, request.user) if username: list_data = self._get_list_data(records) else: list_data = None if not username...
class RecommendationsView(TemplateView, ListView):
Given the following code snippet before the placeholder: <|code_start|> class ChangeRatingView(AjaxView): def put(self, request, **kwargs): try: id_ = kwargs["id"] rating = request.PUT["rating"] except KeyError: return self.render_bad_request_response() ...
add_movie_to_list(movie_id, list_id, request.user)
Predict the next line for this snippet: <|code_start|> movies = [x[1] for x in record_ids_and_movies] return (movies, {x[0]: x[1] for x in record_ids_and_movies}) def _get_list_data(self, records): movies, record_ids_and_movies_dict = self._get_record_movie_data(records.values_list("id", "mo...
anothers_account = get_anothers_account(username)
Predict the next line for this snippet: <|code_start|> if record.rating: data["rating"] = record.rating comments_and_ratings[record.movie.pk].append(data) data = {} for record_id, value in record_ids_and_movies_dict.items(): data[record_id] ...
self.request.user.get_records().filter(movie_id__in=movies).values_list("movie_id", "list_id")
Using the snippet: <|code_start|> def get_context_data(self, list_name, username=None): if username is None and self.request.user.is_anonymous: raise Http404 anothers_account = get_anothers_account(username) if anothers_account: if User.objects.get(username=username) ...
records = paginate(records, request.GET.get("page"), settings.RECORDS_ON_PAGE)
Predict the next line for this snippet: <|code_start|> if friends is None: records = [] else: records = records.filter(user__in=friends) comments_and_ratings = {} for record in records: if record.comment or record.rating: data = {"user"...
return sort_by_rating(records, username, list_name)
Based on the snippet: <|code_start|> def load_user_data(backend, user, **kwargs): # pylint: disable=unused-argument if user.loaded_initial_data: return None if backend.name in settings.VK_BACKENDS: # We don't need the username and email because they are already loaded. FIELDS = ( ...
avatar_small = get_vk_avatar(data["photo_100"])
Given the following code snippet before the placeholder: <|code_start|> def load_omdb_movie_data(imdb_id): try: response = requests.get(f"http://www.omdbapi.com/?i={imdb_id}&apikey={settings.OMDB_KEY}") except RequestException as e: if settings.DEBUG: raise capture_excepti...
raise OmdbRequestError from e
Here is a snippet: <|code_start|> i = 0 for action in actions: action_ = { "user": action.user, "action": action, "movie": action.movie, "movie_poster": posters[i], "movie_poster_2x": posters_2x[i], ...
class FriendsView(TemplateView, PeopleView):
Here is a snippet: <|code_start|> users = self.request.user.get_users(friends=list_name == "friends") actions = actions.filter(user__in=users) posters = [action.movie.poster_small for action in actions] posters_2x = [action.movie.poster_normal for action in actions] actions_outpu...
return {"users": paginate(self.users, self.request.GET.get("page"), settings.PEOPLE_ON_PAGE)}
Using the snippet: <|code_start|> comodel_name="res.partner.bank", string="Bank account", ondelete="restrict" ) invoice_message_ids = fields.One2many( comodel_name="paynet.invoice.message", inverse_name="service_id", string="Invoice Messages", readonly=True, ) ebil...
dws = PayNetDWS(self.url, self.use_test_service)
Based on the snippet: <|code_start|> ("error", "Error"), ], default="draft", ) ic_ref = fields.Char( string="IC Ref", size=14, help="Document interchange reference" ) # Set with invoice_id.number but also with returned data from server ? ref = fields.Char("Referenc...
message.response = PayNetDWS.handle_fault(e)
Using the snippet: <|code_start|> class TestEbillPaynet(SingleTransactionCase): @classmethod def setUpClass(cls): super().setUpClass() cls.env = cls.env(context=dict(cls.env.context, tracking_disable=True)) # Invoice and account should be the same company cls.env.user.company_id...
cls.dws = PayNetDWS(cls.paynet.url, True)
Predict the next line for this snippet: <|code_start|> "reconcile": True, } ) cls.product = cls.env["product.template"].create( {"name": "Product One", "list_price": 100.00} ) cls.invoice_1 = cls.env["account.move"].create( { ...
@recorder.use_cassette
Using the snippet: <|code_start|> class Plugin(Process): # pragma: no cover def __repr__(self): return "<Plugin {}>".format(self.name) def execute(self, **kwargs): raise NotImplementedError() <|code_end|> , determine the next line of code. You have imports: from therapist.collection import...
class PluginCollection(Collection):
Next line prediction: <|code_start|> class Plugin(Process): # pragma: no cover def __repr__(self): return "<Plugin {}>".format(self.name) def execute(self, **kwargs): raise NotImplementedError() class PluginCollection(Collection): class Meta: object_class = Plugin <|code_end|> ...
class DoesNotExist(Error):
Next line prediction: <|code_start|> def list_plugins(): return [ entry_point.name for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin") ] def load_plugin(name): for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin", name=name): plugin...
if issubclass(plugin, Plugin):
Given snippet: <|code_start|> def list_plugins(): return [ entry_point.name for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin") ] def load_plugin(name): for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin", name=name): plugin = entr...
raise InvalidPlugin("Plugin must inherit from `Plugin`.")
Here is a snippet: <|code_start|> def list_plugins(): return [ entry_point.name for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin") ] def load_plugin(name): for entry_point in pkg_resources.iter_entry_points(group="therapist.plugin", name=name): plugin = ...
raise PluginNotInstalled("Plugin `{}` has not been installed.".format(name))
Next line prediction: <|code_start|> def is_failure(self): return self.status == self.FAILURE @property def is_error(self): return self.status == self.ERROR @property def is_skip(self): return not (self.is_success or self.is_failure or self.is_error) @property def e...
class ResultCollection(Collection):
Predict the next line for this snippet: <|code_start|> def __init__(self, process, status=None): self._process = None self.process = process self.status = status self.output = None self.error = None self.start_time = time.time() self.end_time = self.start_time...
if not (isinstance(value, Process)):
Given the code snippet: <|code_start|> self._options[key.replace("-", "_")] = value[key] else: self.options = {value.replace("-", "_"): True} @property def flags(self): return self._flags @flags.setter def flags(self, value): if value is None: ...
class ShortcutCollection(Collection):
Here is a snippet: <|code_start|> @property def flags(self): return self._flags @flags.setter def flags(self, value): if value is None: self._flags = set() elif isinstance(value, set): self._flags = value elif isinstance(value, list): s...
class DoesNotExist(Error):
Based on the snippet: <|code_start|> class Runner(object): def __init__(self, cwd, files=None, **kwargs): # Options from kwargs: fix = kwargs.get("fix", False) # Git related options enable_git = kwargs.get("enable_git", False) include_unstaged = kwargs.get("include_unstage...
self.git = Git(repo_path=self.cwd) if enable_git else None
Given the code snippet: <|code_start|> class Runner(object): def __init__(self, cwd, files=None, **kwargs): # Options from kwargs: fix = kwargs.get("fix", False) # Git related options enable_git = kwargs.get("enable_git", False) include_unstaged = kwargs.get("include_unstage...
file_status = Status(line)
Predict the next line for this snippet: <|code_start|> # open the camera camera = self.get_camera() # clear latest image latest_image = None while True: # constantly get the image from the webcam success_flag, image=camera.read() # if success...
self.parent_conn, imgcap_conn = multiproc.Pipe()
Using the snippet: <|code_start|> class MPMenuCallTextDialog(object): '''used to create a value dialog callback''' def __init__(self, title='Enter Value', default=''): self.title = title self.default = default def call(self): '''show a value dialog''' try: dlg = ...
mp_util.child_close_fds()
Here is a snippet: <|code_start|> else: dlg = wx.FileDialog(None, self.title, '', "", self.wildcard, flagsMapped[0]|flagsMapped[1]) if dlg.ShowModal() != wx.ID_OK: return None return "\"" + dlg.GetPath() + "\"" class MPMenuCallTextDialog(object): '''used to create a v...
t = multiproc.Process(target=self.call)
Predict the next line for this snippet: <|code_start|> self.display_list.SetCellValue(row_changed, PE_VALUE, str(round(newval, 4))) elif event.Col == PE_VALUE: newval = float(self.display_list.GetCellValue(row_changed, PE_VALUE)) celleditor = self.display_list.GetCellEditor(ro...
child = multiproc.Process(target=mp_util.download_files, args=(files,))
Based on the snippet: <|code_start|> if (self.display_list.GetNumberRows() > 0): self.display_list.DeleteRows(0, self.display_list.GetNumberRows()) self.display_list.AppendRows(len(datalist)) row = 0 for paramname, paramvalue in sorted(datalist.items()): self.add_n...
self.display_list.SetCellEditor(row, PE_OPTION, cle.GridCheckListEditor(bits, PE_VALUE, pvalue))
Continue the code snippet: <|code_start|> if param in temp: temp[param] = value self.redraw_grid(temp) def ParamChanged(self, event): # wxGlade: ParamEditor.<event_handler> row_changed = event.GetRow() if event.Col == PE_OPTION: newval = float(self.di...
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
Continue the code snippet: <|code_start|> class ParamHelp: def __init__(self): self.xml_filepath = None self.vehicle_name = None self.last_pair = (None,None) self.last_htree = None def param_help_download(self): '''download XML files for parameters''' files = [] ...
path = mp_util.dot_mavproxy("%s.xml" % vehicle)
Given the code snippet: <|code_start|> class ParamHelp: def __init__(self): self.xml_filepath = None self.vehicle_name = None self.last_pair = (None,None) self.last_htree = None def param_help_download(self): '''download XML files for parameters''' files = [] ...
child = multiproc.Process(target=mp_util.download_files, args=(files,))
Continue the code snippet: <|code_start|> def __getitem__(self, a): return str(getattr(self, a)) class TileInfo: '''description of a tile''' def __init__(self, tile, zoom, service, offset=(0,0)): self.tile = tile (self.x, self.y) = tile self.zoom = zoom self.service...
lon = mp_util.wrap_180(x * 180.0)
Next line prediction: <|code_start|>def set_wx_window_layout(wx_window, layout): '''set a WinLayout for a wx window''' try: wx_window.SetSize(layout.size) wx_window.SetPosition(layout.pos) except Exception as ex: print(ex) def set_layout(wlayout, callback): '''set window layout'...
dirname = mp_util.dot_mavproxy()
Given snippet: <|code_start|> """ def __init__(self,resultsdir,**kwargs): self.resultsdir = resultsdir self.plotlist = {} #collections.OrderedDict self.error = {} self.name = self.resultsdir.split('/')[-2] # Check directory exists before instantiating object and check ...
raise NoResultsInDir
Predict the next line after this snippet: <|code_start|> This will instantiate a velocity field (see MDFields for details of the complex inheritance and containment), read and store the data from multiple files to construct a velocity profile, and finally will plot the x-compone...
raise OutsideRecRange
Predict the next line for this snippet: <|code_start|> os.chdir(self.savedPath ) class VmdReformat: def __init__(self, fdir, fname, scriptdir): self.fdir = fdir self.fname = fname self.scriptdir = scriptdir self.Reformatted = False headerfile = self.fdir + 'simulat...
raise ScriptMissing
Given snippet: <|code_start|> class channelflow_PostProc(PostProc): """ Post processing class for channelflow runs """ def __init__(self,resultsdir,**kwargs): self.resultsdir = resultsdir self.plotlist = {} # Check directory exists before instantiating object and check ...
raise NoResultsInDir
Next line prediction: <|code_start|> 'Density': LAMMPS_dField, 'Velocity': LAMMPS_vField, 'Momentum': LAMMPS_momField, 'Temperature': LAMMPS_TField, 'Pressure': LAMMPS_PressureField, 'Shear Stess...
raise NoResultsInDir
Predict the next line for this snippet: <|code_start|> class CFD_PostProc(PostProc): """ Post processing class for CFD runs """ def __init__(self,resultsdir,**kwargs): self.resultsdir = resultsdir self.plotlist = {} # Check directory exists before instantiating object an...
raise NoResultsInDir
Given the code snippet: <|code_start|> if ("controlDict" in files): controlDictfound = True with open(root+"/controlDict") as f: for line in f: try: if "writeControl" in line: ...
raise NoResultsInDir
Here is a snippet: <|code_start|> #First two records are positions in y and z rec_ = rec+3 # plot ! note the parent parameter x = []; y = []; z = [] for i in range(nz): if (i%2 == 0): d = -1 else: d = 1 x.append(r[rec_,::d,i]) y.append(r[0,::d,...
class MolAllPostProc(PostProc):
Next line prediction: <|code_start|>class MolAllPostProc(PostProc): def __init__(self, resultsdir, **kwargs): self.resultsdir = resultsdir self.plotlist = {} #collections.OrderedDict self.error = {} self.name = self.resultsdir.split('/')[-2] # Check directory exists before ...
raise NoResultsInDir
Given the code snippet: <|code_start|> self.error = {} self.name = self.resultsdir.split('/')[-2] # Check directory exists before instantiating object and check # which files associated with plots are in directory self.potentialfiles = ( "mslice", "mbins", "msnap","vslice", "vbi...
raise NoResultsInDir
Given the code snippet: <|code_start|> P1 = MD_hfVAField(self.resultsdir,fname='hfVA_c', **kwargs) self.plotlist.update({'hfVA_c':P1}) except DataNotAvailable: pass if (('hfVA' in self.fieldfiles1) or ('hfVA_k' in self.fieldfiles1 and ...
except DataMismatch:
Based on the snippet: <|code_start|> lines.append(' # OPTIONAL: add posts to your organizaion using this format,') lines.append(' # where label is a human-readable description of the post ' '(eg "Ward 8 councilmember")') lines.append(' # and role is the position type (eg...
class Command(BaseCommand):
Continue the code snippet: <|code_start|> lines.append('') with open(os.path.join(dirname, '__init__.py'), 'w') as of: of.write('\n'.join(lines)) # write scraper files for stype in scraper_types: lines = ['from pupa.scrape import Scraper'] lines.append('from pupa.scrape import {...
raise CommandError('Directory {} already exists'.format(repr(args.module)))
Predict the next line for this snippet: <|code_start|> "related_entities": { "items": { "properties": { "entity_type": { "type": "string", "minL...
"sources": sources,
Continue the code snippet: <|code_start|> "related_entities": { "items": { "properties": { "entity_type": { "type": "string", "minLength": 1, ...
"extras": extras,
Predict the next line after this snippet: <|code_start|>""" Schema for event objects. """ media_schema = { "items": { "properties": { "name": {"type": "string", "minLength": 1}, "type": {"type": "string", "minLength": 1}, <|code_end|> using the current file's imports: from .c...
"date": fuzzy_date_blank,
Predict the next line after this snippet: <|code_start|>""" media_schema = { "items": { "properties": { "name": {"type": "string", "minLength": 1}, "type": {"type": "string", "minLength": 1}, "date": fuzzy_date_blank, "offset": {"type": ["number", "null"]}, ...
'start_date': fuzzy_datetime,
Here is a snippet: <|code_start|> media_schema = { "items": { "properties": { "name": {"type": "string", "minLength": 1}, "type": {"type": "string", "minLength": 1}, "date": fuzzy_date_blank, "offset": {"type": ["number", "null"]}, "links": { ...
'end_date': fuzzy_datetime_blank,
Given the code snippet: <|code_start|> def create_jurisdiction(): Division.objects.create(id='ocd-division/country:us', name='USA') Jurisdiction.objects.create(id='jid', division_id='ocd-division/country:us') @pytest.mark.django_db def test_full_person(): <|code_end|> , generate the next line using the impor...
person = ScrapePerson('Tom Sawyer')
Here is a snippet: <|code_start|> @pytest.mark.django_db def test_resolve_json_id(): create_jurisdiction() o = Organization.objects.create(name='WWE', jurisdiction_id='jid') p = Person.objects.create(name='Dwayne Johnson', family_name='Johnson') p.other_names.create(name='Rock') p.memberships.create...
with pytest.raises(UnresolvedIdError):
Given snippet: <|code_start|> assert Person.objects.all().count() == 2 @pytest.mark.django_db def test_multiple_memberships(): create_jurisdiction() # there was a bug where two or more memberships to the same jurisdiction # would cause an ORM error, this test ensures that it is fixed p = Person.obj...
with pytest.raises(SameNameError):
Based on the snippet: <|code_start|> def create_jurisdiction(): Division.objects.create(id='ocd-division/country:us', name='USA') j = Jurisdiction.objects.create(id='jid', division_id='ocd-division/country:us') return j def create_other_jurisdiction(): Division.objects.create(id='ocd-division/country...
event = ScrapeEvent(
Given the following code snippet before the placeholder: <|code_start|> def create_data(): Division.objects.create(id='ocd-division/country:us', name='USA') j = Jurisdiction.objects.create(id='jid', division_id='ocd-division/country:us') org = Organization.objects.create(jurisdiction=j, name='House', class...
report = generate_session_report(session)
Based on the snippet: <|code_start|>class BaseImporter(object): """ BaseImporter Override: get_object(data) limit_spec(spec) [optional, required if pseudo_ids are used] prepare_for_db(data) [optional] postimport() [optional] """ ...
if settings.IMPORT_TRANSFORMERS.get(self._type):
Using the snippet: <|code_start|> return {self._type: record} def import_item(self, data): """ function used by import_data """ what = 'noop' # remove the JSON _id (may still be there if called directly) data.pop('_id', None) # add fields/etc. data = self.a...
raise DuplicateItemError(data, obj, related.get('sources', []))
Continue the code snippet: <|code_start|> identifier=identifier, jurisdiction_id=self.jurisdiction_id).id return self.session_cache[identifier] # no-ops to be overriden def prepare_for_db(self, data): return data def postimport(self): pass def resolve_json_id(se...
spec = get_pseudo_id(json_id)
Given the following code snippet before the placeholder: <|code_start|> yield json.load(f) return self.import_data(json_stream()) def _prepare_imports(self, dicts): """ filters the import stream to remove duplicates also serves as a good place to override if anything s...
'start': utcnow(),
Given the following code snippet before the placeholder: <|code_start|> raises: ValueError if id couldn't be resolved """ if not json_id: return None if json_id.startswith('~'): # keep caches of all the pseudo-ids to avoid doing 1000s of lookup...
raise UnresolvedIdError(errmsg)
Next line prediction: <|code_start|> pupa_id = data.pop('pupa_id', None) # pull related fields off related = {} for field in self.related_models: related[field] = data.pop(field) # obj existed, check if we need to do an update if obj: if obj.id in...
raise DataImportError('{} while importing {} as {}'.format(e, data,
Using the snippet: <|code_start|> if obj.id in self.json_to_db_id.values(): raise DuplicateItemError(data, obj, related.get('sources', [])) # check base object for changes for key, value in data.items(): if getattr(obj, key) != value and key not in obj....
Identifier.objects.get_or_create(identifier=pupa_id,
Based on the snippet: <|code_start|> schema = { "properties": { "label": {"type": "string"}, "role": {"type": "string"}, "person_id": {"type": ["string", "null"]}, "person_name": {"type": ["string"], "minLength": 1}, "organization_id": {"type": "string", "minLength": 1}, ...
"links": links,
Given the code snippet: <|code_start|> schema = { "properties": { "label": {"type": "string"}, "role": {"type": "string"}, "person_id": {"type": ["string", "null"]}, "person_name": {"type": ["string"], "minLength": 1}, "organization_id": {"type": "string", "minLength": 1}, ...
"contact_details": contact_details,
Given the code snippet: <|code_start|> schema = { "properties": { "label": {"type": "string"}, "role": {"type": "string"}, "person_id": {"type": ["string", "null"]}, "person_name": {"type": ["string"], "minLength": 1}, "organization_id": {"type": "string", "minLength": 1}, ...
"extras": extras,
Next line prediction: <|code_start|> schema = { "properties": { "label": {"type": "string"}, "role": {"type": "string"}, "person_id": {"type": ["string", "null"]}, "person_name": {"type": ["string"], "minLength": 1}, "organization_id": {"type": "string", "minLength": 1}, ...
"start_date": fuzzy_date_blank,
Predict the next line after this snippet: <|code_start|> def create_jurisdictions(): Division.objects.create(id='ocd-division/country:us', name='USA') Jurisdiction.objects.create(id='jid1', division_id='ocd-division/country:us') Jurisdiction.objects.create(id='jid2', division_id='ocd-division/country:us') ...
org = ScrapeOrganization('United Nations', classification='international')
Next line prediction: <|code_start|> @pytest.mark.django_db def test_deduplication_prevents_identical(): create_jurisdictions() org1 = ScrapeOrganization('United Nations', classification='international') org2 = ScrapeOrganization('United Nations', classification='international', ...
with pytest.raises(UnresolvedIdError):
Given the code snippet: <|code_start|> OrganizationImporter('jid1').import_data([od]) assert Organization.objects.all().count() == 1 @pytest.mark.django_db def test_deduplication_other_name_overlaps(): create_jurisdictions() create_org() org = ScrapeOrganization('The United Nations', classification...
with pytest.raises(SameOrgNameError):
Predict the next line after this snippet: <|code_start|> logger.error('exception "%s" prevented loading of %s module', e, mod) # process args args, other = parser.parse_known_args() # set log level from command line handler_level = getattr(logging, args.loglevel.upper(), 'INFO') setting...
except CommandError as e:
Continue the code snippet: <|code_start|> self.set_bill(bill, chamber=bill_chamber) if isinstance(bill, Bill) and not self.legislative_session: self.legislative_session = bill.legislative_session if not self.legislative_session: raise ScrapeValueError('must set legislati...
self.bill = _make_pseudo_id(**kwargs)
Using the snippet: <|code_start|> class VoteEvent(BaseModel, SourceMixin): _type = 'vote_event' _schema = schema def __init__(self, *, motion_text, start_date, classification, result, legislative_session=None, identifier='', bill=None, bill_chamber=None, bill_action=None,...
self.motion_classification = cleanup_list(classification, [])
Predict the next line after this snippet: <|code_start|> class VoteEvent(BaseModel, SourceMixin): _type = 'vote_event' _schema = schema def __init__(self, *, motion_text, start_date, classification, result, legislative_session=None, identifier='', bill=None, bill_chamber=...
self.organization = pseudo_organization(organization, chamber, 'legislature')
Given the following code snippet before the placeholder: <|code_start|> class VoteEvent(BaseModel, SourceMixin): _type = 'vote_event' _schema = schema def __init__(self, *, motion_text, start_date, classification, result, legislative_session=None, identifier='', bill=None...
raise ScrapeValueError('must set legislative_session or bill')