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): ''' Get a valid match, given: text - the portion of text currently trying to complete state - the index 0..inf which is an index into the list of valid matches. Put another way, given the text, this function is supposed to return matches_for(text)[state], where 'matches_for' returns the matches for the text from the options. ''' # a copy of all the valid options options = [o for o in items] # the full user-entered text full_text = _readline.get_line_buffer() # insensitivity if insensitive: options = [o.lower() for o in options] text = text.lower() full_text = full_text.lower() # matches matches = [] try: # get matches if fuzzy: # space-delimited - match words _readline.set_completer_delims(' ') matches = _get_fuzzy_tc_matches(text, full_text, options) else: # not delimited - match the whole text _readline.set_completer_delims('') matches = _get_standard_tc_matches(text, full_text, options) # re-sensitization not necessary - this completes what's on # the command prompt. If the search is insensitive, then # a lower-case entry will match as well as an original-case # entry. except Exception: # try/catch is for debugging only. The readline # lib swallows exceptions and just doesn't print anything import traceback as _traceback print(_traceback.format_exc()) raise return matches[state] def _completion_display(substitution, matches, length): ''' Display the matches for the substitution, which is the text being completed. ''' try: response = substitution stream.write("\n[!] \"{response}\" matches multiple options:\n".format( response=response )) if fuzzy: if insensitive: ordered_matches = [o for o in items if substitution in o.lower()] else: ordered_matches = [o for o in items if substitution in o] else: if insensitive: ordered_matches = [o for o in items if o.lower().startswith(substitution)] else: ordered_matches = [o for o in items if o.startswith(substitution)] for match in ordered_matches: stream.write("[!] {}\n".format(match)) stream.write("[!] Please specify your choice further.\n") # the full user-entered text full_text = _readline.get_line_buffer() stream.write(post_prompt + full_text) stream.flush() except Exception: # try/catch is for debugging only. The readline # lib swallows exceptions and just doesn't print anything #import traceback as _traceback #print(_traceback.format_exc()) raise # activate tab completion # got libedit bit from: # https://stackoverflow.com/a/7116997 # ----------------------------------- if "libedit" in _readline.__doc__: # tabcompletion init for libedit _readline.parse_and_bind("bind ^I rl_complete") else: # tabcompletion init for actual readline _readline.parse_and_bind("tab: complete") # ----------------------------------- # set the function that will actually provide the valid completions _readline.set_completer(_get_matches) # set the function that will display the valid completions _readline.set_completion_display_matches_hook(_completion_display)
<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) # match partial words, fewest matches first match_pairs = [] for partial in sorted(r_words, key=lambda p: len(p), reverse=True): matches = [w for w in c_words if partial in w] match_pairs.append((partial, matches)) # if all items can be uniquly matched, the match is passed while len(match_pairs): min_pair = min(match_pairs, key=lambda x:len(x[1])) # this is the partial and matches with the shortest match list # if there are ever no matches for something, the match is failed if len(min_pair[1]) == 0: return False # choose the match with the fewest matches to remaining partials. # that way we leave more options for more partials, for the best # chance of a full match partials_left = [p[0] for p in match_pairs] min_option = min(min_pair[1], key=lambda x:len([p for p in partials_left if x in p])) # remove the current pair - we've matched it now match_pairs.remove(min_pair) # remove the matched option from all pairs' options so it won't be matched again for pair in match_pairs: pair_options = pair[1] if min_option in pair_options: pair_options.remove(min_option) # if all the items in the response were matched, this is match return 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 _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() # match whole words first for word in r_words: if word in m_words: r_words.remove(word) m_words.remove(word) # no partial matches allowed # if all the items in the response were matched, # and all the items in the match were matched, # then this is an exact fuzzy match return len(r_words) == 0 and len(m_words) == 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 _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 elif fuzzy and _exact_fuzzy_match(response, match, insensitive): return match else: return 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 _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_response < len(items): selection = items[index_response] # if not matched by an index, match by text if selection is None: # insensivitize, if necessary original_items = items[:] original_response = response if insensitive: response = response.lower() items = [i.lower() for i in items] # Check for text matches if fuzzy: matches = _get_fuzzy_matches(response, items) # if insensitive, lowercase the comparison else: matches = [i for i in items if i.startswith(response)] # re-sensivitize if necessary if insensitive: matches = [ i for i in original_items if i.lower() in matches ] response = original_response num_matches = len(matches) # Empty response, no default if response == '' and default is None: stream.write("[!] an empty response is not valid.\n") elif response == '': selection = default # Bad response elif num_matches == 0: stream.write("[!] \"{response}\" does not match any of the valid choices.\n".format( response=response )) # One match elif num_matches == 1: selection = matches[0] # Multiple matches else: # look for an exact match selection = _exact_match(response, matches, insensitive, fuzzy) # Multiple matches left if selection is None: stream.write("[!] \"{response}\" matches multiple choices:\n".format( response=response )) for match in matches: stream.write("[!] {}\n".format(match)) stream.write("[!] Please specify your choice further.\n") return selection
<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 not a string!")
<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_index is not None and default_index >= num_items: raise ValueError("The default index ({}) >= length of the list ({})".format(default_index, num_items)) if default_index is not None and default_index < 0: raise ValueError("The default index ({}) < 0.".format(default_index)) if default_index is not None and not items[default_index]: raise ValueError("The default index ({}) points to an empty item.".format(default_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 _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() if lowered not in i_deduped: deduped.append(item) i_deduped.append(lowered) else: for item in items: if item not in deduped: deduped.append(item) return deduped
<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 options. post_prompt - Text to print after the option list. default_index - The index of the item which should be default, if any. indexed - Boolean. True if the options should be indexed. stream - the stream to use to prompt the user. Defaults to stderr so that stdout can be reserved for program output rather than interactive menu output. insensitive - allow insensitive matching. Also drops items which case-insensitively match prior items. fuzzy - search for the individual words in the user input anywhere in the item strings. Specifying a default index: The default index must index into the items. In other words, `items[default_index]` must exist. It is encouraged, but not required, that you show the user that there is a default, and what it is, via string interpolation in either of the prompts: "prompt [{}]" as the prompt string will print "prompt [default]" if "default" were the value of the item at the default index. The default post-prompt: The default post prompt is different depending on whether or not you provide a default_index. If you don't, the prompt is just "Enter an option to continue: ". If you do, the prompt adds the default value: "Enter an option to continue [{}]: " Return: result - The full text of the unambiguously selected item. ''' # arg checking _check_prompts(pre_prompt, post_prompt) _check_items(items) _check_default_index(items, default_index) _check_stream(stream) # arg mapping # - Fill in post-prompt dynamically if no arg actual_post_prompt = post_prompt if post_prompt is _NO_ARG: if default_index is None: actual_post_prompt = "Enter an option to continue: " else: actual_post_prompt = "Enter an option to continue [{}]: " # - convert items to rstripped strings items = [str(i).rstrip() for i in items] # - set the default argument default = None if default_index is not None: default = items[default_index] # - deduplicate items items = _dedup(items, insensitive) # - remove empty options items = [i for i in items if i] # - re-check the items _check_items(items) # other state init acceptable_response_given = False if _readline is None: stream.write('[!] readline library not present - tab completion not available\n') stream.write('[!] readline library not present - arrow support not available\n') elif not stream.isatty(): stream.write('[!] output stream is not interactive - tab completion not available\n') stream.write('[!] output stream is not interactive - arrow support not available\n') elif _sys.version_info.major == 3 and stream is not _sys.stdout: stream.write('[!] python3 input bug (issue24402) - tab completion not available\n') stream.write('[!] python3 input bug (issue24402) - arrow support not available\n') stream.write('[!] set sys.stdout as the stream to work around\n') else: _tab_complete_init(items, actual_post_prompt, insensitive, fuzzy, stream) # Set both stdout and stderr to the stream selected. # - in py2, raw_input uses sys.stdout # - in py3, input uses a lower-level stdout stream which is not redirectable. # - there is an open bug for this, scheduled to be resolved in py3.6 (https://bugs.python.org/issue24402) # [raw_]input uses readline to do fancy things like tab completion, and also like reprinting the user # text on the cli when you type. If we don't redirect the output streams, [raw_]input will always use # the default (stdout) even though most of the time we want stderr for interactive prompts. we could just # print the prompt ourselves (and not let [raw_]input do so), but only when we control reprinting (which # we don't always for tab completion), and even then, if the user backspaces into the prompt, [raw_]input # would reprint the line itself, erasing the prompt it doesn't know about. (see issue #70) try: _old_stdout = _sys.stdout _old_stderr = _sys.stderr # only overwrite the stream if we need to, due to the python3 issue if stream is _sys.stdout: pass else: _sys.stdout = stream # Prompt Loop # - wait until an acceptable response has been given while not acceptable_response_given: selection = None # Prompt and get response response = _prompt(pre_prompt, items, actual_post_prompt, default, indexed, stream) # validate response selection = _check_response(response, items, default, indexed, stream, insensitive, fuzzy) # NOTE: acceptable response logic is purposely verbose to be clear about the semantics. if selection is not None: acceptable_response_given = True finally: _sys.stdout = _old_stdout _sys.stderr = _old_stderr return selection
<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', 'nickname']) return render_template('login.html', next=oid.get_next_url(), error=oid.fetch_error())
<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: The hash of the transaction containing the output. :param int output_index: The index of the output. :return: An object containing the output as well as its asset ID and asset quantity. :rtype: Future[TransactionOutput] """
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 not be retrieved'.format(bitcoin.core.b2lx(transaction_hash))) colored_outputs = yield from self.color_transaction(transaction) for index, output in enumerate(colored_outputs): yield from self._cache.put(transaction_hash, index, output) return colored_outputs[output_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 color_transaction(self, transaction): """ Computes the asset ID and asset quantity of every output in the transaction. :param CTransaction transaction: The transaction to color. :return: A list containing all the colored outputs of the transaction. :rtype: Future[list[TransactionOutput]] """
# 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.scriptPubKey) if marker_output_payload is not None: # Deserialize the payload as a marker output marker_output = MarkerOutput.deserialize_payload(marker_output_payload) if marker_output is not None: # Fetch the colored outputs for previous transactions inputs = [] for input in transaction.vin: inputs.append((yield from asyncio.async( self.get_output(input.prevout.hash, input.prevout.n), loop=self._loop))) asset_ids = self._compute_asset_ids( inputs, i, transaction.vout, marker_output.asset_quantities) if asset_ids is not None: return asset_ids # If no valid marker output was found in the transaction, all outputs are considered uncolored return [ TransactionOutput(output.nValue, output.scriptPubKey, None, 0, OutputType.uncolored) for output in transaction.vout]
<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[TransactionOutput] inputs: The outputs referenced by the inputs of the transaction. :param int marker_output_index: The position of the marker output in the transaction. :param list[CTxOut] outputs: The outputs of the transaction. :param list[int] asset_quantities: The list of asset quantities of the outputs. :return: A list of outputs with asset ID and asset quantity information. :rtype: list[TransactionOutput] """
# 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 is always invalid if len(inputs) == 0: return None result = [] # Add the issuance outputs issuance_asset_id = cls.hash_script(bytes(inputs[0].script)) for i in range(0, marker_output_index): value, script = outputs[i].nValue, outputs[i].scriptPubKey if i < len(asset_quantities) and asset_quantities[i] > 0: output = TransactionOutput(value, script, issuance_asset_id, asset_quantities[i], OutputType.issuance) else: output = TransactionOutput(value, script, None, 0, OutputType.issuance) result.append(output) # Add the marker output issuance_output = outputs[marker_output_index] result.append(TransactionOutput( issuance_output.nValue, issuance_output.scriptPubKey, None, 0, OutputType.marker_output)) # Add the transfer outputs input_iterator = iter(inputs) input_units_left = 0 for i in range(marker_output_index + 1, len(outputs)): if i <= len(asset_quantities): output_asset_quantity = asset_quantities[i - 1] else: output_asset_quantity = 0 output_units_left = output_asset_quantity asset_id = None while output_units_left > 0: # Move to the next input if the current one is depleted if input_units_left == 0: current_input = next(input_iterator, None) if current_input is None: # There are less asset units available in the input than in the outputs: # the marker output is considered invalid return None else: input_units_left = current_input.asset_quantity # If the current input is colored, assign its asset ID to the current output if current_input.asset_id is not None: progress = min(input_units_left, output_units_left) output_units_left -= progress input_units_left -= progress if asset_id is None: # This is the first input to map to this output asset_id = current_input.asset_id elif asset_id != current_input.asset_id: # Another different asset ID has already been assigned to that output: # the marker output is considered invalid return None result.append(TransactionOutput( outputs[i].nValue, outputs[i].scriptPubKey, asset_id, output_asset_quantity, OutputType.transfer)) return 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 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: The marker output object. :rtype: MarkerOutput """
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 output_count = bitcoin.core.VarIntSerializer.stream_deserialize(stream) # LEB128-encoded unsigned integers representing the asset quantity of every output in order asset_quantities = [] for i in range(0, output_count): asset_quantity = cls.leb128_decode(stream) # If the LEB128-encoded asset quantity of any output exceeds 9 bytes, # the marker output is deemed invalid if asset_quantity > cls.MAX_ASSET_QUANTITY: return None asset_quantities.append(asset_quantity) # The var-integer encoded length of the metadata field. metadata_length = bitcoin.core.VarIntSerializer.stream_deserialize(stream) # The actual metadata metadata = stream.read(metadata_length) # If the metadata string wasn't long enough, the marker output is malformed if len(metadata) != metadata_length: return None # If there are bytes left to read, the marker output is malformed last_byte = stream.read(1) if len(last_byte) > 0: return None except bitcoin.core.SerializationTruncationError: return None return MarkerOutput(asset_quantities, metadata)
<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)) bitcoin.core.VarIntSerializer.stream_serialize(len(self.metadata), stream) stream.write(self.metadata) return stream.getvalue()
<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. :param CScript output_script: The output script to be parsed. :return: The marker output payload if the output fits the pattern, None otherwise. :rtype: bytes """
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.CScriptTruncatedPushDataError: return None except bitcoin.core.script.CScriptInvalidError: return None if first_opcode == bitcoin.core.script.OP_RETURN and data is not None and remainder is None: return data else: return 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 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 script. :rtype: CScript """
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. :return: The decoded integer. :rtype: int """
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 == 0: break shift += 7 return 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 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": self.online_users.append(result["nick"]) for handler in list(self.on_join): handler(self, result["nick"]) elif result["cmd"] == "onlineRemove": self.online_users.remove(result["nick"]) for handler in list(self.on_leave): handler(self, result["nick"]) elif result["cmd"] == "onlineSet": for nick in result["nicks"]: self.online_users.append(nick)
<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: flash(u'Error: you have to enter a valid email address') else: flash(u'Profile successfully created') User.get_collection().insert(User(name, email, session['openid'])) return redirect(oid.get_next_url()) return render_template('create_profile.html', next_url=oid.get_next_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 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 SymPy expression or a key in `scipy_data_fitting.Model.expressions`. `replacements` can be any of the following, or a list of any combination of the following: - A replacement tuple as in `scipy_data_fitting.Model.replacements`. - The name of a replacement in `scipy_data_fitting.Model.replacements`. - The name of a replacement group in `scipy_data_fitting.Model.replacement_groups`. Examples: #!python z + y """
# 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 replacements to be a string. if isinstance(replacements, str): if replacements in self.replacements: return self.replace(expression, self.replacements[replacements]) elif replacements in self.replacement_groups: return self.replace(expression, self.replacement_groups[replacements]) # When replacements is a list of strings or tuples, # Use reduce to make all the replacements. if all(isinstance(item, str) for item in replacements) \ or all(isinstance(item, tuple) for item in replacements): return functools.reduce(self.replace, replacements, expression) # Otherwise make the replacement. return expression.replace(*replacements)
<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 advance beyond the end of the token flow. """
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 token matches that class (is an instance). Note that when calling a token's nud() or led() functions, the "current" token is the token following the token whose method has been called. Returns: Token: the previous current token. Raises: InvalidTokenError: If an expect_class is provided and the current token doesn't match that class. """
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() return current_token
<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 the (right) precedence of the previous token, and will be compared to the (left) precedence of next tokens. Returns: Whatever the led/nud functions of tokens returned. """
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'. # Those are tokens that prefer binding to the left of an expression # than to the right of an expression. prev_token = self.consume() left = prev_token.led(left, context=self) return left
<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("Coil CMS running @ {0}".format(url)) coil.web.app.run('localhost', port, debug=True) return 0 else: print("FATAL: no conf.py found") return 255
<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] == 'SEPARATOR': op = lambda l, r: list(flatten([l, r])) token = next(token_stream) else: return [lval] rval = self.expr(token_stream, token) return op(lval, 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 keyword(self, token_stream, token, operators): """Lowest level parsing function. A keyword consists of zero or more prefix operators (NOT, or COMPARISON) followed by a TEXT, COLOR, or NUMBER block. """
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: problem = 'end of input.' else: problem = 'token {0} in input'.format(token[1]) raise SyntaxError('Unexpected {0}'.format(problem)) token = next(token_stream) return self.keyword(token_stream, token, operators)
<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.openxmlformats.org/officeDocument/2006/docPropsVTypes namespace :return: mapping of metadata """
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_map) propname_xpath = XPath('@name') propvalue_xpath = XPath('*/text()') for tree in self.content_types.getTreesFor(self, contenttypes.CT_CUSTOM_PROPS): for elt in properties_xpath(tree.getroot()): rval[toUnicode(propname_xpath(elt)[0])] = u" ".join(propvalue_xpath(elt)) 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 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) try: cover_path = rels_xpath(rels_xml)[0].attrib["Target"] except IndexError: return None cover_fp = open(self._cache_dir + os.sep + cover_path, "rb") cover_type = imghdr.what(None, h=cover_fp.read(32)) cover_fp.seek(0) # some MS docs say the type can be JPEG which is ok, # or WMF, which imghdr does not recognize... if not cover_type: cover_type = cover_path.split('.')[-1] else: cover_type = cover_type.replace("jpeg", "jpg") return (cover_type, cover_fp)
<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 :return: Space separated words of the document. """
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 |= words if include_properties: for prop_value in self.allProperties.values(): if prop_value is not None: text.add(prop_value) return u' '.join([word for word in 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 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 process such file """
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): the position where matches should be searched in the string (see re.match(rx, txt, pos)) Yields: (token_class, re.Match): all token class whose regexp matches the text, and the related re.Match object. """
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_kind, token_text): the token kind and its content. """
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 str): the regexp for elements of that token. Defaults to the `regexp` attribute of the token class. """
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.end() elif text[0] in self.blank_chars: text = text[1:] pos += 1 else: raise LexerError( 'Invalid character %s in %s' % (text[0], text), position=pos) yield self.end_token()
<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'), meta=fit.metadata) plot = Plot(fit) plot.save(os.path.join(plot_directory, fit.name + '.svg')) plot.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 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 metadata is defined by `figure.fit._extend_meta`. That method should be redefined or extended to suit specific use cases. """
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_type: a MIME content type @return: list of etree._ElementTree of that content type """
# 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) yield etree.parse(utils.xmlFile(file_path, 'rb')) 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 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 whatever type suits. """
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://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.savefig """
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: raise IOError('Invalid credentials 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 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() p = subprocess.Popen([executable, '-m', 'nikola', 'build'] + amode, stderr=subprocess.PIPE) milestones = { 'done!': 0, 'render_posts': 0, 'render_pages': 0, 'generate_rss': 0, 'render_indexes': 0, 'sitemap': 0 } out = [] while p.poll() is None: nl = p.stderr.readline().decode('utf-8') for k in milestones: if k in nl: milestones[k] = 1 out.append(nl) job.meta.update({'milestone': sum(milestones.values()), 'total': len(milestones), 'out': ''.join(out), 'return': None, 'status': None}) job.save() out += p.stderr.readlines() out = ''.join(out) job.meta.update({'milestone': len(milestones), 'total': len(milestones), 'out': ''.join(out), 'return': p.returncode, 'status': p.returncode == 0}) job.save() os.chdir(oldcwd) return p.returncode
<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': returncode == 0}) job.save() os.chdir(oldcwd) return returncode
<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'] + amode, stderr=subprocess.PIPE) p.wait() rl = p.stderr.readlines() try: out = ''.join(rl) except TypeError: out = ''.join(l.decode('utf-8') for l in rl) return (p.returncode == 0), out
<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) p.wait() files = [l.strip().decode('utf-8') for l in p.stdout.readlines()] for f in files: if f: os.unlink(f) out = '\n'.join(files) return p.returncode, out
<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, each column is text to add to the plot. `r0` is a tuple `(x, y)` that positions the initial text. `dr` is a tuple `(dx, dy)` that determines the column and row spacing. Any keyword arguments will be passed to `matplotlib.pyplot.text`. Example: #!python horizontalalignment='left', verticalalignment='top') [1]: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.text """
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: next_url = request.user.get_absolute_url() if not next_url: next_url = '/' return next_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 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: texts.append(text[0]) texts = self.separator.join(texts) texts = [toUnicode(x) for x in self.wordssearch_rx.findall(texts) if len(x) > 0] rval |= set(texts) 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 _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 to mana symbols return ''.join(result).replace('}(', '} (')
<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 raise the current exception ''' if self.shared_client: Storage.storage = None else: self.storage = None if self.context.config.REDIS_STORAGE_IGNORE_ERRORS is True: logger.error("[REDIS_STORAGE] %s" % exc_value) if fname == '_exists': return False return None else: raise exc_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 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 hash :rtype: str """
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>'.format( url_for('rebuild'))) else: return ('</li><li><a href="{0}"><i class="fa fa-fw ' 'fa-cog"></i> Rebuild</a></li>'.format(url_for('rebuild')))
<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 :param dict context: Context (variables) to use in the template :param int code: HTTP status code :param headers: Headers to use for the response :return: HTML fragment :rtype: str """
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 app.config['COIL_URL'].startswith('https') and not request.url.startswith('https'): # patch request URL for HTTPS proxy (eg. CloudFlare) context['permalink'] = request.url.replace('http', 'https', 1) else: context['permalink'] = request.url context['url_for'] = url_for headers['Pragma'] = 'no-cache' headers['Cache-Control'] = 'private, max-age=0, no-cache' try: mcp = current_user.must_change_password in (True, '1') except AttributeError: mcp = False if mcp and not context.get('pwdchange_skip', False): return redirect(url_for('acp_account') + '?status=pwdchange') return _site.render_template(template_name, None, context), code, headers
<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 KeyError: if user does not exist """
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')] = d[k].decode('utf-8') except AttributeError: try: nd[k.decode('utf-8')] = d[k] except AttributeError: nd[k] = d[k] for p in PERMISSIONS: nd[p] = nd.get(p) == '1' return User(uid=uid, **nd) else: return None else: d = app.config['COIL_USERS'].get(uid) if d: return User(uid=uid, **d) else: return 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 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 request/login attempt """
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 credentials.' code = 401 if captcha['enabled']: r = requests.post('https://www.google.com/recaptcha/api/siteverify', data={'secret': captcha['secret_key'], 'response': request.form['g-recaptcha-response'], 'remoteip': request.remote_addr}) if r.status_code != 200: alert = 'Cannot check CAPTCHA response.' code = 500 else: rj = r.json() if not rj['success']: alert = 'Invalid CAPTCHA response. Please try again.' code = 401 if code == 200: try: pwd_ok = check_password(user.password, request.form['password']) except ValueError: if user.password.startswith('$2a$12'): # old bcrypt hash pwd_ok = check_old_password(user.password, request.form['password']) if pwd_ok: user.password = password_hash( request.form['password']) write_user(user) else: pwd_ok = False if pwd_ok and user.is_active: login_user(user, remember=('remember' in request.form)) return redirect(url_for('index')) else: alert = "Invalid credentials." code = 401 else: alert = 'Invalid credentials.' code = 401 else: if request.args.get('status') == 'unauthorized': alert = 'Please log in to access this page.' elif request.args.get('status') == 'logout': alert = 'Logged out successfully.' alert_status = 'success' return render('coil_login.tmpl', {'title': 'Login', 'alert': alert, 'form': form, 'alert_status': alert_status, 'pwdchange_skip': True, 'captcha': captcha}, code)
<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 else: wants = wants_now if current_user.can_edit_all_posts and wants: posts = site.all_posts pages = site.pages else: wants = False posts = [] pages = [] for p in site.timeline: if (p.meta('author.uid') and p.meta('author.uid') != str(current_user.uid)): continue if p.is_post: posts.append(p) else: pages.append(p) context['posts'] = posts context['pages'] = pages context['title'] = 'Posts & Pages' context['wants'] = wants return render('coil_index.tmpl', context)
<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_rebuild', '-1') if not q.fetch_job('build') and not q.fetch_job('orphans'): b = q.enqueue_call(func=coil.tasks.build, args=(app.config['REDIS_URL'], app.config['NIKOLA_ROOT'], mode), job_id='build') q.enqueue_call(func=coil.tasks.orphans, args=(app.config['REDIS_URL'], app.config['NIKOLA_ROOT']), job_id='orphans', depends_on=b) return render('coil_rebuild.tmpl', {'title': 'Rebuild'}) else: status, outputb = coil.tasks.build_single(mode) _, outputo = coil.tasks.orphans_single() site.coil_needs_rebuild = '0' return render('coil_rebuild_single.tmpl', {'title': 'Rebuild', 'status': '1' if status else '0', 'outputb': outputb, 'outputo': outputo})
<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 requests to this URL:: /bower_components/ => coil/data/bower_components """
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 to this URL:: /coil_assets/ => coil/data/coil_assets """
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 this URL:: /assets/ => output/assets """
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() return render('coil_account_single.tmpl', context={'title': 'My account', 'form': form, 'alert': alert, 'alert_status': alert_status}) action = 'edit' form = AccountForm() if request.method == 'POST': if int(current_user.uid) in app.config['COIL_USERS_PREVENT_EDITING']: return error("Cannot edit data for this user.", 403) if not form.validate(): return error("Bad Request", 400) action = 'save' data = request.form if data['newpwd1']: try: pwd_ok = check_password(current_user.password, data['oldpwd']) except ValueError: if current_user.password.startswith('$2a$12'): # old bcrypt hash pwd_ok = check_old_password(current_user.password, data['oldpwd']) if data['newpwd1'] == data['newpwd2'] and pwd_ok: current_user.password = password_hash(data['newpwd1']) current_user.must_change_password = False pwdchange_skip = True else: alert = 'Passwords don’t match.' alert_status = 'danger' action = 'save_fail' current_user.realname = data['realname'] current_user.email = data['email'] current_user.wants_all_posts = 'wants_all_posts' in data write_user(current_user) return render('coil_account.tmpl', context={'title': 'My account', 'action': action, 'alert': alert, 'alert_status': alert_status, 'form': form, 'pwdchange_skip': pwdchange_skip})
<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", 400) action = data['action'] if action == 'new': if not data['username']: return error("No username to create specified.", 400) uid = max(int(i) for i in db.hgetall('users').values()) + 1 pf = [False for p in PERMISSIONS] pf[0] = True # active pf[7] = True # must_change_password user = User(uid, data['username'], '', '', '', *pf) write_user(user) db.hset('users', user.username, user.uid) new = True else: user = get_user(data['uid']) new = False if not user: return error("User does not exist.", 404) alert = '' alert_status = '' if action == 'save': if data['newpwd1']: if data['newpwd1'] == data['newpwd2']: user.password = password_hash(data['newpwd1']) else: alert = 'Passwords don’t match.' alert_status = 'danger' action = 'save_fail' elif new: alert = 'Must set a password.' alert_status = 'danger' action = 'save_fail' if data['username'] != user.username: db.hdel('users', user.username) user.username = data['username'] db.hset('users', user.username, user.uid) user.realname = data['realname'] user.email = data['email'] for p in PERMISSIONS: setattr(user, p, p in data) user.active = True if user.uid == current_user.uid: user.is_admin = True user.must_change_password = False current_user = user write_user(user) return render('coil_users_edit.tmpl', context={'title': 'Edit user', 'user': user, 'new': new, 'action': action, 'alert': alert, 'alert_status': alert_status, 'form': 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_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 tsv = fh.read() return tsv
<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['uid'])) direction = request.form['direction'] if not user: return error("User does not exist.", 404) else: for p in PERMISSIONS: setattr(user, p, False) user.active = direction == 'undel' write_user(user) return redirect(url_for('acp_users') + '?status={_del}eted'.format( _del=direction))
<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 form.validate(): return error("Bad Request", 400) for uid in uids: user = get_user(uid) for perm in PERMISSIONS: if '{0}.{1}'.format(uid, perm) in request.form: setattr(user, perm, True) else: setattr(user, perm, False) if int(uid) == current_user.uid: # Some permissions cannot apply to the current user. user.is_admin = True user.active = True user.must_change_password = False write_user(user) users.append((uid, user)) action = 'save' else: action = 'edit' def display_permission(user, permission): """Display a permission.""" checked = 'checked' if getattr(user, permission) else '' if permission == 'wants_all_posts' and not user.can_edit_all_posts: # If this happens, permissions are damaged. checked = '' if (user.uid == current_user.uid and permission in [ 'active', 'is_admin', 'must_change_password']): disabled = 'disabled' else: disabled = '' permission_a = permission if permission == 'active': permission_a = 'is_active' d = ('<input type="checkbox" name="{0}.{1}" data-uid="{0}" ' 'data-perm="{4}" class="u{0}" {2} {3}>') return d.format(user.uid, permission, checked, disabled, permission_a) if not users: users = [(i, get_user(i)) for i in uids] return render('coil_users_permissions.tmpl', context={'title': 'Permissions', 'USERS': sorted(users), 'UIDS': sorted(uids), 'PERMISSIONS_E': PERMISSIONS_E, 'action': action, 'json': json, 'form': form, 'display_permission': display_permission})
<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): return getattr(Compare, comp)(key, value, obj) raise AttributeError("No comparison '%s'" % 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 query string and appended to the URL. """
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._column
<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 end of the input. """
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=query, default_q=default_q).encode('utf-8')).strip() if inp or default is None: return inp else: return default
<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._timeline.append(Post(data[0], self.config, data[1], data[2], data[3], self.messages, self._site.compilers[data[4]])) self._read_indexlist('posts') self._read_indexlist('all_posts') self._read_indexlist('pages') self.revision = rev self.logger.info("Site updated to revision {0}.".format(rev)) elif rev == self.revision and self.db.exists('site:rev'): pass else: self.logger.warn("Site needs rescanning.")
<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._site.scan_posts(really, ignore_quit, quiet) timeline = [] for post in self._site.timeline: data = [post.source_path, post.folder, post.is_post, post._template_name, post.compiler.name] timeline.append(json.dumps(data)) self.db.delete('site:timeline') if timeline: self.db.rpush('site:timeline', *timeline) self._write_indexlist('posts') self._write_indexlist('all_posts') self._write_indexlist('pages') self.db.incr('site:rev') self.db.decr('site:lock') self.logger.info("Lock released.") self.logger.info("Site scanned.") self.reload_site()
<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