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 decode_length(self, data, state):
""" Extract and decode a frame length from the data buffer. The consumed data should be removed from the buffer. If the len... |
# Do we have enough data yet?
if len(data) < self.fmt.size:
raise exc.NoFrames()
# Extract the length
length = self.fmt.unpack(six.binary_type(data[:self.fmt.size]))[0]
del data[:self.fmt.size]
# Return the length
return length |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interpret(self, infile):
""" Process a file of rest and return json """ |
# need row headings
data = pandas.read_csv(infile)
# FIXME find the right foo
return json.dumps(data.foo()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binary_search(data, target, lo=0, hi=None):
""" Perform binary search on sorted list data for target. Returns int representing position of target in data. ""... |
hi = hi if hi is not None else len(data)
mid = (lo + hi) // 2
if hi < 2 or hi > len(data) or target > data[-1] or target < data[0]:
return -1
if data[mid] > target:
return binary_search(data, target, lo=lo, hi=mid)
elif data[mid] < target:
return binary_search(data, target, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def new(self, user_id, tokens=None, user_data=None, valid_until=None, client_ip=None, encoding='utf-8'):
"""Creates a new authentication ticket. Args: user_id: U... |
if valid_until is None:
valid_until = int(time.time()) + TicketFactory._DEFAULT_TIMEOUT
else:
valid_until = int(valid_until)
# Make sure we dont have any exclamations in the user_id
user_id = ulp.quote(user_id)
# Create a comma seperated list of tokens
... |
<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(self, ticket, client_ip=None, now=None, encoding='utf-8'):
"""Validates the passed ticket, , raises a TicketError on failure Args: ticket: String va... |
parts = self.parse(ticket)
# Check if our ticket matches
new_ticket = self.new(*(parts[1:]), client_ip=client_ip, encoding=encoding)
if new_ticket[:self._hash.digest_size * 2] != parts.digest:
raise TicketDigestError(ticket)
if now is None:
now = time.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, ticket):
"""Parses the passed ticket, returning a tuple containing the digest, user_id, valid_until, tokens, and user_data fields """ |
if len(ticket) < self._min_ticket_size():
raise TicketParseError(ticket, 'Invalid ticket length')
digest_len = self._hash.digest_size * 2
digest = ticket[:digest_len]
try:
time_len = 8
time = int(ticket[digest_len:digest_len + time_len], 16)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_word(self, *args, **kwargs):
""" Return a random word from this tree. The length of the word depends on the this tree. :return: a random word from thi... |
word = ""
current = (">", 0)
while current[0] != "<":
choices = self[current]
choice = random_weighted_choice(choices)
current = choice
word += current[0][-1]
return word[:-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 buy(self):
""" Attempts to purchase a user shop item, returns result Uses the associated user and buyURL to attempt to purchase the user shop item. Returns w... |
# Buy the item
pg = self.usr.getPage("http://www.neopets.com/" + self.buyURL, vars = {'Referer': 'http://www.neopets.com/browseshop.phtml?owner=' + self.owner})
# If it was successful a redirect to the shop is sent
if "(owned by" in pg.content:
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 fetch(self, cache=None):
"""Query the info page to fill in the property cache. Return a dictionary with the fetched properties and values. """ |
self.reset()
soup = get(self.url).soup
details = soup.find(id="detailsframe")
getdef = lambda s: [elem
for elem in details.find("dt",
text=re.compile(s)).next_siblings
if elem.name == 'dd'][0]
getdefstring = lambda s: getdef(s).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 get(self, item, cache=None):
"""Lookup a torrent info property. If cache is True, check the cache first. If the cache is empty, then fetch torrent info befor... |
if item not in self._keys:
raise KeyError(item)
if self._use_cache(cache) and (self._fetched or
item in self._attrs):
return self._attrs[item]
info = self.fetch(cache=cache)
return info[item] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def as_dict(self, cache=None, fetch=True):
"""Return torrent properties as a dictionary. Set the cache flag to False to disable the cache. On the other hand, set... |
if not self._fetched and fetch:
info = self.fetch(cache)
elif self._use_cache(cache):
info = self._attrs.copy()
else:
info = {}
info.update(url=self.url)
return 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 user_filter(config, message, fasnick=None, *args, **kw):
""" A particular user Use this rule to include messages that are associated with a specific user. ""... |
fasnick = kw.get('fasnick', fasnick)
if fasnick:
return fasnick in fmn.rules.utils.msg2usernames(message, **config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def not_user_filter(config, message, fasnick=None, *args, **kw):
""" Everything except a particular user Use this rule to exclude messages that are associated wi... |
fasnick = kw.get('fasnick', fasnick)
if not fasnick:
return False
fasnick = (fasnick or []) and fasnick.split(',')
valid = True
for nick in fasnick:
if nick.strip() in fmn.rules.utils.msg2usernames(message, **config):
valid = False
break
return valid |
<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_users_of_group(config, group):
""" Utility to query fas for users of a group. """ |
if not group:
return set()
fas = fmn.rules.utils.get_fas(config)
return fmn.rules.utils.get_user_of_group(config, fas, group) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fas_group_member_filter(config, message, group=None, *args, **kw):
""" Messages regarding any member of a FAS group Use this rule to include messages that ha... |
if not group:
return False
fasusers = _get_users_of_group(config, group)
msgusers = fmn.rules.utils.msg2usernames(message, **config)
return bool(fasusers.intersection(msgusers)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def package_filter(config, message, package=None, *args, **kw):
""" A particular package Use this rule to include messages that relate to a certain package (*i.e... |
package = kw.get('package', package)
if package:
return package in fmn.rules.utils.msg2packages(message, **config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def package_regex_filter(config, message, pattern=None, *args, **kw):
""" All packages matching a regular expression Use this rule to include messages that relat... |
pattern = kw.get('pattern', pattern)
if pattern:
packages = fmn.rules.utils.msg2packages(message, **config)
regex = fmn.rules.utils.compile_regex(pattern.encode('utf-8'))
return any([regex.search(p.encode('utf-8')) for p in packages]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regex_filter(config, message, pattern=None, *args, **kw):
""" All messages matching a regular expression Use this rule to include messages that bear a certai... |
pattern = kw.get('pattern', pattern)
if pattern:
regex = fmn.rules.utils.compile_regex(pattern.encode('utf-8'))
return bool(regex.search(
fedmsg.encoding.dumps(message['msg']).encode('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 add_option(self, opt_name, otype, hidden=False):
""" Add an option to the object :param opt_name: option name :type opt_name: str :param otype: option type :... |
if self.has_option(opt_name):
raise ValueError("The option is already present !")
opt = ValueOption.FromType(opt_name, otype)
opt.hidden = hidden
self._options[opt_name] = opt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_options(self):
""" print description of the component options """ |
summary = []
for opt_name, opt in self.options.items():
if opt.hidden:
continue
summary.append(opt.summary())
print("\n".join(summary)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadtxt(fn, **kwargs):
"""Study the text data file fn. Call numpys loadtxt with keyword arguments based on the study. Return data returned from numpy `loadtx... |
global PP
PP = PatternPull(fn)
txtargs = PP.loadtxtargs()
txtargs.update(kwargs) # Let kwargs dominate.
return np.loadtxt(fn, **txtargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadtxt_asdict(fn, **kwargs):
"""Return what is returned from loadtxt as a dict. The 'unpack' keyword is enforced to True. The keys in the dict is the column... |
kwargs.update(unpack=True)
d = loadtxt(fn, **kwargs)
if len(np.shape(d)) == 2:
keys = kwargs.get('usecols', None) or range(len(d))
D = dict([(k, v) for k, v in zip(keys, d)])
elif len(np.shape(d)) == 1:
keys = kwargs.get('usecols', None) or [0]
D = dict([(keys[0], 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 file_rows(self, fo):
"""Return the lines in the file as a list. fo is the open file object.""" |
rows = []
for i in range(NUMROWS):
line = fo.readline()
if not line:
break
rows += [line]
return rows |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_matches(self):
"""Set the matches_p, matches_c and rows attributes.""" |
try:
self.fn = self.fo.name
rows = self.file_rows(self.fo)
self.fo.seek(0)
except AttributeError:
with open(self.fn) as fo:
rows = self.file_rows(fo)
matches_p = []
matches_c = []
for line in rows:
cn... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rows2skip(self, decdel):
""" Return the number of rows to skip based on the decimal delimiter decdel. When each record start to have the same number of match... |
if decdel == '.':
ms = self.matches_p
elif decdel == ',':
ms = self.matches_c
# else make error...
cnt = row = 0
for val1, val2 in zip(ms, ms[1:]):
# val2 is one element ahead.
row += 1
if val2 == val1 != 0: # 0 is ... |
<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_decdel_rts(self):
"""Figure out the decimal seperator and rows to skip and set corresponding attributes. """ |
lnr = max(self.rows2skip(','), self.rows2skip('.')) + 1
# If EQUAL_CNT_REQ was not met, raise error. Implement!
if self.cnt > EQUAL_CNT_REQ:
raise PatternError('Did not find ' + str(EQUAL_CNT_REQ) +
' data rows with equal data pattern in file: ' +
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def study_datdel(self):
"""Figure out the data delimiter.""" |
nodigs = r'(\D+)'
line = self.rows[self.rts + 1] # Study second line of data only.
digs = re.findall(self.datrx, line)
# if any of the numbers contain a '+' in it, it need to be escaped
# before used in the pattern:
digs = [dig.replace('+', r'\+') for dig in digs]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def channel_names(self, usecols=None):
"""Attempt to extract the channel names from the data file. Return a list with names. Return None on failed attempt. useco... |
# Search from [rts - 1] and up (last row before data). Split respective
# row on datdel. Accept consecutive elements starting with alphas
# character after strip. If the count of elements equals the data count
# on row rts + 1, accept it as the channel names.
if self.decdel ==... |
<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, cls, instance):
""" Register the given instance as implementation for a class interface """ |
if not issubclass(cls, DropletInterface):
raise TypeError('Given class is not a NAZInterface subclass: %s'
% cls)
if not isinstance(instance, cls):
raise TypeError('Given instance does not implement the class: %s'
% instan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stream_tap(callables, stream):
""" Calls each callable with each item in the stream. Use with Buckets. Make a Bucket with a callable and then pass a tuple of... |
for item in stream:
for caller in callables:
caller(item)
yield item |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def selected(self, interrupt=False):
"""This object has been selected.""" |
self.ao2.output(self.get_title(), interrupt=interrupt) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def header(self, k, v, replace=True):
""" Sets header value. Replaces existing value if `replace` is True. Otherwise create a list of existing values and `v` :pa... |
if replace:
self._headers[k] = [v]
else:
self._headers.setdefault(k, []).append(v)
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 cookie(self, k, v, expires=None, domain=None, path='/', secure=False):
""" Sets cookie value. :param k: Name for cookie value :param v: Cookie value :param e... |
ls = ['{}={}'.format(k, v)]
if expires is not None:
dt = format_date_time(mktime(expires.timetuple()))
ls.append('expires={}'.format(dt))
if domain is not None:
ls.append('domain={}'.format(domain))
if path is not None:
ls.append('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 decorate_all_methods(decorator):
""" Build and return a decorator that will decorate all class members. This will apply the passed decorator to all of the me... |
def decorate_class(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
if name != "__init__":
setattr(cls, name, decorator(m))
return cls
return decorate_class |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def just_in_time_method(func):
""" This is a dcorator for methods. It redirect calls to the decorated method to the equivalent method in a class member called 'i... |
if not inspect.ismethod:
raise MetaError("oops")
def wrapper(self, *args, **kwargs):
if self.item is None:
self.item = self.factory[self.key]
return getattr(self.item, func.__name__)(*args, **kwargs)
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def AddAccelerator(self, modifiers, key, action):
""" Add an accelerator. Modifiers and key follow the same pattern as the list used to create wx.AcceleratorTabl... |
newId = wx.NewId()
self.Bind(wx.EVT_MENU, action, id = newId)
self.RawAcceleratorTable.append((modifiers, key, newId))
self.SetAcceleratorTable(wx.AcceleratorTable(self.RawAcceleratorTable))
return newId |
<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_config(lines, module=None):
"""Parse a config file. Names referenced within the config file are found within the calling scope. For example:: would fin... |
if module is None:
module = _calling_scope(2)
lines = IndentChecker(lines)
path_router = PathRouter()
for depth, line in lines:
if depth > 0:
raise SyntaxError('unexpected indent')
name, path, types = parse_path_spec(line)
if types:
template_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 load_config(name='urls.conf'):
"""Load a config from a resource file. The resource is found using `pkg_resources.resource_stream()`_, relative to the calling... |
module = _calling_scope(2)
config = resource_stream(module.__name__, name)
return parse_config(config, module) |
<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_placeholder(self, name=None, db_type=None):
"""Returns a placeholder for the specified name, by applying the instance's format strings. :name: if None an ... |
if name is None:
placeholder = self.unnamed_placeholder
else:
placeholder = self.named_placeholder.format(name)
if db_type:
return self.typecast(placeholder, db_type)
else:
return placeholder |
<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_tuple(self, iterable, surround="()", joiner=", "):
"""Returns the iterable as a SQL tuple.""" |
return "{0}{1}{2}".format(surround[0], joiner.join(iterable), surround[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 to_expression(self, lhs, rhs, op):
"""Builds a binary sql expression. At its most basic, returns 'lhs op rhs' such as '5 + 3'. However, it also specially han... |
if op == "raw":
# TODO: This is not documented
return lhs
elif op == "between":
return "{0} between {1} and {2}".format(lhs, *rhs)
elif op == "in":
return "{0} in {1}".format(lhs, self.to_tuple(rhs))
elif op.startswith("not(") and op.endswith(")"):
return "not ({0} {1} {2}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_comparisons(self, values, comp="=", is_assignment=False):
"""Builds out a series of value comparisions. :values: can either be a dictionary, in which c... |
if isinstance(values, dict):
if self.sort_columns:
keys = sorted(values.keys())
else:
keys = list(values.keys())
params = zip(keys, [self.to_placeholder(k) for k in keys])
return [
self.to_expression(
i[0],
i[1],
comp if is_assignment e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_comparisons(self, values, joiner, *, is_assignment=False, comp="="):
"""Generates comparisons with the value_comparisions method, and joins them with jo... |
if isinstance(values, str):
return values
else:
return joiner.join(self.value_comparisons(values, comp, is_assignment)) |
<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_params(self, values):
"""Gets params to be passed to execute from values. :values: can either be a dict, in which case it will be returned as is, or can ... |
if values is None:
return None
elif isinstance(values, dict):
return values
elif isinstance(values, (list, tuple)):
params = []
for val in values:
if len(val) == 2:
params.append(val[1])
else:
if val[2] in ("in", "between"):
params.ext... |
<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_find_all_query(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=(None, None)):
"""Builds a find query. :limiting: if present ... |
where, params = self.parse_constraints(constraints)
if columns:
if isinstance(columns, str):
pass
else:
columns = ", ".join(columns)
else:
columns = "*"
if order_by:
order = " order by {0}".format(order_by)
else:
order = ""
paging = ""
if lim... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pretty_print(rows, keyword, domain):
""" rows is list when get domains dict when get specific domain """ |
if isinstance(rows, dict):
pretty_print_domain(rows, keyword, domain)
elif isinstance(rows, list):
pretty_print_zones(rows) |
<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_data(self, data, datatype="ttl", namespace=None, graph=None, is_file=False, **kwargs):
""" Loads data via file stream from python to triplestore Args: -... |
log.setLevel(kwargs.get("log_level", self.log_level))
time_start = datetime.datetime.now()
datatype_map = {
'ttl': 'text/turtle',
'xml': 'application/rdf+xml',
'rdf': 'application/rdf+xml',
'nt': 'text/plain'
}
if is_file:
... |
<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_local_file(self, file_path, namespace=None, graph=None, **kwargs):
""" Uploads data to the Blazegraph Triplestore that is stored in files in directory t... |
time_start = datetime.datetime.now()
url = self._make_url(namespace)
params = {}
if graph:
params['context-uri'] = graph
new_path = []
container_dir = pick(kwargs.get('container_dir'), self.container_dir)
if container_dir:
new_path.append(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_namespace(self, namespace):
""" tests to see if the namespace exists args: namespace: the name of the namespace """ |
result = requests.get(self._make_url(namespace))
if result.status_code == 200:
return True
elif result.status_code == 404:
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 create_namespace(self, namespace=None, params=None):
""" Creates a namespace in the triplestore args: namespace: the name of the namspace to create params: D... |
namespace = pick(namespace, self.namespace)
params = pick(params, self.namespace_params)
if not namespace:
raise ReferenceError("No 'namespace' specified")
_params = {'axioms': 'com.bigdata.rdf.axioms.NoAxioms',
'geoSpatial': False,
'iso... |
<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_namespace(self, namespace):
""" Deletes a namespace fromt the triplestore args: namespace: the name of the namespace """ |
# if not self.has_namespace(namespace):
# return "Namespace does not exists"
# log = logging.getLogger("%s.%s" % (self.log_name,
# inspect.stack()[0][3]))
# log.setLevel(self.log_level)
url = self._make_url(namespace).replace("/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 _make_url(self, namespace=None, url=None, **kwargs):
""" Creates the REST Url based on the supplied namespace args: namespace: string of the namespace kwargs... |
if not kwargs.get("check_status_call"):
if not self.url:
self.check_status
rtn_url = self.url
if url:
rtn_url = url
if rtn_url is None:
rtn_url = self.ext_url
namespace = pick(namespace, self.namespace)
if namespace:
... |
<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_namespace(self, namespace=None, params=None):
""" Will delete and recreate specified namespace args: namespace(str):
Namespace to reset params(dict):
... |
log = logging.getLogger("%s.%s" % (self.log_name,
inspect.stack()[0][3]))
log.setLevel(self.log_level)
namespace = pick(namespace, self.namespace)
params = pick(params, self.namespace_params)
log.warning(" Reseting namespace '%s' at hos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tree_render(request, upy_context, vars_dictionary):
""" It renders template defined in upy_context's page passed in arguments """ |
page = upy_context['PAGE']
return render_to_response(page.template.file_name, vars_dictionary, context_instance=RequestContext(request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view_404(request, url=None):
""" It returns a 404 http response """ |
res = render_to_response("404.html", {"PAGE_URL": request.get_full_path()},
context_instance=RequestContext(request))
res.status_code = 404
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def view_500(request, url=None):
""" it returns a 500 http response """ |
res = render_to_response("500.html", context_instance=RequestContext(request))
res.status_code = 500
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def favicon(request):
""" It returns favicon's location """ |
favicon = u"{}tree/images/favicon.ico".format(settings.STATIC_URL)
try:
from seo.models import MetaSite
site = MetaSite.objects.get(default=True)
return HttpResponseRedirect(site.favicon.url)
except:
return HttpResponseRedirect(favicon) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_username(self):
""" Ensure the username doesn't exist or contain invalid chars. We limit it to slugifiable chars since it's used as the slug for the us... |
username = self.cleaned_data.get("username")
if username.lower() != slugify(username).lower():
raise forms.ValidationError(
ugettext("Username can only contain letters, numbers, dashes "
"or underscores."))
lookup = {"username__iexact": usern... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_password2(self):
""" Ensure the password fields are equal, and match the minimum length defined by ``ACCOUNTS_MIN_PASSWORD_LENGTH``. """ |
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1:
errors = []
if password1 != password2:
errors.append(ugettext("Passwords do not match"))
if len(password1) < settings.ACCOUNTS_MIN_PAS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean_email(self):
""" Ensure the email address is not already registered. """ |
email = self.cleaned_data.get("email")
qs = User.objects.exclude(id=self.instance.id).filter(email=email)
if len(qs) == 0:
return email
raise forms.ValidationError(
ugettext("This email is already registered")) |
<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_articles(self, issue=''):
""" Yields a list of articles from the given issue. """ |
soup = get_soup() # get soup of all articles
issues = soup.find_all('ul')
# validating and assigning default value for issue
if not type(issue) is int or issue < 0 :
issue = 1
if issue > len(issues):
issue = len(issues)
# considering latest article is last element
articles = issues[len(is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromLink(self, link):
""" Factory Method. Fetches article data from given link and builds the object """ |
soup = get_article_soup(link)
head = soup.find_all('article',class_='')[0]
parts = link.split('/')
id = '%s-%s'%(parts[0],parts[-1])
issue = parts[0].split('-')[-1]
#fetching head
title = head.find("h1").contents[0] if head.find("h1") else ''
tagline = head.find("h2").contents[0] if head.find("h2") ... |
<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_soup(self,soup):
""" Factory Pattern. Fetches author data from given soup and builds the object """ |
if soup is None or soup is '':
return None
else:
author_name = soup.find('em').contents[0].strip() if soup.find('em') else ''
author_image = soup.find('img').get('src') if soup.find('img') else ''
author_contact = Contact.from_soup(self,soup)
return Author(author_name,author_image,author_contact) |
<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_soup(self,author,soup):
""" Factory Pattern. Fetches contact data from given soup and builds the object """ |
email = soup.find('span',class_='icon icon-mail').findParent('a').get('href').split(':')[-1] if soup.find('span',class_='icon icon-mail') else ''
facebook = soup.find('span',class_='icon icon-facebook').findParent('a').get('href') if soup.find('span',class_='icon icon-facebook') else ''
twitter = soup.find('sp... |
<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(self, text):
""" Return a list of genres found in text. """ |
genres = []
text = text.lower()
category_counter = Counter()
counter = Counter()
for genre in self.db.genres:
found = self.contains_entity(genre, text)
if found:
counter[genre] += found
category = self.db.reference[genr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains_entity(entity, text):
""" Attempt to try entity, return false if not found. Otherwise the amount of time entitu is occuring. """ |
try:
entity = re.escape(entity)
entity = entity.replace("\ ", "([^\w])?")
pattern = "(\ |-|\\\|/|\.|,|^)%s(\ |\-|\\\|/|\.|,|$)" % entity
found = len(re.findall(pattern, text, re.I | re.M))
except Exception as e:
found = False
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 is_executable(path):
'''is the given path executable?'''
return (stat.S_IXUSR & os.stat(path)[stat.ST_MODE]
or stat.S_IXGRP & os.stat(path)[stat.ST_MODE]
or stat.S_IXOTH & os.stat(path)[stat.ST_MODE]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def prepare_writeable_dir(tree):
''' make sure a directory exists and is writeable '''
if tree != '/':
tree = os.path.realpath(os.path.expanduser(tree))
if not os.path.exists(tree):
try:
os.makedirs(tree)
except (IOError, OSError), e:
exit("Could not make dir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def path_dwim(basedir, given):
'''
make relative paths work like folks expect.
'''
if given.startswith("/"):
return given
elif given.startswith("~/"):
return os.path.expanduser(given)
else:
return os.path.join(basedir, given) |
<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_json(raw_data):
''' this version for module return data only '''
orig_data = raw_data
# ignore stuff like tcgetattr spewage or other warnings
data = filter_leading_non_json_lines(raw_data)
try:
return json.loads(data)
except:
# not JSON, but try "Baby JSON" which all... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def md5(filename):
''' Return MD5 hex digest of local file, or None if file is not present. '''
if not os.path.exists(filename):
return None
digest = _md5()
blocksize = 64 * 1024
infile = open(filename, 'rb')
block = infile.read(blocksize)
while block:
digest.update(block)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _gitinfo():
''' returns a string containing git branch, commit id and commit date '''
result = None
repo_path = os.path.join(os.path.dirname(__file__), '..', '..', '..', '.git')
if os.path.exists(repo_path):
# Check if the .git is a file. If it is a file, it means that we are in a submodule... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compile_when_to_only_if(expression):
'''
when is a shorthand for writing only_if conditionals. It requires less quoting
magic. only_if is retained for backwards compatibility.
'''
# when: set $variable
# when: unset $variable
# when: failed $json_result
# when: changed $json_resul... |
<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_sudo_cmd(sudo_user, executable, cmd):
""" helper function for connection plugins to create sudo commands """ |
# Rather than detect if sudo wants a password this time, -k makes
# sudo always ask for a password if one is required.
# Passing a quoted compound command to sudo (or sudo -s)
# directly doesn't work, so we shellquote it with pipes.quote()
# and pass the quoted string to the user's shell. We loop ... |
<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(self):
""" Logs the user in, returns the result Returns bool - Whether or not the user logged in successfully """ |
# Request index to obtain initial cookies and look more human
pg = self.getPage("http://www.neopets.com")
form = pg.form(action="/login.phtml")
form.update({'username': self.username, 'password': self.password})
pg = form.submit()
logging.getLogger("neolib.us... |
<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(self, browser):
""" Enables cookie synchronization with specified browser, returns result Returns bool - True if successful, false otherwise """ |
BrowserCookies.loadBrowsers()
if not browser in BrowserCookies.browsers:
return False
self.browserSync = True
self.browser = browser
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 save(self):
""" Exports all user attributes to the user's configuration and writes configuration Saves the values for each attribute stored in User.configVar... |
# Code to load all attributes
for prop in dir(self):
if getattr(self, prop) == None: continue
if not prop in self.configVars: continue
# Special handling for some attributes
if prop == "session":
pic = pickle.dumps(getattr(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mod_git_ignore(directory, ignore_item, action):
""" checks if an item is in the specified gitignore file and adds it if it is not in the file """ |
if not os.path.isdir(directory):
return
ignore_filepath = os.path.join(directory,".gitignore")
if not os.path.exists(ignore_filepath):
items = []
else:
with open(ignore_filepath) as ig_file:
items = ig_file.readlines()
# strip and clean the lines
clean_items ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def monitor_running_process(context: RunContext):
""" Runs an infinite loop that waits for the process to either exit on its or time out Captures all output from... |
while True:
capture_output_from_running_process(context)
if context.process_finished():
context.return_code = context.command.returncode
break
if context.process_timed_out():
context.return_code = -1
raise ProcessTimeoutError(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def base_elts(elt, cls=None, depth=None):
"""Get bases elements of the input elt. - If elt is an instance, get class and all base classes. - If elt is a method, ... |
result = []
elt_name = getattr(elt, '__name__', None)
if elt_name is not None:
cls = [] if cls is None else ensureiterable(cls)
elt_is_class = False
# if cls is None and elt is routine, it is possible to find the cls
if not cls and isroutine(elt):
if hasat... |
<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_embedding(elt, embedding=None):
"""Try to get elt embedding elements. :param embedding: embedding element. Must have a module. :return: a list of [modul... |
result = [] # result is empty in the worst case
# start to get module
module = getmodule(elt)
if module is not None: # if module exists
visited = set() # cache to avoid to visit twice same element
if embedding is None:
embedding = module
# list of compounds ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def projects(accountable):
""" List all projects. """ |
projects = accountable.metadata()['projects']
headers = sorted(['id', 'key', 'self'])
rows = [[v for k, v in sorted(p.items()) if k in headers] for p in projects]
rows.insert(0, headers)
print_table(SingleTable(rows)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def issuetypes(accountable, project_key):
""" List all issue types. Optional parameter to list issue types by a given project. """ |
projects = accountable.issue_types(project_key)
headers = sorted(['id', 'name', 'description'])
rows = []
for key, issue_types in sorted(projects.items()):
for issue_type in issue_types:
rows.append(
[key] + [v for k, v in sorted(issue_type.items())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def components(accountable, project_key):
""" Returns a list of all a project's components. """ |
components = accountable.project_components(project_key)
headers = sorted(['id', 'name', 'self'])
rows = [[v for k, v in sorted(component.items()) if k in headers]
for component in components]
rows.insert(0, headers)
print_table(SingleTable(rows)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkoutbranch(accountable, options):
""" Create a new issue and checkout a branch named after it. """ |
issue = accountable.checkout_branch(options)
headers = sorted(['id', 'key', 'self'])
rows = [headers, [itemgetter(header)(issue) for header in headers]]
print_table(SingleTable(rows)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def checkout(accountable, issue_key):
""" Checkout a new branch or checkout to a branch for a given issue. """ |
issue = accountable.checkout(issue_key)
headers = issue.keys()
rows = [headers, [v for k, v in issue.items()]]
print_table(SingleTable(rows)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def issue(ctx, accountable, issue_key):
""" List metadata for a given issue key. """ |
accountable.issue_key = issue_key
if not ctx.invoked_subcommand:
issue = accountable.issue_meta()
headers = issue.keys()
rows = [headers, [v for k, v in issue.items()]]
print_table(SingleTable(rows)) |
<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(accountable, options):
""" Update an existing issue. """ |
issue = accountable.issue_update(options)
headers = issue.keys()
rows = [headers, [v for k, v in issue.items()]]
print_table(SingleTable(rows)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comments(accountable):
""" Lists all comments for a given issue key. """ |
comments = accountable.issue_comments()
headers = sorted(['author_name', 'body', 'updated'])
if comments:
rows = [[v for k, v in sorted(c.items()) if k in headers]
for c in comments]
rows.insert(0, headers)
print_table(SingleTable(rows))
else:
click.sech... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def addcomment(accountable, body):
""" Add a comment to the given issue key. Accepts a body argument to be used as the comment's body. """ |
r = accountable.issue_add_comment(body)
headers = sorted(['author_name', 'body', 'updated'])
rows = [[v for k, v in sorted(r.items()) if k in headers]]
rows.insert(0, headers)
print_table(SingleTable(rows)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def worklog(accountable):
""" List all worklogs for a given issue key. """ |
worklog = accountable.issue_worklog()
headers = ['author_name', 'comment', 'time_spent']
if worklog:
rows = [[v for k, v in sorted(w.items()) if k in headers]
for w in worklog]
rows.insert(0, headers)
print_table(SingleTable(rows))
else:
click.secho(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transitions(accountable):
""" List all possible transitions for a given issue. """ |
transitions = accountable.issue_transitions().get('transitions')
headers = ['id', 'name']
if transitions:
rows = [[v for k, v in sorted(t.items()) if k in headers]
for t in transitions]
rows.insert(0, headers)
print_table(SingleTable(rows))
else:
click.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 dotransition(accountable, transition_id):
""" Transition the given issue to the provided ID. The API does not return a JSON response for this call. """ |
t = accountable.issue_do_transition(transition_id)
if t.status_code == 204:
click.secho(
'Successfully transitioned {}'.format(accountable.issue_key),
fg='green'
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def users(accountable, query):
""" Executes a user search for the given query. """ |
users = accountable.users(query)
headers = ['display_name', 'key']
if users:
rows = [[v for k, v in sorted(u.items()) if k in headers]
for u in users]
rows.insert(0, headers)
print_table(SingleTable(rows))
else:
click.secho('No users found for query {}'.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 guess_saves(zone, data):
"""Return types with guessed DST saves""" |
saves = {}
details = {}
for (time0, type0), (time1, type1) in pairs(data.times):
is_dst0 = bool(data.types[type0][1])
is_dst1 = bool(data.types[type1][1])
if (is_dst0, is_dst1) == (False, True):
shift = data.types[type1][0] - data.types[type0][0]
if shift:
... |
<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_commit_tree(profile, sha):
"""Get the SHA of a commit's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profil... |
data = commits.get_commit(profile, sha)
tree = data.get("tree")
sha = tree.get("sha")
return sha |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_file_from_tree(tree, file_path):
"""Remove a file from a tree. Args: tree A list of dicts containing info about each blob in a tree. file_path The pat... |
match = None
for item in tree:
if item.get("path") == file_path:
match = item
break
if match:
tree.remove(match)
return tree |
<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_file_to_tree(tree, file_path, file_contents, is_executable=False):
"""Add a file to a tree. Args: tree A list of dicts containing info about each blob in... |
record = {
"path": file_path,
"mode": "100755" if is_executable else "100644",
"type": "blob",
"content": file_contents,
}
tree.append(record)
return tree |
<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_files_in_branch(profile, branch_sha):
"""Get all files in a branch's tree. Args: profile A profile generated from ``simplygithub.authentication.profile``... |
tree_sha = get_commit_tree(profile, branch_sha)
files = get_files_in_tree(profile, tree_sha)
tree = [prepare(x) for x in files]
return tree |
<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_file( profile, branch, file_path, file_contents, is_executable=False, commit_message=None):
"""Add a file to a branch. Args: profile A profile generated ... |
branch_sha = get_branch_sha(profile, branch)
tree = get_files_in_branch(profile, branch_sha)
new_tree = add_file_to_tree(tree, file_path, file_contents, is_executable)
data = trees.create_tree(profile, new_tree)
sha = data.get("sha")
if not commit_message:
commit_message = "Added " + fi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.