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 _tab_complete_init(items, post_prompt, insensitive, fuzzy, stream):
'''Create and use a tab-completer object'''
# using some sort of nested-scope construct is
# required because readline doesn't pass the necessary args to
# its callback functions
def _get_matches(text, state):
'''
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _fuzzily_matches(response, candidate):
'''return True if response fuzzily matches candidate'''
r_words = response.split()
c_words = candidate.split()
# match whole words first
for word in r_words:
if word in c_words:
r_words.remove(word)
c_words.remove(word)
#... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _exact_fuzzy_match(response, match, insensitive):
'''
Return True if the response matches fuzzily exactly.
Insensitivity is taken into account.
'''
if insensitive:
response = response.lower()
match = match.lower()
r_words = response.split()
m_words = match.split()
# m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _exact_match(response, matches, insensitive, fuzzy):
'''
returns an exact match, if it exists, given parameters
for the match
'''
for match in matches:
if response == match:
return match
elif insensitive and response.lower() == match.lower():
return match
... |
<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_response(response, items, default, indexed, stream, insensitive, fuzzy):
'''Check the response against the items'''
# Set selection
selection = None
# if indexed, check for index
if indexed:
if response.isdigit():
index_response = int(response)
if index_res... |
<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_prompts(pre_prompt, post_prompt):
'''Check that the prompts are strings'''
if not isinstance(pre_prompt, str):
raise TypeError("The pre_prompt was not a string!")
if post_prompt is not _NO_ARG and not isinstance(post_prompt, str):
raise TypeError("The post_prompt was given and was... |
<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_default_index(items, default_index):
'''Check that the default is in the list, and not empty'''
num_items = len(items)
if default_index is not None and not isinstance(default_index, int):
raise TypeError("The default index ({}) is not an integer".format(default_index))
if default_inde... |
<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_stream(stream):
'''Check that the stream is a file'''
if not isinstance(stream, type(_sys.stderr)):
raise TypeError("The stream given ({}) is not a file object.".format(stream)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _dedup(items, insensitive):
'''
Deduplicate an item list, and preserve order.
For case-insensitive lists, drop items if they case-insensitively match
a prior item.
'''
deduped = []
if insensitive:
i_deduped = []
for item in items:
lowered = item.lower()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def menu(items, pre_prompt="Options:", post_prompt=_NO_ARG, default_index=None, indexed=False,
stream=_sys.stderr, insensitive=False, fuzzy=False, quiet=False):
'''
Prompt with a menu.
Arguments:
pre_prompt - Text to print before the option list.
items - The items to print as opt... |
<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_openid(f):
"""Require user to be logged in.""" |
@wraps(f)
def decorator(*args, **kwargs):
if g.user is None:
next_url = url_for("login") + "?next=" + request.url
return redirect(next_url)
else:
return f(*args, **kwargs)
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login():
"""Does the login via OpenID. Has to call into `oid.try_login` to start the OpenID machinery. """ |
# if we are already logged in, go back to were we came from
if g.user is not None:
return redirect(oid.get_next_url())
if request.method == 'POST':
openid = request.form.get('openid')
if openid:
return oid.try_login(openid, ask_for=['email', 'fullname',
... |
<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_output(self, transaction_hash, output_index):
""" Gets an output and information about its asset ID and asset quantity. :param bytes transaction_hash: Th... |
cached_output = yield from self._cache.get(transaction_hash, output_index)
if cached_output is not None:
return cached_output
transaction = yield from self._transaction_provider(transaction_hash)
if transaction is None:
raise ValueError('Transaction {0} could ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def color_transaction(self, transaction):
""" Computes the asset ID and asset quantity of every output in the transaction. :param CTransaction transaction: The t... |
# If the transaction is a coinbase transaction, the marker output is always invalid
if not transaction.is_coinbase():
for i, output in enumerate(transaction.vout):
# Parse the OP_RETURN script
marker_output_payload = MarkerOutput.parse_script(output.scriptPub... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_asset_ids(cls, inputs, marker_output_index, outputs, asset_quantities):
""" Computes the asset IDs of every output in a transaction. :param list[Tra... |
# If there are more items in the asset quantities list than outputs in the transaction (excluding the
# marker output), the marker output is deemed invalid
if len(asset_quantities) > len(outputs) - 1:
return None
# If there is no input in the transaction, the marker output ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hash_script(data):
""" Hashes a script into an asset ID using SHA256 followed by RIPEMD160. :param bytes data: The data to hash. """ |
sha256 = hashlib.sha256()
ripemd = hashlib.new('ripemd160')
sha256.update(data)
ripemd.update(sha256.digest())
return ripemd.digest() |
<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_payload(cls, payload):
""" Deserializes the marker output payload. :param bytes payload: A buffer containing the marker output payload. :return: ... |
with io.BytesIO(payload) as stream:
# The OAP marker and protocol version
oa_version = stream.read(4)
if oa_version != cls.OPEN_ASSETS_TAG:
return None
try:
# Deserialize the expected number of items in the asset quantity list
... |
<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_payload(self):
""" Serializes the marker output data into a payload buffer. :return: The serialized payload. :rtype: bytes """ |
with io.BytesIO() as stream:
stream.write(self.OPEN_ASSETS_TAG)
bitcoin.core.VarIntSerializer.stream_serialize(len(self.asset_quantities), stream)
for asset_quantity in self.asset_quantities:
stream.write(self.leb128_encode(asset_quantity))
bitc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_script(output_script):
""" Parses an output and returns the payload if the output matches the right pattern for a marker output, or None otherwise. :pa... |
script_iterator = output_script.raw_iter()
try:
first_opcode, _, _ = next(script_iterator, (None, None, None))
_, data, _ = next(script_iterator, (None, None, None))
remainder = next(script_iterator, None)
except bitcoin.core.script.CScriptTruncatedPushDataE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_script(data):
""" Creates an output script containing an OP_RETURN and a PUSHDATA. :param bytes data: The content of the PUSHDATA. :return: The final s... |
return bitcoin.core.script.CScript(
bytes([bitcoin.core.script.OP_RETURN]) + bitcoin.core.script.CScriptOp.encode_op_pushdata(data)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def leb128_decode(data):
""" Decodes a LEB128-encoded unsigned integer. :param BufferedIOBase data: The buffer containing the LEB128-encoded integer to decode. :... |
result = 0
shift = 0
while True:
character = data.read(1)
if len(character) == 0:
raise bitcoin.core.SerializationTruncationError('Invalid LEB128 integer')
b = ord(character)
result |= (b & 0x7f) << shift
if b & 0x80 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def leb128_encode(value):
""" Encodes an integer using LEB128. :param int value: The value to encode. :return: The LEB128-encoded integer. :rtype: bytes """ |
if value == 0:
return b'\x00'
result = []
while value != 0:
byte = value & 0x7f
value >>= 7
if value != 0:
byte |= 0x80
result.append(byte)
return bytes(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 run(self):
"""Sends data to the callback functions.""" |
while True:
result = json.loads(self.ws.recv())
if result["cmd"] == "chat" and not result["nick"] == self.nick:
for handler in list(self.on_message):
handler(self, result["text"], result["nick"])
elif result["cmd"] == "onlineAdd":
... |
<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_profile():
"""If this is the user's first login, the create_or_login function will redirect here so that the user can set up his profile. """ |
if g.user is not None or 'openid' not in session:
return redirect(url_for('index'))
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
if not name:
flash(u'Error: you have to provide a name')
elif '@' not in email:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def do_setmode(self, arg):
''' shift from ASM to DISASM '''
op_modes = config.get_op_modes()
if arg in op_modes:
op_mode = op_modes[arg]
op_mode.cmdloop()
else:
print("Error: unknown operational mode, please use 'help setmode'.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace(self, expression, replacements):
""" All purpose method to reduce an expression by applying successive replacement rules. `expression` is either a Sy... |
# When expression is a string,
# get the expressions from self.expressions.
if isinstance(expression, str):
expression = self.expressions[expression]
# Allow for replacements to be empty.
if not replacements:
return expression
# Allow replacemen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _forward(self):
"""Advance to the next token. Internal methods, updates: - self.current_token - self.current_pos Raises: MissingTokensError: when trying to a... |
try:
self.current_token = next(self.tokens)
except StopIteration:
raise MissingTokensError("Unexpected end of token stream at %d." %
self.current_pos)
self.current_pos += 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 consume(self, expect_class=None):
"""Retrieve the current token, then advance the parser. If an expected class is provided, it will assert that the current t... |
if expect_class and not isinstance(self.current_token, expect_class):
raise InvalidTokenError("Unexpected token at %d: got %r, expected %s" % (
self.current_pos, self.current_token, expect_class.__name__))
current_token = self.current_token
self._forward()
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 expression(self, rbp=0):
"""Extract an expression from the flow of tokens. Args: rbp (int):
the "right binding power" of the previous token. This represents... |
prev_token = self.consume()
# Retrieve the value from the previous token situated at the
# leftmost point in the expression
left = prev_token.nud(context=self)
while rbp < self.current_token.lbp:
# Read incoming tokens with a higher 'left binding power'.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self):
"""Parse the flow of tokens, and return their evaluation.""" |
expr = self.expression()
if not isinstance(self.current_token, EndToken):
raise InvalidTokenError("Unconsumed trailing tokens.")
return expr |
<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_cached_value(self, *args, **kwargs):
""" Sets the cached value """ |
key = self.get_cache_key(*args, **kwargs)
logger.debug(key)
return namedtuple('Settable', ['to'])(lambda value: self.cache.set(key, 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 devserver(arguments):
"""Run a development server.""" |
import coil.web
if coil.web.app:
port = int(arguments['--port'])
url = 'http://localhost:{0}/'.format(port)
coil.web.configure_url(url)
coil.web.app.config['DEBUG'] = True
if arguments['--browser']:
webbrowser.open(url)
coil.web.app.logger.info("Coi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unlock(arguments):
"""Unlock the database.""" |
import redis
u = coil.utils.ask("Redis URL", "redis://localhost:6379/0")
db = redis.StrictRedis.from_url(u)
db.set('site:lock', 0)
print("Database unlocked.")
return 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 expr(self, token_stream, token):
"""Top level parsing function. An expression is <keyword> <OR> <expr> or <keyword> <SEP> <expr> or <keyword> """ |
lval = self.keyword(token_stream, token, {})
token = next(token_stream)
if token[0] == 'OR':
op = or_
token = next(token_stream)
elif token[0] == 'TEXT' or token[0] == 'COLOR':
op = lambda l, r: list(flatten([l, r]))
elif token[0] == 'SEPARATO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def keyword(self, token_stream, token, operators):
"""Lowest level parsing function. A keyword consists of zero or more prefix operators (NOT, or COMPARISON) fol... |
if token[0] == 'TEXT' or token[0] == 'COLOR':
return SearchKeyword(token[1], **operators)
elif token[0] == 'COMPARISON':
operators['comparison'] = token[1]
elif token[0] == 'NOT':
operators['boolean'] = 'not'
else:
if token[1] == 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 parse(self, text):
"""Parse the given text, return a list of Keywords.""" |
token_stream = self.lexer.tokenize(text)
return self.expr(token_stream, next(token_stream)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def customProperties(self):
"""Document custom properties added by the document author. We canot convert the properties as indicated with the http://schemas.open... |
rval = {}
if len(self.content_types.getPathsForContentType(contenttypes.CT_CUSTOM_PROPS)) == 0:
# We may have no custom properties at all.
return rval
XPath = lxml.etree.XPath # Class shortcut
properties_xpath = XPath('custom-properties:property', namespaces=ns_m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def allProperties(self):
"""Helper that merges core, extended and custom properties :return: mapping of all properties """ |
rval = {}
rval.update(self.coreProperties)
rval.update(self.extendedProperties)
rval.update(self.customProperties)
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 documentCover(self):
"""Cover page image :return: (file extension, file object) tuple. """ |
rels_pth = os.path.join(self._cache_dir, "_rels", ".rels")
rels_xml = lxml.etree.parse(xmlFile(rels_pth, 'rb'))
thumb_ns = ns_map["thumbnails"]
thumb_elm_xpr = "relationships:Relationship[@Type='%s']" % thumb_ns
rels_xpath = lxml.etree.XPath(thumb_elm_xpr, namespaces=ns_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 indexableText(self, include_properties=True):
"""Words found in the various texts of the document. :param include_properties: Adds words from properties :ret... |
text = set()
for extractor in self._text_extractors:
if extractor.content_type in self.content_types.overrides:
for tree in self.content_types.getTreesFor(self, extractor.content_type):
words = extractor.indexableText(tree)
text |= wor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def canProcessFilename(cls, filename):
"""Check if we can process such file based on name :param filename: File name as 'mydoc.docx' :return: True if we can proc... |
supported_patterns = cls._extpattern_to_mime.keys()
for pattern in supported_patterns:
if fnmatch.fnmatch(filename, pattern):
return True
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 register(self, token, regexp):
"""Register a token. Args: token (Token):
the token class to register regexp (str):
the regexp for that token """ |
self._tokens.append((token, re.compile(regexp))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def matching_tokens(self, text, start=0):
"""Retrieve all token definitions matching the beginning of a text. Args: text (str):
the text to test start (int):
t... |
for token_class, regexp in self._tokens:
match = regexp.match(text, pos=start)
if match:
yield token_class, match |
<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_token(self, text, start=0):
"""Retrieve the next token from some text. Args: text (str):
the text from which tokens should be extracted Returns: (token_... |
best_class = best_match = None
for token_class, match in self.matching_tokens(text):
if best_match and best_match.end() >= match.end():
continue
best_match = match
best_class = token_class
return best_class, best_match |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_token(self, token_class, regexp=None):
"""Register a token class. Args: token_class (tdparser.Token):
the token class to register regexp (optional ... |
if regexp is None:
regexp = token_class.regexp
self.tokens.register(token_class, regexp) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lex(self, text):
"""Split self.text into a list of tokens. Args: text (str):
text to parse Yields: Token: the tokens generated from the given text. """ |
pos = 0
while text:
token_class, match = self.tokens.get_token(text)
if token_class is not None:
matched_text = text[match.start():match.end()]
yield token_class(matched_text)
text = text[match.end():]
pos += match.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, text):
"""Parse self.text. Args: text (str):
the text to lex Returns: object: a node representing the current rule. """ |
tokens = self.lex(text)
parser = Parser(tokens)
return parser.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 save_example_fit(fit):
""" Save fit result to a json file and a plot to an svg file. """ |
json_directory = os.path.join('examples', 'json')
plot_directory = os.path.join('examples', 'plots')
if not os.path.isdir(json_directory): os.makedirs(json_directory)
if not os.path.isdir(plot_directory): os.makedirs(plot_directory)
fit.to_json(os.path.join(json_directory, fit.name + '.json'), met... |
<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_directory(directory):
""" Remove `directory` if it exists, then create it if it doesn't exist. """ |
if os.path.isdir(directory): shutil.rmtree(directory)
if not os.path.isdir(directory): os.makedirs(directory) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maps(self):
""" A dictionary of dictionaries. Each dictionary defines a map which is used to extend the metadata. The precise way maps interact with the meta... |
if not hasattr(self, '_maps'):
maps = {}
maps['tex_symbol'] = {}
maps['siunitx'] = {}
maps['value_transforms'] = {
'__default__': lambda x: round(x, 2),
}
self._maps = maps
return self._maps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getTreesFor(self, document, content_type):
"""Provides all XML documents for that content type @param document: a Document or subclass object @param content_... |
# Relative path without potential leading path separator
# otherwise os.path.join doesn't work
for rel_path in self.overrides[content_type]:
if rel_path[0] in ('/', '\\'):
rel_path = rel_path[1:]
file_path = os.path.join(document._cache_dir, rel_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 listMetaContentTypes(self):
"""The content types with metadata """ |
all_md_content_types = (
CT_CORE_PROPS,
CT_EXT_PROPS,
CT_CUSTOM_PROPS)
return [k for k in self.overrides.keys() if k in all_md_content_types] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_number_converter(number_str):
""" Converts the string representation of a json number into its python object equivalent, an int, long, float or whate... |
is_int = (number_str.startswith('-') and number_str[1:].isdigit()) or number_str.isdigit()
# FIXME: this handles a wider range of numbers than allowed by the json standard,
# etc.: float('nan') and float('inf'). But is this a problem?
return int(number_str) if is_int else float(number_str) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, path, **kwargs):
""" Save the plot to the file at `path`. Any keyword arguments are passed to [`matplotlib.pyplot.savefig`][1]. [1]: http://matplo... |
self.plot if not hasattr(self, '_plot') else None
self.figure.savefig(path, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(cls, filename):
""" Load ACCESS_KEY_ID and SECRET_ACCESS_KEY from csv generated by Amazon's IAM. """ |
import csv
with open(filename, 'r') as f:
reader = csv.DictReader(f)
row = reader.next() # Only one row in the file
try:
cls.ACCESS_KEY_ID = row['Access Key Id']
cls.SECRET_ACCESS_KEY = row['Secret Access Key']
except KeyError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(dburl, sitedir, mode):
"""Build a site.""" |
if mode == 'force':
amode = ['-a']
else:
amode = []
oldcwd = os.getcwd()
os.chdir(sitedir)
db = StrictRedis.from_url(dburl)
job = get_current_job(db)
job.meta.update({'out': '', 'milestone': 0, 'total': 1, 'return': None,
'status': None})
job.save()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def orphans(dburl, sitedir):
"""Remove all orphans in the site.""" |
oldcwd = os.getcwd()
os.chdir(sitedir)
db = StrictRedis.from_url(dburl)
job = get_current_job(db)
job.meta.update({'out': '', 'return': None, 'status': None})
job.save()
returncode, out = orphans_single(default_exec=True)
job.meta.update({'out': out, 'return': returncode, 'status':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_single(mode):
"""Build, in the single-user mode.""" |
if mode == 'force':
amode = ['-a']
else:
amode = []
if executable.endswith('uwsgi'):
# hack, might fail in some environments!
_executable = executable[:-5] + 'python'
else:
_executable = executable
p = subprocess.Popen([_executable, '-m', 'nikola', 'build'] +... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def orphans_single(default_exec=False):
"""Remove all orphans in the site, in the single user-mode.""" |
if not default_exec and executable.endswith('uwsgi'):
# default_exec => rq => sys.executable is sane
_executable = executable[:-5] + 'python'
else:
_executable = executable
p = subprocess.Popen([_executable, '-m', 'nikola', 'orphans'],
stdout=subprocess.PIPE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_data(self):
""" Add the data points to the plot. """ |
self.plt.plot(*self.fit.data, **self.options['data']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_fit(self):
""" Add the fit to the plot. """ |
self.plt.plot(*self.fit.fit, **self.options['fit']) |
<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_xlabel(self, text=None):
""" Add a label to the x-axis. """ |
x = self.fit.meta['independent']
if not text:
text = '$' + x['tex_symbol'] + r'$ $(\si{' + x['siunitx'] + r'})$'
self.plt.set_xlabel(text) |
<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_ylabel(self, text=None):
""" Add a label to the y-axis. """ |
y = self.fit.meta['dependent']
if not text:
text = '$' + y['tex_symbol'] + r'$ $(\si{' + y['siunitx'] + r'})$'
self.plt.set_ylabel(text) |
<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_text_table(self, rows, r0, dr, **kwargs):
""" Add text to a plot in a grid fashion. `rows` is a list of lists (the rows). Each row contains the columns, ... |
for m, row in enumerate(rows):
for n, column in enumerate(row):
self.plt.text(r0[0] + dr[0] * n, r0[1] + dr[1] * m, column,
transform=self.plt.axes.transAxes, **kwargs) |
<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_redirect_url(self, request):
""" Next gathered from session, then GET, then POST, then users absolute url. """ |
if 'next' in request.session:
next_url = request.session['next']
del request.session['next']
elif 'next' in request.GET:
next_url = request.GET.get('next')
elif 'next' in request.POST:
next_url = request.POST.get('next')
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 indexableText(self, tree):
"""Provides the indexable - search engine oriented - raw text @param tree: an ElementTree """ |
rval = set()
root = tree.getroot()
for txp in self.text_elts_xpaths:
elts = txp(root)
texts = []
# Texts in element may be empty
for elt in elts:
text = self.text_extract_xpath(elt)
if len(text) > 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 _flatten(self, element):
"""Recursively enter and extract text from all child elements.""" |
result = [(element.text or '')]
if element.attrib.get('alt'):
result.append(Symbol(element.attrib.get('alt')).textbox)
for sel in element:
result.append(self._flatten(sel))
result.append(sel.tail or '')
# prevent reminder text from getting too close ... |
<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_storage(self):
'''Get the storage instance.
:return Redis: Redis instance
'''
if self.storage:
return self.storage
self.storage = self.reconnect_redis()
return self.storage |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def on_redis_error(self, fname, exc_type, exc_value):
'''Callback executed when there is a redis error.
:param string fname: Function name that was being called.
:param type exc_type: Exception type
:param Exception exc_value: The current exception
:returns: Default value or rai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configure_url(url):
"""Configure site URL.""" |
app.config['COIL_URL'] = \
_site.config['SITE_URL'] = _site.config['BASE_URL'] =\
_site.GLOBAL_CONTEXT['blog_url'] =\
site.config['SITE_URL'] = site.config['BASE_URL'] =\
url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def password_hash(password):
"""Hash the password, using bcrypt+sha256. .. versionchanged:: 1.1.0 :param str password: Password in plaintext :return: password ha... |
try:
return bcrypt_sha256.encrypt(password)
except TypeError:
return bcrypt_sha256.encrypt(password.decode('utf-8')) |
<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_menu():
"""Generate ``menu`` with the rebuild link. :return: HTML fragment :rtype: str """ |
if db is not None:
needs_rebuild = db.get('site:needs_rebuild')
else:
needs_rebuild = site.coil_needs_rebuild
if needs_rebuild not in (u'0', u'-1', b'0', b'-1'):
return ('</li><li><a href="{0}"><i class="fa fa-fw '
'fa-warning"></i> <strong>Rebuild</strong></a></li>'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _author_uid_get(post):
"""Get the UID of the post author. :param Post post: The post object to determine authorship of :return: Author UID :rtype: str """ |
u = post.meta('author.uid')
return u if u else str(current_user.uid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(template_name, context=None, code=200, headers=None):
"""Render a response using standard Nikola templates. :param str template_name: Template name :p... |
if context is None:
context = {}
if headers is None:
headers = {}
context['g'] = g
context['request'] = request
context['session'] = session
context['current_user'] = current_user
context['_author_get'] = _author_get
context['_author_uid_get'] = _author_uid_get
if a... |
<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_user(uid):
"""Get an user by the UID. :param str uid: UID to find :return: the user :rtype: User object :raises ValueError: uid is not an integer :raises... |
if db is not None:
try:
uid = uid.decode('utf-8')
except AttributeError:
pass
d = db.hgetall('user:{0}'.format(uid))
if d:
nd = {}
# strings everywhere
for k in d:
try:
nd[k.decode('utf-8... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_user_by_name(username):
"""Get an user by their username. :param str username: Username to find :return: the user :rtype: User object or None """ |
if db is not None:
uid = db.hget('users', username)
if uid:
return get_user(uid)
else:
for uid, u in app.config['COIL_USERS'].items():
if u['username'] == username:
return get_user(uid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_user(user):
"""Write an user ot the database. :param User user: User to write """ |
udata = {}
for f in USER_FIELDS:
udata[f] = getattr(user, f)
for p in PERMISSIONS:
udata[p] = '1' if getattr(user, p) else '0'
db.hmset('user:{0}'.format(user.uid), udata) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login():
"""Handle user authentication. If requested over GET, present login page. If requested over POST, log user in. :param str status: Status of previous... |
alert = None
alert_status = 'danger'
code = 200
captcha = app.config['COIL_LOGIN_CAPTCHA']
form = LoginForm()
if request.method == 'POST':
if form.validate():
user = find_user_by_name(request.form['username'])
if not user:
alert = 'Invalid credent... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index():
"""Show the index with all posts. :param int all: Whether or not should show all posts """ |
context = {'postform': NewPostForm(),
'pageform': NewPageForm(),
'delform': DeleteForm()}
n = request.args.get('all')
if n is None:
wants_now = None
else:
wants_now = n == '1'
if wants_now is None and current_user.wants_all_posts:
wants = True... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rebuild(mode=''):
"""Rebuild the site with a nice UI.""" |
scan_site() # for good measure
if not current_user.can_rebuild_site:
return error('You are not permitted to rebuild the site.</p>'
'<p class="lead">Contact an administartor for '
'more information.', 401)
if db is not None:
db.set('site:needs_rebui... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serve_bower_components(path):
"""Serve bower components. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle... |
res = pkg_resources.resource_filename(
'coil', os.path.join('data', 'bower_components'))
return send_from_directory(res, 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 serve_coil_assets(path):
"""Serve Coil assets. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests ... |
res = pkg_resources.resource_filename(
'coil', os.path.join('data', 'coil_assets'))
return send_from_directory(res, 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 serve_assets(path):
"""Serve Nikola assets. This is meant to be used ONLY by the internal dev server. Please configure your web server to handle requests to ... |
res = os.path.join(app.config['NIKOLA_ROOT'],
_site.config["OUTPUT_FOLDER"], 'assets')
return send_from_directory(res, 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 acp_account():
"""Manage the user account of currently-logged-in users. This does NOT accept admin-specific options. """ |
if request.args.get('status') == 'pwdchange':
alert = 'You must change your password before proceeding.'
alert_status = 'danger'
pwdchange_skip = True
else:
alert = ''
alert_status = ''
pwdchange_skip = False
if db is None:
form = PwdHashForm()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acp_users_edit():
"""Edit an user account.""" |
global current_user
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
data = request.form
form = UserEditForm()
if not form.validate():
return error("Bad 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 acp_users_import():
"""Import users from a TSV file.""" |
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = UserImportForm()
if not form.validate():
return error("Bad Request", 400)
fh = request.files['tsv'].stream
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def acp_users_delete():
"""Delete or undelete an user account.""" |
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = UserDeleteForm()
if not form.validate():
return error("Bad Request", 400)
user = get_user(int(request.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 acp_users_permissions():
"""Change user permissions.""" |
if not current_user.is_admin:
return error("Not authorized to edit users.", 401)
if not db:
return error('The ACP is not available in single-user mode.', 500)
form = PermissionsForm()
users = []
uids = db.hgetall('users').values()
if request.method == 'POST':
if not for... |
<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_installed():
# type: () -> bool """ Returns whether the C extension is installed correctly. """ |
try:
# noinspection PyUnresolvedReferences
from ccurl import Curl as CCurl
except ImportError:
return False
else:
# noinspection PyUnresolvedReferences
from iota.crypto import Curl
return issubclass(Curl, CCurl) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def make_compare(key, value, obj):
"Map a key name to a specific comparison function"
if '__' not in key:
# If no __ exists, default to doing an "exact" comparison
key, comp = key, 'exact'
else:
key, comp = key.rsplit('__', 1)
# Check if comp is valid
if hasattr(Compare, comp... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mock_attr(self, *args, **kwargs):
""" Empty method to call to slurp up args and kwargs. `args` get pushed onto the url path. `kwargs` are converted to a quer... |
self.path.extend(args)
self.qs.update(kwargs)
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 column(self):
""" Returns the zero based column number based on the current position of the parser. """ |
for i in my_xrange(self._column_query_pos, self.pos):
if self.text[i] == '\t':
self._column += self.tab_size
self._column -= self._column % self.tab_size
else:
self._column += 1
self._column_query_pos = self.pos
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 peek(self, offset=0):
""" Looking forward in the input text without actually stepping the current position. returns None if the current position is at the en... |
pos = self.pos + offset
if pos >= self.end:
return None
return self.text[pos] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ask(query, default=None):
"""Ask a question.""" |
if default:
default_q = ' [{0}]'.format(default)
else:
default_q = ''
if sys.version_info[0] == 3:
inp = input("{query}{default_q}: ".format(
query=query, default_q=default_q)).strip()
else:
inp = raw_input("{query}{default_q}: ".format(
query=que... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload_site(self):
"""Reload the site from the database.""" |
rev = int(self.db.get('site:rev'))
if rev != self.revision and self.db.exists('site:rev'):
timeline = self.db.lrange('site:timeline', 0, -1)
self._timeline = []
for data in timeline:
data = json.loads(data.decode('utf-8'))
self._timeli... |
<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_indexlist(self, name):
"""Read a list of indexes.""" |
setattr(self, '_' + name, [self._timeline[int(i)] for i in
self.db.lrange('site:{0}'.format(name), 0,
-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 _write_indexlist(self, name):
"""Write a list of indexes.""" |
d = [self._site.timeline.index(p) for p in getattr(self._site, name)]
self.db.delete('site:{0}'.format(name))
if d:
self.db.rpush('site:{0}'.format(name), *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 scan_posts(self, really=True, ignore_quit=False, quiet=True):
"""Rescan the site.""" |
while (self.db.exists('site:lock') and
int(self.db.get('site:lock')) != 0):
self.logger.info("Waiting for DB lock...")
time.sleep(0.5)
self.db.incr('site:lock')
self.logger.info("Lock acquired.")
self.logger.info("Scanning site...")
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 timeline(self):
"""Get timeline, reloading the site if needed.""" |
rev = int(self.db.get('site:rev'))
if rev != self.revision:
self.reload_site()
return self._timeline |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def posts(self):
"""Get posts, reloading the site if needed.""" |
rev = int(self.db.get('site:rev'))
if rev != self.revision:
self.reload_site()
return self._posts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.