_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q3400
Artifact.fetch
train
def fetch(self): """ Method for getting artifact's content. Could only be applicable for file type. :return: content of the artifact. """ if self.data.type == self._manager.FOLDER_TYPE: raise YagocdException("Can't fetch folder <{}>, only file!".format(self._path)) response = self._session.get(self.data.url) return response.content
python
{ "resource": "" }
q3401
LTILaunchValidator.validate_launch_request
train
def validate_launch_request( self, launch_url, headers, args ): """ Validate a given launch request launch_url: Full URL that the launch request was POSTed to headers: k/v pair of HTTP headers coming in with the POST args: dictionary of body arguments passed to the launch_url Must have the following keys to be valid: oauth_consumer_key, oauth_timestamp, oauth_nonce, oauth_signature """ # Validate args! if 'oauth_consumer_key' not in args: raise web.HTTPError(401, "oauth_consumer_key missing") if args['oauth_consumer_key'] not in self.consumers: raise web.HTTPError(401, "oauth_consumer_key not known") if 'oauth_signature' not in args: raise web.HTTPError(401, "oauth_signature missing") if 'oauth_timestamp' not in args: raise web.HTTPError(401, 'oauth_timestamp missing') # Allow 30s clock skew between LTI Consumer and Provider # Also don't accept timestamps from before our process started, since that could be # a replay attack - we won't have nonce lists from back then. This would allow users # who can control / know when our process restarts to trivially do replay attacks. oauth_timestamp = int(float(args['oauth_timestamp'])) if ( int(time.time()) - oauth_timestamp > 30 or oauth_timestamp < LTILaunchValidator.PROCESS_START_TIME ): raise web.HTTPError(401, "oauth_timestamp too old") if 'oauth_nonce' not in args: raise web.HTTPError(401, 'oauth_nonce missing') if ( oauth_timestamp in LTILaunchValidator.nonces and args['oauth_nonce'] in LTILaunchValidator.nonces[oauth_timestamp] ): raise web.HTTPError(401, "oauth_nonce + oauth_timestamp already used") LTILaunchValidator.nonces.setdefault(oauth_timestamp, set()).add(args['oauth_nonce']) args_list = [] for key, values in args.items(): if type(values) is list: args_list += [(key, value) for value in values] else: args_list.append((key, values)) base_string = signature.construct_base_string( 'POST', signature.normalize_base_string_uri(launch_url), signature.normalize_parameters( signature.collect_parameters(body=args_list, headers=headers) ) ) consumer_secret = self.consumers[args['oauth_consumer_key']] sign = signature.sign_hmac_sha1(base_string, consumer_secret, None) is_valid = signature.safe_string_equals(sign, args['oauth_signature']) if not is_valid: raise web.HTTPError(401, "Invalid oauth_signature") return True
python
{ "resource": "" }
q3402
Lightning.enable_ipython
train
def enable_ipython(self, **kwargs): """ Enable plotting in the iPython notebook. Once enabled, all lightning plots will be automatically produced within the iPython notebook. They will also be available on your lightning server within the current session. """ # inspired by code powering similar functionality in mpld3 # https://github.com/jakevdp/mpld3/blob/master/mpld3/_display.py#L357 from IPython.core.getipython import get_ipython from IPython.display import display, Javascript, HTML self.ipython_enabled = True self.set_size('medium') ip = get_ipython() formatter = ip.display_formatter.formatters['text/html'] if self.local_enabled: from lightning.visualization import VisualizationLocal js = VisualizationLocal.load_embed() display(HTML("<script>" + js + "</script>")) if not self.quiet: print('Running local mode, some functionality limited.\n') formatter.for_type(VisualizationLocal, lambda viz, kwds=kwargs: viz.get_html()) else: formatter.for_type(Visualization, lambda viz, kwds=kwargs: viz.get_html()) r = requests.get(self.get_ipython_markup_link(), auth=self.auth) display(Javascript(r.text))
python
{ "resource": "" }
q3403
Lightning.disable_ipython
train
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = False ip = get_ipython() formatter = ip.display_formatter.formatters['text/html'] formatter.type_printers.pop(Visualization, None) formatter.type_printers.pop(VisualizationLocal, None)
python
{ "resource": "" }
q3404
Lightning.create_session
train
def create_session(self, name=None): """ Create a lightning session. Can create a session with the provided name, otherwise session name will be "Session No." with the number automatically generated. """ self.session = Session.create(self, name=name) return self.session
python
{ "resource": "" }
q3405
Lightning.use_session
train
def use_session(self, session_id): """ Use the specified lightning session. Specify a lightning session by id number. Check the number of an existing session in the attribute lightning.session.id. """ self.session = Session(lgn=self, id=session_id) return self.session
python
{ "resource": "" }
q3406
Lightning.set_basic_auth
train
def set_basic_auth(self, username, password): """ Set authenatication. """ from requests.auth import HTTPBasicAuth self.auth = HTTPBasicAuth(username, password) return self
python
{ "resource": "" }
q3407
Lightning.set_host
train
def set_host(self, host): """ Set the host for a lightning server. Host can be local (e.g. http://localhost:3000), a heroku instance (e.g. http://lightning-test.herokuapp.com), or a independently hosted lightning server. """ if host[-1] == '/': host = host[:-1] self.host = host return self
python
{ "resource": "" }
q3408
Lightning.check_status
train
def check_status(self): """ Check the server for status """ try: r = requests.get(self.host + '/status', auth=self.auth, timeout=(10.0, 10.0)) if not r.status_code == requests.codes.ok: print("Problem connecting to server at %s" % self.host) print("status code: %s" % r.status_code) return False else: print("Connected to server at %s" % self.host) return True except (requests.exceptions.ConnectionError, requests.exceptions.MissingSchema, requests.exceptions.InvalidSchema) as e: print("Problem connecting to server at %s" % self.host) print("error: %s" % e) return False
python
{ "resource": "" }
q3409
Base._clean_data
train
def _clean_data(cls, *args, **kwargs): """ Convert raw data into a dictionary with plot-type specific methods. The result of the cleaning operation should be a dictionary. If the dictionary contains a 'data' field it will be passed directly (ensuring appropriate formatting). Otherwise, it should be a dictionary of data-type specific array data (e.g. 'points', 'timeseries'), which will be labeled appropriately (see _check_unkeyed_arrays). """ datadict = cls.clean(*args, **kwargs) if 'data' in datadict: data = datadict['data'] data = cls._ensure_dict_or_list(data) else: data = {} for key in datadict: if key == 'images': data[key] = datadict[key] else: d = cls._ensure_dict_or_list(datadict[key]) data[key] = cls._check_unkeyed_arrays(key, d) return data
python
{ "resource": "" }
q3410
Base._baseplot
train
def _baseplot(cls, session, type, *args, **kwargs): """ Base method for plotting data and images. Applies a plot-type specific cleaning operation to generate a dictionary with the data, then creates a visualization with the data. Expects a session and a type, followed by all plot-type specific positional and keyword arguments, which will be handled by the clean method of the given plot type. If the dictionary contains only images, or only non-image data, they will be passed on their own. If the dictionary contains both images and non-image data, the images will be appended to the visualization. """ if not type: raise Exception("Must provide a plot type") options, description = cls._clean_options(**kwargs) data = cls._clean_data(*args) if 'images' in data and len(data) > 1: images = data['images'] del data['images'] viz = cls._create(session, data=data, type=type, options=options, description=description) first_image, remaining_images = images[0], images[1:] viz._append_image(first_image) for image in remaining_images: viz._append_image(image) elif 'images' in data: images = data['images'] viz = cls._create(session, images=images, type=type, options=options, description=description) else: viz = cls._create(session, data=data, type=type, options=options, description=description) return viz
python
{ "resource": "" }
q3411
Base.update
train
def update(self, *args, **kwargs): """ Base method for updating data. Applies a plot-type specific cleaning operation, then updates the data in the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] for img in images: self._update_image(img) else: self._update_data(data=data)
python
{ "resource": "" }
q3412
Base.append
train
def append(self, *args, **kwargs): """ Base method for appending data. Applies a plot-type specific cleaning operation, then appends data to the visualization. """ data = self._clean_data(*args, **kwargs) if 'images' in data: images = data['images'] for img in images: self._append_image(img) else: self._append_data(data=data)
python
{ "resource": "" }
q3413
Base._get_user_data
train
def _get_user_data(self): """ Base method for retrieving user data from a viz. """ url = self.session.host + '/sessions/' + str(self.session.id) + '/visualizations/' + str(self.id) + '/settings/' r = requests.get(url) if r.status_code == 200: content = r.json() else: raise Exception('Error retrieving user data from server') return content
python
{ "resource": "" }
q3414
check_property
train
def check_property(prop, name, **kwargs): """ Check and parse a property with either a specific checking function or a generic parser """ checkers = { 'color': check_color, 'alpha': check_alpha, 'size': check_size, 'thickness': check_thickness, 'index': check_index, 'coordinates': check_coordinates, 'colormap': check_colormap, 'bins': check_bins, 'spec': check_spec } if name in checkers: return checkers[name](prop, **kwargs) elif isinstance(prop, list) or isinstance(prop, ndarray) or isscalar(prop): return check_1d(prop, name) else: return prop
python
{ "resource": "" }
q3415
check_colormap
train
def check_colormap(cmap): """ Check if cmap is one of the colorbrewer maps """ names = set(['BrBG', 'PiYG', 'PRGn', 'PuOr', 'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral', 'Blues', 'BuGn', 'BuPu', 'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu', 'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'Lightning']) if cmap not in names: raise Exception("Invalid cmap '%s', must be one of %s" % (cmap, names)) else: return cmap
python
{ "resource": "" }
q3416
polygon_to_mask
train
def polygon_to_mask(coords, dims, z=None): """ Given a list of pairs of points which define a polygon, return a binary mask covering the interior of the polygon with dimensions dim """ bounds = array(coords).astype('int') path = Path(bounds) grid = meshgrid(range(dims[1]), range(dims[0])) grid_flat = zip(grid[0].ravel(), grid[1].ravel()) mask = path.contains_points(grid_flat).reshape(dims[0:2]).astype('int') if z is not None: if len(dims) < 3: raise Exception('Dims must have three-dimensions for embedding z-index') if z >= dims[2]: raise Exception('Z-index %g exceeds third dimension %g' % (z, dims[2])) tmp = zeros(dims) tmp[:, :, z] = mask mask = tmp return mask
python
{ "resource": "" }
q3417
polygon_to_points
train
def polygon_to_points(coords, z=None): """ Given a list of pairs of points which define a polygon, return a list of points interior to the polygon """ bounds = array(coords).astype('int') bmax = bounds.max(0) bmin = bounds.min(0) path = Path(bounds) grid = meshgrid(range(bmin[0], bmax[0]+1), range(bmin[1], bmax[1]+1)) grid_flat = zip(grid[0].ravel(), grid[1].ravel()) points = path.contains_points(grid_flat).reshape(grid[0].shape).astype('int') points = where(points) points = (vstack([points[0], points[1]]).T + bmin[-1::-1]).tolist() if z is not None: points = map(lambda p: [p[0], p[1], z], points) return points
python
{ "resource": "" }
q3418
VisualizationLocal.save_html
train
def save_html(self, filename=None, overwrite=False): """ Save self-contained html to a file. Parameters ---------- filename : str The filename to save to """ if filename is None: raise ValueError('Please provide a filename, e.g. viz.save_html(filename="viz.html").') import os base = self._html js = self.load_embed() if os.path.exists(filename): if overwrite is False: raise ValueError("File '%s' exists. To ovewrite call save_html with overwrite=True." % os.path.abspath(filename)) else: os.remove(filename) with open(filename, "wb") as f: f.write(base.encode('utf-8')) f.write('<script>' + js.encode('utf-8') + '</script>')
python
{ "resource": "" }
q3419
temporary_unavailable
train
def temporary_unavailable(request, template_name='503.html'): """ Default 503 handler, which looks for the requested URL in the redirects table, redirects if found, and displays 404 page if not redirected. Templates: ``503.html`` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') """ context = { 'request_path': request.path, } return http.HttpResponseTemporaryUnavailable( render_to_string(template_name, context))
python
{ "resource": "" }
q3420
simplify_specifiers
train
def simplify_specifiers(spec): """Try to simplify a SpecifierSet by combining redundant specifiers.""" def key(s): return (s.version, 1 if s.operator in ['>=', '<'] else 2) def in_bounds(v, lo, hi): if lo and v not in lo: return False if hi and v not in hi: return False return True def err(reason='inconsistent'): return ValueError('{} specifier set {}'.format(reason, spec)) gt = None lt = None eq = None ne = [] for i in spec: if i.operator == '==': if eq is None: eq = i elif eq != i: # pragma: no branch raise err() elif i.operator == '!=': ne.append(i) elif i.operator in ['>', '>=']: gt = i if gt is None else max(gt, i, key=key) elif i.operator in ['<', '<=']: lt = i if lt is None else min(lt, i, key=key) else: raise err('invalid') ne = [i for i in ne if in_bounds(i.version, gt, lt)] if eq: if ( any(i.version in eq for i in ne) or not in_bounds(eq.version, gt, lt)): raise err() return SpecifierSet(str(eq)) if lt and gt: if lt.version not in gt or gt.version not in lt: raise err() if ( gt.version == lt.version and gt.operator == '>=' and lt.operator == '<='): return SpecifierSet('=={}'.format(gt.version)) return SpecifierSet( ','.join(str(i) for i in chain(iterate(gt), iterate(lt), ne)) )
python
{ "resource": "" }
q3421
SymbolFUNCTION.reset
train
def reset(self, lineno=None, offset=None, type_=None): """ This is called when we need to reinitialize the instance state """ self.lineno = self.lineno if lineno is None else lineno self.type_ = self.type_ if type_ is None else type_ self.offset = self.offset if offset is None else offset self.callable = True self.params = SymbolPARAMLIST() self.body = SymbolBLOCK() self.__kind = KIND.unknown self.local_symbol_table = None
python
{ "resource": "" }
q3422
check_type
train
def check_type(*args, **kwargs): ''' Checks the function types ''' args = tuple(x if isinstance(x, collections.Iterable) else (x,) for x in args) kwargs = {x: kwargs[x] if isinstance(kwargs[x], collections.Iterable) else (kwargs[x],) for x in kwargs} def decorate(func): types = args kwtypes = kwargs gi = "Got <{}> instead" errmsg1 = "to be of type <{}>. " + gi errmsg2 = "to be one of type ({}). " + gi errar = "{}:{} expected '{}' " errkw = "{}:{} expected {} " def check(*ar, **kw): line = inspect.getouterframes(inspect.currentframe())[1][2] fname = os.path.basename(inspect.getouterframes(inspect.currentframe())[1][1]) for arg, type_ in zip(ar, types): if type(arg) not in type_: if len(type_) == 1: raise TypeError((errar + errmsg1).format(fname, line, arg, type_[0].__name__, type(arg).__name__)) else: raise TypeError((errar + errmsg2).format(fname, line, arg, ', '.join('<%s>' % x.__name__ for x in type_), type(arg).__name__)) for kwarg in kw: if kwtypes.get(kwarg, None) is None: continue if type(kw[kwarg]) not in kwtypes[kwarg]: if len(kwtypes[kwarg]) == 1: raise TypeError((errkw + errmsg1).format(fname, line, kwarg, kwtypes[kwarg][0].__name__, type(kw[kwarg]).__name__)) else: raise TypeError((errkw + errmsg2).format( fname, line, kwarg, ', '.join('<%s>' % x.__name__ for x in kwtypes[kwarg]), type(kw[kwarg]).__name__) ) return func(*ar, **kw) return check return decorate
python
{ "resource": "" }
q3423
TranslatorVisitor.norm_attr
train
def norm_attr(self): """ Normalize attr state """ if not self.HAS_ATTR: return self.HAS_ATTR = False self.emit('call', 'COPY_ATTR', 0) backend.REQUIRES.add('copy_attr.asm')
python
{ "resource": "" }
q3424
TranslatorVisitor.traverse_const
train
def traverse_const(node): """ Traverses a constant and returns an string with the arithmetic expression """ if node.token == 'NUMBER': return node.t if node.token == 'UNARY': mid = node.operator if mid == 'MINUS': result = ' -' + Translator.traverse_const(node.operand) elif mid == 'ADDRESS': if node.operand.scope == SCOPE.global_ or node.operand.token in ('LABEL', 'FUNCTION'): result = Translator.traverse_const(node.operand) else: syntax_error_not_constant(node.operand.lineno) return else: raise InvalidOperatorError(mid) return result if node.token == 'BINARY': mid = node.operator if mid == 'PLUS': mid = '+' elif mid == 'MINUS': mid = '-' elif mid == 'MUL': mid = '*' elif mid == 'DIV': mid = '/' elif mid == 'MOD': mid = '%' elif mid == 'POW': mid = '^' elif mid == 'SHL': mid = '>>' elif mid == 'SHR': mid = '<<' else: raise InvalidOperatorError(mid) return '(%s) %s (%s)' % (Translator.traverse_const(node.left), mid, Translator.traverse_const(node.right)) if node.token == 'TYPECAST': if node.type_ in (Type.byte_, Type.ubyte): return '(' + Translator.traverse_const(node.operand) + ') & 0xFF' if node.type_ in (Type.integer, Type.uinteger): return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFF' if node.type_ in (Type.long_, Type.ulong): return '(' + Translator.traverse_const(node.operand) + ') & 0xFFFFFFFF' if node.type_ == Type.fixed: return '((' + Translator.traverse_const(node.operand) + ') & 0xFFFF) << 16' syntax_error_cant_convert_to_type(node.lineno, str(node.operand), node.type_) return if node.token in ('VAR', 'VARARRAY', 'LABEL', 'FUNCTION'): # TODO: Check what happens with local vars and params return node.t if node.token == 'CONST': return Translator.traverse_const(node.expr) if node.token == 'ARRAYACCESS': return '({} + {})'.format(node.entry.mangled, node.offset) raise InvalidCONSTexpr(node)
python
{ "resource": "" }
q3425
TranslatorVisitor.check_attr
train
def check_attr(node, n): """ Check if ATTR has to be normalized after this instruction has been translated to intermediate code. """ if len(node.children) > n: return node.children[n]
python
{ "resource": "" }
q3426
Translator.loop_exit_label
train
def loop_exit_label(self, loop_type): """ Returns the label for the given loop type which exits the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][1] raise InvalidLoopError(loop_type)
python
{ "resource": "" }
q3427
Translator.loop_cont_label
train
def loop_cont_label(self, loop_type): """ Returns the label for the given loop type which continues the loop. loop_type must be one of 'FOR', 'WHILE', 'DO' """ for i in range(len(self.LOOPS) - 1, -1, -1): if loop_type == self.LOOPS[i][0]: return self.LOOPS[i][2] raise InvalidLoopError(loop_type)
python
{ "resource": "" }
q3428
Translator.has_control_chars
train
def has_control_chars(i): """ Returns true if the passed token is an unknown string or a constant string having control chars (inverse, etc """ if not hasattr(i, 'type_'): return False if i.type_ != Type.string: return False if i.token in ('VAR', 'PARAMDECL'): return True # We don't know what an alphanumeric variable will hold if i.token == 'STRING': for c in i.value: if 15 < ord(c) < 22: # is it an attr char? return True return False for j in i.children: if Translator.has_control_chars(j): return True return False
python
{ "resource": "" }
q3429
BuiltinTranslator.visit_USR
train
def visit_USR(self, node): """ Machine code call from basic """ self.emit('fparam' + self.TSUFFIX(gl.PTR_TYPE), node.children[0].t) self.emit('call', 'USR', node.type_.size) backend.REQUIRES.add('usr.asm')
python
{ "resource": "" }
q3430
DefinesTable.define
train
def define(self, id_, lineno, value='', fname=None, args=None): """ Defines the value of a macro. Issues a warning if the macro is already defined. """ if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: # If no files opened yet, use owns program fname fname = sys.argv[0] if self.defined(id_): i = self.table[id_] warning(lineno, '"%s" redefined (previous definition at %s:%i)' % (i.name, i.fname, i.lineno)) self.set(id_, lineno, value, fname, args)
python
{ "resource": "" }
q3431
DefinesTable.set
train
def set(self, id_, lineno, value='', fname=None, args=None): """ Like the above, but issues no warning on duplicate macro definitions. """ if fname is None: if CURRENT_FILE: fname = CURRENT_FILE[-1] else: # If no files opened yet, use owns program fname fname = sys.argv[0] self.table[id_] = ID(id_, args, value, lineno, fname)
python
{ "resource": "" }
q3432
SymbolPARAMLIST.appendChild
train
def appendChild(self, param): ''' Overrides base class. ''' Symbol.appendChild(self, param) if param.offset is None: param.offset = self.size self.size += param.size
python
{ "resource": "" }
q3433
SymbolTable.get_entry
train
def get_entry(self, id_, scope=None): """ Returns the ID entry stored in self.table, starting by the first one. Returns None if not found. If scope is not None, only the given scope is searched. """ if id_[-1] in DEPRECATED_SUFFIXES: id_ = id_[:-1] # Remove it if scope is not None: assert len(self.table) > scope return self[scope][id_] for sc in self: if sc[id_] is not None: return sc[id_] return None
python
{ "resource": "" }
q3434
SymbolTable.check_is_declared
train
def check_is_declared(self, id_, lineno, classname='identifier', scope=None, show_error=True): """ Checks if the given id is already defined in any scope or raises a Syntax Error. Note: classname is not the class attribute, but the name of the class as it would appear on compiler messages. """ result = self.get_entry(id_, scope) if isinstance(result, symbols.TYPE): return True if result is None or not result.declared: if show_error: syntax_error(lineno, 'Undeclared %s "%s"' % (classname, id_)) return False return True
python
{ "resource": "" }
q3435
SymbolTable.check_is_undeclared
train
def check_is_undeclared(self, id_, lineno, classname='identifier', scope=None, show_error=False): """ The reverse of the above. Check the given identifier is not already declared. Returns True if OK, False otherwise. """ result = self.get_entry(id_, scope) if result is None or not result.declared: return True if scope is None: scope = self.current_scope if show_error: syntax_error(lineno, 'Duplicated %s "%s" (previous one at %s:%i)' % (classname, id_, self.table[scope][id_].filename, self.table[scope][id_].lineno)) return False
python
{ "resource": "" }
q3436
SymbolTable.check_class
train
def check_class(self, id_, class_, lineno, scope=None, show_error=True): """ Check the id is either undefined or defined with the given class. - If the identifier (e.g. variable) does not exists means it's undeclared, and returns True (OK). - If the identifier exists, but its class_ attribute is unknown yet (None), returns also True. This means the identifier has been referenced in advanced and it's undeclared. Otherwise fails returning False. """ assert CLASS.is_valid(class_) entry = self.get_entry(id_, scope) if entry is None or entry.class_ == CLASS.unknown: # Undeclared yet return True if entry.class_ != class_: if show_error: if entry.class_ == CLASS.array: a1 = 'n' else: a1 = '' if class_ == CLASS.array: a2 = 'n' else: a2 = '' syntax_error(lineno, "identifier '%s' is a%s %s, not a%s %s" % (id_, a1, entry.class_, a2, class_)) return False return True
python
{ "resource": "" }
q3437
SymbolTable.enter_scope
train
def enter_scope(self, funcname): """ Starts a new variable scope. Notice the *IMPORTANT* marked lines. This is how a new scope is added, by pushing a new dict at the end (and popped out later). """ old_mangle = self.mangle self.mangle = '%s%s%s' % (self.mangle, global_.MANGLE_CHR, funcname) self.table.append(SymbolTable.Scope(self.mangle, parent_mangle=old_mangle)) global_.META_LOOPS.append(global_.LOOPS) # saves current LOOPS state global_.LOOPS = []
python
{ "resource": "" }
q3438
SymbolTable.leave_scope
train
def leave_scope(self): """ Ends a function body and pops current scope out of the symbol table. """ def entry_size(entry): """ For local variables and params, returns the real variable or local array size in bytes """ if entry.scope == SCOPE.global_ or \ entry.is_aliased: # aliases or global variables = 0 return 0 if entry.class_ != CLASS.array: return entry.size return entry.memsize for v in self.table[self.current_scope].values(filter_by_opt=False): if not v.accessed: if v.scope == SCOPE.parameter: kind = 'Parameter' v.accessed = True # HINT: Parameters must always be present even if not used! warning_not_used(v.lineno, v.name, kind=kind) entries = sorted(self.table[self.current_scope].values(filter_by_opt=True), key=entry_size) offset = 0 for entry in entries: # Symbols of the current level if entry.class_ is CLASS.unknown: self.move_to_global_scope(entry.name) if entry.class_ in (CLASS.function, CLASS.label, CLASS.type_): continue # Local variables offset if entry.class_ == CLASS.var and entry.scope == SCOPE.local: if entry.alias is not None: # alias of another variable? if entry.offset is None: entry.offset = entry.alias.offset else: entry.offset = entry.alias.offset - entry.offset else: offset += entry_size(entry) entry.offset = offset if entry.class_ == CLASS.array and entry.scope == SCOPE.local: entry.offset = entry_size(entry) + offset offset = entry.offset self.mangle = self[self.current_scope].parent_mangle self.table.pop() global_.LOOPS = global_.META_LOOPS.pop() return offset
python
{ "resource": "" }
q3439
SymbolTable.move_to_global_scope
train
def move_to_global_scope(self, id_): """ If the given id is in the current scope, and there is more than 1 scope, move the current id to the global scope and make it global. Labels need this. """ # In the current scope and more than 1 scope? if id_ in self.table[self.current_scope].keys(filter_by_opt=False) and len(self.table) > 1: symbol = self.table[self.current_scope][id_] symbol.offset = None symbol.scope = SCOPE.global_ if symbol.class_ != CLASS.label: symbol.mangled = "%s%s%s" % (self.table[self.global_scope].mangle, global_.MANGLE_CHR, id_) self.table[self.global_scope][id_] = symbol del self.table[self.current_scope][id_] # Removes it from the current scope __DEBUG__("'{}' entry moved to global scope".format(id_))
python
{ "resource": "" }
q3440
SymbolTable.access_id
train
def access_id(self, id_, lineno, scope=None, default_type=None, default_class=CLASS.unknown): """ Access a symbol by its identifier and checks if it exists. If not, it's supposed to be an implicit declared variable. default_class is the class to use in case of an undeclared-implicit-accessed id """ if isinstance(default_type, symbols.BASICTYPE): default_type = symbols.TYPEREF(default_type, lineno, implicit=False) assert default_type is None or isinstance(default_type, symbols.TYPEREF) if not check_is_declared_explicit(lineno, id_): return None result = self.get_entry(id_, scope) if result is None: if default_type is None: default_type = symbols.TYPEREF(self.basic_types[global_.DEFAULT_IMPLICIT_TYPE], lineno, implicit=True) result = self.declare_variable(id_, lineno, default_type) result.declared = False # It was implicitly declared result.class_ = default_class return result # The entry was already declared. If it's type is auto and the default type is not None, # update its type. if default_type is not None and result.type_ == self.basic_types[TYPE.auto]: result.type_ = default_type warning_implicit_type(lineno, id_, default_type) return result
python
{ "resource": "" }
q3441
SymbolTable.access_array
train
def access_array(self, id_, lineno, scope=None, default_type=None): """ Called whenever an accessed variable is expected to be an array. ZX BASIC requires arrays to be declared before usage, so they're checked. Also checks for class array. """ if not self.check_is_declared(id_, lineno, 'array', scope): return None if not self.check_class(id_, CLASS.array, lineno, scope): return None return self.access_id(id_, lineno, scope=scope, default_type=default_type)
python
{ "resource": "" }
q3442
SymbolTable.declare_variable
train
def declare_variable(self, id_, lineno, type_, default_value=None): """ Like the above, but checks that entry.declared is False. Otherwise raises an error. Parameter default_value specifies an initialized variable, if set. """ assert isinstance(type_, symbols.TYPEREF) if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False): entry = self.get_entry(id_) if entry.scope == SCOPE.parameter: syntax_error(lineno, "Variable '%s' already declared as a parameter " "at %s:%i" % (id_, entry.filename, entry.lineno)) else: syntax_error(lineno, "Variable '%s' already declared at " "%s:%i" % (id_, entry.filename, entry.lineno)) return None if not self.check_class(id_, CLASS.var, lineno, scope=self.current_scope): return None entry = (self.get_entry(id_, scope=self.current_scope) or self.declare(id_, lineno, symbols.VAR(id_, lineno, class_=CLASS.var))) __DEBUG__("Entry %s declared with class %s at scope %i" % (entry.name, CLASS.to_string(entry.class_), self.current_scope)) if entry.type_ is None or entry.type_ == self.basic_types[TYPE.unknown]: entry.type_ = type_ if entry.type_ != type_: if not type_.implicit and entry.type_ is not None: syntax_error(lineno, "'%s' suffix is for type '%s' but it was " "declared as '%s'" % (id_, entry.type_, type_)) return None # type_ = entry.type_ # TODO: Unused?? entry.scope = SCOPE.global_ if self.current_scope == self.global_scope else SCOPE.local entry.callable = False entry.class_ = CLASS.var # HINT: class_ attribute could be erased if access_id was used. entry.declared = True # marks it as declared if entry.type_.implicit and entry.type_ != self.basic_types[TYPE.unknown]: warning_implicit_type(lineno, id_, entry.type_.name) if default_value is not None and entry.type_ != default_value.type_: if is_number(default_value): default_value = symbols.TYPECAST.make_node(entry.type_, default_value, lineno) if default_value is None: return None else: syntax_error(lineno, "Variable '%s' declared as '%s' but initialized " "with a '%s' value" % (id_, entry.type_, default_value.type_)) return None entry.default_value = default_value return entry
python
{ "resource": "" }
q3443
SymbolTable.declare_type
train
def declare_type(self, type_): """ Declares a type. Checks its name is not already used in the current scope, and that it's not a basic type. Returns the given type_ Symbol, or None on error. """ assert isinstance(type_, symbols.TYPE) # Checks it's not a basic type if not type_.is_basic and type_.name.lower() in TYPE.TYPE_NAMES.values(): syntax_error(type_.lineno, "'%s' is a basic type and cannot be redefined" % type_.name) return None if not self.check_is_undeclared(type_.name, type_.lineno, scope=self.current_scope, show_error=True): return None entry = self.declare(type_.name, type_.lineno, type_) return entry
python
{ "resource": "" }
q3444
SymbolTable.declare_const
train
def declare_const(self, id_, lineno, type_, default_value): """ Similar to the above. But declares a Constant. """ if not self.check_is_undeclared(id_, lineno, scope=self.current_scope, show_error=False): entry = self.get_entry(id_) if entry.scope == SCOPE.parameter: syntax_error(lineno, "Constant '%s' already declared as a parameter " "at %s:%i" % (id_, entry.filename, entry.lineno)) else: syntax_error(lineno, "Constant '%s' already declared at " "%s:%i" % (id_, entry.filename, entry.lineno)) return None entry = self.declare_variable(id_, lineno, type_, default_value) if entry is None: return None entry.class_ = CLASS.const return entry
python
{ "resource": "" }
q3445
SymbolTable.declare_param
train
def declare_param(self, id_, lineno, type_=None): """ Declares a parameter Check if entry.declared is False. Otherwise raises an error. """ if not self.check_is_undeclared(id_, lineno, classname='parameter', scope=self.current_scope, show_error=True): return None entry = self.declare(id_, lineno, symbols.PARAMDECL(id_, lineno, type_)) if entry is None: return entry.declared = True if entry.type_.implicit: warning_implicit_type(lineno, id_, type_) return entry
python
{ "resource": "" }
q3446
SymbolTable.check_labels
train
def check_labels(self): """ Checks if all the labels has been declared """ for entry in self.labels: self.check_is_declared(entry.name, entry.lineno, CLASS.label)
python
{ "resource": "" }
q3447
SymbolTable.check_classes
train
def check_classes(self, scope=-1): """ Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked. """ for entry in self[scope].values(): if entry.class_ is None: syntax_error(entry.lineno, "Unknown identifier '%s'" % entry.name)
python
{ "resource": "" }
q3448
SymbolTable.vars_
train
def vars_(self): """ Returns symbol instances corresponding to variables of the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.var]
python
{ "resource": "" }
q3449
SymbolTable.labels
train
def labels(self): """ Returns symbol instances corresponding to labels in the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.label]
python
{ "resource": "" }
q3450
SymbolTable.types
train
def types(self): """ Returns symbol instances corresponding to type declarations within the current scope. """ return [x for x in self[self.current_scope].values() if isinstance(x, symbols.TYPE)]
python
{ "resource": "" }
q3451
SymbolTable.arrays
train
def arrays(self): """ Returns symbol instances corresponding to arrays of the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ == CLASS.array]
python
{ "resource": "" }
q3452
SymbolTable.functions
train
def functions(self): """ Returns symbol instances corresponding to functions of the current scope. """ return [x for x in self[self.current_scope].values() if x.class_ in (CLASS.function, CLASS.sub)]
python
{ "resource": "" }
q3453
SymbolTable.aliases
train
def aliases(self): """ Returns symbol instances corresponding to aliased vars. """ return [x for x in self[self.current_scope].values() if x.is_aliased]
python
{ "resource": "" }
q3454
check_type
train
def check_type(lineno, type_list, arg): """ Check arg's type is one in type_list, otherwise, raises an error. """ if not isinstance(type_list, list): type_list = [type_list] if arg.type_ in type_list: return True if len(type_list) == 1: syntax_error(lineno, "Wrong expression type '%s'. Expected '%s'" % (arg.type_, type_list[0])) else: syntax_error(lineno, "Wrong expression type '%s'. Expected one of '%s'" % (arg.type_, tuple(type_list))) return False
python
{ "resource": "" }
q3455
check_call_arguments
train
def check_call_arguments(lineno, id_, args): """ Check arguments against function signature. Checks every argument in a function call against a function. Returns True on success. """ if not global_.SYMBOL_TABLE.check_is_declared(id_, lineno, 'function'): return False if not global_.SYMBOL_TABLE.check_class(id_, CLASS.function, lineno): return False entry = global_.SYMBOL_TABLE.get_entry(id_) if len(args) != len(entry.params): c = 's' if len(entry.params) != 1 else '' syntax_error(lineno, "Function '%s' takes %i parameter%s, not %i" % (id_, len(entry.params), c, len(args))) return False for arg, param in zip(args, entry.params): if not arg.typecast(param.type_): return False if param.byref: from symbols.var import SymbolVAR if not isinstance(arg.value, SymbolVAR): syntax_error(lineno, "Expected a variable name, not an " "expression (parameter By Reference)") return False if arg.class_ not in (CLASS.var, CLASS.array): syntax_error(lineno, "Expected a variable or array name " "(parameter By Reference)") return False arg.byref = True if entry.forwarded: # The function / sub was DECLARED but not implemented syntax_error(lineno, "%s '%s' declared but not implemented" % (CLASS.to_string(entry.class_), entry.name)) return False return True
python
{ "resource": "" }
q3456
check_pending_calls
train
def check_pending_calls(): """ Calls the above function for each pending call of the current scope level """ result = True # Check for functions defined after calls (parametres, etc) for id_, params, lineno in global_.FUNCTION_CALLS: result = result and check_call_arguments(lineno, id_, params) return result
python
{ "resource": "" }
q3457
check_pending_labels
train
def check_pending_labels(ast): """ Iteratively traverses the node looking for ID with no class set, marks them as labels, and check they've been declared. This way we avoid stack overflow for high line-numbered listings. """ result = True visited = set() pending = [ast] while pending: node = pending.pop() if node is None or node in visited: # Avoid recursive infinite-loop continue visited.add(node) for x in node.children: pending.append(x) if node.token != 'VAR' or (node.token == 'VAR' and node.class_ is not CLASS.unknown): continue tmp = global_.SYMBOL_TABLE.get_entry(node.name) if tmp is None or tmp.class_ is CLASS.unknown: syntax_error(node.lineno, 'Undeclared identifier "%s"' % node.name) else: assert tmp.class_ == CLASS.label node.to_label(node) result = result and tmp is not None return result
python
{ "resource": "" }
q3458
is_null
train
def is_null(*symbols): """ True if no nodes or all the given nodes are either None, NOP or empty blocks. For blocks this applies recursively """ from symbols.symbol_ import Symbol for sym in symbols: if sym is None: continue if not isinstance(sym, Symbol): return False if sym.token == 'NOP': continue if sym.token == 'BLOCK': if not is_null(*sym.children): return False continue return False return True
python
{ "resource": "" }
q3459
is_const
train
def is_const(*p): """ A constant in the program, like CONST a = 5 """ return is_SYMBOL('VAR', *p) and all(x.class_ == CLASS.const for x in p)
python
{ "resource": "" }
q3460
is_number
train
def is_number(*p): """ Returns True if ALL of the arguments are AST nodes containing NUMBER or numeric CONSTANTS """ try: for i in p: if i.token != 'NUMBER' and (i.token != 'ID' or i.class_ != CLASS.const): return False return True except: pass return False
python
{ "resource": "" }
q3461
is_unsigned
train
def is_unsigned(*p): """ Returns false unless all types in p are unsigned """ from symbols.type_ import Type try: for i in p: if not i.type_.is_basic or not Type.is_unsigned(i.type_): return False return True except: pass return False
python
{ "resource": "" }
q3462
is_type
train
def is_type(type_, *p): """ True if all args have the same type """ try: for i in p: if i.type_ != type_: return False return True except: pass return False
python
{ "resource": "" }
q3463
is_block_accessed
train
def is_block_accessed(block): """ Returns True if a block is "accessed". A block of code is accessed if it has a LABEL and it is used in a GOTO, GO SUB or @address access :param block: A block of code (AST node) :return: True / False depending if it has labels accessed or not """ if is_LABEL(block) and block.accessed: return True for child in block.children: if not is_callable(child) and is_block_accessed(child): return True return False
python
{ "resource": "" }
q3464
common_type
train
def common_type(a, b): """ Returns a type which is common for both a and b types. Returns None if no common types allowed. """ from symbols.type_ import SymbolBASICTYPE as BASICTYPE from symbols.type_ import Type as TYPE from symbols.type_ import SymbolTYPE if a is None or b is None: return None if not isinstance(a, SymbolTYPE): a = a.type_ if not isinstance(b, SymbolTYPE): b = b.type_ if a == b: # Both types are the same? return a # Returns it if a == TYPE.unknown and b == TYPE.unknown: return BASICTYPE(global_.DEFAULT_TYPE) if a == TYPE.unknown: return b if b == TYPE.unknown: return a # TODO: This will removed / expanded in the future assert a.is_basic assert b.is_basic types = (a, b) if TYPE.float_ in types: return TYPE.float_ if TYPE.fixed in types: return TYPE.fixed if TYPE.string in types: # TODO: Check this ?? return TYPE.unknown result = a if a.size > b.size else b if not TYPE.is_unsigned(a) or not TYPE.is_unsigned(b): result = TYPE.to_signed(result) return result
python
{ "resource": "" }
q3465
_sub16
train
def _sub16(ins): ''' Pops last 2 words from the stack and subtract them. Then push the result onto the stack. Top of the stack is subtracted Top -1 Optimizations: * If 2nd op is ZERO, then do NOTHING: A - 0 = A * If any of the operands is < 4, then DEC is used * If any of the operands is > 65531 (-4..-1), then INC is used ''' op1, op2 = tuple(ins.quad[2:4]) if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op == 0: output.append('push hl') return output if op < 4: output.extend(['dec hl'] * op) output.append('push hl') return output if op > 65531: output.extend(['inc hl'] * (0x10000 - op)) output.append('push hl') return output output.append('ld de, -%i' % op) output.append('add hl, de') output.append('push hl') return output if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('or a') output.append('sbc hl, de') output.append('push hl') return output
python
{ "resource": "" }
q3466
_mul16
train
def _mul16(ins): ''' Multiplies tow last 16bit values on top of the stack and and returns the value on top of the stack Optimizations: * If any of the ops is ZERO, then do A = 0 ==> XOR A, cause A * 0 = 0 * A = 0 * If any ot the ops is ONE, do NOTHING A * 1 = 1 * A = A * If B is 2^n and B < 16 => Shift Right n ''' op1, op2 = tuple(ins.quad[2:]) if _int_ops(op1, op2) is not None: # If any of the operands is constant op1, op2 = _int_ops(op1, op2) # put the constant one the 2nd output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op2 == 1: # A * 1 = 1 * A == A => Do nothing output.append('push hl') return output if op2 == 0xFFFF: # This is the same as (-1) output.append('call __NEGHL') output.append('push hl') REQUIRES.add('neg16.asm') return output if is_2n(op2) and log2(op2) < 4: output.extend(['add hl, hl'] * int(log2(op2))) output.append('push hl') return output output.append('ld de, %i' % op2) else: if op2[0] == '_': # stack optimization op1, op2 = op2, op1 output = _16bit_oper(op1, op2) output.append('call __MUL16_FAST') # Inmmediate output.append('push hl') REQUIRES.add('mul16.asm') return output
python
{ "resource": "" }
q3467
_divu16
train
def _divu16(ins): ''' Divides 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd op is 1 then do nothing * If 2nd op is 2 then Shift Right Logical ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op1) and int(op1) == 0: # 0 / A = 0 if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack else: output = _16bit_oper(op2) # Normalize stack output.append('ld hl, 0') output.append('push hl') return output if is_int(op2): op = int16(op2) output = _16bit_oper(op1) if op2 == 0: # A * 0 = 0 * A = 0 if op1[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if op == 1: output.append('push hl') return output if op == 2: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld de, %i' % op) else: if op2[0] == '_': # Optimization when 2nd operand is an id rev = True op1, op2 = op2, op1 else: rev = False output = _16bit_oper(op1, op2, rev) output.append('call __DIVU16') output.append('push hl') REQUIRES.add('div16.asm') return output
python
{ "resource": "" }
q3468
_modu16
train
def _modu16(ins): ''' Reminder of div. 2 16bit unsigned integers. The result is pushed onto the stack. Optimizations: * If 2nd operand is 1 => Return 0 * If 2nd operand = 2^n => do AND (2^n - 1) ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op2 = int16(op2) output = _16bit_oper(op1) if op2 == 1: if op2[0] in ('_', '$'): output = [] # Optimization: Discard previous op if not from the stack output.append('ld hl, 0') output.append('push hl') return output if is_2n(op2): k = op2 - 1 if op2 > 255: # only affects H output.append('ld a, h') output.append('and %i' % (k >> 8)) output.append('ld h, a') else: output.append('ld h, 0') # High part goes 0 output.append('ld a, l') output.append('and %i' % (k % 0xFF)) output.append('ld l, a') output.append('push hl') return output output.append('ld de, %i' % op2) else: output = _16bit_oper(op1, op2) output.append('call __MODU16') output.append('push hl') REQUIRES.add('div16.asm') return output
python
{ "resource": "" }
q3469
_shru16
train
def _shru16(ins): ''' Logical right shift 16bit unsigned integer. The result is pushed onto the stack. Optimizations: * If 2nd op is 0 then do nothing * If 2nd op is 1 Shift Right Arithmetic ''' op1, op2 = tuple(ins.quad[2:]) if is_int(op2): op = int16(op2) if op == 0: return [] output = _16bit_oper(op1) if op == 1: output.append('srl h') output.append('rr l') output.append('push hl') return output output.append('ld b, %i' % op) else: output = _8bit_oper(op2) output.append('ld b, a') output.extend(_16bit_oper(op1)) label = tmp_label() output.append('%s:' % label) output.append('srl h') output.append('rr l') output.append('djnz %s' % label) output.append('push hl') return output
python
{ "resource": "" }
q3470
read_txt_file
train
def read_txt_file(fname): """Reads a txt file, regardless of its encoding """ encodings = ['utf-8-sig', 'cp1252'] with open(fname, 'rb') as f: content = bytes(f.read()) for i in encodings: try: result = content.decode(i) if six.PY2: result = result.encode('utf-8') return result except UnicodeDecodeError: pass global_.FILENAME = fname errmsg.syntax_error(1, 'Invalid file encoding. Use one of: %s' % ', '.join(encodings)) return ''
python
{ "resource": "" }
q3471
TZX.out
train
def out(self, l): """ Adds a list of bytes to the output string """ if not isinstance(l, list): l = [l] self.output.extend([int(i) & 0xFF for i in l])
python
{ "resource": "" }
q3472
TZX.standard_block
train
def standard_block(self, _bytes): """ Adds a standard block of bytes """ self.out(self.BLOCK_STANDARD) # Standard block ID self.out(self.LH(1000)) # 1000 ms standard pause self.out(self.LH(len(_bytes) + 1)) # + 1 for CHECKSUM byte checksum = 0 for i in _bytes: checksum ^= (int(i) & 0xFF) self.out(i) self.out(checksum)
python
{ "resource": "" }
q3473
TZX.dump
train
def dump(self, fname): """ Saves TZX file to fname """ with open(fname, 'wb') as f: f.write(self.output)
python
{ "resource": "" }
q3474
TZX.standard_bytes_header
train
def standard_bytes_header(self, title, addr, length): """ Generates a standard header block of CODE type """ self.save_header(self.HEADER_TYPE_CODE, title, length, param1=addr, param2=32768)
python
{ "resource": "" }
q3475
TZX.standard_program_header
train
def standard_program_header(self, title, length, line=32768): """ Generates a standard header block of PROGRAM type """ self.save_header(self.HEADER_TYPE_BASIC, title, length, param1=line, param2=length)
python
{ "resource": "" }
q3476
TZX.save_code
train
def save_code(self, title, addr, _bytes): """ Saves the given bytes as code. If bytes are strings, its chars will be converted to bytes """ self.standard_bytes_header(title, addr, len(_bytes)) _bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in _bytes] # & 0xFF truncates to bytes self.standard_block(_bytes)
python
{ "resource": "" }
q3477
TZX.save_program
train
def save_program(self, title, bytes, line=32768): """ Saves the given bytes as a BASIC program. """ self.standard_program_header(title, len(bytes), line) bytes = [self.BLOCK_TYPE_DATA] + [(int(x) & 0xFF) for x in bytes] # & 0xFF truncates to bytes self.standard_block(bytes)
python
{ "resource": "" }
q3478
SymbolSTRSLICE.make_node
train
def make_node(cls, lineno, s, lower, upper): """ Creates a node for a string slice. S is the string expression Tree. Lower and upper are the bounds, if lower & upper are constants, and s is also constant, then a string constant is returned. If lower > upper, an empty string is returned. """ if lower is None or upper is None or s is None: return None if not check_type(lineno, Type.string, s): return None lo = up = None base = NUMBER(api.config.OPTIONS.string_base.value, lineno=lineno) lower = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', lower, base, lineno=lineno, func=lambda x, y: x - y), lineno) upper = TYPECAST.make_node(gl.SYMBOL_TABLE.basic_types[gl.STR_INDEX_TYPE], BINARY.make_node('MINUS', upper, base, lineno=lineno, func=lambda x, y: x - y), lineno) if lower is None or upper is None: return None if is_number(lower): lo = lower.value if lo < gl.MIN_STRSLICE_IDX: lower.value = lo = gl.MIN_STRSLICE_IDX if is_number(upper): up = upper.value if up > gl.MAX_STRSLICE_IDX: upper.value = up = gl.MAX_STRSLICE_IDX if is_number(lower, upper): if lo > up: return STRING('', lineno) if s.token == 'STRING': # A constant string? Recalculate it now up += 1 st = s.value.ljust(up) # Procrustean filled (right) return STRING(st[lo:up], lineno) # a$(0 TO INF.) = a$ if lo == gl.MIN_STRSLICE_IDX and up == gl.MAX_STRSLICE_IDX: return s return cls(s, lower, upper, lineno)
python
{ "resource": "" }
q3479
to_byte
train
def to_byte(stype): """ Returns the instruction sequence for converting from the given type to byte. """ output = [] if stype in ('i8', 'u8'): return [] if is_int_type(stype): output.append('ld a, l') elif stype == 'f16': output.append('ld a, e') elif stype == 'f': # Converts C ED LH to byte output.append('call __FTOU32REG') output.append('ld a, l') REQUIRES.add('ftou32reg.asm') return output
python
{ "resource": "" }
q3480
_end
train
def _end(ins): """ Outputs the ending sequence """ global FLAG_end_emitted output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') if FLAG_end_emitted: return output + ['jp %s' % END_LABEL] FLAG_end_emitted = True output.append('%s:' % END_LABEL) if OPTIONS.headerless.value: return output + ['ret'] output.append('di') output.append('ld hl, (%s)' % CALL_BACK) output.append('ld sp, hl') output.append('exx') output.append('pop hl') output.append('exx') output.append('pop iy') output.append('pop ix') output.append('ei') output.append('ret') output.append('%s:' % CALL_BACK) output.append('DEFW 0') return output
python
{ "resource": "" }
q3481
_var
train
def _var(ins): """ Defines a memory variable. """ output = [] output.append('%s:' % ins.quad[1]) output.append('DEFB %s' % ((int(ins.quad[2]) - 1) * '00, ' + '00')) return output
python
{ "resource": "" }
q3482
_lvarx
train
def _lvarx(ins): """ Defines a local variable. 1st param is offset of the local variable. 2nd param is the type a list of bytes in hexadecimal. """ output = [] l = eval(ins.quad[3]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = label ins.quad = tmp AT_END.extend(_varx(ins)) output.append('push ix') output.append('pop hl') output.append('ld bc, %i' % -offset) output.append('add hl, bc') output.append('ex de, hl') output.append('ld hl, %s' % label) output.append('ld bc, %i' % (len(l) * YY_TYPES[ins.quad[2]])) output.append('ldir') return output
python
{ "resource": "" }
q3483
_lvard
train
def _lvard(ins): """ Defines a local variable. 1st param is offset of the local variable. 2nd param is a list of bytes in hexadecimal. """ output = [] l = eval(ins.quad[2]) # List of bytes to push label = tmp_label() offset = int(ins.quad[1]) tmp = list(ins.quad) tmp[1] = label ins.quad = tmp AT_END.extend(_vard(ins)) output.append('push ix') output.append('pop hl') output.append('ld bc, %i' % -offset) output.append('add hl, bc') output.append('ex de, hl') output.append('ld hl, %s' % label) output.append('ld bc, %i' % len(l)) output.append('ldir') return output
python
{ "resource": "" }
q3484
_out
train
def _out(ins): """ Translates OUT to asm. """ output = _8bit_oper(ins.quad[2]) output.extend(_16bit_oper(ins.quad[1])) output.append('ld b, h') output.append('ld c, l') output.append('out (c), a') return output
python
{ "resource": "" }
q3485
_in
train
def _in(ins): """ Translates IN to asm. """ output = _16bit_oper(ins.quad[1]) output.append('ld b, h') output.append('ld c, l') output.append('in a, (c)') output.append('push af') return output
python
{ "resource": "" }
q3486
_jzerostr
train
def _jzerostr(ins): """ Jumps if top of the stack contains a NULL pointer or its len is Zero """ output = [] disposable = False # True if string must be freed from memory if ins.quad[1][0] == '_': # Variable? output.append('ld hl, (%s)' % ins.quad[1][0]) else: output.append('pop hl') output.append('push hl') # Saves it for later disposable = True output.append('call __STRLEN') if disposable: output.append('ex (sp), hl') output.append('call __MEM_FREE') output.append('pop hl') REQUIRES.add('alloc.asm') output.append('ld a, h') output.append('or l') output.append('jp z, %s' % str(ins.quad[2])) REQUIRES.add('strlen.asm') return output
python
{ "resource": "" }
q3487
_param32
train
def _param32(ins): """ Pushes 32bit param into the stack """ output = _32bit_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
python
{ "resource": "" }
q3488
_paramf16
train
def _paramf16(ins): """ Pushes 32bit fixed point param into the stack """ output = _f16_oper(ins.quad[1]) output.append('push de') output.append('push hl') return output
python
{ "resource": "" }
q3489
_memcopy
train
def _memcopy(ins): """ Copies a block of memory from param 2 addr to param 1 addr. """ output = _16bit_oper(ins.quad[3]) output.append('ld b, h') output.append('ld c, l') output.extend(_16bit_oper(ins.quad[1], ins.quad[2], reversed=True)) output.append('ldir') # *** return output
python
{ "resource": "" }
q3490
Lexer.include_end
train
def include_end(self): """ Performs and end of include. """ self.lex = self.filestack[-1][2] self.input_data = self.filestack[-1][3] self.filestack.pop() if not self.filestack: # End of input? return self.filestack[-1][1] += 1 # Increment line counter of previous file result = lex.LexToken() result.value = self.put_current_line(suffix='\n') result.type = '_ENDFILE_' result.lineno = self.lex.lineno result.lexpos = self.lex.lexpos return result
python
{ "resource": "" }
q3491
getDEHL
train
def getDEHL(duration, pitch): """Converts duration,pitch to a pair of unsigned 16 bit integers, to be loaded in DE,HL, following the ROM listing. Returns a t-uple with the DE, HL values. """ intPitch = int(pitch) fractPitch = pitch - intPitch # Gets fractional part tmp = 1 + 0.0577622606 * fractPitch if not -60 <= intPitch <= 127: raise BeepError('Pitch out of range: must be between [-60, 127]') if duration < 0 or duration > 10: raise BeepError('Invalid duration: must be between [0, 10]') A = intPitch + 60 B = -5 + int(A / 12) # -5 <= B <= 10 A %= 0xC # Semitones above C frec = TABLE[A] tmp2 = tmp * frec f = tmp2 * 2.0 ** B DE = int(0.5 + f * duration - 1) HL = int(0.5 + 437500.0 / f - 30.125) return DE, HL
python
{ "resource": "" }
q3492
SymbolBLOCK.make_node
train
def make_node(cls, *args): """ Creates a chain of code blocks. """ new_args = [] args = [x for x in args if not is_null(x)] for x in args: assert isinstance(x, Symbol) if x.token == 'BLOCK': new_args.extend(SymbolBLOCK.make_node(*x.children).children) else: new_args.append(x) result = SymbolBLOCK(*new_args) return result
python
{ "resource": "" }
q3493
is_label
train
def is_label(token): """ Return whether the token is a label (an integer number or id at the beginning of a line. To do so, we compute find_column() and moves back to the beginning of the line if previous chars are spaces or tabs. If column 0 is reached, it's a label. """ if not LABELS_ALLOWED: return False c = i = token.lexpos input = token.lexer.lexdata c -= 1 while c > 0 and input[c] in (' ', '\t'): c -= 1 while i > 0: if input[i] == '\n': break i -= 1 column = c - i if column == 0: column += 1 return column == 1
python
{ "resource": "" }
q3494
_get_val
train
def _get_val(other): """ Given a Number, a Numeric Constant or a python number return its value """ assert isinstance(other, (numbers.Number, SymbolNUMBER, SymbolCONST)) if isinstance(other, SymbolNUMBER): return other.value if isinstance(other, SymbolCONST): return other.expr.value return other
python
{ "resource": "" }
q3495
ID.__dumptable
train
def __dumptable(self, table): """ Dumps table on screen for debugging purposes """ for x in table.table.keys(): sys.stdout.write("{0}\t<--- {1} {2}".format(x, table[x], type(table[x]))) if isinstance(table[x], ID): sys.stdout(" {0}".format(table[x].value)), sys.stdout.write("\n")
python
{ "resource": "" }
q3496
SymbolVARARRAY.count
train
def count(self): """ Total number of array cells """ return functools.reduce(lambda x, y: x * y, (x.count for x in self.bounds))
python
{ "resource": "" }
q3497
SymbolVARARRAY.memsize
train
def memsize(self): """ Total array cell + indexes size """ return self.size + 1 + TYPE.size(gl.BOUND_TYPE) * len(self.bounds)
python
{ "resource": "" }
q3498
SymbolTYPECAST.make_node
train
def make_node(cls, new_type, node, lineno): """ Creates a node containing the type cast of the given one. If new_type == node.type, then nothing is done, and the same node is returned. Returns None on failure (and calls syntax_error) """ assert isinstance(new_type, SymbolTYPE) # None (null) means the given AST node is empty (usually an error) if node is None: return None # Do nothing. Return None assert isinstance(node, Symbol), '<%s> is not a Symbol' % node # The source and dest types are the same if new_type == node.type_: return node # Do nothing. Return as is STRTYPE = TYPE.string # Typecasting, at the moment, only for number if node.type_ == STRTYPE: syntax_error(lineno, 'Cannot convert string to a value. ' 'Use VAL() function') return None # Converting from string to number is done by STR if new_type == STRTYPE: syntax_error(lineno, 'Cannot convert value to string. ' 'Use STR() function') return None # If the given operand is a constant, perform a static typecast if is_CONST(node): node.expr = cls(new_type, node.expr, lineno) return node if not is_number(node) and not is_const(node): return cls(new_type, node, lineno) # It's a number. So let's convert it directly if is_const(node): node = SymbolNUMBER(node.value, node.lineno, node.type_) if new_type.is_basic and not TYPE.is_integral(new_type): # not an integer node.value = float(node.value) else: # It's an integer new_val = (int(node.value) & ((1 << (8 * new_type.size)) - 1)) # Mask it if node.value >= 0 and node.value != new_val: errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val elif node.value < 0 and (1 << (new_type.size * 8)) + \ node.value != new_val: # Test for positive to negative coercion errmsg.warning_conversion_lose_digits(node.lineno) node.value = new_val - (1 << (new_type.size * 8)) node.type_ = new_type return node
python
{ "resource": "" }
q3499
assemble
train
def assemble(input_): """ Assembles input string, and leave the result in the MEMORY global object """ global MEMORY if MEMORY is None: MEMORY = Memory() parser.parse(input_, lexer=LEXER, debug=OPTIONS.Debug.value > 2) if len(MEMORY.scopes): error(MEMORY.scopes[-1], 'Missing ENDP to close this scope') return gl.has_errors
python
{ "resource": "" }