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 parse_kv_args(self, args):
"""parse key-value style arguments""" |
for arg in ["start", "end", "count", "stride"]:
try:
arg_raw = args.pop(arg, None)
if arg_raw is None:
continue
arg_cooked = int(arg_raw, 0)
setattr(self, arg, arg_cooked)
except ValueError:
... |
<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_headers(self, use_cookies, raw):
""" analyze headers from file or raw messages :return: (url, dat) :rtype: """ |
if not raw:
packet = helper.to_str(helper.read_file(self.fpth))
else:
packet = raw
dat = {}
pks = [x for x in packet.split('\n') if x.replace(' ', '')]
url = pks[0].split(' ')[1]
for i, cnt in enumerate(pks[1:]):
arr = cnt.split(':')... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spawn(self, url, force_spawn=False):
"""use the url for creation of domain and fetch cookies - init cache dir by the url domain as ``<base>/domain`` - save t... |
_url, domain = self.get_domain_home_from_url(url)
if not _url:
return False
self.cache['site_dir'] = os.path.join(self.cache['base'], self.domain)
for k in ['raw', 'media']:
self.cache['site_' + k] = os.path.join(self.cache['site_dir'], k)
helper.mkd... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map_url_to_cache_id(self, url):
"""use of the url resource location as cached id e.g.: ``<domain>/foo/bar/a.html => <base>/domain/foo/bar/a.html`` - map the ... |
base, _ = self.get_domain_home_from_url(url)
if base == '':
# invalid url
_sub_page = ''
elif base == url or base + '/' == url:
# homepage
_sub_page = 'homepage'
else:
# sub page
_sub_page = url.replace(base, '').s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_sess_get(self, url):
"""get url by requests synchronized :param url: :type url: :return: :rtype: """ |
try:
res = self.sess.get(url, headers=self.headers['get'], timeout=self.timeout)
if res.status_code == 200:
return res.content
except (requests.ReadTimeout, requests.ConnectTimeout, requests.ConnectionError) as _:
zlog.error('failed of: {} with 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 load(self, url, use_cache=True, show_log=False):
"""fetch the url ``raw info``, use cache first, if no cache hit, try get from Internet :param url: :type url... |
_name = self.map_url_to_cache_id(url)
raw = ''
hit = False
if use_cache:
hit = True
raw = self.load_from_cache(_name)
if not raw:
if show_log:
zlog.debug('from cache got nothing {}'.format(_name))
raw = self.do_se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sync_save(self, res, overwrite=False):
""" save ``res`` to local synchronized :param res: {'url': '', 'name': ''} :type res: dict :param overwrite: :type ove... |
if not isinstance(res, dict):
raise CrawlerParamsError('res must be dict')
url_, file_name = res.get('url', ''), res.get('name', '')
if not url_ or not file_name:
raise CrawlerParamsError('url&name is needed!')
# log.debug('Sync {}'.format(res.get('name')))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def crawl_raw(self, res):
""" crawl the raw doc, and save it asynchronous. :param res: {'url','', 'name': ''} :type res: ``dict`` :return: :rtype: """ |
cnt = await self.async_get(res)
if cnt:
loop_ = asyncio.get_event_loop()
await loop_.run_in_executor(None, self.write_hd, res.get('name'), cnt)
return True
else:
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:
async def _sem_crawl(self, sem, res):
""" use semaphore ``encapsulate`` the crawl_media \n with async crawl, should avoid crawl too fast to become DDos attack to... |
async with sem:
st_ = await self.crawl_raw(res)
if st_:
self.result['ok'] += 1
else:
self.result['fail'] += 1
# take a little gap
await asyncio.sleep(random.randint(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 json_decoder(content, *args, **kwargs):
""" Json decoder parser to be used by service_client """ |
if not content:
return None
json_value = content.decode()
return json.loads(json_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 init(changelog_name):
"""Setup your project.""" |
changelog_path = find_chglog_file()
create_changelog_flag = True
mark = style("?", fg="blue", bold=True)
if not changelog_name:
if changelog_path:
filename = style(changelog_path.name, fg="blue", bold=True)
message = f" {mark} {filename} was found." " Is this the chang... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def changelog_file_option_validator(ctx, param, value):
"""Checks that the given file path exists in the current working directory. Returns a :class:`~pathlib.Pa... |
path = Path(value)
if not path.exists():
filename = click.style(path.name, fg="blue", bold=True)
ctx.fail(
"\n"
f" {x_mark} Unable to find {filename}\n"
' Run "$ brau init" to create one'
)
return 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 current_version_option_validator(ctx, param, value):
"""If a version string is provided, validates it. Otherwise it tries to determine the current version fr... |
current_version = None
if value:
try:
current_version = Version(value)
except ValueError:
ctx.fail(f"{value} is not a valid version string")
# Look for the last git tag for the curren version
git = Git()
tag_pattern = ctx.params["tag_pattern"]
versions... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def layout(self, indent=' '):
"""This will indent each new tag in the body by given number of spaces.""" |
self.__indent(self.head, indent)
self.__indent(self.meta, indent)
self.__indent(self.stylesheet, indent)
self.__indent(self.header, indent)
self.__indent(self.body, indent, initial=3)
self.__indent(self.footer, indent)
self.__indent(self.body_pre_docinfo, indent, initial=3)
self.__indent(self.docinfo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Show the intervention screen. """ |
application = Application(sys.argv, ignore_close=not SKIP_FILTER)
platform.hide_cursor()
with open(resource_filename(__name__, 'intervention.css')) as css:
application.setStyleSheet(css.read())
# exec() is required for objc so we must use spawn
# multiprocessing.set_start_method('spawn')... |
<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(self, path, data, offset, fh):
# pragma: no cover """ This is a readonly filesystem right now """ |
# print("write {}".format(path))
with self.attr_lock:
base = self.attr[path][BASE_KEY]
staged = self.attr[path][STAGED_KEY]
if not staged.closed:
base.st_size += len(data)
staged.write(data)
return len(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 _cleanup(self):
# pragma: no cover """ cleans up data that's been in the cache for a while should be called from an async OS call like release? to not impact... |
need_to_delete = [] # can't delete from a dict while iterating
with self.attr_lock:
now_time = time()
for path in self.cache:
if now_time - self.attr[path][TIMESTAMP_KEY] >= MAX_CACHE_TIME:
need_to_delete.append(path)
for path in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def validate_args(args):
'''
Apply custom validation and actions based on parsed arguments.
Parameters
----------
args : argparse.Namespace
Result from ``parse_args`` method of ``argparse.ArgumentParser``
instance.
Returns
-------
argparse.Namespace
Reference to... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_events(self, max_attempts=3):
"""Returns a list of `Event`s detected from differences in state between the current snapshot and the Kindle Library. `b... |
# Attempt to retrieve current state from KindleAPI
for _ in xrange(max_attempts):
try:
with KindleCloudReaderAPI\
.get_instance(self.uname, self.pword) as kcr:
self.books = kcr.get_library_metadata()
self.progre... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit_events(self):
"""Applies all outstanding `Event`s to the internal state """ |
# Events are sorted such that, when applied in order, each event
# represents a logical change in state. That is, an event never requires
# future events' data in order to be parsed.
# e.g. All ADDs must go before START READINGs
# All START READINGs before all READs
... |
<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_registry_names(self, registry):
""" Returns functions names for a registry """ |
return ', '.join(
f.__name__ if not isinstance(f, tuple) else f[0].__name__
for f in getattr(self, registry, [])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def receiver(self, func=None, json=False):
""" Registers a receiver function """ |
self.receivers.append((func, json)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sender(self, func, routing=None, routing_re=None):
""" Registers a sender function """ |
if routing and not isinstance(routing, list):
routing = [routing]
if routing_re:
if not isinstance(routing_re, list):
routing_re = [routing_re]
routing_re[:] = [re.compile(r) for r in routing_re]
self.senders.append((func, routing, routing_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 call_openers(self, client, clients_list):
""" Calls openers callbacks """ |
for func in self.openers:
func(client, clients_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 call_closers(self, client, clients_list):
""" Calls closers callbacks """ |
for func in self.closers:
func(client, clients_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 call_receivers(self, client, clients_list, message):
""" Calls receivers callbacks """ |
# Try to parse JSON
try:
json_message = json.loads(message)
except ValueError:
json_message = None
for func, to_json in self.receivers:
# Check if json version is available
if to_json:
if json_message is None:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_senders(self, routing, clients_list, *args, **kwargs):
""" Calls senders callbacks """ |
for func, routings, routings_re in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings_re is None):
call_callback = True
# Message is not published globally
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 run_websocket_server(self, host='localhost', port=9090, debug=False):
""" Runs websocket server """ |
from .server import MeaseWebSocketServerFactory
websocket_factory = MeaseWebSocketServerFactory(
mease=self, host=host, port=port, debug=debug)
websocket_factory.run_server() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stackclimber(height=0):
# http://stackoverflow.com/a/900404/48251 """ Obtain the name of the caller's module. Uses the inspect module to find the caller's po... |
caller = inspect.stack()[height+1]
scope = caller[0].f_globals
path = scope['__name__'].split('__main__')[0].strip('.')
if path == '':
if scope['__package__']:
path = scope['__package__']
else:
path = os.path.basename(sys.argv[0]).split('.')[0]
return 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 flatten_list(l):
""" Nested lists to single-level list, does not split strings""" |
return list(chain.from_iterable(repeat(x,1) if isinstance(x,str) else x for x in l)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_diff(list1, list2):
""" Ssymetric list difference """ |
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
for item in list2:
if not item in list1:
diff_list.append(item)
return diff_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 asym_list_diff(list1, list2):
""" Asymmetric list difference """ |
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_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 next_tokens_in_sequence(observed, current):
""" Given the observed list of tokens, and the current list, finds out what should be next next emitted word """ |
idx = 0
for word in current:
if observed[idx:].count(word) != 0:
found_pos = observed.index(word, idx)
idx = max(idx + 1, found_pos)
# otherwise, don't increment idx
if idx < len(observed):
return observed[idx:]
else:
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 to_latex(self):
""" Returns an interval representation """ |
if self.low == self.high:
if self.low * 10 % 10 == 0:
return "{0:d}".format(int(self.low))
else:
return "{0:0.2f}".format(self.low)
else:
t = ""
if self.low == -np.inf:
t += r"(-\infty, "
elif se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Main entry point for the `respect` command. """ |
args = parse_respect_args(sys.argv[1:])
if validate_username(args['<username>']):
print("processing...")
else:
print("@"+args['<username>'], "is not a valid username.")
print("Username may only contain alphanumeric ASCII characters or "
"dashes and cannot begin with 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 clear_caches():
# suppress(unused-function) """Clear all caches.""" |
for _, reader in _spellchecker_cache.values():
reader.close()
_spellchecker_cache.clear()
_valid_words_cache.clear()
_user_dictionary_cache.clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _comment_system_for_file(contents):
"""For file contents, return the comment system.""" |
if contents[0] == "#":
return FileCommentSystem(begin="#", middle="", end="", single="#")
elif contents[:2] == "/*":
return FileCommentSystem(begin="/*", middle="*", end="*/", single="//")
elif contents[:2] == "//":
return FileCommentSystem(begin="//", middle="//", end="", single="/... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_line_with_offsets(line):
"""Split a line by delimiter, but yield tuples of word and offset. This function works by dropping all the english-like punct... |
for delimiter in re.finditer(r"[\.,:\;](?![^\s])", line):
span = delimiter.span()
line = line[:span[0]] + " " + line[span[1]:]
for delimiter in re.finditer(r"[\"'\)\]\}>](?![^\.,\;:\"'\)\]\}>\s])",
line):
span = delimiter.span()
line = line[:spa... |
<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_dictionary_file(dictionary_path):
"""Return all words in dictionary file as set.""" |
try:
return _user_dictionary_cache[dictionary_path]
except KeyError:
if dictionary_path and os.path.exists(dictionary_path):
with open(dictionary_path, "rt") as dict_f:
words = set(re.findall(r"(\w[\w']*\w|\w)",
" ".join(dict_f.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def valid_words_set(path_to_user_dictionary=None, user_dictionary_words=None):
"""Get a set of valid words. If :path_to_user_dictionary: is specified, then the n... |
def read_file(binary_file):
"""Read a binary file for its text lines."""
return binary_file.read().decode("ascii").splitlines()
try:
valid = _valid_words_cache[path_to_user_dictionary]
return valid
except KeyError:
words = set()
with resource_stream("polysqu... |
<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_word_graph_file(name, file_storage, word_set):
"""Create a word graph file and open it in memory.""" |
word_graph_file = file_storage.create_file(name)
spelling.wordlist_to_graph_file(sorted(list(word_set)),
word_graph_file)
return copy_to_ram(file_storage).open_file(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_nonspellcheckable_tokens(line, block_out_regexes=None):
"""Return line with paths, urls and emails filtered out. Block out other strings of text match... |
all_block_out_regexes = [
r"[^\s]*:[^\s]*[/\\][^\s]*",
r"[^\s]*[/\\][^\s]*",
r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+\b"
] + (block_out_regexes or list())
for block_regex in all_block_out_regexes:
for marker in re.finditer(block_regex, line):
spaces = " "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _chunk_from_ranges(contents_lines, start_line_index, start_column_index, end_line_index, end_column_index):
"""Create a _ChunkInfo from a range of lines and ... |
# If the start and end line are the same we have to compensate for
# that by subtracting start_column_index from end_column_index
if start_line_index == end_line_index:
end_column_index -= start_column_index
lines = contents_lines[start_line_index:end_line_index + 1]
lines[0] = lines[0][st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _token_at_col_in_line(line, column, token, token_len=None):
"""True if token is at column.""" |
if not token_len:
token_len = len(token)
remaining_len = len(line) - column
return (remaining_len >= token_len and
line[column:column + token_len] == 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 _maybe_append_chunk(chunk_info, line_index, column, contents, chunks):
"""Append chunk_info to chunks if it is set.""" |
if chunk_info:
chunks.append(_chunk_from_ranges(contents,
chunk_info[0],
chunk_info[1],
line_index,
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 _find_spellcheckable_chunks(contents, comment_system):
"""Given some contents for a file, find chunks that can be spellchecked. This applies the following ru... |
state = InTextParser()
comment_system_transitions = CommentSystemTransitions(comment_system)
chunks = []
for line_index, line in enumerate(contents):
column = 0
line_len = len(line)
escape_next = False
# We hit a new line. If we were waiting until the end of the line
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def spellcheckable_and_shadow_contents(contents, block_out_regexes=None):
"""For contents, split into spellcheckable and shadow parts. :contents: is a list of li... |
if not len(contents):
return ([], [])
comment_system = _comment_system_for_file(contents[0])
# Shadow contents excludes anything in quotes
chunks = _find_spellcheckable_chunks(contents, comment_system)
shadow_contents = _shadow_contents_from_chunks(contents,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_into_symbol_words(sym):
"""Split a technical looking word into a set of symbols. This handles cases where technical words are separated by dots or arr... |
punc = r"[\s\-\*/\+\.,:\;=\)\(\[\]\{\}<>\|\?&\^\$@]"
words = [w.strip() for w in re.split(punc, sym)]
return words |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _error_if_word_invalid(word, valid_words_dictionary, technical_words_dictionary, line_offset, col_offset):
"""Return SpellcheckError if this non-technical wo... |
word_lower = word.lower()
valid_words_result = valid_words_dictionary.corrections(word_lower)
if technical_words_dictionary:
technical_words_result = technical_words_dictionary.corrections(word)
else:
# No technical words available to make an otherwise invalid
# result 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 _error_if_symbol_unused(symbol_word, technical_words_dictionary, line_offset, col_offset):
"""Return SpellcheckError if this symbol is not used in the code."... |
result = technical_words_dictionary.corrections(symbol_word,
distance=5,
prefix=0)
if not result.valid:
return SpellcheckError(symbol_word,
line_offset,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def should_terminate_now(self, line, waiting_for):
"""Whether parsing within a comment should terminate now. This is used for comment systems where there is no c... |
if waiting_for not in (ParserState.EOL, self._end):
return False
if self._continue_regex:
return (re.match(self._continue_regex, line) is None)
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 get_transition(self, # suppress(too-many-arguments) line, line_index, column, is_escaped, comment_system_transitions, eof=False):
"""Return a parser state, a... |
raise NotImplementedError("""Cannot instantiate base ParserState""") |
<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_transition(self, # suppress(too-many-arguments) line, line_index, column, is_escaped, comment_system_transitions, eof=False):
"""Get transition from InTe... |
parser_transition = {
STATE_IN_COMMENT: InCommentParser,
STATE_IN_QUOTE: InQuoteParser
}
(state,
start_state_from,
waiting_until) = comment_system_transitions.from_text(line,
line_index,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_transition(self, # suppress(too-many-arguments) line, line_index, column, is_escaped, comment_system_transitions, eof=False):
"""Get transition from Disa... |
# If we are at the beginning of a line, to see if we should
# disable processing from this point onward and get out - this will
# happen if we reach the end of some comment block that doesn't have
# an explicit end marker. We can't detect line endings here because
# we want a di... |
<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_transition(self, # suppress(too-many-arguments) line, line_index, column, is_escaped, comment_system_transitions, eof=False):
"""Get transition from InCo... |
del comment_system_transitions
if (_token_at_col_in_line(line,
column,
"```",
3) and
not _is_escaped(line, column, is_escaped)):
# Hit a disable token, so resume the last p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_transition(self, # suppress(too-many-arguments) line, line_index, column, is_escaped, *args, **kwargs):
"""Get transition from InQuoteParser.""" |
del line_index
del args
del kwargs
wait_until_len = len(self._waiting_until)
if (_token_at_col_in_line(line,
column,
self._waiting_until,
wait_until_len) and
no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def corrections(self, word, prefix=1, distance=2):
"""Get corrections for word, if word is an invalid word. :prefix: is the number of characters the prefix of th... |
if word not in self._words:
return Dictionary.Result(False,
self._corrector.suggest(word,
prefix=prefix,
maxdist=distance))
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 _create_dom(data):
""" Creates doublelinked DOM from `data`. Args: data (str/HTMLElement):
Either string or HTML element. Returns: obj: HTMLElement containi... |
if not isinstance(data, dhtmlparser.HTMLElement):
data = dhtmlparser.parseString(
utils.handle_encodnig(data)
)
dhtmlparser.makeDoubleLinked(data)
return 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 _locate_element(dom, el_content, transformer=None):
""" Find element containing `el_content` in `dom`. Use `transformer` function to content of all elements ... |
return dom.find(
None,
fn=utils.content_matchs(el_content, transformer)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_elements(dom, matches):
""" Find location of elements matching patterns specified in `matches`. Args: dom (obj):
HTMLElement DOM tree. matches (dict)... |
out = {}
for key, content in matches.items():
pattern = content["data"].strip()
if "\n" in pattern:
pattern = pattern.split()
transformer = lambda x: x.strip().split()
else:
transformer = lambda x: x.strip()
matching_elements = _locate_elemen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collect_paths(element):
""" Collect all possible path which leads to `element`. Function returns standard path from root element to this, reverse path, whic... |
output = []
# look for element by parameters - sometimes the ID is unique
path = vectors.el_to_path_vector(element)
root = path[0]
params = element.params if element.params else None
match = root.find(element.getTagName(), params)
if len(match) == 1:
output.append(
Pat... |
<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_working_path(dom, path, element):
""" Check whether the path is working or not. Aply proper search function interpreting `path` to `dom` and check, if re... |
def i_or_none(el, i):
"""
Return ``el[i]`` if the list is not blank, or None otherwise.
Args:
el (list, tuple): Any indexable object.
i (int): Index.
Returns:
obj: Element at index `i` if `el` is not blank, or ``None``.
"""
if no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_best_paths(examples):
""" Process `examples`, select only paths that works for every example. Select best paths with highest priority. Args: examples ... |
possible_paths = {} # {varname: [paths]}
# collect list of all possible paths to all existing variables
for example in examples:
dom = _create_dom(example["html"])
matching_elements = _match_elements(dom, example["vars"])
for key, match in matching_elements.items():
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _assert_obj_type(pub, name="pub", obj_type=DBPublication):
""" Make sure, that `pub` is instance of the `obj_type`. Args: pub (obj):
Instance which will be ... |
if not isinstance(pub, obj_type):
raise InvalidType(
"`%s` have to be instance of %s, not %s!" % (
name,
obj_type.__name__,
pub.__class__.__name__
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_publication(pub):
""" Save `pub` into database and into proper indexes. Attr: pub (obj):
Instance of the :class:`.DBPublication`. Returns: obj: :class:... |
_assert_obj_type(pub)
_get_handler().store_object(pub)
return pub.to_comm(light_request=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 clear_dir(self):
"""Clear the output directory of all output files.""" |
for snapshot in output_utils.get_filenames(self.output_dir):
if snapshot.endswith('.pkl'):
os.remove(snapshot) |
<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_snapshot_time(self, output_every=None, t_output_every=None):
"""Determine whether or not the model's iteration number is one where the runner is expected ... |
if t_output_every is not None:
output_every = int(round(t_output_every // self.model.dt))
return not self.model.i % output_every |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate(self, n=None, n_upto=None, t=None, t_upto=None, output_every=None, t_output_every=None):
"""Run the model for a number of iterations, expressed in a ... |
if t is not None:
t_upto = self.model.t + t
if t_upto is not None:
n_upto = int(round(t_upto // self.model.dt))
if n is not None:
n_upto = self.model.i + n
while self.model.i <= n_upto:
if self.is_snapshot_time(output_every, t_output_ever... |
<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_snapshot(self):
"""Output a snapshot of the current model state, as a pickle of the `Model` object in a file inside the output directory, with a name de... |
filename = join(self.output_dir, '{:010d}.pkl'.format(self.model.i))
output_utils.model_to_file(self.model, filename) |
<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_line(self, line):
"""Parser for the debugging shell. Treat everything after the first token as one literal entity. Whitespace characters between the fi... |
line = line.lstrip()
toks = shlex.split(line)
cmd = toks[0]
arg = line[len(cmd):]
return cmd, [ arg, ] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def bind(self, **kwargs):
'''
creates a copy of the object without the
cached results and with the given keyword
arguments as properties.
'''
d = dict(self.__dict__)
for k in d.keys():
if k[0] == '_':
del d[k]
elif k.startsw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, name, *subkey):
""" retrieves a data item, or loads it if it is not present. """ |
if subkey == []:
return self.get_atomic(name)
else:
return self.get_subkey(name, tuple(subkey)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def val(self, name):
""" retrieves a value, substituting actual values for ConfigValue templates. """ |
v = getattr(self, name)
if hasattr(v, 'retrieve_value'):
v = v.retrieve_value(self.__dict__)
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def harvest_collection(community_name):
"""Harvest a Zenodo community's record metadata. Examples -------- You can harvest record metadata for a Zenodo community... |
url = zenodo_harvest_url(community_name)
r = requests.get(url)
r.status_code
xml_content = r.content
return Datacite3Collection.from_collection_xml(xml_content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def zenodo_harvest_url(community_name, format='oai_datacite3'):
"""Build a URL for the Zenodo Community's metadata. Parameters community_name : str Zenodo commun... |
template = 'http://zenodo.org/oai2d?verb=ListRecords&' \
'metadataPrefix={metadata_format}&set=user-{community}'
return template.format(metadata_format=format,
community=community_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pluralize(value, item_key):
""""Force the value of a datacite3 key to be a list. ['Sick, Jonathan', 'Economou, Frossie'] Background When `xmltodict` procese... |
v = value[item_key]
if not isinstance(v, list):
# Force a singular value to be a list
return [v]
else:
return v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_xmldict(cls, xml_dict):
"""Create an `Author` from a datacite3 metadata converted by `xmltodict`. Parameters xml_dict : :class:`collections.OrderedDict`... |
name = xml_dict['creatorName']
kwargs = {}
if 'affiliation' in xml_dict:
kwargs['affiliation'] = xml_dict['affiliation']
return cls(name, **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 published(self, for_user=None):
""" For non-staff users, return items with a published status and whose publish and expiry dates fall before and after the cu... |
from yacms.core.models import CONTENT_STATUS_PUBLISHED
if for_user is not None and for_user.is_staff:
return self.all()
return self.filter(
Q(publish_date__lte=now()) | Q(publish_date__isnull=True),
Q(expiry_date__gte=now()) | Q(expiry_date__isnull=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 search(self, query, search_fields=None):
""" Build a queryset matching words in the given search query, treating quoted terms as exact phrases and taking int... |
# ### DETERMINE FIELDS TO SEARCH ###
# Use search_fields arg if given, otherwise use search_fields
# initially configured by the manager class.
if search_fields:
self._search_fields = search_fields_to_dict(search_fields)
if not self._search_fields:
retu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clone(self, *args, **kwargs):
""" Ensure attributes are copied to subsequent queries. """ |
for attr in ("_search_terms", "_search_fields", "_search_ordered"):
kwargs[attr] = getattr(self, attr)
return super(SearchableQuerySet, self)._clone(*args, **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 order_by(self, *field_names):
""" Mark the filter as being ordered if search has occurred. """ |
if not self._search_ordered:
self._search_ordered = len(self._search_terms) > 0
return super(SearchableQuerySet, self).order_by(*field_names) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterator(self):
""" If search has occurred and no ordering has occurred, decorate each result with the number of search terms so that it can be sorted by the... |
results = super(SearchableQuerySet, self).iterator()
if self._search_terms and not self._search_ordered:
results = list(results)
for i, result in enumerate(results):
count = 0
related_weights = []
for (field, weight) in self._searc... |
<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_search_fields(self):
""" Returns the search field names mapped to weights as a dict. Used in ``get_queryset`` below to tell ``SearchableQuerySet`` which ... |
search_fields = self._search_fields.copy()
if not search_fields:
for cls in reversed(self.model.__mro__):
super_fields = getattr(cls, "search_fields", {})
search_fields.update(search_fields_to_dict(super_fields))
if not search_fields:
sear... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contribute_to_class(self, model, name):
""" Newer versions of Django explicitly prevent managers being accessed from abstract classes, which is behaviour the... |
super(SearchableManager, self).contribute_to_class(model, name)
setattr(model, name, ManagerDescriptor(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 search(self, *args, **kwargs):
""" Proxy to queryset's search method for the manager's model and any models that subclass from this manager's model if the mo... |
if not settings.SEARCH_MODEL_CHOICES:
# No choices defined - build a list of leaf models (those
# without subclasses) that inherit from Displayable.
models = [m for m in apps.get_models()
if issubclass(m, self.model)]
parents = reduce(ior, [... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def url_map(self, for_user=None, **kwargs):
""" Returns a dictionary of urls mapped to Displayable subclass instances, including a fake homepage instance if none... |
class Home:
title = _("Home")
home = Home()
setattr(home, "get_absolute_url", home_slug)
items = {home.get_absolute_url(): home}
for model in apps.get_models():
if issubclass(model, self.model):
for item in (model.objects.published(for_use... |
<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_name(model_id):
""" Get the name for a model. :returns str: The model's name. If the id has no associated name, then "id = {ID} (no name)" is returned. "... |
name = _names.get(model_id)
if name is None:
name = 'id = %s (no name)' % str(model_id)
return name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def define_logger_func(self, level, field_names, default=NO_DEFAULT, filters=None, include_exc_info=False):
"""Define a new logger function that will log the giv... |
kv_formatter = KvFormatter(field_names, default, filters)
return lambda *a, **kw: self._log(level, kv_formatter(*a, **kw),
include_exc_info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, level, *args, **kwargs):
"""Delegate a log call to the underlying logger.""" |
return self._log_kw(level, args, 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 exception(self, *args, **kwargs):
"""Delegate a exception call to the underlying logger.""" |
return self._log_kw(ERROR, args, kwargs, exc_info=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 update(self):
""" Update all the switch values """ |
self.states = [bool(int(x)) for x in self.get('port list') or '0000'] |
<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_correct_audience(self, audience):
"Assert that Dataporten sends back our own client id as audience"
client_id, _ = self.get_key_and_secret()
if audience != client_id:
raise AuthException('Wrong audience') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ChoiceHumanReadable(choices, choice):
""" Return the human readable representation for a list of choices. @see https://docs.djangoproject.com/en/dev/ref/mode... |
if choice == None: raise NoChoiceError()
for _choice in choices:
if _choice[0] == choice:
return _choice[1]
raise NoChoiceMatchError("The choice '%s' does not exist in '%s'" % (choice, ", ".join([choice[0] for choice in choices]))) |
<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_db_prep_value(self, value, connection=None, prepared=False):
"""Returns field's value prepared for interacting with the database backend. Used by the def... |
if not value:
return
if prepared:
return value
else:
assert(isinstance(value, list) or isinstance(value, tuple))
return self.separator.join([unicode(s) for s in 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 load(self):
""" Loads the user's SDB inventory Raises parseException """ |
self.inventory = SDBInventory(self.usr)
self.forms = self.inventory.forms |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
""" Upates the user's SDB inventory Loops through all items on a page and checks for an item that has changed. A changed item is identified as ... |
for x in range(1, self.inventory.pages + 1):
if self._hasPageChanged(x):
form = self._updateForm(x)
form.usePin = True
pg = form.submit()
# Success redirects to SDB page
if "Your Safety Deposit Box" in ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_series_url(key):
"""For internal use. Given a series key, generate a valid URL to the series endpoint for that key. :param string key: the series key :r... |
url = urlparse.urljoin(endpoint.SERIES_ENDPOINT, 'key/')
url = urlparse.urljoin(url, urllib.quote(key))
return 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 create_series(self, key=None, tags=[], attrs={}):
"""Create a new series with an optional string key. A list of tags and a map of attributes can also be opti... |
body = protocol.make_series_key(key, tags, attrs)
resp = self.session.post(endpoint.SERIES_ENDPOINT, body)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_series(self, keys=None, tags=None, attrs=None, allow_truncation=False):
"""Delete a series according to the given criteria. **Note:** for the key argu... |
params = {
'key': keys,
'tag': tags,
'attr': attrs,
'allow_truncation': str(allow_truncation).lower()
}
url_args = endpoint.make_url_args(params)
url = '?'.join([endpoint.SERIES_ENDPOINT, url_args])
resp = self.session.delete(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 get_series(self, key):
"""Get a series object from TempoDB given its key. :param string key: a string name for the series :rtype: :class:`tempodb.response.Re... |
url = make_series_url(key)
resp = self.session.get(url)
return resp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.