text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_path():
""" Add any new modules that are directories to the PATH """ |
sitedirs = getsyssitepackages()
for sitedir in sitedirs:
env_path = os.environ['PATH'].split(os.pathsep)
for module in allowed_modules:
p = join(sitedir, module)
if isdir(p) and not p in env_path:
os.environ['PATH'] += env_t(os.pathsep + p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_importer():
""" If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """ |
logging.debug('install_importer')
if not in_venv():
logging.debug('No virtualenv active py:[%s]', sys.executable)
return False
if disable_vext:
logging.debug('Vext disabled by environment variable')
return False
if GatekeeperFinder.PATH_TRIGGER not in sys.path:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_module(self, name):
""" Only lets modules in allowed_modules be loaded, others will get an ImportError """ |
# Get the name relative to SITEDIR ..
filepath = self.module_info[1]
fullname = splitext( \
relpath(filepath, self.sitedir) \
)[0].replace(os.sep, '.')
modulename = filename_to_module(fullname)
if modulename not in allowed_modules:
if rememb... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(g: Graph, schema: Union[str, ShExJ.Schema], focus: Optional[Union[str, URIRef, IRIREF]], start: Optional[Union[str, URIRef, IRIREF, START, START_TYPE... |
if isinstance(schema, str):
schema = SchemaLoader().loads(schema)
if schema is None:
return False, "Error parsing schema"
if not isinstance(focus, URIRef):
focus = URIRef(str(focus))
if start is None:
start = str(schema.start) if schema.start else None
if start is No... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_sysdeps(vext_files):
""" Check that imports in 'test_imports' succeed otherwise display message in 'install_hints' """ |
@run_in_syspy
def run(*modules):
result = {}
for m in modules:
if m:
try:
__import__(m)
result[m] = True
except ImportError:
result[m] = False
return result
success = True
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_collection(g: Graph, subj: Union[URIRef, BNode], max_entries: int = None, nentries: int = 0) -> Optional[List[str]]: """ Return the turtle representati... |
if subj == RDF.nil:
return [')']
if max_entries is not None and nentries >= max_entries:
return [' ...', ')']
cadr = cdr = None
for p, o in g.predicate_objects(subj):
if p == RDF.first and cadr is None:
cadr = o
elif p == RDF.rest and cdr is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upgrade_setuptools():
""" setuptools 12.2 can trigger a really nasty bug that eats all memory, so upgrade it to 18.8, which is known to be good. """ |
# Note - I tried including the higher version in
# setup_requires, but was still able to trigger
# the bug. - stu.axon
global MIN_SETUPTOOLS
r = None
try:
r = pkg_resources.require(["setuptools"])[0]
except DistributionNotFound:
# ok, setuptools will be installed later
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" Need to find any pre-existing vext contained in dependent packages and install them example: you create a setup.py with install_requires["vext... |
logger.debug("vext InstallLib [started]")
# Find packages that depend on vext and check for .vext files...
logger.debug("find_vext_files")
vext_files = self.find_vext_files()
logger.debug("manually_install_vext: ", vext_files)
self.manually_install_vext(vext_files)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_servers(self, servers):
""" Iter to a list of servers and instantiate Protocol class. :param servers: A list of servers :type servers: list :return: Retu... |
if isinstance(servers, six.string_types):
servers = [servers]
assert servers, "No memcached servers supplied"
self._servers = [Protocol(
server=server,
username=self.username,
password=self.password,
compression=self.compression,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_in_syspy(f):
""" Decorator to run a function in the system python :param f: :return: """ |
fname = f.__name__
code_lines = inspect.getsource(f).splitlines()
code = dedent("\n".join(code_lines[1:])) # strip this decorator
# add call to the function and print it's result
code += dedent("""\n
import sys
args = sys.argv[1:]
result = {fname}(*args)
print("%r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cas(self, key, value, cas, time=0, compress_level=-1):
""" Set a value for a key on server if its CAS value matches cas. :param key: Key's name :type key: si... |
server = self._get_server(key)
return server.cas(key, value, cas, time, compress_level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matchesCardinality(cntxt: Context, T: RDFGraph, expr: Union[ShExJ.tripleExpr, ShExJ.tripleExprLabel], c: DebugContext) -> bool: """ Evaluate cardinality expre... |
# TODO: Cardinality defaults into spec
min_ = expr.min if expr.min is not None else 1
max_ = expr.max if expr.max is not None else 1
cardinality_text = f"{{{min_},{'*' if max_ == -1 else max_}}}"
if c.debug and (min_ != 0 or len(T) != 0):
print(f"{cardinality_text} matching {len(T)} triple... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matchesExpr(cntxt: Context, T: RDFGraph, expr: ShExJ.tripleExpr, _: DebugContext) -> bool: """ Evaluate the expression """ |
if isinstance(expr, ShExJ.OneOf):
return matchesOneOf(cntxt, T, expr)
elif isinstance(expr, ShExJ.EachOf):
return matchesEachOf(cntxt, T, expr)
elif isinstance(expr, ShExJ.TripleConstraint):
return matchesCardinality(cntxt, T, expr)
elif isinstance_(expr, ShExJ.tripleExprLabel)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, key, get_cas=False):
""" Get a key from server. :param key: Key's name :type key: six.string_types :param get_cas: If true, return (value, cas), wh... |
for server in self.servers:
value, cas = server.get(key)
if value is not None:
if get_cas:
return value, cas
else:
return value
if get_cas:
return None, None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gets(self, key):
""" Get a key from server, returning the value and its CAS key. This method is for API compatibility with other implementations. :param key:... |
for server in self.servers:
value, cas = server.get(key)
if value is not None:
return value, cas
return None, None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_result(self, rval: bool) -> None: """ Set the result of the evaluation. If the result is true, prune all of the children that didn't cut it :param rval: R... |
self.result = rval
if self.result:
self.nodes = [pn for pn in self.nodes if pn.result] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reference_of(selector: shapeLabel, cntxt: Union[Context, ShExJ.Schema] ) -> Optional[ShExJ.shapeExpr]: """ Return the shape expression in the schema reference... |
schema = cntxt.schema if isinstance(cntxt, Context) else cntxt
if selector is START:
return schema.start
for expr in schema.shapes:
if not isinstance(expr, ShExJ.ShapeExternal) and expr.id == selector:
return expr
return schema.start if schema.start is not None and schema.st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triple_reference_of(label: ShExJ.tripleExprLabel, cntxt: Context) -> Optional[ShExJ.tripleExpr]: """ Search for the label in a Schema """ |
te: Optional[ShExJ.tripleExpr] = None
if cntxt.schema.start is not None:
te = triple_in_shape(cntxt.schema.start, label, cntxt)
if te is None:
for shapeExpr in cntxt.schema.shapes:
te = triple_in_shape(shapeExpr, label, cntxt)
if te:
break
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triple_in_shape(expr: ShExJ.shapeExpr, label: ShExJ.tripleExprLabel, cntxt: Context) \ -> Optional[ShExJ.tripleExpr]: """ Search for the label in a shape expr... |
te = None
if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)):
for expr2 in expr.shapeExprs:
te = triple_in_shape(expr2, label, cntxt)
if te is not None:
break
elif isinstance(expr, ShExJ.ShapeNot):
te = triple_in_shape(expr.shapeExpr, label, cntxt)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def integer_partition(size: int, nparts: int) -> Iterator[List[List[int]]]: """ Partition a list of integers into a list of partitions """ |
for part in algorithm_u(range(size), nparts):
yield part |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_simple_literal(n: Node) -> bool: """ simple literal denotes a plain literal with no language tag. """ |
return is_typed_literal(n) and cast(Literal, n).datatype is None and cast(Literal, n).language is None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print(self, txt: str, hold: bool=False) -> None: """ Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another... |
if hold:
self.held_prints[self.trace_depth] = txt
elif self.held_prints[self.trace_depth]:
if self.max_print_depth > self.trace_depth:
print(self.held_prints[self.trace_depth])
print(txt)
self.max_print_depth = self.trace_depth
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reset(self) -> None: """ Reset the context preceeding an evaluation """ |
self.evaluating = set()
self.assumptions = {}
self.known_results = {}
self.current_node = None
self.evaluate_stack = []
self.bnode_map = {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gen_schema_xref(self, expr: Optional[Union[ShExJ.shapeExprLabel, ShExJ.shapeExpr]]) -> None: """ Generate the schema_id_map :param expr: root shape expressio... |
if expr is not None and not isinstance_(expr, ShExJ.shapeExprLabel) and 'id' in expr and expr.id is not None:
abs_id = self._resolve_relative_uri(expr.id)
if abs_id not in self.schema_id_map:
self.schema_id_map[abs_id] = expr
if isinstance(expr, (ShExJ.Sh... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tripleExprFor(self, id_: ShExJ.tripleExprLabel) -> ShExJ.tripleExpr: """ Return the triple expression that corresponds to id """ |
return self.te_id_map.get(id_) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shapeExprFor(self, id_: Union[ShExJ.shapeExprLabel, START]) -> Optional[ShExJ.shapeExpr]: """ Return the shape expression that corresponds to id """ |
rval = self.schema.start if id_ is START else self.schema_id_map.get(str(id_))
return rval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_shapes(self, expr: ShExJ.shapeExpr, f: Callable[[Any, ShExJ.shapeExpr, "Context"], None], arg_cntxt: Any, visit_center: _VisitorCenter = None, follow_in... |
if visit_center is None:
visit_center = _VisitorCenter(f, arg_cntxt)
has_id = getattr(expr, 'id', None) is not None
if not has_id or not (visit_center.already_seen_shape(expr.id)
or visit_center.actively_visiting_shape(expr.id)):
# Visit th... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _visit_te_shape(self, shape: ShExJ.shapeExpr, visit_center: _VisitorCenter) -> None: """ Visit a shape expression that was reached through a triple expression... |
if isinstance(shape, ShExJ.Shape) and shape.expression is not None:
visit_center.f(visit_center.arg_cntxt, shape.expression, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def type_last(self, obj: JsonObj) -> JsonObj: """ Move the type identifiers to the end of the object for print purposes """ |
def _tl_list(v: List) -> List:
return [self.type_last(e) if isinstance(e, JsonObj)
else _tl_list(e) if isinstance(e, list) else e for e in v if e is not None]
rval = JsonObj()
for k in as_dict(obj).keys():
v = obj[k]
if v i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def satisfiesExternal(cntxt: Context, n: Node, se: ShExJ.ShapeExternal, c: DebugContext) -> bool: """ Se is a ShapeExternal and implementation-specific mechansims... |
if c.debug:
print(f"id: {se.id}")
extern_shape = cntxt.external_shape_for(se.id)
if extern_shape:
return satisfies(cntxt, n, extern_shape)
cntxt.fail_reason = f"{se.id}: Shape is not in Schema"
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_uri(u: URI) -> URIRef: """ Return a URIRef for a str or URIRef """ |
return u if isinstance(u, URIRef) else URIRef(str(u)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_uriparm(p: URIPARM) -> List[URIRef]: """ Return an optional list of URIRefs for p""" |
return normalize_urilist(p) if isinstance(p, List) else \
normalize_urilist([p]) if isinstance(p, (str, URIRef)) else p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def normalize_startparm(p: STARTPARM) -> List[Union[type(START), START_TYPE, URIRef]]: """ Return the startspec for p """ |
if not isinstance(p, list):
p = [p]
return [normalize_uri(e) if isinstance(e, str) and e is not START else e for e in p] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rdf(self, rdf: Optional[Union[str, Graph]]) -> None: """ Set the RDF DataSet to be evaulated. If ``rdf`` is a string, the presence of a return is the indicato... |
if isinstance(rdf, Graph):
self.g = rdf
else:
self.g = Graph()
if isinstance(rdf, str):
if '\n' in rdf or '\r' in rdf:
self.g.parse(data=rdf, format=self.rdf_format)
elif ':' in rdf:
self.g.parse... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def schema(self, shex: Optional[Union[str, ShExJ.Schema]]) -> None: """ Set the schema to be used. Schema can either be a ShExC or ShExJ string or a pre-parsed sc... |
self.pfx = None
if shex is not None:
if isinstance(shex, ShExJ.Schema):
self._schema = shex
else:
shext = shex.strip()
loader = SchemaLoader()
if ('\n' in shex or '\r' in shex) or shext[0] in '#<_: ':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_base(path: str) -> str: """ Convert path, which can be a URL or a file path into a base URI :param path: file location or url :return: file location ... |
if ':' in path:
parts = urlparse(path)
parts_dict = parts._asdict()
parts_dict['path'] = os.path.split(parts.path)[0] if '/' in parts.path else ''
return urlunparse(ParseResult(**parts_dict)) + '/'
else:
return (os.path.split(path)[0] if '/' in path else '') + '/' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_socket(self, size):
""" Reads data from socket. :param size: Size in bytes to be read. :return: Data from socket """ |
value = b''
while len(value) < size:
data = self.connection.recv(size - len(value))
if not data:
break
value += data
# If we got less data than we requested, the server disconnected.
if len(value) < size:
raise socket.erro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_response(self):
""" Get memcached response from socket. :return: A tuple with binary values from memcached. :rtype: tuple """ |
try:
self._open_connection()
if self.connection is None:
# The connection wasn't opened, which means we're deferring a reconnection attempt.
# Raise a socket.error, so we'll return the same server_disconnected message as we
# do below.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self, username, password):
""" Authenticate user on server. :param username: Username used to be authenticated. :type username: six.string_types... |
self._username = username
self._password = password
# Reopen the connection with the new credentials.
self.disconnect()
self._open_connection()
return self.authenticated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, value, compress_level=-1):
""" Serializes a value based on its type. :param value: Something to be serialized :type value: six.string_types, ... |
flags = 0
if isinstance(value, binary_type):
flags |= self.FLAGS['binary']
elif isinstance(value, text_type):
value = value.encode('utf8')
elif isinstance(value, int) and isinstance(value, bool) is False:
flags |= self.FLAGS['integer']
val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(self, value, flags):
""" Deserialized values based on flags or just return it if it is not serialized. :param value: Serialized or not value. :ty... |
FLAGS = self.FLAGS
if flags & FLAGS['compressed']: # pragma: no branch
value = self.compression.decompress(value)
if flags & FLAGS['binary']:
return value
if flags & FLAGS['integer']:
return int(value)
elif flags & FLAGS['long']:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def noop(self):
""" Send a NOOP command :return: Returns the status. :rtype: int """ |
logger.debug('Sending NOOP')
data = struct.pack(self.HEADER_STRUCT +
self.COMMANDS['noop']['struct'],
self.MAGIC['request'],
self.COMMANDS['noop']['command'],
0, 0, 0, 0, 0, 0, 0)
self._s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_multi(self, mappings, time=100, compress_level=-1):
""" Set multiple keys with its values on server. If a key is a (key, cas) tuple, insert as if cas(key... |
mappings = mappings.items()
msg = []
for key, value in mappings:
if isinstance(key, tuple):
key, cas = key
else:
cas = None
if cas == 0:
# Like cas(), if the cas value is 0, treat it as compare-and-set against... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _incr_decr(self, command, key, value, default, time):
""" Function which increments and decrements. :param key: Key's name :type key: six.string_types :param... |
time = time if time >= 0 else self.MAXIMUM_EXPIRE_TIME
self._send(struct.pack(self.HEADER_STRUCT +
self.COMMANDS[command]['struct'] % len(key),
self.MAGIC['request'],
self.COMMANDS[command]['command'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def incr(self, key, value, default=0, time=1000000):
""" Increment a key, if it exists, returns its actual value, if it doesn't, return 0. :param key: Key's name... |
return self._incr_decr('incr', key, value, default, time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decr(self, key, value, default=0, time=100):
""" Decrement a key, if it exists, returns its actual value, if it doesn't, return 0. Minimum value of decrement... |
return self._incr_decr('decr', key, value, default, time) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_multi(self, keys):
""" Delete multiple keys from server in one command. :param keys: A list of keys to be deleted :type keys: list :return: True in ca... |
logger.debug('Deleting keys %r', keys)
if six.PY2:
msg = ''
else:
msg = b''
for key in keys:
msg += struct.pack(
self.HEADER_STRUCT +
self.COMMANDS['delete']['struct'] % len(key),
self.MAGIC['request'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_shex(self, schema: str) -> "PrefixLibrary": """ Add a ShExC schema to the library :param schema: ShExC schema text, URL or file name :return: prefix libra... |
if '\n' in schema or '\r' in schema or ' ' in schema:
shex = schema
else:
shex = load_shex_file(schema)
for line in shex.split('\n'):
line = line.strip()
m = re.match(r'PREFIX\s+(\S+):\s+<(\S+)>', line)
if not m:
m = r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_bindings(self, g: Graph) -> "PrefixLibrary": """ Add bindings in the library to the graph :param g: graph to add prefixes to :return: PrefixLibrary object... |
for prefix, namespace in self:
g.bind(prefix.lower(), namespace)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, schema_file: Union[str, TextIO], schema_location: Optional[str]=None) -> ShExJ.Schema: """ Load a ShEx Schema from schema_location :param schema_fi... |
if isinstance(schema_file, str):
schema_file = self.location_rewrite(schema_file)
self.schema_text = load_shex_file(schema_file)
else:
self.schema_text = schema_file.read()
if self.base_location:
self.root_location = self.base_location
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loads(self, schema_txt: str) -> ShExJ.Schema: """ Parse and return schema as a ShExJ Schema :param schema_txt: ShExC or ShExJ representation of a ShEx Schema ... |
self.schema_text = schema_txt
if schema_txt.strip()[0] == '{':
# TODO: figure out how to propagate self.base_location into this parse
return cast(ShExJ.Schema, loads(schema_txt, ShExJ))
else:
return generate_shexj.parse(schema_txt, self.base_location) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _run(self):
'''Continually poll TWS'''
stop = self._stop_evt
connected = self._connected_evt
tws = self._tws
fd = tws.fd()
pollfd = [fd]
while not stop.is_set():
while (not connected.is_set() or not tws.isConnected()) and not stop.is_set():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def error(self, id, errorCode, errorString):
'''Error during communication with TWS'''
if errorCode == 165: # Historical data sevice message
sys.stderr.write("TWS INFO - %s: %s\n" % (errorCode, errorString))
elif errorCode >= 501 and errorCode < 600: # Socket read failed
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def pyError(self, type, value, traceback):
'''Handles an error thrown during invocation of an EWrapper method.
Arguments are those provided by sys.exc_info()
'''
sys.stderr.write("Exception thrown during EWrapper method dispatch:\n")
print_exception(type, value, traceback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _decompress(self, compressed_payload):
'''Decompress a compressed payload into this payload wrapper.
Note that the decompressed buffer is saved in self._data and the
counts array is not yet allocated.
Args:
compressed_payload (string) a payload in zlib compressed form
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def encode(self):
'''Compress the associated encodable payload,
prepend the header then encode with base64 if requested
Returns:
the b64 encoded wire encoding of the histogram (as a string)
or the compressed payload (as a string, if b64 wrappinb is disabled)
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def record_value(self, value, count=1):
'''Record a new value into the histogram
Args:
value: the value to record (must be in the valid range)
count: incremental count (defaults to 1)
'''
if value < 0:
return False
counts_index = self._counts_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def record_corrected_value(self, value, expected_interval, count=1):
'''Record a new value into the histogram and correct for
coordinated omission if needed
Args:
value: the value to record (must be in the valid range)
expected_interval: the expected interval between 2 v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_value_at_percentile(self, percentile):
'''Get the value for a given percentile
Args:
percentile: a float in [0.0..100.0]
Returns:
the value for the given percentile
'''
count_at_percentile = self.get_target_count_at_percentile(percentile)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_percentile_to_value_dict(self, percentile_list):
'''A faster alternative to query values for a list of percentiles.
Args:
percentile_list: a list of percentiles in any order, dups will be ignored
each element in the list must be a float value in [0.0 .. 100.0]
Re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reset(self):
'''Reset the histogram to a pristine state
'''
for index in range(self.counts_len):
self.counts[index] = 0
self.total_count = 0
self.min_value = sys.maxsize
self.max_value = 0
self.start_time_stamp_msec = sys.maxsize
self.end_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_counts_array_index(self, value):
'''Return the index in the counts array for a given value
'''
if value < 0:
raise ValueError("Histogram recorded value cannot be negative.")
bucket_index = self._get_bucket_index(value)
sub_bucket_index = self._get_sub_bucket_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_jsonschema_from_file(self, json_string, path_to_schema):
""" Validate JSON according to schema, loaded from a file. *Args:*\n _json_string_ - JSON s... |
schema = open(path_to_schema).read()
load_input_json = self.string_to_json(json_string)
try:
load_schema = json.loads(schema)
except ValueError as e:
raise JsonValidatorError('Error in schema: {}'.format(e))
self._validate_json(load_input_json, load_sch... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_jsonschema(self, json_string, input_schema):
""" Validate JSON according to schema. *Args:*\n _json_string_ - JSON string;\n _input_schema_ - schema... |
load_input_json = self.string_to_json(json_string)
try:
load_schema = json.loads(input_schema)
except ValueError as e:
raise JsonValidatorError('Error in schema: {}'.format(e))
self._validate_json(load_input_json, load_schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_json(self, json_string, expr, value, index=0):
""" Replace the value in the JSON string. *Args:*\n _json_string_ - JSON string;\n _expr_ - JSONPath ex... |
load_input_json = self.string_to_json(json_string)
matches = self._json_path_search(load_input_json, expr)
datum_object = matches[int(index)]
if not isinstance(datum_object, DatumInContext):
raise JsonValidatorError("Nothing found by the given json-path")
path = d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sanitize(value):
'''
Sanitizes strings according to SANITIZER_ALLOWED_TAGS,
SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in
settings.
Example usage:
{% load sanitizer %}
{{ post.content|escape_html }}
'''
if isinstance(value, basestring):
value =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def strip_filter(value):
'''
Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS,
SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in
settings.
Example usage:
{% load sanitizer %}
{{ post.content|strip_html }}
'''
if isinstance(value, basestring):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def escape_html(value, allowed_tags=[], allowed_attributes=[], allowed_styles=[]):
""" Template tag to sanitize string values. It accepts lists of allowed tags, ... |
if isinstance(value, basestring):
value = bleach.clean(value, tags=allowed_tags,
attributes=allowed_attributes,
styles=allowed_styles, strip=False)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_html(value, allowed_tags=[], allowed_attributes=[], allowed_styles=[]):
""" Template tag to strip html from string values. It accepts lists of allowed ... |
if isinstance(value, basestring):
value = bleach.clean(value, tags=allowed_tags,
attributes=allowed_attributes,
styles=allowed_styles, strip=True)
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def censor(input_text):
""" Returns the input string with profanity replaced with a random string of characters plucked from the censor_characters pool. """ |
ret = input_text
words = get_words()
for word in words:
curse_word = re.compile(re.escape(word), re.IGNORECASE)
cen = "".join(get_censor_char() for i in list(word))
ret = curse_word.sub(cen, ret)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def convert(csv, json, **kwargs):
'''Convert csv to json.
csv: filename or file-like object
json: filename or file-like object
if csv is '-' or None:
stdin is used for input
if json is '-' or None:
stdout is used for output
'''
csv_local, json_local = None, None
try... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_dicts(self, sentence):
"""Add new sentence to generate dictionaries. :param sentence: A list of strings representing the sentence. """ |
self.dict_generator(sentence=sentence)
self.word_dict, self.char_dict = None, None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_dicts(self, word_dict, char_dict):
"""Set with custom dictionaries. :param word_dict: The word dictionary. :param char_dict: The character dictionary. ""... |
self.word_dict = word_dict
self.char_dict = char_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dicts(self):
"""Get word and character dictionaries. :return word_dict, char_dict: """ |
if self.word_dict is None:
self.word_dict, self.char_dict, self.max_word_len = self.dict_generator(return_dict=True)
return self.word_dict, self.char_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dicts_generator(word_min_freq=4, char_min_freq=2, word_ignore_case=False, char_ignore_case=False):
"""Get word and character dictionaries from sentences.... |
word_count, char_count = {}, {}
def get_dicts(sentence=None,
return_dict=False):
"""Update and return dictionaries for each sentence.
:param sentence: A list of strings representing the sentence.
:param return_dict: Returns the dictionaries if it is True.
:re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_word_list_eng(text):
"""A naive function that extracts English words from raw texts. :param text: The raw text. :return words: A list of strings. """ |
words, index = [''], 0
while index < len(text):
while index < len(text) and ('a' <= text[index] <= 'z' or 'A' <= text[index] <= 'Z'):
words[-1] += text[index]
index += 1
if words[-1]:
words.append('')
while index < len(text) and not ('a' <= text[index... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_embedding_weights_from_file(word_dict, file_path, ignore_case=False):
"""Load pre-trained embeddings from a text file. Each line in the file should look ... |
pre_trained = {}
with codecs.open(file_path, 'r', 'utf8') as reader:
for line in reader:
line = line.strip()
if not line:
continue
parts = line.split()
if ignore_case:
parts[0] = parts[0].lower()
pre_trained[par... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_backends():
"""Loads all backends""" |
global _BACKENDS, _ACTIVE_BACKENDS
try:
from .cffi_backend import CFFIBackend
except ImportError:
pass
else:
_BACKENDS.append(CFFIBackend)
from .ctypes_backend import CTypesBackend
from .null_backend import NullBackend
_BACKENDS.append(CTypesBackend)
_ACTIVE_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_backend(name):
"""Returns the backend by name or raises KeyError""" |
for backend in _BACKENDS:
if backend.NAME == name:
return backend
raise KeyError("Backend %r not available" % name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pprint(obj, file_=None):
"""Prints debug information for various public objects like methods, functions, constructors etc. """ |
if file_ is None:
file_ = sys.stdout
# functions, methods
if callable(obj) and hasattr(obj, "_code"):
obj._code.pprint(file_)
return
# classes
if isinstance(obj, type) and hasattr(obj, "_constructors"):
constructors = obj._constructors
for names, func in s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field_type(info):
"""A field python type""" |
type_ = info.get_type()
cls = get_field_class(type_)
field = cls(info, type_, None)
field.setup()
return field.py_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def child_get(self, child, *prop_names):
"""Returns a list of child property values for the given names.""" |
return [self.child_get_property(child, name) for name in prop_names] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_tag(self, tag_name=None, **properties):
"""Creates a tag and adds it to the tag table of the TextBuffer. :param str tag_name: Name of the new tag, or ... |
tag = Gtk.TextTag(name=tag_name, **properties)
self._get_or_create_tag_table().add(tag)
return tag |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _convert_value(self, column, value):
'''Convert value to a GObject.Value of the expected type'''
if isinstance(value, GObject.Value):
return value
return GObject.Value(self.get_column_type(column), value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_value(self, iter, column, value):
"""Set the value of the child model""" |
# Delegate to child model
iter = self.convert_iter_to_child_iter(iter)
self.get_model().set_value(iter, column, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_foreign_module(namespace):
"""Returns the module or raises ForeignError""" |
if namespace not in _MODULES:
try:
module = importlib.import_module("." + namespace, __package__)
except ImportError:
module = None
_MODULES[namespace] = module
module = _MODULES.get(namespace)
if module is None:
raise ForeignError("Foreign %r struc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_foreign_struct(namespace, name):
"""Returns a ForeignStruct implementation or raises ForeignError""" |
get_foreign_module(namespace)
try:
return ForeignStruct.get(namespace, name)
except KeyError:
raise ForeignError("Foreign %s.%s not supported" % (namespace, name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_foreign(namespace, symbol=None):
"""Raises ImportError if the specified foreign module isn't supported or the needed dependencies aren't installed. e... |
try:
if symbol is None:
get_foreign_module(namespace)
else:
get_foreign_struct(namespace, symbol)
except ForeignError as e:
raise ImportError(e) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create(self, format, args):
"""Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (ar... |
# leaves (simple types)
constructor = self._LEAF_CONSTRUCTORS.get(format[0])
if constructor:
if args is not None:
if not args:
raise TypeError('not enough arguments for GVariant format string')
v = constructor(args[0])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_tuple(self, format, args):
"""Handle the case where the outermost type of format is a tuple.""" |
format = format[1:] # eat the '('
if args is None:
# empty value: we need to call _create() to parse the subtype
rest_format = format
while rest_format:
if rest_format.startswith(')'):
break
rest_format = self._cr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_dict(self, format, args):
"""Handle the case where the outermost type of format is a dict.""" |
builder = None
if args is None or not args[0]:
# empty value: we need to call _create() to parse the subtype,
# and specify the element type precisely
rest_format = self._create(format[2:], None)[1]
rest_format = self._create(rest_format, None)[1]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_array(self, format, args):
"""Handle the case where the outermost type of format is an array.""" |
builder = None
if args is None or not args[0]:
# empty value: we need to call _create() to parse the subtype,
# and specify the element type precisely
rest_format = self._create(format[1:], None)[1]
element_type = format[:len(format) - len(rest_format)]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unpack(self):
"""Decompose a GVariant into a native Python object.""" |
LEAF_ACCESSORS = {
'b': self.get_boolean,
'y': self.get_byte,
'n': self.get_int16,
'q': self.get_uint16,
'i': self.get_int32,
'u': self.get_uint32,
'x': self.get_int64,
't': self.get_uint64,
'h': self.g... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_signature(klass, signature):
"""Return a list of the element signatures of the topmost signature tuple. If the signature is not a tuple, it returns one... |
if signature == '()':
return []
if not signature.startswith('('):
return [signature]
result = []
head = ''
tail = signature[1:-1] # eat the surrounding ()
while tail:
c = tail[0]
head += c
tail = tail[1:]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_from_memory(cls, data):
"""Takes bytes and returns a GITypelib, or raises GIError""" |
size = len(data)
copy = g_memdup(data, size)
ptr = cast(copy, POINTER(guint8))
try:
with gerror(GIError) as error:
return GITypelib._new_from_memory(ptr, size, error)
except GIError:
free(copy)
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_type(cls, ptr):
"""Get the subtype class for a pointer""" |
# fall back to the base class if unknown
return cls.__types.get(lib.g_base_info_get_type(ptr), cls) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_method(info, target_cls, virtual=False, dont_replace=False):
"""Add a method to the target class""" |
# escape before prefixing, like pygobject
name = escape_identifier(info.name)
if virtual:
name = "do_" + name
attr = VirtualMethodAttribute(info, target_cls, name)
else:
attr = MethodAttribute(info, target_cls, name)
if dont_replace and hasattr(target_cls, name):
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def InterfaceAttribute(iface_info):
"""Creates a GInterface class""" |
# Create a new class
cls = type(iface_info.name, (InterfaceBase,), dict(_Interface.__dict__))
cls.__module__ = iface_info.namespace
# GType
cls.__gtype__ = PGType(iface_info.g_type)
# Properties
cls.props = PropertyAttribute(iface_info)
# Signals
cls.signals = SignalsAttribute(i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new_class_from_gtype(gtype):
"""Create a new class for a gtype not in the gir. The caller is responsible for caching etc. """ |
if gtype.is_a(PGType.from_name("GObject")):
parent = gtype.parent.pytype
if parent is None or parent == PGType.from_name("void"):
return
interfaces = [i.pytype for i in gtype.interfaces]
bases = tuple([parent] + interfaces)
cls = type(gtype.name, bases, dict())... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ObjectAttribute(obj_info):
"""Creates a GObject class. It inherits from the base class and all interfaces it implements. """ |
if obj_info.name == "Object" and obj_info.namespace == "GObject":
cls = Object
else:
# Get the parent class
parent_obj = obj_info.get_parent()
if parent_obj:
attr = import_attribute(parent_obj.namespace, parent_obj.name)
bases = (attr,)
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.