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(... |
<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("#"):
... |
<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 retrie... |
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)
... |
<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: ... |
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,
... |
<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'])
... |
<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)
... |
<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(
... |
<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 wel... |
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 foun... |
<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 ... |
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())
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 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:
render... |
<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 ... |
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=to... |
<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... |
<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 reg... |
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... |
<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_LEVE... |
<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... |
<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 '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 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 resourc... |
<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:
... |
<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.ke... |
<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('*')... |
<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
... |
<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.g... |
<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_... |
<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.__custo... |
<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 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 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... |
<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("... |
<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 =... |
<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 = v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def __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(... |
<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("... |
<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]),
prec... |
<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
... |
<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.... |
<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,
... |
<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 DeliveryMethodEr... |
<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' attribu... |
<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... |
<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 nu... |
<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 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 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(gro... |
<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(su... |
<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,
... |
<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' a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def __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.inter... |
<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.interva... |
<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}.ite... |
<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. Alo... |
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'... |
<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:
... |
<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))),
... |
<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, war... |
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._ra... |
<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 fro... |
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:
... |
<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... |
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 ... |
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 in... |
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 in... |
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 extr... |
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 p... |
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 w... |
<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 disc... |
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_form... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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")
... |
<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)... |
<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 = sel... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.