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 unique_slug(queryset, slug_field, slug):
""" Ensures a slug is unique for the given queryset, appending an integer to its end until the slug is unique. """ |
i = 0
while True:
if i > 0:
if i > 1:
slug = slug.rsplit("-", 1)[0]
slug = "%s-%s" % (slug, i)
try:
queryset.get(**{slug_field: slug})
except ObjectDoesNotExist:
break
i += 1
return slug |
<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_url(request):
""" Returns URL to redirect to from the ``next`` param in the request. """ |
next = request.GET.get("next", request.POST.get("next", ""))
host = request.get_host()
return next if next and is_safe_url(next, host=host) else 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 path_to_slug(path):
""" Removes everything from the given URL path, including language code and ``PAGES_SLUG`` if any is set, returning a slug that would mat... |
from yacms.urls import PAGES_SLUG
lang_code = translation.get_language_from_path(path)
for prefix in (lang_code, settings.SITE_PREFIX, PAGES_SLUG):
if prefix:
path = path.replace(prefix, "", 1)
return clean_slashes(path) or "/" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_exception(self, request, exception):
"""Report exceptions from requests via Exreporter. """ |
gc = GithubCredentials(
user=settings.EXREPORTER_GITHUB_USER,
repo=settings.EXREPORTER_GITHUB_REPO,
auth_token=settings.EXREPORTER_GITHUB_AUTH_TOKEN)
gs = GithubStore(credentials=gc)
reporter = ExReporter(
store=gs, labels=settings.EXREPORTER_GITH... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
""" Connects to publisher """ |
self.client = redis.Redis(
host=self.host, port=self.port, password=self.password) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
""" Connects to Redis """ |
logger.info("Connecting to Redis on {host}:{port}...".format(
host=self.host, port=self.port))
super(RedisSubscriber, self).connect()
logger.info("Successfully connected to Redis")
# Subscribe to channel
self.pubsub = self.client.pubsub()
self.pubsub.subscr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen(self):
""" Listen for messages """ |
for message in self.pubsub.listen():
if message['type'] == 'message':
message_type, client_id, client_storage, args, kwargs = self.unpack(
message['data'])
self.dispatch_message(
message_type, client_id, client_storage, args, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exit(self):
""" Closes the connection """ |
self.pubsub.unsubscribe()
self.client.connection_pool.disconnect()
logger.info("Connection to Redis closed") |
<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_kwargs(self):
""" Returns kwargs for both publisher and subscriber classes """ |
return {
'host': self.host,
'port': self.port,
'channel': self.channel,
'password': self.password
} |
<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(fname):
" read the passed file "
if exists(fname):
return open(join(dirname(__file__), fname)).read() |
<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(url, **args):
"""Get the object from a ftp URL.""" |
all_ = args.pop('all', False)
password = args.pop('password', '')
if not password:
raise ValueError('password')
try:
username, __ = url.username.split(';')
except ValueError:
username = url.username
if not username:
username = os.environ.get('USERNAME')
u... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get():
""" Get all nagios status information from a local nagios instance """ |
livestatus = mk_livestatus()
hosts = livestatus.get_hosts()
services = livestatus.get_services()
result = {}
result['hosts'] = hosts
result['services'] = services
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(remote_host=None):
""" Send local nagios data to a remote nago instance """ |
my_data = get()
if not remote_host:
remote_host = nago.extensions.settings.get('server')
remote_node = nago.core.get_node(remote_host)
remote_node.send_command('checkresults', 'post', **my_data)
return "checkresults sent to %s" % remote_host |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_checkresult(**kwargs):
""" Returns a string in a nagios "checkresults" compatible format """ |
o = {}
o['check_type'] = '1'
o['check_options'] = '0'
o['scheduled_check'] = '1'
o['reschedule_check'] = '1'
o['latency'] = '0.0'
o['start_time'] = '%5f' % time.time()
o['finish_time'] = '%5f' % time.time()
o['early_timeout'] = '0'
o['exited_ok'] = '1'
o['long_plugin_output'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_data(self, time, value, series_id=None, key=None, tz=None):
"""Create a DataPoint object from data, rather than a JSON object or string. This should be ... |
t = check_time_param(time)
if type(value) in [float, int]:
v = value
else:
raise ValueError('Values must be int or float. Got "%s".' %
str(value))
j = {
't': t,
'v': v,
'id': series_id,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate(self, size=0):
""" Truncates the stream to the specified length. @param size: The length of the stream, in bytes. @type size: C{int} """ |
if size == 0:
self._buffer = StringIO()
self._len_changed = True
return
cur_pos = self.tell()
self.seek(0)
buf = self.read(size)
self._buffer = StringIO()
self._buffer.write(buf)
self.seek(cur_pos)
self._len_changed ... |
<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_len(self):
""" Return total number of bytes in buffer. """ |
if hasattr(self._buffer, 'len'):
self._len = self._buffer.len
return
old_pos = self._buffer.tell()
self._buffer.seek(0, 2)
self._len = self._buffer.tell()
self._buffer.seek(old_pos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_big_endian(self):
""" Whether the current endian is big endian. """ |
if self.endian == DataTypeMixIn.ENDIAN_NATIVE:
return SYSTEM_ENDIAN == DataTypeMixIn.ENDIAN_BIG
return self.endian in (DataTypeMixIn.ENDIAN_BIG, DataTypeMixIn.ENDIAN_NETWORK) |
<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_ushort(self, s):
""" Writes a 2 byte unsigned integer to the stream. @param s: 2 byte unsigned integer @type s: C{int} @raise TypeError: Unexpected typ... |
if type(s) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(s),))
if not 0 <= s <= 65535:
raise OverflowError("Not in range, %d" % s)
self.write(struct.pack("%sH" % self.endian, 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 write_ulong(self, l):
""" Writes a 4 byte unsigned integer to the stream. @param l: 4 byte unsigned integer @type l: C{int} @raise TypeError: Unexpected type... |
if type(l) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(l),))
if not 0 <= l <= 4294967295:
raise OverflowError("Not in range, %d" % l)
self.write(struct.pack("%sL" % self.endian, 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 read_24bit_uint(self):
""" Reads a 24 bit unsigned integer from the stream. @since: 0.4 """ |
order = None
if not self._is_big_endian():
order = [0, 8, 16]
else:
order = [16, 8, 0]
n = 0
for x in order:
n += (self.read_uchar() << x)
return n |
<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_24bit_uint(self, n):
""" Writes a 24 bit unsigned integer to the stream. @since: 0.4 @param n: 24 bit unsigned integer @type n: C{int} @raise TypeError... |
if type(n) not in python.int_types:
raise TypeError('expected an int (got:%r)' % (type(n),))
if not 0 <= n <= 0xffffff:
raise OverflowError("n is out of range")
order = None
if not self._is_big_endian():
order = [0, 8, 16]
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 write_double(self, d):
""" Writes an 8 byte float to the stream. @param d: 8 byte float @type d: C{float} @raise TypeError: Unexpected type for float C{d}. "... |
if not type(d) is float:
raise TypeError('expected a float (got:%r)' % (type(d),))
self.write(struct.pack("%sd" % self.endian, 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 write_float(self, f):
""" Writes a 4 byte float to the stream. @param f: 4 byte float @type f: C{float} @raise TypeError: Unexpected type for float C{f}. """ |
if type(f) is not float:
raise TypeError('expected a float (got:%r)' % (type(f),))
self.write(struct.pack("%sf" % self.endian, 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 read_utf8_string(self, length):
""" Reads a UTF-8 string from the stream. @rtype: C{unicode} """ |
s = struct.unpack("%s%ds" % (self.endian, length), self.read(length))[0]
return s.decode('utf-8') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_utf8_string(self, u):
""" Writes a unicode object to the stream in UTF-8. @param u: unicode object @raise TypeError: Unexpected type for str C{u}. """ |
if not isinstance(u, python.str_types):
raise TypeError('Expected %r, got %r' % (python.str_types, u))
bytes = u
if isinstance(bytes, unicode):
bytes = u.encode("utf8")
self.write(struct.pack("%s%ds" % (self.endian, len(bytes)), bytes)) |
<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(self, length=-1):
""" Reads up to the specified number of bytes from the stream into the specified byte array of specified length. @raise IOError: Attem... |
if length == -1 and self.at_eof():
raise IOError(
'Attempted to read from the buffer but already at the end')
elif length > 0 and self.tell() + length > len(self):
raise IOError('Attempted to read %d bytes from the buffer but '
'only %d remain' % ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, data):
""" Append data to the end of the stream. The pointer will not move if this operation is successful. @param data: The data to append to t... |
t = self.tell()
# seek to the end of the stream
self.seek(0, 2)
if hasattr(data, 'getvalue'):
self.write_utf8_string(data.getvalue())
else:
self.write_utf8_string(data)
self.seek(t) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calibration(date, satellite):
""" Return the calibration dictionary. Keyword arguments: satellite -- the name of the satellite. date -- the datetime of an im... |
counts_shift = CountsShift()
space_measurement = SpaceMeasurement()
prelaunch = PreLaunch()
postlaunch = PostLaunch()
return {
'counts_shift': counts_shift.coefficient(satellite),
'space_measurement': space_measurement.coefficient(satellite),
'prelaunch': prelaunch.coefficie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def install_dependencies(plugins_directory, ostream=sys.stdout):
'''
Run ``on_plugin_install`` script for each plugin directory found in
specified plugins directory.
Parameters
----------
plugins_directory : str
File system path to directory containing zero or more plugin
subdir... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def previous_weekday(date):
'''
Returns the last weekday before date
Args:
date (datetime or datetime.date)
Returns:
(datetime or datetime.date)
Raises:
-
'''
weekday = date.weekday()
if weekday == 0:
n_days = 3
elif weekday == 6:
n_days = 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 next_weekday(date):
'''
Return the first weekday after date
Args:
date (datetime or datetime.date)
Returns:
(datetime or datetime.date)
Raises:
-
'''
n_days = 7 - date.weekday()
if n_days > 3:
n_days = 1
return date + datetime.timedelta(days=n_day... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def last_year(date_):
'''
Returns the same date 1 year ago.
Args:
date (datetime or datetime.date)
Returns:
(datetime or datetime.date)
Raises:
-
'''
day = 28 if date_.day == 29 and date_.month == 2 else date_.day
return datetime.date(date_.year-1, date_.month, 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 timestr2time(time_str):
'''
Turns a string into a datetime.time object. This will only work if the
format can be "guessed", so the string must have one of the formats from
VALID_TIME_FORMATS_TEXT.
Args:
time_str (str) a string that represents a date
Returns:
datetime.time o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def time2timestr(time, fmt='hhmmss'):
'''
Turns a datetime.time object into a string. The string must have one of the
formats from VALID_TIME_FORMATS_TEXT to make it compatible with
timestr2time.
Args:
time (datetime.time) the time to be translated
fmt (str) a format string.
Re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_custom_concurrency(default, forced, logger=None):
""" Get the proper concurrency value according to the default one and the one specified by the crawle... |
logger = logger or LOGGER
cmc_msg = 'Invalid "max_concurrent_tasks: '
if not isinstance(forced, int):
logger.warn(cmc_msg + 'expecting int')
elif forced > default:
msg = 'may not be greater than: %s' % default
logger.warn(cmc_msg + msg)
elif forced < 1:
msg = 'may 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 reorg_crawl_tasks(tasks, concurrency, logger=None):
""" Extract content returned by the crawler `iter_crawl_tasks` member method. :return: tuple made of the ... |
futures = tasks['tasks']
epilogue = tasks.get('epilogue')
custom_concurrency = tasks.get('max_concurrent_tasks', concurrency)
check_custom_concurrency(concurrency, custom_concurrency, logger)
futures = list(futures)
return futures, epilogue, concurrency |
<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_crawl_tasks(tasks, concurrency):
""" Reorganize tasks according to the tasks max concurrency value. :param tasks: sub-tasks to execute, can be either a... |
if any(tasks) and isinstance(tasks[0], list):
for seq in tasks:
if not isinstance(seq, list):
raise Exception("Expected a list of tasks")
else:
if concurrency > 1:
chain_size = int(ceil(float(len(tasks)) / concurrency))
tasks = [
... |
<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_static_merge(cls, c_source, c_target):
"""By the time we're just folding in clusters, there's no need to maintain self.INSTANCES and self.clusters, so we ... |
c_target.extend(c_source)
c_source.parent = c_target.parent
cls.CLUSTERS.remove(c_source)
for m in c_source.mentions:
cls.MENTION_TO_CLUSTER[m] = c_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 random_letters(count):
"""Get a series of pseudo-random letters with no repeats.""" |
rv = random.choice(string.ascii_uppercase)
while len(rv) < count:
l = random.choice(string.ascii_uppercase)
if not l in rv:
rv += l
return rv |
<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_codebuch(path):
"""Generate a month-long codebuch and save it to a file.""" |
lines = []
for i in range(31):
line = str(i+1) + " "
# Pick rotors
all_rotors = ['I', 'II', 'III', 'IV', 'V']
rotors = [random.choice(all_rotors)]
while len(rotors) < 3:
r = random.choice(all_rotors)
if not r in rotors:
rotors.ap... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encrypt(self, plaintext):
"""Have the operator encrypt a message.""" |
# Encrpyt message key.
msg_key = random_letters(3)
while msg_key == self.grundstellung:
msg_key = random_letters(3)
self.machine.set_display(self.grundstellung)
enc_key = self.machine.process_text(msg_key)
# Encrpyt message.
self.machine.set_display... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decrypt(self, ciphertext):
"""Have the operator decrypt a message.""" |
# Separate keys from message.
enc_key = ciphertext[:3]
message = ciphertext[3:-3]
grundstellung = ciphertext[-3:]
# Decrypt message key.
self.machine.set_display(grundstellung)
msg_key = self.machine.process_text(enc_key)
# Decrpyt message.
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 get_version(full=False):
""" Returns a string-ified version number. Optionally accepts a ``full`` parameter, which if ``True``, will include any pre-release ... |
version = '.'.join([str(bit) for bit in __version__[:3]])
if full:
version = '-'.join([version] + list(__version__[3:]))
return version |
<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_args_kwargs(self, *args, **kwargs):
'''Parse the arguments with keywords.'''
# unpack the arginfo
keys, defdict = self.arginfo
assigned = keys[:len(args)]
not_assigned = keys[len(args):]
# validate kwargs
for key in kwargs:
assert key not 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 _get_keys_defdict(self):
'''Get the keys and the default dictionary of the given function's
arguments
'''
# inspect argspecs
argspec = inspect.getargspec(self.func)
keys, defvals = argspec.args, argspec.defaults
# convert to (list_of_argkeys, dict_of_default_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compile_with_value(self, func, args=None, owner=None):
'''Compile the function with array-like objects'''
# format args
if args is None:
args = []
# cast numpy.ndarray into theano.tensor
theano_args = [self.cast2theano_var(a, 'extheano.jit.Compiler-arg-%d' % 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 compile_with_symbol(self, func, theano_args=None, owner=None):
'''Compile the function with theano symbols'''
if theano_args is None:
theano_args = []
# initialize the shared buffers
upc = UpdateCollector()
# get the output symbols and other Theano options
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cast2theano_var(self, array_like, name=None):
'''Cast `numpy.ndarray` into `theano.tensor` keeping `dtype` and `ndim`
compatible
'''
# extract the information of the input value
array = np.asarray(array_like)
args = (name, array.dtype)
ndim = array.ndim
... |
<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_fn(fn, mode, load):
'''
Load a contents, checking that the file was not modified during the read.
'''
try:
mtime_before = os.path.getmtime(fn)
except OSError:
mtime_before = None
try:
with open(fn, mode) as fp:
item = load(fp)
except OpenError:
... |
<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_iterable(iterable):
""" Flattens a nested iterable into a single layer. Generator. If you only want to flatten a single level, use more_itertools.fla... |
for item in iterable:
if isinstance(item, Iterable) and not isinstance(item, string_types):
for sub in flatten_iterable(item):
yield sub
else:
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 list_events_view(request):
''' A list view of upcoming events. '''
page_name = "Upcoming Events"
profile = UserProfile.objects.get(user=request.user)
event_form = EventForm(
request.POST if 'post_event' in request.POST else None,
profile=profile,
)
if event_form.is_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 edit_event_view(request, event_pk):
''' The view to edit an event. '''
page_name = "Edit Event"
profile = UserProfile.objects.get(user=request.user)
event = get_object_or_404(Event, pk=event_pk)
if event.owner != profile and not request.user.is_superuser:
return HttpResponseRedirect(
... |
<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_url_node(parser, bits):
""" Parses the expression as if it was a normal url tag. Was copied from the original function django.template.defaulttags.url, ... |
viewname = parser.compile_filter(bits[1])
args = []
kwargs = {}
bits = bits[2:]
if len(bits):
kwarg_re = re.compile(r"(?:(\w+)=)?(.+)")
for bit in bits:
match = kwarg_re.match(bit)
if not match:
raise TemplateSyntaxError("Malformed arguments ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def trigger(self, identifier, force=True):
"""Trigger an upgrade task.""" |
self.debug(identifier)
url = "{base}/{identifier}".format(
base=self.local_base_url,
identifier=identifier
)
param = {}
if force:
param['force'] = force
encode = urllib.urlencode(param)
if encode:
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 _negate_compare_text(atok: asttokens.ASTTokens, node: ast.Compare) -> str: """ Generate the text representing the negation of the comparison node. :param atok... |
assert len(node.ops) == 1, "A single comparison expected, but got: {}".format(len(node.ops))
assert len(node.comparators) == 1, "A single comparator expected, but got: {}".format(len(node.comparators))
operator = node.ops[0]
left = node.left
right = node.comparators[0]
left_text = atok.get_te... |
<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_type_and_message( decorator_inspection: icontract._represent.DecoratorInspection) -> Tuple[Optional[str], Optional[str]]: """ Inspect the error argumen... |
call_node = decorator_inspection.node
error_arg_node = None # type: Optional[ast.AST]
for keyword in call_node.keywords:
if keyword.arg == 'error':
error_arg_node = keyword.value
if error_arg_node is None and len(call_node.args) == 5:
error_arg_node = call_node.args[4]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_contract(contract: icontract._Contract) -> str: """Format the contract as reST.""" |
# pylint: disable=too-many-branches
decorator_inspection = None # type: Optional[icontract._represent.DecoratorInspection]
##
# Parse condition
##
if not icontract._represent._is_lambda(a_function=contract.condition):
condition_text = ':py:func:`{}`'.format(contract.condition.__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 _format_preconditions(preconditions: List[List[icontract._Contract]], prefix: Optional[str] = None) -> List[str]: """ Format preconditions as reST. :param pre... |
if not preconditions:
return []
result = [] # type: List[str]
for i, group in enumerate(preconditions):
if i == 0:
if prefix is not None:
result.append(":{} requires:".format(prefix))
else:
result.append(":requires:")
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Convert the capture function into its text representation by parsing the source code of the decorator.""" |
if not icontract._represent._is_lambda(a_function=capture):
signature = inspect.signature(capture)
param_names = list(signature.parameters.keys())
return "{}({})".format(capture.__qualname__, ", ".join(param_names))
lines, lineno = inspect.findsource(capture)
filename = inspect.ge... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_snapshots(snapshots: List[icontract._Snapshot], prefix: Optional[str] = None) -> List[str]: """ Format snapshots as reST. :param snapshots: snapshots ... |
if not snapshots:
return []
result = [] # type: List[str]
if prefix is not None:
result.append(":{} OLD:".format(prefix))
else:
result.append(":OLD:")
for snapshot in snapshots:
text = _capture_as_text(capture=snapshot.capture)
result.append(" * :code:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_postconditions(postconditions: List[icontract._Contract], prefix: Optional[str] = None) -> List[str]: """ Format postconditions as reST. :param postco... |
if not postconditions:
return []
result = [] # type: List[str]
if prefix is not None:
result.append(":{} ensures:".format(prefix))
else:
result.append(":ensures:")
for postcondition in postconditions:
result.append(" * {}".format(_format_contract(contract=post... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_invariants(invariants: List[icontract._Contract]) -> List[str]: """Format invariants as reST.""" |
if not invariants:
return []
result = [":establishes:"] # type: List[str]
for invariant in invariants:
result.append(" * {}".format(_format_contract(contract=invariant)))
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _preconditions_snapshots_postconditions(checker: Callable) -> _PrePostSnaps: """Collect the preconditions, snapshots and postconditions from a contract checke... |
preconditions = getattr(checker, "__preconditions__", []) # type: List[List[icontract._Contract]]
assert all(isinstance(precondition_group, list) for precondition_group in preconditions)
assert (all(
isinstance(precondition, icontract._Contract) for precondition_group in preconditions
for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_function_contracts(func: Callable, prefix: Optional[str] = None) -> List[str]: """ Format the preconditions and postconditions of a function given its... |
checker = icontract._checkers.find_checker(func=func)
if checker is None:
return []
pps = _preconditions_snapshots_postconditions(checker=checker)
pre_block = _format_preconditions(preconditions=pps.preconditions, prefix=prefix)
old_block = _format_snapshots(snapshots=pps.snapshots, prefi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _format_contracts(what: str, obj: Any) -> List[str]: """Format the contracts as reST.""" |
if what in ['function', 'method', 'attribute']:
if what == 'attribute':
if not isinstance(obj, property):
return []
return _format_property_contracts(prop=obj)
if what in ['function', 'method']:
return _format_function_contracts(func=obj)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_docstring(app, what, name, obj, options, lines):
"""React to a docstring event and append contracts to it.""" |
# pylint: disable=unused-argument
# pylint: disable=too-many-arguments
lines.extend(_format_contracts(what=what, obj=obj)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_wheel(ireq, sources, hashes=None, cache_dir=None):
"""Build a wheel file for the InstallRequirement object. An artifact is downloaded (or read from cac... |
kwargs = _prepare_wheel_building_kwargs(ireq)
finder = _get_finder(sources, cache_dir=cache_dir)
# Not for upgrade, hash not required. Hashes are not required here even
# when we provide them, because pip skips local wheel cache if we set it
# to True. Hashes are checked later if we need to downlo... |
<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_euid():
""" Set settings.DROPLET_USER effective UID for the current process This adds some security, but nothing magic, an attacker can still gain root a... |
current = os.geteuid()
logger.debug("Current EUID is %s" % current)
if settings.DROPLET_USER is None:
logger.info("Not changing EUID, DROPLET_USER is None")
return
uid = int(pwd.getpwnam(settings.DROPLET_USER).pw_uid)
if current != uid:
try:
os.seteuid(uid)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def drop_privileges():
""" Set settings.DROPLET_USER UID for the current process After calling this, root operation will be impossible to execute See root contex... |
uid = int(pwd.getpwnam(settings.DROPLET_USER).pw_uid)
os.setuid(uid) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_by_value(cls, value):
""" Get constant by its value. :param value: value of the constant to look for :returns: first found constant with given value :rai... |
for constant in cls.iterconstants():
if constant.value == value:
return constant
raise ValueError(
"Constant with value \"{0}\" is not present in \"{1}\""
.format(value, cls)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_by_value(cls, value):
""" Get all constants which have given value. :param value: value of the constants to look for :returns: list of all found const... |
constants = []
for constant in cls.iterconstants():
if constant.value == value:
constants.append(constant)
return constants |
<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_machine(self, key):
""" Returns the number of the machine which key gets sent to. """ |
h = self.hash(key)
# edge case where we cycle past hash value of 1 and back to 0.
if h > self.hash_tuples[-1][2]:
return self.hash_tuples[0][0]
hash_values = map(lambda x: x[2], self.hash_tuples)
index = bisect.bisect_left(hash_values, h)
return self.hash_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_user(name, username, email, password, token_manager=None, app_url=defaults.APP_URL):
""" create a new user with the specified name, username email and... |
headers = token_manager.get_access_token_headers()
auth_url = environment.get_auth_url(app_url=app_url)
url = "%s/api/v1/accounts" % auth_url
payload = {
'name': name,
'username': username,
'email': email,
'password': password
}
response = requests.post(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_logged_in_account(token_manager=None, app_url=defaults.APP_URL):
""" get the account details for logged in account of the auth token_manager """ |
return get_logged_in_account(token_manager=token_manager,
app_url=app_url)['id'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_logged_in_account(token_manager=None, app_url=defaults.APP_URL):
""" get the account details for credentials provided """ |
headers = token_manager.get_access_token_headers()
auth_url = environment.get_auth_url(app_url=app_url)
url = "%s/api/v1/account" % auth_url
response = requests.get(url,
headers=headers)
if response.status_code == 200:
return response.json()
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 user_exists(username, token_manager=None, app_url=defaults.APP_URL):
""" check if the user exists with the specified username """ |
headers = token_manager.get_access_token_headers()
auth_url = environment.get_auth_url(app_url=app_url)
url = "%s/api/v1/accounts?username=%s" % (auth_url, username)
response = requests.get(url, headers=headers)
if response.status_code == 404:
return False
elif response.status_code == ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FromType(ftype):
""" DocField subclasses factory, creates a convenient field to store data from a given Type. attribute precedence : * ``|attrs| > 0`` (``mul... |
if ftype.attrs is not None and len(ftype.attrs):
return VectorField(ftype)
elif ftype.uniq:
return SetField(ftype)
elif ftype.multi:
return ListField(ftype)
else:
return ValueField(ftype) |
<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_attributes(self):
""" removes all attributes """ |
self._attrs = {} # removes all attr
for name, attr_field in six.iteritems(self._ftype.attrs):
self._attrs[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 set_attr_value(self, key, attr, value):
""" set the value of a given attribute for a given key """ |
idx = self._keys[key]
self._attrs[attr][idx].set(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_field(self, name, value, parse=False):
""" Set the value of a field """ |
# explicit getitem needed for ValueField
try:
item = dict.__getitem__(self, name)
item.set( item.parse(value) if parse else value )
except ValidationError as err:
raise FieldValidationError(name, value, list(err)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export(self, exclude=[]):
""" returns a dictionary representation of the document """ |
fields = ( (key, self.get_field(key)) for key in self.schema
if not key.startswith("_") and key not in exclude )
doc = {name: field.export() for name, field in fields}
return doc |
<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_dirs(rootdir_or_loader, outputpath, saveto_dir='data', auximages_dir='auximages', prefix='crd'):
"""Initialize the directiories. Inputs: rootdir_or_load... |
ip = get_ipython()
if isinstance(rootdir_or_loader, str):
print("Initializing loaders for SAXSCtrl and CCT.", flush=True)
ip.user_ns['_loaders'] = [
credo_cct.Loader(rootdir_or_loader, processed=True, exposureclass=prefix),
credo_saxsctrl.Loader(rootdir_or_loader, proces... |
<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_pg_core(connection_string, *, cursor_factory=None, edit_connection=None):
"""Creates a simple PostgreSQL core. Requires the psycopg2 library.""" |
import psycopg2 as pq
from psycopg2.extras import NamedTupleCursor
def opener():
"""Opens a single PostgreSQL connection with the scope-captured connection string."""
cn = pq.connect(connection_string)
cn.cursor_factory = cursor_factory or NamedTupleCursor
if edit_connection:
edit_connecti... |
<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_pooled_pg_core(connection_string, pool_size=None, *, cursor_factory=None, edit_connection=None, threaded=True):
"""Creates a pooled PostgreSQL core. Requ... |
from psycopg2.extras import NamedTupleCursor
from psycopg2.pool import ThreadedConnectionPool as TPool, SimpleConnectionPool as SPool
if not pool_size:
pool_size = (5, 10)
if threaded:
pool = TPool(pool_size[0], pool_size[1], connection_string)
else:
pool = SPool(pool_size[0], pool_size[1], conne... |
<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_sqlite_autocommit(cn, autocommit):
"""SQLite autocommit setter for core.""" |
if isinstance(autocommit, bool):
cn.isolation_level = None if autocommit else ""
else:
cn.isolation_level = autocommit |
<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_sqlite_core(connection_string, *, cursor_factory=None, edit_connection=None):
"""Creates a simple SQLite3 core.""" |
import sqlite3 as sqlite
def opener():
"""Opens a single connection with the scope-captured connection string."""
cn = sqlite.connect(connection_string)
if cursor_factory:
cn.row_factory = cursor_factory
if edit_connection:
edit_connection(cn)
return cn
return InjectedDataAccess... |
<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_mysql_core(connection_args, *, cursor_factory=None, edit_connection=None):
"""Creates a simple MySQL core. Requires the pymysql library.""" |
import pymysql
def opener():
"""Opens a single connection with the scope-captured connection string."""
cn = pymysql.connect(**connection_args)
if cursor_factory:
cn.cursorclass = cursor_factory
if edit_connection:
edit_connection(cn)
return cn
return InjectedDataAccessCore(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self, connection, *, commit=True):
"""Close the connection using the closer method passed to the constructor.""" |
if commit:
connection.commit()
else:
connection.rollback()
self.closer(connection) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download():
"""Download cities database.""" |
url = "http://download.geonames.org/export/dump/cities1000.zip"
logging.info("Download cities from %s", url)
if not os.path.exists(MISC_PATH):
os.makedirs(MISC_PATH)
zip_path = os.path.join(MISC_PATH, "cities1000.zip")
urlretrieve(url, zip_path)
with zipfile.ZipFile(zip_path, "r") as z... |
<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, pos):
"""Get the closest dataset.""" |
latitude = int(round(pos['latitude']))
search_set = self.bins[latitude]
i = 1
if latitude - i >= -90:
search_set += self.bins[latitude-i]
if latitude + i <= 90:
search_set += self.bins[latitude+i]
while len(search_set) == 0 and i <= 200:
... |
<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_urlencode(self, data, options=None):
""" handles basic formencoded url posts """ |
qs = dict((k, v if len(v) > 1 else v[0])
for k, v in urlparse.parse_qs(data).iteritems())
return qs |
<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_electricity_info(self, apart_id, meter_room):
"""get electricity info :param apart_id: 栋数 :param meter_room: 宿舍号 """ |
apart_id = str(apart_id)
meter_room = str(meter_room)
try:
content = LifeService._get_electricity_info_html(apart_id, meter_room)
except KeyError as e:
_.d(e.message)
result = {
'response': None
}
return _.to_js... |
<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_channels(self, channels):
"""Sets the state of multiple channels in one operation. :param channels: A dictionary where keys are channels and values the v... |
for key in channels:
self.set(key, channels[key]) |
<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_pdf_filenames_at(source_directory):
"""Find all PDF files in the specified directory. Args: source_directory (str):
The source directory. Returns: list... |
if not os.path.isdir(source_directory):
raise ValueError("%s is not a directory!" % source_directory)
return [os.path.join(source_directory, filename)
for filename in os.listdir(source_directory)
if filename.endswith(PDF_EXTENSION)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary):
"""Compress all PDF files in the current directory and place the output in th... |
source_paths = _get_pdf_filenames_at(source_directory)
yield len(source_paths)
for source_path in source_paths:
output = os.path.join(output_directory, os.path.basename(source_path))
compress_pdf(source_path, output, ghostscript_binary)
yield output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post_init(self, name, container=None):
""" Called automatically by container after container's class construction. """ |
self.name = name
self.container = container |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pathresource(self, rscpath=None, logger=None):
"""Returns specific resource. :param str rscpath: resource path. :param Logger logger: logger to use. :param b... |
result = None
try:
result = self._pathresource(rscpath=rscpath)
except Exception as ex:
if logger is not None:
msg = 'Error while getting resource from {0}.'.format(rscpath)
full_msg = '{0} {1}: {2}'.format(msg, ex, format_exc())
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getconf(self, path, conf=None, logger=None):
"""Parse a configuration path with input conf and returns parameters by param name. :param str path: conf resour... |
result = conf
pathconf = None
rscpaths = self.rscpaths(path=path)
for rscpath in rscpaths:
pathconf = self._getconf(rscpath=rscpath, logger=logger, conf=conf)
if pathconf is not None:
if result is None:
result = pathconf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setconf(self, conf, rscpath, logger=None):
"""Set input conf in input path. :param Configuration conf: conf to write to path. :param str rscpath: specific re... |
resource = self.pathresource(rscpath=rscpath, logger=logger)
if resource is None:
resource = self.resource()
try:
self._setconf(conf=conf, resource=resource, rscpath=rscpath)
except Exception as ex:
if logger is not None:
msg = 'Er... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.