Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Given the following code snippet before the placeholder: <|code_start|> class WireguardPeers(OpenWrtConverter): netjson_key = 'wireguard_peers' intermediate_key = 'network' <|code_end|> , predict the next line using imports from the current file: from ..schema import schema from .base import OpenWrtConverter ...
_schema = schema['properties']['wireguard_peers']['items']
Given snippet: <|code_start|> class TestDefault(unittest.TestCase, _TabsMixin): maxDiff = None def test_render_default(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from openwisp_utils.tests import capture_stdout from netjsonconfig import OpenWrt...
o = OpenWrt(
Given snippet: <|code_start|> 'contents': tar.extractfile(member).read().decode(), } ) return self.parse_text(text) def _get_vpns(self, text): results = re.split(vpn_pattern, text) vpns = [] for result in results: result = r...
return sorted_dict(config)
Given snippet: <|code_start|> vpn_pattern = re.compile('^# openvpn config:\s', flags=re.MULTILINE) config_pattern = re.compile('^([^\s]*) ?(.*)$') config_suffix = '.conf' <|code_end|> , continue by predicting the next line. Consider current file imports: import re import tarfile from ...utils import sorted_dict fro...
class OpenVpnParser(BaseParser):
Continue the code snippet: <|code_start|> }, }, {"$ref": "#/definitions/tunnel"}, {"$ref": "#/definitions/server"}, ], }, }, "properties": { "openvpn": { "type": "array", "title": "OpenVPN", ...
schema['properties']['files'] = default_schema['properties']['files']
Given the code snippet: <|code_start|> class TestDialup(unittest.TestCase, _TabsMixin): maxDiff = None _dialup_interface_netjson = { "interfaces": [ { "mtu": 1448, "network": "xdsl", "type": "dialup", "name": "dsl0", ...
result = OpenWrt(self._dialup_interface_netjson).render()
Using the snippet: <|code_start|> class TestBackend(unittest.TestCase): """ tests for OpenVpn backend """ maxDiff = None def test_server_mode(self): <|code_end|> , determine the next line of code. You have imports: import copy import tarfile import unittest from netjsonconfig import OpenVpn fro...
c = OpenVpn(
Continue the code snippet: <|code_start|> class TestWireguard(unittest.TestCase, _TabsMixin): maxDiff = None def test_render_wireguard_interface(self): <|code_end|> . Use current file imports: import unittest from netjsonconfig import OpenWrt from netjsonconfig.utils import _TabsMixin and context (classes,...
o = OpenWrt(
Next line prediction: <|code_start|> class TestParser(unittest.TestCase): maxDiff = None def test_parse_text(self): native = """# openvpn config: bridged ca ca.pem cert cert.pem dev tap0 dev-type tap dh dh.pem key key.pem mode server proto udp server-bridge 10.8.0.4 255.255.255.0 10.8.0.128 10.8.0.2...
o = OpenVpn(native=native)
Given snippet: <|code_start|> class Ntp(OpenWrtConverter): netjson_key = 'ntp' intermediate_key = 'system' _uci_types = ['timeserver'] <|code_end|> , continue by predicting the next line. Consider current file imports: from ..schema import schema from .base import OpenWrtConverter and context: # Path: n...
_schema = schema['properties']['ntp']
Given the following code snippet before the placeholder: <|code_start|> client[key] = server[key] files = cls._auto_client_files( client, ca_path, ca_contents, cert_path, cert_contents, key_path, key_contents, ...
files.append(dict(path=ca_path, contents=ca_contents, mode=X509_FILE_MODE))
Here is a snippet: <|code_start|> class OpenVpn(BaseVpnBackend): """ OpenVPN 2.x Configuration Backend """ schema = schema converters = [converters.OpenVpn] <|code_end|> . Write the next line using the current file imports: from ...schema import X509_FILE_MODE from ..base.backend import BaseVpnBa...
parser = OpenVpnParser
Continue the code snippet: <|code_start|> class OpenVpn(BaseVpnBackend): """ OpenVPN 2.x Configuration Backend """ schema = schema converters = [converters.OpenVpn] parser = OpenVpnParser renderer = OpenVpnRenderer list_identifiers = ['name'] # BaseVpnBackend attributes vpn_pat...
config_suffix = config_suffix
Given the code snippet: <|code_start|> class OpenVpn(BaseVpnBackend): """ OpenVPN 2.x Configuration Backend """ schema = schema converters = [converters.OpenVpn] parser = OpenVpnParser renderer = OpenVpnRenderer list_identifiers = ['name'] # BaseVpnBackend attributes <|code_end|> ,...
vpn_pattern = vpn_pattern
Predict the next line for this snippet: <|code_start|> class OpenVpn(BaseVpnBackend): """ OpenVPN 2.x Configuration Backend """ schema = schema converters = [converters.OpenVpn] parser = OpenVpnParser <|code_end|> with the help of current file imports: from ...schema import X509_FILE_MODE fr...
renderer = OpenVpnRenderer
Based on the snippet: <|code_start|> if not isinstance(templates, list): raise TypeError('templates argument must be an instance of list') # merge templates with main configuration result = {} config_list = templates + [config] for merging in config_list: r...
mode = f.get('mode', DEFAULT_FILE_MODE)
Here is a snippet: <|code_start|> if not isinstance(config, dict): raise TypeError( 'config block must be an instance of dict or a valid NetJSON string' ) return config def _merge_config(self, config, templates): """ Merges config with template...
return evaluate_vars(config, context)
Given the following code snippet before the placeholder: <|code_start|> ) def _load(self, config): """ Loads config from string or dict """ if isinstance(config, str): try: config = json.loads(config) except ValueError: ...
result = merge_config(result, self._load(merging), self.list_identifiers)
Predict the next line for this snippet: <|code_start|> "mac": "82:29:23:7d:c2:14", "mtu": 1500, "txqueuelen": 0, "autostart": True, "bridge_members": ["wlan0", "vpn.40"], "addresses": [ { "address": "fe80::8029:23...
o = OpenWrt(netjson_example)
Based on the snippet: <|code_start|> counter = 0 for result in results: result = result.strip() if not result: continue counter += 1 lines = result.split('\n') parts = lines[0].split() config_type = self._strip_quotes...
blocks.append(sorted_dict(block))
Here is a snippet: <|code_start|> packages_pattern = re.compile('^package\s', flags=re.MULTILINE) block_pattern = re.compile('^config\s', flags=re.MULTILINE) config_pattern = re.compile('^(option|list)\s*([^\s]*)\s*(.*)') config_path = 'etc/config/' <|code_end|> . Write the next line using the current file imports: ...
class OpenWrtParser(BaseParser):
Predict the next line after this snippet: <|code_start|> self.assertEqual(result, {"list": ["element1", "element2"]}) def test_merge_originals_unchanged(self): template = {"str": "original", "dict": {"a": "a"}, "list": ["element1"]} config = {"str": "changed", "dict": {"b": "b"}, "list": ["e...
self.assertEqual(evaluate_vars('{{ tz }}', {'tz': 'UTC'}), 'UTC')
Predict the next line after this snippet: <|code_start|> self.assertEqual(output, 'contentAcontentBcontent') def test_evaluate_vars_immersed(self): output = evaluate_vars('content{{a}}content', {'a': 'A'}) self.assertEqual(output, 'contentAcontent') def test_evaluate_vars_one_char(self)...
self.assertEqual('test', get_copy({}, key='hello', default='test'))
Given the code snippet: <|code_start|> class TestUtils(unittest.TestCase): """ tests for netjsonconfig.utils """ def test_merge_config(self): template = {"a": "a", "c": "template"} config = {"b": "b", "c": "config"} <|code_end|> , generate the next line using the imports in this file:...
result = merge_config(template, config)
Given snippet: <|code_start|> """ see https://github.com/openwisp/netjsonconfig/issues/55 """ output = evaluate_vars('{{ a }}\n{{ b }}\n', {'a': 'a', 'b': 'b'}) self.assertEqual(output, 'a\nb\n') def test_evaluate_vars_multiple_space(self): output = evaluate_vars('{{ ...
result = merge_list(template, config, ['name'])
Using the snippet: <|code_start|> class Rules(OpenWrtConverter): netjson_key = 'ip_rules' intermediate_key = 'network' _uci_types = ['rule', 'rule6'] <|code_end|> , determine the next line of code. You have imports: from ipaddress import ip_network from ..schema import schema from .base import OpenWrtCon...
_schema = schema['properties']['ip_rules']['items']
Predict the next line after this snippet: <|code_start|>""" OpenWisp specific JSON-Schema definition (extends OpenWrt JSON-Schema) """ schema = merge_config( <|code_end|> using the current file's imports: from ...utils import merge_config from ..openwrt.schema import schema as openwrt_schema and any relevant contex...
openwrt_schema,
Given snippet: <|code_start|> result.setdefault('network', []) result['network'].append(route) return result def __intermediate_route(self, route, index): network = ip_interface(route.pop('destination')) target = network.ip if network.version == 4 else network.network ...
_schema = schema['properties']['routes']['items']
Using the snippet: <|code_start|> # determine extra packages used extra_packages = OrderedDict() for key, value in self.netjson.items(): # skip blocks present in ignore_list # or blocks not represented by lists if key in ignore_list or not isinstance(value, lis...
block_list.append(sorted_dict(block))
Given the code snippet: <|code_start|> def test_eggs_object(self): test_i = {'test_object': {'eggs': True}} validate(test_i, schema) def test_burrito_object(self): test_i = {'test_object': {'burrito': 'yes'}} self.assertRaises(ValidationError, validate, test_i, schema) def ...
o = OpenWrt({'interfaces': [{'wrong': True}]})
Continue the code snippet: <|code_start|> class TestSystem(unittest.TestCase, _TabsMixin): maxDiff = None _system_netjson = { "general": {"hostname": "test-system", "timezone": "Europe/Rome"} } _system_uci = """package system config system 'system' option hostname 'test-system' option...
o = OpenWrt(self._system_netjson)
Using the snippet: <|code_start|> _system_id_uci = """package system config system 'arbitrary' option hostname 'test-system' option timezone 'UTC' option zonename 'UTC' """ def test_parse_system_custom_id(self): o = OpenWrt(native=self._system_id_uci) self.assertDictEqual(o.config, ...
"timezone": timezones_reversed["CET-1CEST,M3.5.0,M10.5.0/3"],
Given the following code snippet before the placeholder: <|code_start|> during the backward conversion process (native to NetJSON) """ return cls.intermediate_key in intermediate_data def type_cast(self, item, schema=None): """ Loops over item and performs type casting ...
def get_copy(self, dict_, key, default=None):
Given the following code snippet before the placeholder: <|code_start|> def type_cast(self, item, schema=None): """ Loops over item and performs type casting according to supplied schema fragment """ if schema is None: schema = self._schema properties = sc...
def sorted_dict(self, dict_):
Predict the next line after this snippet: <|code_start|> class Radios(OpenWrtConverter): netjson_key = 'radios' intermediate_key = 'wireless' _uci_types = ['wifi-device'] def to_intermediate_loop(self, block, result, index=None): radio = self.__intermediate_radio(block) result.setdefau...
radio['type'] = radio.pop('driver', default_radio_driver)
Next line prediction: <|code_start|> else: varargs.append(arg) return func(self, *chain(args[:nposargs], varargs), **kwargs) method.__name__ = func.__name__ return method @staticmethod def option_keys_from_vars(func): def method(self, *arg...
return func(self, *args, **normdictdata(kwargs))
Using the snippet: <|code_start|> def create_dictionary(*args, **items): iargs = iter(args) return dict(zip(iargs, iargs), **items) class KeywordDecoratorType(object): """The base class for a Test Library's `keyword` decorator. - Stores the Keyword method function in the Test Library's `keywor...
self.keyword_name = name and KeywordName(name, convert=False)
Given snippet: <|code_start|> def create_dictionary(*args, **items): iargs = iter(args) return dict(zip(iargs, iargs), **items) class KeywordDecoratorType(object): """The base class for a Test Library's `keyword` decorator. - Stores the Keyword method function in the Test Library's `keywor...
raise InvalidKeywordOption(optionname)
Based on the snippet: <|code_start|> decorator = getattr(type(self), 'option_' + optionname) func = decorator(func) try: # does returned function still have argspec attribute? # (unchanged function or option has assigned new argspec) argspec = func.args...
raise KeywordNotDefined(name)
Predict the next line for this snippet: <|code_start|> that catches the exception that caused a Keyword FAIL for debugging. """ # Robot 2.8 def _report_failure(self, context): debug_fail(context) # Robot >= 2.9 def __enter__(self): if NormalRunner: # Robot ...
class Keyword(KeywordInspector):
Using the snippet: <|code_start|> # Robot 2.8 def _report_failure(self, context): debug_fail(context) # Robot >= 2.9 def __enter__(self): if NormalRunner: # Robot 2.9 # HACK: monkey-patch robot.running's NormalRunner # to catch the Keyword exception ...
if not isinstance(handler, Handler):
Predict the next line after this snippet: <|code_start|># the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # robotframework-tools is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY...
return KeywordArgumentsInspector(self._handler.arguments)
Using the snippet: <|code_start|> LOGGER.unregister_logger(self) # unset internal streams self._out = self._err = None _re_log_level = re.compile('|'.join(r % '|'.join(LOG_LEVELS) for r in [r'^\[ ?(%s) ?\] *', r'^\* ?(%s) ?\* *'])) def message(self, message): msg = message...
with Highlighter(color, stream) as hl:
Using the snippet: <|code_start|> #HACK: Registers output to LOGGER self.output.__enter__() return self def __exit__(self, *exc): #HACK: Unregisters output from LOGGER self.output.__exit__(*exc) #HACK: EXECUTION_CONTEXTS._contexts = [] robot.running.na...
if type(keyword) is not Keyword:
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python """ Generate a sitemap.xml file for dc metro metrics and a json file with an array of urls. The json file is used with grunt in order to crawl dcmetrometrics.com and regenerate the static version of the site. """ ####################### # Se...
units = models_eles.Unit.objects
Based on the snippet: <|code_start|> Save the KeyStatuses doc and return it. If the key statuses have already been computed, use the KeyStatuses.update method to simply update the existing KeyStatuses record with the latest escalator status. """ statuses = self.get_statuses() ...
for day in gen_days(start_day, last_day):
Predict the next line after this snippet: <|code_start|> Add a unit to the database if it does not already exist. If the unit is being added for the first time, create an initial operational UnitStatus entry. If the unit already exists and a status already exists, do nothing. """ unit_id = k...
G = dbGlobals.G()
Here is a snippet: <|code_start|>Define the HotCarApp as a restartingGreenlet. This app will use the Twitter API to search for tweets about #wmata #hotcar's. These tweets and the hotcar data are stored in a database. Tweet acknowledgements are posted to the @MetroHotCars twitter account. """ # TEST CODE if __name__ ...
class HotCarApp(RestartingGreenlet):
Next line prediction: <|code_start|>Tweet acknowledgements are posted to the @MetroHotCars twitter account. """ # TEST CODE if __name__ == "__main__": OUTPUT_DIR = DATA_DIR ############################################################### # Log the HotCarApp App to a file. LOG_FILE_NAME = os.path.join(DATA_DIR, 'Ho...
dbGlobals.connect()
Using the snippet: <|code_start|>LOG_FILE_NAME = os.path.join(DATA_DIR, 'HotCarApp.log') fh = logging.FileHandler(LOG_FILE_NAME) sh = logging.StreamHandler(sys.stderr) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) sh.setFormatter(formatter) logger = l...
hotCars.tick(tweetLive = self.LIVE)
Based on the snippet: <|code_start|> Create a cumulative histogram for each label in a probabilistic atlas Parameters ---------- p: numpy array keys nrows ncols fontsize img_fname Returns ------- """ fig, axs = plt.subplots(nrows, ncols, figsize=(12,9)) axs = n...
key = do_strip_prefix(keys[aa])
Predict the next line for this snippet: <|code_start|>#!/usr/bin/env python """ This example shows how to use the FedEx Service Validation, Availability and Commitment Service. The variables populated below represents common values. You will need to fill out the required values or risk seeing a SchemaValidationError ex...
avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ, customer_transaction_id=customer_transaction_id)
Based on the snippet: <|code_start|>""" Test module for the Fedex TrackService WSDL. """ sys.path.insert(0, '..') # Common global config object for testing. CONFIG_OBJ = get_fedex_config() logging.getLogger('suds').setLevel(logging.ERROR) logging.getLogger('fedex').setLevel(logging.INFO) @unittest.skipIf(not CON...
track = FedexTrackRequest(CONFIG_OBJ)
Predict the next line after this snippet: <|code_start|> i = i - 1 p1 = h.find('"', p) p2 = h.find('"', p1+1) self.parms[key] = h[p1+1:p2] p = self.header.find('=', p+1) #print(self.parms) def rootNode(self): if self.parent is None: ...
rotateParms = map(float, extractParms(self.header, 0, 'rotate(', ', ', ')'))
Predict the next line after this snippet: <|code_start|>if __name__ == '__main__': print('''run tests via FreeCAD_drawing_dimensioning$ python2 test''') exit() def xml_prettify( xml_str ): xml = minidom.parseString( xml_str ) S = xml.toprettyxml(indent=' ') return '\n'.join( s for s in S.split(...
svg_string = linearDimensionSVG_points( x1 = 0, y1 = 10 , x2 = 30, y2= 25, x3 = 40, y3= 20, x4 = 50, y4 = 30 )
Continue the code snippet: <|code_start|> return _centerLinesSVG( center, topLeft, bottomRight, viewScale, centerLine_len_dot, centerLine_len_dash, centerLine_len_gap, centerLine_width, centerLine_color, v, not v ) d.registerPreference( 'centerLine_len_dot', 3 , label='dot length', increment=0.5) d.registerPrefere...
linearDimension_parallels_hide_non_parallel( elementParms, elementViewObject)
Given the code snippet: <|code_start|> if instruction == None: pass elif instruction.startswith('createDimension:'): viewName = instruction.split(':')[1] FreeCAD.ActiveDocument.openTransaction(viewName) XML = ...
if isinstance(XML, unicode_type):
Given snippet: <|code_start|> pass elif instruction.startswith('createDimension:'): viewName = instruction.split(':')[1] FreeCAD.ActiveDocument.openTransaction(viewName) XML = self.dimensionSvgFun( x, y ) ...
XML = encode_if_py2(XML)
Next line prediction: <|code_start|> if radialLine_x != None and radialLine_y != None: XML_body.append( svgLine(radialLine_x, radialLine_y, start_x, start_y, lineColor, strokeWidth) ) if tail_x != None and tail_y != None: XML_body.append( svgLine(radialLine_x, radialLine_y, tail_x, radial...
obj.noteText = encode_if_py2(d.noteCircleText)
Predict the next line after this snippet: <|code_start|> self.label_3 = QtGui.QLabel(Dialog) self.label_3.setObjectName("label_3") self.horizontalLayout_4.addWidget(self.label_3) spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.h...
Dialog.setWindowTitle(translate("Dialog", "Add Text", None))
Predict the next line for this snippet: <|code_start|> return self.dd_parms.GetFloat( self.name, self.defaultValue ) def updateDefault(self): self.dd_parms.SetFloat( self.name, self.dimensioningProcess.dimensionConstructorKWs[ self.name ] ) def revertToDefault( self ): self.spinbox.setV...
return unicode( encoded_value, 'utf8' )
Using the snippet: <|code_start|>if sys.version_info.major < 3: DimensioningPreferenceClasses["<type 'float'>"] = DimensioningPreference_float DimensioningPreferenceClasses["<type 'int'>"] = DimensioningPreference_float else: DimensioningPreferenceClasses["<class 'float'>"] = DimensioningPreference_float ...
if not type(KWs[self.name]) == unicode_type:
Next line prediction: <|code_start|> def FreeCAD_parm_to_val( self, FreeCAD_parm ): return [ unicode( line, 'utf8' ) for line in FreeCAD_parm.split('\n') ] def getDefaultValue(self): return self.FreeCAD_parm_to_val( self.dd_parms.GetString( self.name, self.val_to_FreeCAD_parm( self.defaultValue )...
return '\n'.join(map(str, val))
Here is a snippet: <|code_start|> def getDefaultValue(self): return self.dd_parms.GetFloat( self.name, self.defaultValue ) def updateDefault(self): self.dd_parms.SetFloat( self.name, self.dimensioningProcess.dimensionConstructorKWs[ self.name ] ) def revertToDefault( self ): self.sp...
encoded_value = self.dd_parms.GetString( self.name, encode_if_py2(self.defaultValue) )
Predict the next line after this snippet: <|code_start|> return DimensioningTaskDialog_generate_row_hbox( self.label, colorBox ) def add_properties_to_dimension_object( self, obj ): obj.addProperty("App::PropertyString", self.name, self.category) KWs = self.dimensioningProcess.dimensionConst...
return SvgTextRenderer(family, size, color)
Given the following code snippet before the placeholder: <|code_start|>BD 0 5E 232 189 0 94 BD 7E 9D 233 189 126 157 81 0 40 234 129 0 64 81 56 6B 235 129 86 107 68 0 34 236 104 0 52 68 45 56 237 104 69 86 4F 0 27 238 79 0 39 4F 35 42 239 79 53 66 FF 0 3F 240 255 0 63 FF AA BF 241 255 170 191 BD 0 2E 242 189 0 46 BD 7E...
r,g,b = map(int, parts[4:])
Here is a snippet: <|code_start|>sys.path.append('/usr/lib/freecad/lib/') #path to FreeCAD library on Linux try: except ImportError as msg: print('Import error, is this testing script being run from Python2?') raise ImportError(msg) assert not hasattr(FreeCADGui, 'addCommand') def addCommand_check( name, comma...
start_dir = os.path.join( __dir__ , 'test' ),
Continue the code snippet: <|code_start|>sys.path.append('/usr/lib/freecad/lib/') #path to FreeCAD library on Linux try: except ImportError as msg: print('Import error, is this testing script being run from Python2?') raise ImportError(msg) assert not hasattr(FreeCADGui, 'addCommand') def addCommand_check( nam...
debugPrint.level = 0
Predict the next line for this snippet: <|code_start|> sizePolicy.setHeightForWidth(self.label_2.sizePolicy().hasHeightForWidth()) self.label_2.setSizePolicy(sizePolicy) self.label_2.setMinimumSize(QtCore.QSize(61, 0)) self.label_2.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|Q...
Dialog.setWindowTitle(translate("Dialog", "Add tolerance", None))
Predict the next line for this snippet: <|code_start|> return '<g> %s </g>' % textRenderer_addText(x,y,text,rotation=rotation) d.registerPreference( 'textRenderer_addText', ['inherit','5', 0], 'text properties (AddText)', kind='font' ) class text_widget: def valueChanged( self, arg1): d.text = arg1 ...
self.spinbox.setSuffix(unicode('°','utf8'))
Using the snippet: <|code_start|># This Python file uses the following encoding: utf-8 d = DimensioningCommand() def textSVG( x, y, text='text', rotation=0.0, textRenderer_addText= defaultTextRenderer): return '<g> %s </g>' % textRenderer_addText(x,y,text,rotation=rotation) d.registerPreference( 'textRenderer_ad...
obj.text = encode_if_py2(d.text)
Based on the snippet: <|code_start|> class Dimensioning_Selection_prototype: 'these selection classes are for purposes of recording a drawing view selection for later updates' def __init__( self, svg_KWs, svg_element, viewInfo, **extraKWs ): self.init_for_svg_KWs( svg_KWs, svg_element, **extraKWs ) ...
debugPrint(3,'PointSelection: drawing %s has changed, updating values' % self.viewInfo.name )
Given the code snippet: <|code_start|> def svg_fun_args( self, args ): if self.output_mode == 'xyr': args.extend( [self.x, self.y, self.r] ) elif self.output_mode == 'xy': args.append( [self.x, self.y] ) else: raise(NotImplementedError, "output_mode %s not ...
self.svgText = SvgTextParser( svg_element.XML[svg_element.pStart:svg_element.pEnd])
Here is a snippet: <|code_start|> class PhotoRequestFilter(django_filters.FilterSet): class Meta: model = models.PhotoRequest fields = {'story': ['exact'], 'assignees': ['exact'], 'time': ['exact', 'lt', 'gt'] } <|code_end|> . Write the next l...
class PhotoRequestViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
Given the code snippet: <|code_start|> router = routers.DefaultRouter() # get the view for auto-generated API docs from Swagger docs_view = get_swagger_view(title='docs') # access router.register(r'users', access_views.UserViewSet) router.register(r'groups', access_views.GroupViewSet) router.register(r'permissions'...
router.register(r'images', attachments_views.ImageViewSet)
Predict the next line after this snippet: <|code_start|> router = routers.DefaultRouter() # get the view for auto-generated API docs from Swagger docs_view = get_swagger_view(title='docs') # access router.register(r'users', access_views.UserViewSet) router.register(r'groups', access_views.GroupViewSet) router.regis...
router.register(r'authors', authors_views.AuthorViewSet)
Continue the code snippet: <|code_start|> router = routers.DefaultRouter() # get the view for auto-generated API docs from Swagger docs_view = get_swagger_view(title='docs') # access router.register(r'users', access_views.UserViewSet) router.register(r'groups', access_views.GroupViewSet) router.register(r'permissio...
router.register(r'internal_comments', comments_views.InternalCommentViewSet)
Based on the snippet: <|code_start|> router = routers.DefaultRouter() # get the view for auto-generated API docs from Swagger docs_view = get_swagger_view(title='docs') # access router.register(r'users', access_views.UserViewSet) router.register(r'groups', access_views.GroupViewSet) router.register(r'permissions', ...
router.register(r'schema', core_views.SchemaViewSet, base_name='schema')
Next line prediction: <|code_start|>docs_view = get_swagger_view(title='docs') # access router.register(r'users', access_views.UserViewSet) router.register(r'groups', access_views.GroupViewSet) router.register(r'permissions', access_views.PermissionViewSet) # attachments router.register(r'images', attachments_views.I...
router.register(r'card_sizes', display_views.CardSizeViewSet)
Based on the snippet: <|code_start|> # attachments router.register(r'images', attachments_views.ImageViewSet) router.register(r'videos', attachments_views.VideoViewSet) router.register(r'audio', attachments_views.AudioViewSet) router.register(r'reviews', attachments_views.ReviewViewSet) router.register(r'polls', attach...
router.register(r'sections', organization_views.SectionViewSet)
Predict the next line after this snippet: <|code_start|>router.register(r'reviews', attachments_views.ReviewViewSet) router.register(r'polls', attachments_views.PollViewSet) router.register(r'poll_choices', attachments_views.PollChoiceViewSet) # authors router.register(r'authors', authors_views.AuthorViewSet) router.r...
router.register(r'photo_requests', requests_views.PhotoRequestViewSet)
Given snippet: <|code_start|>router.register(r'organizations', authors_views.OrganizationViewSet) router.register(r'positions', authors_views.PositionViewSet) # comments router.register(r'internal_comments', comments_views.InternalCommentViewSet) # core router.register(r'schema', core_views.SchemaViewSet, base_name='...
router.register(r'sports', sports_views.SportViewSet)
Predict the next line for this snippet: <|code_start|> """ permission_classes = (permissions.IsAuthenticated,) @method_decorator(cache_page(60*60)) # cache view for one hour def list(self, request): return Response(serializers.schema_serializer(request)) class StatusViewSet(viewsets.ModelView...
class StoryViewSet(VersionableModelViewSetMixin, viewsets.ModelViewSet):
Given the code snippet: <|code_start|>class PositionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Position fields = "__all__" class JobSerializer(serializers.HyperlinkedModelSerializer): position = PositionSerializer() is_current = serializers.SerializerMet...
self.fields['user'] = access_serializers.UserSerializer()
Predict the next line after this snippet: <|code_start|> class Media(models.Model): """A piece of content which has a main component and may have associated Authors and a caption.""" caption = models.TextField(blank=True) @property def credit(self): """Forces child classes to define a "c...
this_organization = Organization.objects.get(pk=1)
Predict the next line after this snippet: <|code_start|> class InternalCommentFilter(django_filters.FilterSet): class Meta: model = models.InternalComment fields = {'user': ['exact'], 'time_posted': ['exact', 'lt', 'gt'], 'content_type': ['exact'], ...
class InternalCommentViewSet(VersionableModelViewSetMixin,
Given snippet: <|code_start|> class BodyTextSerializer(serializers.HyperlinkedModelSerializer): """Abstract base class which strips internal comments from an object's 'body' field and adds a 'body_unsanitized' field for authenticated users. """ body = serializers.SerializerMethodField() def __ini...
card = attachments_serializers.ImageSerializer()
Based on the snippet: <|code_start|>class StatusSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Status fields = "__all__" class BodyTextSerializer(serializers.HyperlinkedModelSerializer): """Abstract base class which strips internal comments from an object's ...
authors = authors_serializers.AuthorSerializer(many=True)
Given the following code snippet before the placeholder: <|code_start|> class Meta: model = models.Status fields = "__all__" class BodyTextSerializer(serializers.HyperlinkedModelSerializer): """Abstract base class which strips internal comments from an object's 'body' field and adds a 'body...
alternate_template = display_serializers.TemplateSerializer()
Using the snippet: <|code_start|> model = models.Status fields = "__all__" class BodyTextSerializer(serializers.HyperlinkedModelSerializer): """Abstract base class which strips internal comments from an object's 'body' field and adds a 'body_unsanitized' field for authenticated users. """ ...
sections = organization_serializers.SectionSerializer(many=True)
Using the snippet: <|code_start|> body = serializers.SerializerMethodField() def __init__(self, *args, **kwargs): super(BodyTextSerializer, self).__init__(*args, **kwargs) request = self.context.get('request') if request and request.user.is_authenticated(): # sometimes a seri...
game = sports_serializers.GameSerializer()
Predict the next line for this snippet: <|code_start|> class ArtRequest(models.Model): """A request for a piece of art to accompany a Story.""" story = models.ForeignKey('core.Story') assignees = models.ManyToManyField('authors.Author', blank=True) instructions = models.TextField(blank=True) <|code_e...
images = GenericRelation(attachments_models.Image)
Using the snippet: <|code_start|> if f not in article["nlp"]: task.log(logging.WARNING, f"Cannot find field {f} in the document {article['_id']}") continue if "tokens" not in article["nlp"][f]: task.log( ...
sent_postags.append(COMPRESS_UPOS_MAPPING[w.upostag])
Predict the next line for this snippet: <|code_start|> ) continue for s in article["nlp"][f]["tokens"].split("\n"): # ignoring default model tokenizer in order to use whitespace tokenizer tok_sent = Sent...
sent_features.append(compress_features(w.feats))
Given the code snippet: <|code_start|> count_by_pos = defaultdict(Counter) document_frequency = defaultdict(Counter) for i, (corpus, article) in enumerate(BuildFreqVocabJob.get_iter(db, job, task)): if BuildFreqVocabJob.apply_filter(job, task, article): processed_art...
decompressed_result = decompress(
Based on the snippet: <|code_start|> class BaseCorpusTask(Job): @staticmethod def get_total_count(db, job, task) -> int: total = 0 for corpus in task.corpora: total += db[corpus].count() return total @staticmethod def get_iter(db, job, task): for corpus in ...
if len(_CORPORA_CHOICES) == len(corpora):
Here is a snippet: <|code_start|> if isinstance(res, list): value = [self.base_field.to_python(val) for val in res] return value def validate(self, value, model_instance): if not self.editable: # Skip validation for non-editable fields. return if ...
for source in db.corpus__sources.find():
Next line prediction: <|code_start|> class CorpusHomeView(TemplateView): template_name = "corpus/corpus_home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) <|code_end|> . Use current file imports: (from django.utils.translation import gettext as _ from djang...
context["corpus_sources"] = Corpus.get_sources()
Using the snippet: <|code_start|> @admin.register(ExportCorpusTask) class ExportCorpusTask(TaskAdmin): pass <|code_end|> , determine the next line of code. You have imports: from django.contrib import admin from django_task.admin import TaskAdmin from .models import ExportCorpusTask, TagWithUDPipeTask, BuildFr...
@admin.register(TagWithUDPipeTask)
Predict the next line for this snippet: <|code_start|> @admin.register(ExportCorpusTask) class ExportCorpusTask(TaskAdmin): pass @admin.register(TagWithUDPipeTask) class TagWithUDPipeTask(TaskAdmin): pass <|code_end|> with the help of current file imports: from django.contrib import admin from django_ta...
@admin.register(BuildFreqVocabTask)