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 createInstance(self, codec=None):
""" Creates an instance of the klass. @return: Instance of C{self.klass}. """ |
if type(self.klass) is type:
return self.klass.__new__(self.klass)
return self.klass() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_date(datasets, **kwargs):
"""Plot points with dates. datasets can be Dataset object or list of Dataset. """ |
defaults = {
'grid': True,
'xlabel': '',
'ylabel': '',
'title': '',
'output': None,
'figsize': (8, 6),
}
plot_params = {
'color': 'b',
'ls': '',
'alpha': 0.75,
}
_update_params(defaults, plot_params, kwargs)
if isinstance(datasets, Dataset):
datasets = [datasets]
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
color = plot_params.pop('color')
try:
del colors[colors.index(color)]
colors.insert(0, color)
except IndexError:
pass
colors = cycle(colors)
fig, ax = plt.subplots()
fig.set_size_inches(*defaults['figsize'])
fig.autofmt_xdate()
ax.autoscale_view()
for dataset in datasets:
if isinstance(dataset, Dataset):
dates = list(dataset.get_column_by_type(dataset.DATE))
values = list(dataset.get_column_by_type(dataset.NUM))
label = dataset.name
else:
dates, values = dataset
label = ''
dates = date2num(dates)
color = next(colors)
plt.plot_date(dates, values, color=color, label=label, **plot_params)
plt.xlabel(defaults['xlabel'])
plt.ylabel(defaults['ylabel'])
plt.title(defaults['title'])
plt.grid(defaults['grid'])
plt.legend(loc='best', prop={'size': 10})
filename = defaults['output'] or get_tmp_file_name('.png')
plt.savefig(filename)
return filename |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def call_actions(self, event, *args, **kwargs):
"""Call each function in self._actions after setting self._event.""" |
self._event = event
for func in self._actions:
func(event, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_query_notes(query_str, first_line=False):
""" Returns the Comments from a query string that are in the header """ |
lines = query_str.split("\n")
started = False
parts = []
for line in lines:
line = line.strip()
if line.startswith("#"):
parts.append(line)
started = True
if first_line:
break
if started and line and not line.startswith("#"):
break
return "\n".join(parts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def can_cloak_as(user, other_user):
""" Returns true if `user` can cloak as `other_user` """ |
# check to see if the user is allowed to do this
can_cloak = False
try:
can_cloak = user.can_cloak_as(other_user)
except AttributeError as e:
try:
can_cloak = user.is_staff
except AttributeError as e:
pass
return can_cloak |
<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_project(self, name):
""" Retrives project information by name :param name: The formal project name in string form. """ |
uri = '{base}/{project}'.format(base=self.BASE_URI, project=name)
resp = self._client.get(uri, model=models.Project)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bugs(self, project, status=None):
""" Retrives a List of bugs for a given project. By default, this will only return activate bugs. If you wish to retrieve a non-active bug then specify the status through the status parameter. :param project: The formal project name. :param status: Allows filtering of bugs by current status. """ |
uri = '{base}/{project}'.format(base=self.BASE_URI, project=project)
parameters = {'ws.op': 'searchTasks'}
if status:
parameters['status'] = status
resp = self._client.get(uri, model=models.Bug, is_collection=True,
params=parameters)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bug_by_id(self, bug_id):
""" Retrieves a single bug by it's Launchpad bug_id :param bug_id: The Launchpad id for the bug. """ |
uri = '{base}/bugs/{bug_id}'.format(base=self.BASE_URI, bug_id=bug_id)
resp = self._client.get(uri, model=models.Bug)
return resp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transition(prior_state, next_state):
""" Transitions to a non-standard state Raises InvalidStateTransition if next_state is not allowed. :param prior_state: <str> :param next_state: <str> :return: <str> """ |
if next_state not in STATES[prior_state][TRANSITION]:
acceptable = STATES[prior_state][TRANSITION]
err = "cannot {}->{} may only {}->{}".format(prior_state,
next_state,
prior_state,
acceptable)
raise InvalidStateTransition(err)
return next_state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, filename):
""" returns subtitles as string """ |
params = {
"v": 'dreambox',
"kolejka": "false",
"nick": "",
"pass": "",
"napios": sys.platform,
"l": self.language.upper(),
"f": self.prepareHash(filename),
}
params['t'] = self.discombobulate(params['f'])
url = self.url_base + urllib.urlencode(params)
subs = urllib.urlopen(url).read()
if subs.startswith('brak pliku tymczasowego'):
raise NapiprojektException('napiprojekt.pl API error')
if subs[0:4] != 'NPc0':
# napiprojekt keeps subtitles in cp1250
# ... but, sometimes they are in utf8
for cdc in ['cp1250', 'utf8']:
try:
return codecs.decode(subs, cdc)
except:
pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discombobulate(self, filehash):
""" prepare napiprojekt scrambled hash """ |
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in xrange(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
t = a + int(filehash[i], 16)
v = int(filehash[t:t + 2], 16)
b.append(("%x" % (v * m))[-1])
return ''.join(b) |
<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_has_email(username):
""" make sure, that given user has an email associated """ |
user = api.user.get(username=username)
if not user.getProperty("email"):
msg = _(
"This user doesn't have an email associated "
"with their account."
)
raise Invalid(msg)
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 workspaces_provider(context):
""" create a vocab of all workspaces in this site """ |
catalog = api.portal.get_tool(name="portal_catalog")
workspaces = catalog(portal_type="ploneintranet.workspace.workspacefolder")
current = api.content.get_uuid(context)
terms = []
for ws in workspaces:
if current != ws["UID"]:
terms.append(SimpleVocabulary.createTerm(
ws["UID"], ws["UID"], ws["Title"]))
return SimpleVocabulary(terms) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def live_weather(self, live_weather):
"""Prints the live weather in a pretty format""" |
summary = live_weather['currently']['summary']
self.summary(summary)
click.echo() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def title(self, title):
"""Prints the title""" |
title = " What's it like out side {0}? ".format(title)
click.secho("{:=^62}".format(title), fg=self.colors.WHITE)
click.echo() |
<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_available_options(self, service_name):
""" Fetches a collection of all JSON files for a given service. This checks user-created files (if present) as well as including the default service files. Example:: { '2013-11-27': [ '~/.boto-overrides/s3-2013-11-27.json', '/path/to/kotocore/data/aws/resources/s3-2013-11-27.json', ], '2010-10-06': [ '/path/to/kotocore/data/aws/resources/s3-2010-10-06.json', ], '2007-09-15': [ '~/.boto-overrides/s3-2007-09-15.json', ], } :param service_name: The name of the desired service :type service_name: string :returns: A dictionary of api_version keys, with a list of filepaths for that version (in preferential order). :rtype: dict """ |
options = {}
for data_dir in self.data_dirs:
# Traverse all the directories trying to find the best match.
service_glob = "{0}-*.json".format(service_name)
path = os.path.join(data_dir, service_glob)
found = glob.glob(path)
for match in found:
# Rip apart the path to determine the API version.
base = os.path.basename(match)
bits = os.path.splitext(base)[0].split('-', 1)
if len(bits) < 2:
continue
api_version = bits[1]
options.setdefault(api_version, [])
options[api_version].append(match)
return 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 get_best_match(self, options, service_name, api_version=None):
""" Given a collection of possible service options, selects the best match. If no API version is provided, the path to the most recent API version will be returned. If an API version is provided & there is an exact match, the path to that version will be returned. If there is no exact match, an attempt will be made to find a compatible (earlier) version. In all cases, user-created files (if present) will be given preference over the default included versions. :param options: A dictionary of options. See :type options: dict :param service_name: The name of the desired service :type service_name: string :param api_version: (Optional) The desired API version to load :type service_name: string :returns: The full path to the best matching JSON file """ |
if not options:
msg = "No JSON files provided. Please check your " + \
"configuration/install."
raise NoResourceJSONFound(msg)
if api_version is None:
# Give them the very latest option.
best_version = max(options.keys())
return options[best_version][0], best_version
# They've provided an api_version. Try to give them exactly what they
# requested, falling back to the best compatible match if no exact
# match can be found.
if api_version in options:
return options[api_version][0], api_version
# Find the best compatible match. Run through in descending order.
# When we find a version that's lexographically less than the provided
# one, run with it.
for key in sorted(options.keys(), reverse=True):
if key <= api_version:
return options[key][0], key
raise NoResourceJSONFound(
"No compatible JSON could be loaded for {0} ({1}).".format(
service_name,
api_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 render_args(arglst, argdct):
'''Render arguments for command-line invocation.
arglst: A list of Argument objects (specifies order)
argdct: A mapping of argument names to values (specifies rendered values)
'''
out = ''
for arg in arglst:
if arg.name in argdct:
rendered = arg.render(argdct[arg.name])
if rendered:
out += ' '
out += rendered
return out |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_webhook_url(deployment_name, space='default', data_source='webhook', token_manager=None, app_url=defaults.APP_URL, **fields):
""" return the webhook URL for posting webhook data to """ |
import_url = data_engine.get_import_data_url(deployment_name,
app_url=app_url,
token_manager=token_manager)
api_key = deployments.get_apikey(deployment_name,
token_manager=token_manager,
app_url=app_url)
fields_string = '&'.join(['%s=%s' % (key, value)
for (key, value) in fields.items()])
return '%s/api/v1/import/webhook/?space=%s&data_source=%sk&apikey=%s&%s' % \
(import_url, space, data_source, api_key, fields_string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Truncate HTML string, preserving tag structure and character entities.""" |
length = int(length)
output_length = 0
i = 0
pending_close_tags = {}
while output_length < length and i < len(string):
c = string[i]
if c == '<':
# probably some kind of tag
if i in pending_close_tags:
# just pop and skip if it's closing tag we already knew about
i += len(pending_close_tags.pop(i))
else:
# else maybe add tag
i += 1
match = tag_end_re.match(string[i:])
if match:
tag = match.groups()[0]
i += match.end()
# save the end tag for possible later use if there is one
match = re.search(r'(</' + tag + '[^>]*>)', string[i:], re.IGNORECASE)
if match:
pending_close_tags[i + match.start()] = match.groups()[0]
else:
output_length += 1 # some kind of garbage, but count it in
elif c == '&':
# possible character entity, we need to skip it
i += 1
match = entity_end_re.match(string[i:])
if match:
i += match.end()
# this is either a weird character or just '&', both count as 1
output_length += 1
else:
# plain old characters
skip_to = string.find('<', i, i + length)
if skip_to == -1:
skip_to = string.find('&', i, i + length)
if skip_to == -1:
skip_to = i + length
# clamp
delta = min(skip_to - i,
length - output_length,
len(string) - i)
output_length += delta
i += delta
output = [string[:i]]
if output_length == length:
output.append(ellipsis)
for k in sorted(pending_close_tags.keys()):
output.append(pending_close_tags[k])
return "".join(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 remove_regions_with_no_gates(regions):
""" Removes all Jove regions from a list of regions. :param regions: A list of tuples (regionID, regionName) :type regions: list :return: A list of regions minus those in jove space :rtype: list """ |
list_of_gateless_regions = [
(10000004, 'UUA-F4'),
(10000017, 'J7HZ-F'),
(10000019, 'A821-A'),
]
for gateless_region in list_of_gateless_regions:
if gateless_region in regions:
regions.remove(gateless_region)
return regions |
<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_cmake(config_info):
"""This function initializes a CMake builder for building the project.""" |
configure_args = ["-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]
cmake_args = {}
options, option_fns = _make_all_options()
def _add_value(value, key):
args_key, args_value = _EX_ARG_FNS[key](value)
cmake_args[args_key] = args_value
devpipeline_core.toolsupport.args_builder(
"cmake",
config_info,
options,
lambda v, key: configure_args.extend(option_fns[key](v)),
)
devpipeline_core.toolsupport.args_builder(
"cmake", config_info, _EX_ARGS, _add_value
)
cmake = CMake(cmake_args, config_info, configure_args)
build_type = config_info.config.get("cmake.build_type")
if build_type:
cmake.set_build_type(build_type)
return devpipeline_build.make_simple_builder(cmake, config_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 configure(self, src_dir, build_dir, **kwargs):
"""This function builds the cmake configure command.""" |
del kwargs
ex_path = self._ex_args.get("project_path")
if ex_path:
src_dir = os.path.join(src_dir, ex_path)
return [{"args": ["cmake", src_dir] + self._config_args, "cwd": build_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 build(self, build_dir, **kwargs):
"""This function builds the cmake build command.""" |
# pylint: disable=no-self-use
del kwargs
args = ["cmake", "--build", build_dir]
args.extend(self._get_build_flags())
return [{"args": 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 install(self, build_dir, install_dir=None, **kwargs):
"""This function builds the cmake install command.""" |
# pylint: disable=no-self-use
del kwargs
install_args = ["cmake", "--build", build_dir, "--target", "install"]
install_args.extend(self._get_build_flags())
if install_dir:
self._target_config.env["DESTDIR"] = install_dir
return [{"args": install_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 types(self, *args):
"""Used for debugging, returns type of each arg. """ |
return ', '.join(['{0}({1})'.format(type(arg).__name__, arg) for arg in 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 join(self, *args):
"""Returns the arguments in the list joined by STR. """ |
call_args = list(args)
joiner = call_args.pop(0)
self.random.shuffle(call_args)
return joiner.join(call_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 shuffle(self, *args):
"""Shuffles all arguments and returns them. """ |
call_args = list(args)
self.random.shuffle(call_args)
return ''.join(call_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 int(self, *args):
"""Returns a random int between -sys.maxint and sys.maxint INT %{INT} -> '1245123' %{INT:10} -> '10000000' %{INT:10,20} -> '19' """ |
return self.random.randint(*self._arg_defaults(args, [-sys.maxint, sys.maxint], int)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge_conf_file(self, result, conf_file_path):
"Merge a configuration in file with current configuration"
conf = parse_conf_file(conf_file_path)
conf_file_name = os.path.splitext(os.path.basename(conf_file_path))[0]
result_part = result
if not conf_file_name in File.TOP_LEVEL_CONF_FILES \
and (
not "top_level" in self._options
or not self._options["top_level"]):
for key_part in conf_file_name.split('.'):
if not key_part in result_part:
result_part[key_part] = {}
result_part = result_part[key_part]
return merge_conf(result_part, conf) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_login(func):
""" Function wrapper to signalize that a login is required. """ |
@wraps(func)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth:
return authenticate()
user = session.query(User).filter(
User.name == auth.username
).first()
if user and user.check(auth.password):
g.user = user
return func(*args, **kwargs)
else:
return authenticate()
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_admin(func):
""" Requires an admin user to access this resource. """ |
@wraps(func)
@require_login
def decorated(*args, **kwargs):
user = current_user()
if user and user.is_admin:
return func(*args, **kwargs)
else:
return Response(
'Forbidden', 403
)
return decorated |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def detect_change_mode(text,change):
"returns 'add' 'delete' or 'internal'. see comments to update_changes for more details."
# warning: some wacky diff logic (in python, probably in JS too) is making some adds / deletes look like replacements (see notes at bottom of diff.py)
if len(change.deltas)>1: return 'internal'
# todo below: why are blank deltas getting sent? is it a new seg thing? I'm picking 'add' because it has to be in some category and add is most likely next if this is a new seg.
elif not change.deltas: return 'add'
delta,=change.deltas # intentional crash if len(deltas)!=1
if delta.a==delta.b and delta.a==len(text): return 'add'
elif delta.b==len(text) and len(delta.text)==0: return 'delete'
else: return 'internal' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def mkchange(text0,text1,version,mtime):
"return a Change diffing the two strings"
return Change(version,mtime,ucrc(text1),diff.word_diff(text0,text1)) |
<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_resources(client):
""" Detect dispensers and return corresponding resources. """ |
wildcard = Keys.DISPENSER.format('*')
pattern = re.compile(Keys.DISPENSER.format('(.*)'))
return [pattern.match(d).group(1)
for d in client.scan_iter(wildcard)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def follow(resources, **kwargs):
""" Follow publications involved with resources. """ |
# subscribe
client = redis.Redis(decode_responses=True, **kwargs)
resources = resources if resources else find_resources(client)
channels = [Keys.EXTERNAL.format(resource) for resource in resources]
if resources:
subscription = Subscription(client, *channels)
# listen
while resources:
try:
message = subscription.listen()
if message['type'] == 'message':
print(message['data'])
except KeyboardInterrupt:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lock(resources, *args, **kwargs):
""" Lock resources from the command line, for example for maintenance. """ |
# all resources are locked if nothing is specified
if not resources:
client = redis.Redis(decode_responses=True, **kwargs)
resources = find_resources(client)
if not resources:
return
# create one process per pid
locker = Locker(**kwargs)
while len(resources) > 1:
pid = os.fork()
resources = resources[:1] if pid else resources[1:]
# at this point there is only one resource - lock it down
resource = resources[0]
try:
print('{}: acquiring'.format(resource))
with locker.lock(resource, label='lock tool'):
print('{}: locked'.format(resource))
try:
signal.pause()
except KeyboardInterrupt:
print('{}: released'.format(resource))
except KeyboardInterrupt:
print('{}: canceled'.format(resource)) |
<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(resources, *args, **kwargs):
""" Remove dispensers and indicators for idle resources. """ |
test = kwargs.pop('test', False)
client = redis.Redis(decode_responses=True, **kwargs)
resources = resources if resources else find_resources(client)
for resource in resources:
# investigate sequences
queue = Queue(client=client, resource=resource)
values = client.mget(queue.keys.indicator, queue.keys.dispenser)
try:
indicator, dispenser = map(int, values)
except TypeError:
print('No such queue: "{}".'.format(resource))
continue
# do a bump if there appears to be a queue
if dispenser - indicator + 1:
queue.message('Reset tool bumps.')
indicator = queue.bump()
# do not reset when there is still a queue
size = dispenser - indicator + 1
if size:
print('"{}" is in use by {} user(s).'.format(resource, size))
continue
# reset, except when someone is incoming
with client.pipeline() as pipe:
try:
pipe.watch(queue.keys.dispenser)
if test:
time.sleep(0.02)
pipe.multi()
pipe.delete(queue.keys.dispenser, queue.keys.indicator)
pipe.execute()
except redis.WatchError:
print('Activity detected for "{}".'.format(resource)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def status(resources, *args, **kwargs):
""" Print status report for zero or more resources. """ |
template = '{:<50}{:>10}'
client = redis.Redis(decode_responses=True, **kwargs)
# resource details
for loop, resource in enumerate(resources):
# blank between resources
if loop:
print()
# strings needed
keys = Keys(resource)
wildcard = keys.key('*')
# header
template = '{:<50}{:>10}'
indicator = client.get(keys.indicator)
if indicator is None:
continue
print(template.format(resource, indicator))
print(SEPARATOR)
# body
numbers = sorted([keys.number(key)
for key in client.scan_iter(wildcard)])
for number in numbers:
label = client.get(keys.key(number))
print(template.format(label, number))
if resources:
return
# show a more general status report for all available queues
resources = find_resources(client)
if resources:
dispensers = (Keys.DISPENSER.format(r) for r in resources)
indicators = (Keys.INDICATOR.format(r) for r in resources)
combinations = zip(client.mget(dispensers), client.mget(indicators))
sizes = (int(dispenser) - int(indicator) + 1
for dispenser, indicator in combinations)
# print sorted results
print(template.format('Resource', 'Queue size'))
print(SEPARATOR)
for size, resource in sorted(zip(sizes, resources), reverse=True):
print(template.format(resource, size)) |
<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_text_node(self, root, name, value, cdata=False):
'''
Creates and adds a text node
@param root:Element Root element
@param name:str Tag name
@param value:object Text value
@param cdata:bool A value indicating whether to use CDATA or not.
@return:Node
'''
if is_empty_or_none(value):
return
if type(value) == date:
value = date_to_string(value)
if type(value) == datetime:
value = datetime_to_string(value)
if isinstance(value, Decimal):
value = "0" if not value else str(value)
tag = root.ownerDocument.createElement(name)
value = value.decode('utf-8')
if cdata:
tag.appendChild(root.ownerDocument.createCDATASection(value))
else:
tag.appendChild(root.ownerDocument.createTextNode(value))
return root.appendChild(tag) |
<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_string(self, indent="", newl="", addindent=""):
'''
Returns a string representation of the XMLi element.
@return: str
'''
buf = StringIO()
self.to_xml().writexml(buf, indent=indent, addindent=addindent,
newl=newl)
return buf.getvalue() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def __createElementNS(self, root, uri, name, value):
'''
Creates and returns an element with a qualified name and a name space
@param root:Element Parent element
@param uri:str Namespace URI
@param tag:str Tag name.
'''
tag = root.ownerDocument.createElementNS(to_unicode(uri),
to_unicode(name))
tag.appendChild(root.ownerDocument
.createCDATASection(to_unicode(value)))
return root.appendChild(tag) |
<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_xml(self, root):
'''
Returns a DOM element contaning the XML representation of the
ExtensibleXMLiElement
@param root:Element Root XML element.
@return: Element
'''
if not len(self.__custom_elements):
return
for uri, tags in self.__custom_elements.items():
prefix, url = uri.split(":", 1)
for name, value in tags.items():
self.__createElementNS(root, url, prefix + ":" + name, value)
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def duplicate(self):
'''
Returns a copy of the current address.
@returns: Address
'''
return self.__class__(street_address=self.street_address,
city=self.city, zipcode=self.zipcode,
state=self.state, country=self.country) |
<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_xml(self, name="address"):
'''
Returns a DOM Element containing the XML representation of the
address.
@return:Element
'''
for n, v in {"street_address": self.street_address, "city": self.city,
"country": self.country}.items():
if is_empty_or_none(v):
raise ValueError("'%s' attribute cannot be empty or None." % n)
doc = Document()
root = doc.createElement(name)
self._create_text_node(root, "streetAddress", self.street_address, True)
self._create_text_node(root, "city", self.city, True)
self._create_text_node(root, "zipcode", self.zipcode)
self._create_text_node(root, "state", self.state, True)
self._create_text_node(root, "country", self.country)
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def duplicate(self):
'''
Returns a copy of the current contact element.
@returns: Contact
'''
return self.__class__(name=self.name, identifier=self.identifier,
phone=self.phone, require_id=self.__require_id,
address=self.address.duplicate()) |
<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_xml(self, tag_name="buyer"):
'''
Returns an XMLi representation of the object.
@param tag_name:str Tag name
@return: Element
'''
for n, v in {"name": self.name, "address": self.address}.items():
if is_empty_or_none(v):
raise ValueError("'%s' attribute cannot be empty or None." % n)
if self.__require_id and is_empty_or_none(self.identifier):
raise ValueError("identifier attribute cannot be empty or None.")
doc = Document()
root = doc.createElement(tag_name)
self._create_text_node(root, "id", self.identifier)
self._create_text_node(root, "name", self.name, True)
if self.phone:
self._create_text_node(root, "phone", self.phone, True)
root.appendChild(self.address.to_xml())
return root |
<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_xml(self):
'''
Returns an XMLi representation of the shipping details.
@return: Element
'''
for n, v in {"recipient": self.recipient}.items():
if is_empty_or_none(v):
raise ValueError("'%s' attribute cannot be empty or None." % n)
doc = Document()
root = doc.createElement("shipping")
root.appendChild(self.recipient.to_xml("recipient"))
return root |
<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_identifier(self, value):
'''
Sets the ID of the invoice.
@param value:str
'''
if not value or not len(value):
raise ValueError("Invalid invoice ID")
self.__identifier = 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_status(self, value):
'''
Sets the status of the invoice.
@param value:str
'''
if value not in [INVOICE_DUE, INVOICE_PAID, INVOICE_CANCELED,
INVOICE_IRRECOVERABLE]:
raise ValueError("Invalid invoice status")
self.__status = 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_date(self, value):
'''
Sets the invoice date.
@param value:datetime
'''
value = date_to_datetime(value)
if value > datetime.now() + timedelta(hours=14, minutes=1): #More or less 14 hours from now in case the submitted date was local
raise ValueError("Date cannot be in the future.")
if self.__due_date and value.date() > self.__due_date:
raise ValueError("Date cannot be posterior to the due date.")
self.__date = 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_due_date(self, value):
'''
Sets the due date of the invoice.
@param value:date
'''
if type(value) != date:
raise ValueError('Due date must be an instance of date.')
if self.__date.date() and value < self.__date.date():
raise ValueError("Due date cannot be anterior to the invoice " \
"date.")
self.__due_date = 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 compute_discounts(self, precision=None):
'''
Returns the total discounts of this group.
@param precision: int Number of decimals
@return: Decimal
'''
return sum([group.compute_discounts(precision) for group
in self.__groups]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute_taxes(self, precision=None):
'''
Returns the total amount of taxes for this group.
@param precision: int Number of decimal places
@return: Decimal
'''
return sum([group.compute_taxes(precision) for group in self.__groups]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute_payments(self, precision=None):
'''
Returns the total amount of payments made to this invoice.
@param precision:int Number of decimal places
@return: Decimal
'''
return quantize(sum([payment.amount for payment in self.__payments]),
precision) |
<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_signed_str(self, private, public, passphrase=None):
'''
Returns a signed version of the invoice.
@param private:file Private key file-like object
@param public:file Public key file-like object
@param passphrase:str Private key passphrase if any.
@return: str
'''
from pyxmli import xmldsig
try:
from Crypto.PublicKey import RSA
except ImportError:
raise ImportError('PyCrypto 2.5 or more recent module is ' \
'required to enable XMLi signing.\n' \
'Please visit: http://pycrypto.sourceforge.net/')
if not isinstance(private, RSA._RSAobj):
private = RSA.importKey(private.read(), passphrase=passphrase)
if not isinstance(public, RSA._RSAobj):
public = RSA.importKey(public.read())
return to_unicode(xmldsig.sign(to_unicode(self.to_string()),
private, public)) |
<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_method(self, value):
'''
Sets the method to use.
@param value: str
'''
if value not in [DELIVERY_METHOD_EMAIL, DELIVERY_METHOD_SMS,
DELIVERY_METHOD_SNAILMAIL]:
raise ValueError("Invalid deliveries method '%s'" % value)
self.__method = 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_status(self, value):
'''
Sets the deliveries status of this method.
@param value: str
'''
if value not in [DELIVERY_METHOD_STATUS_PENDING,
DELIVERY_METHOD_STATUS_SENT,
DELIVERY_METHOD_STATUS_CONFIRMED,
DELIVERY_METHOD_STATUS_BOUNCED]:
raise ValueError("Invalid deliveries method status '%s'" % value)
self.__status = 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 duplicate(self):
'''
Returns a copy of this deliveries method.
@return: DeliveryMethod
'''
return self.__class__(self.method, self.status, self.date, self.ref) |
<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_xml(self):
'''
Returns a DOM representation of the deliveries method
@returns: Element
'''
for n, v in { "method": self.method, "status": self.status,
"date":self.date}.items():
if is_empty_or_none(v):
raise DeliveryMethodError("'%s' attribute cannot be " \
"empty or None." % n)
doc = Document()
root = doc.createElement("delivery")
super(DeliveryMethod, self).to_xml(root)
self._create_text_node(root, "method", self.method)
self._create_text_node(root, "status", self.status)
self._create_text_node(root, "reference", self.ref, True)
self._create_text_node(root, "date", self.date)
return root |
<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_amount(self, value):
'''
Sets the amount of the payment operation.
@param value:float
'''
try:
self.__amount = quantize(Decimal(str(value)))
except:
raise ValueError('Invalid amount 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_method(self, value):
'''
Sets the amount of the payment.
'''
if value not in [PAYMENT_METHOD_OTHER, PAYMENT_METHOD_CARD,
PAYMENT_METHOD_CHEQUE, PAYMENT_METHOD_CASH, ]:
raise ValueError('Invalid amount value')
self.__method = 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_date(self, value):
'''
Sets the date of the payment.
@param value:datetime
'''
if not issubclass(value.__class__, date):
raise ValueError('Invalid date value')
self.__date = 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 to_xml(self):
'''
Returns a DOM representation of the payment.
@return: Element
'''
for n, v in { "amount": self.amount, "date": self.date,
"method":self.method}.items():
if is_empty_or_none(v):
raise PaymentError("'%s' attribute cannot be empty or " \
"None." % n)
doc = Document()
root = doc.createElement("payment")
super(Payment, self).to_xml(root)
self._create_text_node(root, "amount", self.amount)
self._create_text_node(root, "method", self.method)
self._create_text_node(root, "reference", self.ref, True)
self._create_text_node(root, "date", self.date)
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute_discounts(self, precision=None):
'''
Returns the total amount of discounts of this group.
@param precision:int Total amount of discounts
@return: Decimal
'''
return sum([line.compute_discounts(precision) for line in self.__lines]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute_taxes(self, precision=None):
'''
Returns the total amount of taxes of this group.
@param precision:int Total amount of discounts
@return: Decimal
'''
return sum([line.compute_taxes(precision) for line in self.__lines]) |
<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_xml(self):
'''
Returns a DOM representation of the group.
@return: Element
'''
if not len(self.lines):
raise GroupError("A group must at least have one line.")
doc = Document()
root = doc.createElement("group")
super(Group, self).to_xml(root)
self._create_text_node(root, "name", self.name, True)
self._create_text_node(root, "description", self.description, True)
lines = doc.createElement("lines")
root.appendChild(lines)
for line in self.__lines:
if not issubclass(line.__class__, Line):
raise GroupError('line of type %s is not an instance ' \
'or a subclass of %s' %
(line.__class__.__name__, Line.__name__))
lines.appendChild(line.to_xml())
return root |
<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_unit(self, value):
'''
Sets the unit of the line.
@param value:str
'''
if value in UNITS:
value = value.upper()
self.__unit = 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_quantity(self, value):
'''
Sets the quantity
@param value:str
'''
try:
if value < 0:
raise ValueError()
self.__quantity = Decimal(str(value))
except ValueError:
raise ValueError("Quantity must be a positive number") |
<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_unit_price(self, value):
'''
Sets the unit price
@param value:str
'''
try:
if value < 0:
raise ValueError()
self.__unit_price = Decimal(str(value))
except ValueError:
raise ValueError("Unit Price must be a positive number") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute_discounts(self, precision=None):
'''
Returns the total amount of discounts for this line with a specific
number of decimals.
@param precision:int number of decimal places
@return: Decimal
'''
gross = self.compute_gross(precision)
return min(gross,
sum([d.compute(gross, precision) for d in self.__discounts])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute_taxes(self, precision=None):
'''
Returns the total amount of taxes for this line with a specific
number of decimals
@param precision: int Number of decimal places
@return: Decimal
'''
base = self.gross - self.total_discounts
return quantize(sum([t.compute(base, precision) for t in self.__taxes]),
precision) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def duplicate(self):
'''
Returns a copy of the current Line, including its taxes and discounts
@returns: Line.
'''
instance = self.__class__(name=self.name, description=self.description,
unit=self.unit, quantity=self.quantity,
date=self.date, unit_price=self.unit_price,
gin=self.gin, gtin=self.gtin, sscc=self.sscc)
for tax in self.taxes:
instance.taxes.append(tax.duplicate())
for discount in self.discounts:
instance.discounts.append(discount.duplicate())
return instance |
<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_xml(self):
'''
Returns a DOM representation of the line.
@return: Element
'''
for n, v in {"name": self.name, "quantity": self.quantity,
"unit_price": self.unit_price}.items():
if is_empty_or_none(v):
raise LineError("'%s' attribute cannot be empty or None." %
n)
doc = Document()
root = doc.createElement("line")
super(Line, self).to_xml(root)
self._create_text_node(root, "date", self.date)
self._create_text_node(root, "name", self.name, True)
self._create_text_node(root, "description", self.description, True)
self._create_text_node(root, "quantity", self.quantity)
self._create_text_node(root, "unitPrice", self.unit_price)
self._create_text_node(root, "unit", self.unit)
self._create_text_node(root, "gin", self.gin)
self._create_text_node(root, "gtin", self.gtin)
self._create_text_node(root, "sscc", self.sscc)
if len(self.__discounts):
discounts = root.ownerDocument.createElement("discounts")
root.appendChild(discounts)
for discount in self.__discounts:
if not issubclass(discount.__class__, Discount):
raise LineError('discount of type %s is not an ' \
'instance or a subclass of %s' %
(discount.__class__.__name__,
Discount.__name__))
discounts.appendChild(discount.to_xml())
if len(self.__taxes):
taxes = root.ownerDocument.createElement("taxes")
root.appendChild(taxes)
for tax in self.__taxes:
if not issubclass(tax.__class__, Tax):
raise LineError('tax of type %s is not an instance ' \
'or a subclass of %s' %
(tax.__class__.__name__, Tax.__name__))
taxes.appendChild(tax.to_xml())
return root |
<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_interval(self, value):
'''
Sets the treatment interval
@param value:Interval
'''
if not isinstance(self, Interval):
raise ValueError("'value' must be of type Interval")
self.__interval = 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_name(self, value):
'''
Sets the name of the treatment.
@param value:str
'''
if not value or not len(value):
raise ValueError("Invalid name.")
self.__name = 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_rate_type(self, value):
'''
Sets the rate type.
@param value:str
'''
if value not in [RATE_TYPE_FIXED, RATE_TYPE_PERCENTAGE]:
raise ValueError("Invalid rate type.")
self.__rate_type = 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 duplicate(self):
'''
Returns a copy of the current treatment.
@returns: Treatment.
'''
return self.__class__(name=self.name, description=self.description,
rate_type=self.rate_type, rate=self.rate,
interval=self.interval) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute(self, base, precision=None):
'''
Computes the amount of the treatment.
@param base:float Gross
@return: Decimal
'''
if base <= ZERO:
return ZERO
if self.rate_type == RATE_TYPE_FIXED:
if not self.interval or base >= self.interval.lower:
return quantize(self.rate, precision)
return ZERO
if not self.interval:
return quantize(base * self.rate / 100, precision)
if base > self.interval.lower:
base = min(base, self.interval.upper) - self.interval.lower
return quantize(base * self.rate / 100, precision)
return ZERO |
<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_xml(self, name):
'''
Returns a DOM representation of the line treatment.
@return: Element
'''
for n, v in {"rate_type": self.rate_type,
"rate": self.rate,
"name": self.name,
"description": self.description}.items():
if is_empty_or_none(v):
raise TreatmentError("'%s' attribute cannot be empty " \
"or None." % n)
doc = Document()
root = doc.createElement(name)
root.setAttribute("type", self.rate_type)
root.setAttribute("name", to_unicode(self.name))
root.setAttribute("description", to_unicode(self.description))
if self.interval:
root.setAttribute("base", self.interval)
root.appendChild(doc.createTextNode(to_unicode(self.rate)))
return root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def compute(self, base, *args, **kwargs):
'''
Returns the value of the discount.
@param base:float Computation base.
@return: Decimal
'''
return min(base, super(Discount, self).compute(base, *args, **kwargs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, request, **cleaned_data):
""" Given a username, email address and password, register a new user account, which will initially be inactive. Along with the new ``User`` object, a new ``registration.models.RegistrationProfile`` will be created, tied to that ``User``, containing the activation key which will be used for this account. Two emails will be sent. First one to the admin; this email should contain an activation link and a resume of the new user infos. Second one, to the user, for inform him that his request is pending. After the ``User`` and ``RegistrationProfile`` are created and the activation email is sent, the signal ``registration.signals.user_registered`` will be sent, with the new ``User`` as the keyword argument ``user`` and the class of this backend as the sender. """ |
if Site._meta.installed:
site = Site.objects.get_current()
else:
site = RequestSite(request)
create_user = RegistrationProfile.objects.create_inactive_user
new_user = create_user(
cleaned_data['username'],
cleaned_data['email'],
cleaned_data['password1'],
site,
send_email=False
)
new_user.first_name = cleaned_data['first_name']
new_user.last_name = cleaned_data['last_name']
new_user.save()
user_info = UserInfo(
user=new_user,
company=cleaned_data['company'],
function=cleaned_data['function'],
address=cleaned_data['address'],
postal_code=cleaned_data['postal_code'],
city=cleaned_data['city'],
country=cleaned_data['country'],
phone=cleaned_data['phone'],
)
user_info.save()
send_activation_email(new_user, site, user_info)
send_activation_pending_email(new_user, site, user_info)
signals.user_registered.send(sender=self.__class__, user=new_user, request=request)
return new_user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, method, path):
"""find handler from registered rules Example: handler, params = match('GET', '/path') """ |
segments = path.split('/')
while len(segments):
index = '/'.join(segments)
if index in self.__idx__:
handler, params = self.match_rule(method, path,
self.__idx__[index])
if handler:
return handler, params
segments.pop()
return None, 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_for(self, handler, **kwargs):
"""construct path for a given handler Example: path = path_for(show_user, user_id=109) """ |
if type(handler) is not str:
handler = handler.__qualname__
if handler not in self.__reversedidx__:
return None
pattern = self.__reversedidx__[handler].pattern.lstrip('^').rstrip('$')
path = self.param_macher.sub(lambda m: str(kwargs.pop(m.group(1))),
pattern)
if kwargs:
path = "%s?%s" % (path, parse.urlencode(kwargs))
return path |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, setting_name, warn_only_if_overridden=False, accept_deprecated='', suppress_warnings=False, enforce_type=None, check_if_setting_deprecated=True, warning_stacklevel=3):
""" Returns a setting value for the setting named by ``setting_name``. The returned value is actually a reference to the original setting value, so care should be taken to avoid setting the result to a different value. :param setting_name: The name of the app setting for which a value is required. :type setting_name: str (e.g. "SETTING_NAME") :param warn_only_if_overridden: If the setting named by ``setting_name`` is deprecated, a value of ``True`` can be provided to silence the immediate deprecation warning that is otherwise raised by default. Instead, a (differently worded) deprecation warning will be raised, but only when the setting is overriden. :type warn_only_if_overridden: bool :param accept_deprecated: If the setting named by ``setting_name`` replaces multiple deprecated settings, the ``accept_deprecated`` keyword argument can be used to specify which of those deprecated settings to accept as an override value. Where the requested setting replaces only a single deprecated setting, override values for that deprecated setting will be accepted automatically, without having to specify anything. :type accept_deprecated: str (e.g. "DEPRECATED_SETTING_NAME") :param suppress_warnings: Use this to prevent the raising of any deprecation warnings that might otherwise be raised. It may be more useful to use ``warn_only_if_overridden`` instead. :type suppress_warnings: bool :param enforce_type: When a setting value of a specific type is required, this can be used to apply some basic validation at the time of retrieval. If supplied, and setting value is found not to be an instance of the supplied type, a ``SettingValueTypeInvalid`` error will be raised. In cases where more than one type of value is accepted, a tuple of acceptable types can be provided. :type enforce_type: A type (class), or tuple of types :param check_if_setting_deprecated: Can be used to disable the check that usually happens at the beginning of the method to identify whether the setting named by ``setting_name`` is deprecated, and conditionally raise a warning. This can help to improve efficiency where the same check has already been made. :type check_if_setting_deprecated: bool :param warning_stacklevel: When raising deprecation warnings related to the request, this value is passed on as ``stacklevel`` to Python's ``warnings.warn()`` method, to help give a more accurate indication of the code that caused the warning to be raised. :type warning_stacklevel: int :raises: UnknownSettingNameError, SettingValueTypeInvalid Instead of calling this method directly, developers are generally encouraged to use the direct attribute shortcut, which is a syntactically much cleaner way to request values using the default options. For example, the the following lines are equivalent:: appsettingshelper.SETTING_NAME appsettingshelper.get('SETTING_NAME') """ |
if check_if_setting_deprecated:
self._warn_if_deprecated_setting_value_requested(
setting_name, warn_only_if_overridden, suppress_warnings,
warning_stacklevel)
cache_key = self._make_cache_key(setting_name, accept_deprecated)
if cache_key in self._raw_cache:
return self._raw_cache[cache_key]
result = self._get_raw_value(
setting_name,
accept_deprecated=accept_deprecated,
warn_if_overridden=warn_only_if_overridden,
suppress_warnings=suppress_warnings,
warning_stacklevel=warning_stacklevel + 1,
)
if enforce_type and not isinstance(result, enforce_type):
if isinstance(enforce_type, tuple):
msg = (
"The value is expected to be one of the following types, "
"but a value of type '{current_type}' was found: "
"{required_types}."
)
text_format_kwargs = dict(
current_type=type(result).__name__,
required_types=enforce_type,
)
else:
msg = (
"The value is expected to be a '{required_type}', but a "
"value of type '{current_type}' was found."
)
text_format_kwargs = dict(
current_type=type(result).__name__,
required_type=enforce_type.__name__,
)
self._raise_setting_value_error(
setting_name=setting_name,
user_value_error_class=OverrideValueTypeInvalid,
default_value_error_class=DefaultValueTypeInvalid,
additional_text=msg,
**text_format_kwargs
)
self._raw_cache[cache_key] = result
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 is_value_from_deprecated_setting(self, setting_name, deprecated_setting_name):
""" Helps developers to determine where the settings helper got it's value from when dealing with settings that replace deprecated settings. Returns ``True`` when the new setting (with the name ``setting_name``) is a replacement for a deprecated setting (with the name ``deprecated_setting_name``) and the user is using the deprecated setting in their Django settings to override behaviour. """ |
if not self.in_defaults(setting_name):
self._raise_invalid_setting_name_error(setting_name)
if not self.in_defaults(deprecated_setting_name):
self._raise_invalid_setting_name_error(deprecated_setting_name)
if deprecated_setting_name not in self._deprecated_settings:
raise ValueError(
"The '%s' setting is not deprecated. When using "
"settings.is_value_from_deprecated_setting(), the deprecated "
"setting name should be supplied as the second argument." %
deprecated_setting_name
)
if(
not self.is_overridden(setting_name) and
setting_name in self._replacement_settings
):
deprecations = self._replacement_settings[setting_name]
for item in deprecations:
if(
item.setting_name == deprecated_setting_name and
self.is_overridden(item.setting_name)
):
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_parser(self, type, parser, **meta):
"""Registers a parser of a format. :param type: The unique name of the format :param parser: The method to parse data as the format :param meta: The extra information associated with the format """ |
try:
self.registered_formats[type]['parser'] = parser
except KeyError:
self.registered_formats[type] = {'parser': parser}
if meta:
self.register_meta(type, **meta) |
<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_composer(self, type, composer, **meta):
"""Registers a composer of a format. :param type: The unique name of the format :param composer: The method to compose data as the format """ |
try:
self.registered_formats[type]['composer'] = composer
except KeyError:
self.registered_formats[type] = {'composer': composer}
if meta:
self.register_meta(type, **meta) |
<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_meta(self, type, **meta):
"""Registers extra _meta_ information about a format. :param type: The unique name of the format :param meta: The extra information associated with the format """ |
try:
self.registered_formats[type]['meta'] = meta
except KeyError:
self.registered_formats[type] = {'meta': meta} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parser(self, type, **meta):
"""Registers the decorated method as the parser of a format. :param type: The unique name of the format :param meta: The extra information associated with the format """ |
def decorator(f):
self.register_parser(type, f)
if meta:
self.register_meta(type, **meta)
return f
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def composer(self, type, **meta):
"""Registers the decorated method as the composer of a format. :param type: The unique name of the format :param meta: The extra information associated with the format """ |
def decorator(f):
self.register_composer(type, f)
if meta:
self.register_meta(type, **meta)
return f
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, type, data):
"""Parse text as a format. :param type: The unique name of the format :param data: The text to parse as the format """ |
try:
return self.registered_formats[type]['parser'](data)
except KeyError:
raise NotImplementedError("No parser found for "
"type '{type}'".format(type=type)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compose(self, type, data):
"""Compose text as a format. :param type: The unique name of the format :param data: The text to compose as the format """ |
try:
return self.registered_formats[type]['composer'](data)
except KeyError:
raise NotImplementedError("No composer found for "
"type '{type}'".format(type=type)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(self, type_from, type_to, data):
"""Parsers data from with one format and composes with another. :param type_from: The unique name of the format to parse with :param type_to: The unique name of the format to compose with :param data: The text to convert """ |
try:
return self.compose(type_to, self.parse(type_from, data))
except Exception as e:
raise ValueError(
"Couldn't convert '{from_}' to '{to}'. Possibly "
"because the parser of '{from_}' generates a "
"data structure incompatible with the composer "
"of '{to}'. This is the original error: \n\n"
"{error}: {message}".format(from_=type_from, to=type_to,
error=e.__class__.__name__,
message=e.message)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def meta(self, type):
"""Retreived meta information of a format. :param meta: The extra information associated with the format """ |
try:
return self.registered_formats[type].get('meta')
except KeyError:
raise NotImplementedError("No format registered with type "
"'{type}'".format(type=type)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discover(self, exclude=None):
"""Automatically discovers and registers installed formats. If a format is already registered with an exact same name, the discovered format will not be registered. :param exclude: (optional) Exclude formats from registering """ |
if exclude is None:
exclude = []
elif not isinstance(exclude, (list, tuple)):
exclude = [exclude]
if 'json' not in exclude and 'json' not in self.registered_formats:
self.discover_json()
if 'yaml' not in exclude and 'yaml' not in self.registered_formats:
self.discover_yaml() |
<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_domain(clz, dag):
""" Sets the domain. Should only be called once per class instantiation. """ |
logging.info("Setting domain for poset %s" % clz.__name__)
if nx.number_of_nodes(dag) == 0:
raise CellConstructionFailure("Empty DAG structure.")
if not nx.is_directed_acyclic_graph(dag):
raise CellConstructionFailure("Must be directed and acyclic")
if not nx.is_weakly_connected(dag):
raise CellConstructionFailure("Must be connected")
clz.domain_map[clz] = dag |
<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_domain_equal(self, other):
""" Computes whether two Partial Orderings have the same generalization structure. """ |
domain = self.get_domain()
other_domain = other.get_domain()
# if they share the same instance of memory for the domain
if domain == other_domain:
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_equal(self, other):
""" Computes whether two Partial Orderings contain the same information """ |
if not (hasattr(other, 'get_domain') or hasattr(other, 'upper') or hasattr(other, 'lower')):
other = self.coerce(other)
if self.is_domain_equal(other) \
and len(self.upper.symmetric_difference(other.upper)) == 0 \
and len(self.lower.symmetric_difference(other.lower)) == 0:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_contradictory(self, other):
""" Does the merge yield the empty set? """ |
if not self.is_domain_equal(other):
return True
# what would happen if the two were combined?
test_lower = self.lower.union(other.lower)
test_upper = self.upper.union(other.upper)
# if there is a path from lower to upper nodes, we're in trouble:
domain = self.get_domain()
for low in test_lower:
for high in test_upper:
if low != high and has_path(domain, low, high):
return True
# lastly, build a merged ordering and see if it has 0 members
test = self.__class__()
test.lower = test_lower
test.upper = test_upper
return len(test) == 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.