_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| 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
|
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
|
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
|
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
|
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
|
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
|
python
|
{
"resource": ""
}
|
q3406
|
Lightning.set_basic_auth
|
train
|
def set_basic_auth(self, username, password):
"""
Set authenatication.
"""
from requests.auth import
|
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
|
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
|
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
|
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)
|
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:
|
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:
|
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:
|
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,
|
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',
|
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)
|
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 =
|
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:
|
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
|
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')
|
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
|
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:
|
python
|
{
"resource": ""
}
|
q3423
|
TranslatorVisitor.norm_attr
|
train
|
def norm_attr(self):
""" Normalize attr state
"""
if not self.HAS_ATTR:
|
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):
|
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.
|
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):
|
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):
|
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:
|
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)
|
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]
|
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:
|
python
|
{
"resource": ""
}
|
q3432
|
SymbolPARAMLIST.appendChild
|
train
|
def appendChild(self, param):
''' Overrides base class.
'''
Symbol.appendChild(self, param)
if param.offset is None:
|
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.
|
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
|
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:
|
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.
|
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)
|
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
|
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:
|
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)
|
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
|
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
|
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)
|
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))
|
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',
|
python
|
{
"resource": ""
}
|
q3446
|
SymbolTable.check_labels
|
train
|
def check_labels(self):
""" Checks if all the labels has been declared
|
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():
|
python
|
{
"resource": ""
}
|
q3448
|
SymbolTable.vars_
|
train
|
def vars_(self):
""" Returns symbol instances corresponding to variables
of the current scope.
"""
|
python
|
{
"resource": ""
}
|
q3449
|
SymbolTable.labels
|
train
|
def labels(self):
""" Returns symbol instances corresponding to labels
in the current scope.
"""
|
python
|
{
"resource": ""
}
|
q3450
|
SymbolTable.types
|
train
|
def types(self):
""" Returns symbol instances corresponding to type declarations
|
python
|
{
"resource": ""
}
|
q3451
|
SymbolTable.arrays
|
train
|
def arrays(self):
""" Returns symbol instances corresponding to arrays
of the current scope.
"""
|
python
|
{
"resource": ""
}
|
q3452
|
SymbolTable.functions
|
train
|
def functions(self):
""" Returns symbol instances corresponding to functions
of the current scope.
"""
|
python
|
{
"resource": ""
}
|
q3453
|
SymbolTable.aliases
|
train
|
def aliases(self):
""" Returns symbol instances corresponding to aliased vars.
"""
|
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'" %
|
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 "
|
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)
|
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):
|
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':
|
python
|
{
"resource": ""
}
|
q3459
|
is_const
|
train
|
def is_const(*p):
""" A constant in the program, like CONST a = 5
"""
|
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:
|
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:
|
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_:
|
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:
|
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:
|
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')
|
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
|
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:
|
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')
|
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')
|
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
|
python
|
{
"resource": ""
}
|
q3471
|
TZX.out
|
train
|
def out(self, l):
""" Adds a list of bytes to the output string
"""
if not isinstance(l, list):
|
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)) #
|
python
|
{
"resource": ""
}
|
q3473
|
TZX.dump
|
train
|
def dump(self, fname):
""" Saves TZX file to fname
"""
with
|
python
|
{
"resource": ""
}
|
q3474
|
TZX.standard_bytes_header
|
train
|
def standard_bytes_header(self, title, addr, length):
""" Generates a standard header block of CODE type
"""
|
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
"""
|
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,
|
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)
|
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,
|
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
|
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)
|
python
|
{
"resource": ""
}
|
q3481
|
_var
|
train
|
def _var(ins):
""" Defines a memory variable.
"""
output = []
output.append('%s:' % ins.quad[1])
output.append('DEFB %s' %
|
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')
|
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')
|
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')
|
python
|
{
"resource": ""
}
|
q3485
|
_in
|
train
|
def _in(ins):
""" Translates IN to asm.
"""
output = _16bit_oper(ins.quad[1])
|
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
|
python
|
{
"resource": ""
}
|
q3487
|
_param32
|
train
|
def _param32(ins):
""" Pushes 32bit param into the stack
"""
|
python
|
{
"resource": ""
}
|
q3488
|
_paramf16
|
train
|
def _paramf16(ins):
""" Pushes 32bit fixed point param into the stack
"""
output = _f16_oper(ins.quad[1])
|
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')
|
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
|
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
|
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':
|
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
|
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):
|
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])))
|
python
|
{
"resource": ""
}
|
q3496
|
SymbolVARARRAY.count
|
train
|
def count(self):
""" Total number of array cells
"""
|
python
|
{
"resource": ""
}
|
q3497
|
SymbolVARARRAY.memsize
|
train
|
def memsize(self):
""" Total array cell + indexes size
"""
return
|
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 =
|
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_,
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.