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 bezier_real_minmax(p):
"""returns the minimum and maximum for any real cubic bezier""" |
local_extremizers = [0, 1]
if len(p) == 4: # cubic case
a = [p.real for p in p]
denom = a[0] - 3*a[1] + 3*a[2] - a[3]
if denom != 0:
delta = a[1]**2 - (a[0] + a[1])*a[2] + a[2]**2 + (a[0] - a[1])*a[3]
if delta >= 0: # otherwise no local extrema
sqdelta = sqrt(delta)
tau = a[0] - 2*a[1] + a[2]
r1 = (tau + sqdelta)/denom
r2 = (tau - sqdelta)/denom
if 0 < r1 < 1:
local_extremizers.append(r1)
if 0 < r2 < 1:
local_extremizers.append(r2)
local_extrema = [bezier_point(a, t) for t in local_extremizers]
return min(local_extrema), max(local_extrema)
# find reverse standard coefficients of the derivative
dcoeffs = bezier2polynomial(a, return_poly1d=True).deriv().coeffs
# find real roots, r, such that 0 <= r <= 1
local_extremizers += polyroots01(dcoeffs)
local_extrema = [bezier_point(a, t) for t in local_extremizers]
return min(local_extrema), max(local_extrema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_group(group_to_flatten, root, recursive=True, group_filter=lambda x: True, path_filter=lambda x: True, path_conversions=CONVERSIONS, group_search_xpath=SVG_GROUP_TAG):
"""Flatten all the paths in a specific group. The paths will be flattened into the 'root' frame. Note that root needs to be an ancestor of the group that is being flattened. Otherwise, no paths will be returned.""" |
if not any(group_to_flatten is descendant for descendant in root.iter()):
warnings.warn('The requested group_to_flatten is not a '
'descendant of root')
# We will shortcut here, because it is impossible for any paths
# to be returned anyhow.
return []
# We create a set of the unique IDs of each element that we wish to
# flatten, if those elements are groups. Any groups outside of this
# set will be skipped while we flatten the paths.
desired_groups = set()
if recursive:
for group in group_to_flatten.iter():
desired_groups.add(id(group))
else:
desired_groups.add(id(group_to_flatten))
def desired_group_filter(x):
return (id(x) in desired_groups) and group_filter(x)
return flatten_all_paths(root, desired_group_filter, path_filter,
path_conversions, group_search_xpath) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_all_paths(self, group_filter=lambda x: True, path_filter=lambda x: True, path_conversions=CONVERSIONS):
"""Forward the tree of this document into the more general flatten_all_paths function and return the result.""" |
return flatten_all_paths(self.tree.getroot(), group_filter,
path_filter, path_conversions) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_path(self, path, attribs=None, group=None):
"""Add a new path to the SVG.""" |
# If not given a parent, assume that the path does not have a group
if group is None:
group = self.tree.getroot()
# If given a list of strings (one or more), assume it represents
# a sequence of nested group names
elif all(isinstance(elem, str) for elem in group):
group = self.get_or_add_group(group)
elif not isinstance(group, Element):
raise TypeError(
'Must provide a list of strings or an xml.etree.Element '
'object. Instead you provided {0}'.format(group))
else:
# Make sure that the group belongs to this Document object
if not self.contains_group(group):
warnings.warn('The requested group does not belong to '
'this Document')
# TODO: It might be better to use duck-typing here with a try-except
if isinstance(path, Path):
path_svg = path.d()
elif is_path_segment(path):
path_svg = Path(path).d()
elif isinstance(path, str):
# Assume this is a valid d-string.
# TODO: Should we sanity check the input string?
path_svg = path
else:
raise TypeError(
'Must provide a Path, a path segment type, or a valid '
'SVG path d-string. Instead you provided {0}'.format(path))
if attribs is None:
attribs = {}
else:
attribs = attribs.copy()
attribs['d'] = path_svg
return SubElement(group, 'path', attribs) |
<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_or_add_group(self, nested_names, name_attr='id'):
"""Get a group from the tree, or add a new one with the given name structure. `nested_names` is a list of strings which represent group names. Each group name will be nested inside of the previous group name. `name_attr` is the group attribute that is being used to represent the group's name. Default is 'id', but some SVGs may contain custom name labels, like 'inkscape:label'. Returns the requested group. If the requested group did not exist, this function will create it, as well as all parent groups that it requires. All created groups will be left with blank attributes. """ |
group = self.tree.getroot()
# Drill down through the names until we find the desired group
while len(nested_names):
prev_group = group
next_name = nested_names.pop(0)
for elem in group.iterfind(SVG_GROUP_TAG, SVG_NAMESPACE):
if elem.get(name_attr) == next_name:
group = elem
break
if prev_group is group:
# The group we're looking for does not exist, so let's
# create the group structure
nested_names.insert(0, next_name)
while nested_names:
next_name = nested_names.pop(0)
group = self.add_group({'id': next_name}, group)
# Now nested_names will be empty, so the topmost
# while-loop will end
return group |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_group(self, group_attribs=None, parent=None):
"""Add an empty group element to the SVG.""" |
if parent is None:
parent = self.tree.getroot()
elif not self.contains_group(parent):
warnings.warn('The requested group {0} does not belong to '
'this Document'.format(parent))
if group_attribs is None:
group_attribs = {}
else:
group_attribs = group_attribs.copy()
return SubElement(parent, '{{{0}}}g'.format(
SVG_NAMESPACE['svg']), group_attribs) |
<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_transform(transform_str):
"""Converts a valid SVG transformation string into a 3x3 matrix. If the string is empty or null, this returns a 3x3 identity matrix""" |
if not transform_str:
return np.identity(3)
elif not isinstance(transform_str, str):
raise TypeError('Must provide a string to parse')
total_transform = np.identity(3)
transform_substrs = transform_str.split(')')[:-1] # Skip the last element, because it should be empty
for substr in transform_substrs:
total_transform = total_transform.dot(_parse_transform_substr(substr))
return total_transform |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kinks(path, tol=1e-8):
"""returns indices of segments that start on a non-differentiable joint.""" |
kink_list = []
for idx in range(len(path)):
if idx == 0 and not path.isclosed():
continue
try:
u = path[(idx - 1) % len(path)].unit_tangent(1)
v = path[idx].unit_tangent(0)
u_dot_v = u.real*v.real + u.imag*v.imag
flag = False
except ValueError:
flag = True
if flag or abs(u_dot_v - 1) > tol:
kink_list.append(idx)
return kink_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def smoothed_path(path, maxjointsize=3, tightness=1.99, ignore_unfixable_kinks=False):
"""returns a path with no non-differentiable joints.""" |
if len(path) == 1:
return path
assert path.iscontinuous()
sharp_kinks = []
new_path = [path[0]]
for idx in range(len(path)):
if idx == len(path)-1:
if not path.isclosed():
continue
else:
seg1 = new_path[0]
else:
seg1 = path[idx + 1]
seg0 = new_path[-1]
try:
unit_tangent0 = seg0.unit_tangent(1)
unit_tangent1 = seg1.unit_tangent(0)
flag = False
except ValueError:
flag = True # unit tangent not well-defined
if not flag and isclose(unit_tangent0, unit_tangent1): # joint is already smooth
if idx != len(path)-1:
new_path.append(seg1)
continue
else:
kink_idx = (idx + 1) % len(path) # kink at start of this seg
if not flag and isclose(-unit_tangent0, unit_tangent1):
# joint is sharp 180 deg (must be fixed manually)
new_path.append(seg1)
sharp_kinks.append(kink_idx)
else: # joint is not smooth, let's smooth it.
args = (seg0, seg1, maxjointsize, tightness)
new_seg0, elbow_segs, new_seg1 = smoothed_joint(*args)
new_path[-1] = new_seg0
new_path += elbow_segs
if idx == len(path) - 1:
new_path[0] = new_seg1
else:
new_path.append(new_seg1)
# If unfixable kinks were found, let the user know
if sharp_kinks and not ignore_unfixable_kinks:
_report_unfixable_kinks(path, sharp_kinks)
return Path(*new_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 hex2rgb(value):
"""Converts a hexadeximal color string to an RGB 3-tuple EXAMPLE ------- (0, 0, 255) """ |
value = value.lstrip('#')
lv = len(value)
return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def isclose(a, b, rtol=1e-5, atol=1e-8):
"""This is essentially np.isclose, but slightly faster.""" |
return abs(a - b) < (atol + rtol * abs(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 open_in_browser(file_location):
"""Attempt to open file located at file_location in the default web browser.""" |
# If just the name of the file was given, check if it's in the Current
# Working Directory.
if not os.path.isfile(file_location):
file_location = os.path.join(os.getcwd(), file_location)
if not os.path.isfile(file_location):
raise IOError("\n\nFile not found.")
# For some reason OSX requires this adjustment (tested on 10.10.4)
if sys.platform == "darwin":
file_location = "file:///"+file_location
new = 2 # open in a new tab, if possible
webbrowser.get().open(file_location, new=new) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ellipse2pathd(ellipse):
"""converts the parameters from an ellipse or a circle to a string for a Path object d-attribute""" |
cx = ellipse.get('cx', 0)
cy = ellipse.get('cy', 0)
rx = ellipse.get('rx', None)
ry = ellipse.get('ry', None)
r = ellipse.get('r', None)
if r is not None:
rx = ry = float(r)
else:
rx = float(rx)
ry = float(ry)
cx = float(cx)
cy = float(cy)
d = ''
d += 'M' + str(cx - rx) + ',' + str(cy)
d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(2 * rx) + ',0'
d += 'a' + str(rx) + ',' + str(ry) + ' 0 1,0 ' + str(-2 * rx) + ',0'
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def polyline2pathd(polyline_d, is_polygon=False):
"""converts the string from a polyline points-attribute to a string for a Path object d-attribute""" |
points = COORD_PAIR_TMPLT.findall(polyline_d)
closed = (float(points[0][0]) == float(points[-1][0]) and
float(points[0][1]) == float(points[-1][1]))
# The `parse_path` call ignores redundant 'z' (closure) commands
# e.g. `parse_path('M0 0L100 100Z') == parse_path('M0 0L100 100L0 0Z')`
# This check ensures that an n-point polygon is converted to an n-Line path.
if is_polygon and closed:
points.append(points[0])
d = 'M' + 'L'.join('{0} {1}'.format(x,y) for x,y in points)
if is_polygon or closed:
d += 'z'
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def svg2paths(svg_file_location, return_svg_attributes=False, convert_circles_to_paths=True, convert_ellipses_to_paths=True, convert_lines_to_paths=True, convert_polylines_to_paths=True, convert_polygons_to_paths=True, convert_rectangles_to_paths=True):
"""Converts an SVG into a list of Path objects and attribute dictionaries. Converts an SVG file into a list of Path objects and a list of dictionaries containing their attributes. This currently supports SVG Path, Line, Polyline, Polygon, Circle, and Ellipse elements. Args: svg_file_location (string):
the location of the svg file return_svg_attributes (bool):
Set to True and a dictionary of svg-attributes will be extracted and returned. See also the `svg2paths2()` function. convert_circles_to_paths: Set to False to exclude SVG-Circle elements (converted to Paths). By default circles are included as paths of two `Arc` objects. convert_ellipses_to_paths (bool):
Set to False to exclude SVG-Ellipse elements (converted to Paths). By default ellipses are included as paths of two `Arc` objects. convert_lines_to_paths (bool):
Set to False to exclude SVG-Line elements (converted to Paths) convert_polylines_to_paths (bool):
Set to False to exclude SVG-Polyline elements (converted to Paths) convert_polygons_to_paths (bool):
Set to False to exclude SVG-Polygon elements (converted to Paths) convert_rectangles_to_paths (bool):
Set to False to exclude SVG-Rect elements (converted to Paths). Returns: list: The list of Path objects. list: The list of corresponding path attribute dictionaries. dict (optional):
A dictionary of svg-attributes (see `svg2paths2()`). """ |
if os_path.dirname(svg_file_location) == '':
svg_file_location = os_path.join(getcwd(), svg_file_location)
doc = parse(svg_file_location)
def dom2dict(element):
"""Converts DOM elements to dictionaries of attributes."""
keys = list(element.attributes.keys())
values = [val.value for val in list(element.attributes.values())]
return dict(list(zip(keys, values)))
# Use minidom to extract path strings from input SVG
paths = [dom2dict(el) for el in doc.getElementsByTagName('path')]
d_strings = [el['d'] for el in paths]
attribute_dictionary_list = paths
# Use minidom to extract polyline strings from input SVG, convert to
# path strings, add to list
if convert_polylines_to_paths:
plins = [dom2dict(el) for el in doc.getElementsByTagName('polyline')]
d_strings += [polyline2pathd(pl['points']) for pl in plins]
attribute_dictionary_list += plins
# Use minidom to extract polygon strings from input SVG, convert to
# path strings, add to list
if convert_polygons_to_paths:
pgons = [dom2dict(el) for el in doc.getElementsByTagName('polygon')]
d_strings += [polygon2pathd(pg['points']) for pg in pgons]
attribute_dictionary_list += pgons
if convert_lines_to_paths:
lines = [dom2dict(el) for el in doc.getElementsByTagName('line')]
d_strings += [('M' + l['x1'] + ' ' + l['y1'] +
'L' + l['x2'] + ' ' + l['y2']) for l in lines]
attribute_dictionary_list += lines
if convert_ellipses_to_paths:
ellipses = [dom2dict(el) for el in doc.getElementsByTagName('ellipse')]
d_strings += [ellipse2pathd(e) for e in ellipses]
attribute_dictionary_list += ellipses
if convert_circles_to_paths:
circles = [dom2dict(el) for el in doc.getElementsByTagName('circle')]
d_strings += [ellipse2pathd(c) for c in circles]
attribute_dictionary_list += circles
if convert_rectangles_to_paths:
rectangles = [dom2dict(el) for el in doc.getElementsByTagName('rect')]
d_strings += [rect2pathd(r) for r in rectangles]
attribute_dictionary_list += rectangles
if return_svg_attributes:
svg_attributes = dom2dict(doc.getElementsByTagName('svg')[0])
doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list, svg_attributes
else:
doc.unlink()
path_list = [parse_path(d) for d in d_strings]
return path_list, attribute_dictionary_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dtype_to_matlab_class(dtype):
""" convert dtype to matlab class string """ |
if dtype.str in ['<f8']:
return 'double'
elif dtype.str in ['<f4']:
return 'single'
elif dtype.str in ['<i8']:
return 'int64'
elif dtype.str in ['<u8']:
return 'uint64'
elif dtype.str in ['<i4']:
return 'int32'
elif dtype.str in ['<u4']:
return 'uint32'
elif dtype.str in ['<i2']:
return 'int16'
elif dtype.str in ['<u2']:
return 'uint16'
elif dtype.str in ['|i1']:
return 'int8'
elif dtype.str in ['|u1']:
return 'uint8' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
""" establish a connection to the Instrument """ |
if not driver_ok:
logger.error("Visa driver NOT ok")
return False
visa_backend = '@py' # use PyVISA-py as backend
if hasattr(settings, 'VISA_BACKEND'):
visa_backend = settings.VISA_BACKEND
try:
self.rm = visa.ResourceManager(visa_backend)
except:
logger.error("Visa ResourceManager cannot load resources : %s" %self)
return False
try:
resource_prefix = self._device.visadevice.resource_name.split('::')[0]
extras = {}
if hasattr(settings, 'VISA_DEVICE_SETTINGS'):
if resource_prefix in settings.VISA_DEVICE_SETTINGS:
extras = settings.VISA_DEVICE_SETTINGS[resource_prefix]
logger.debug('VISA_DEVICE_SETTINGS for %s: %r'%(resource_prefix,extras))
self.inst = self.rm.open_resource(self._device.visadevice.resource_name, **extras)
except:
logger.error("Visa ResourceManager cannot open resource : %s" %self._device.visadevice.resource_name)
return False
logger.debug('connected visa device')
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 decode_bcd(values):
""" decode bcd as int to dec """ |
bin_str_out = ''
if isinstance(values, integer_types):
bin_str_out = bin(values)[2:].zfill(16)
bin_str_out = bin_str_out[::-1]
else:
for value in values:
bin_str = bin(value)[2:].zfill(16)
bin_str = bin_str[::-1]
bin_str_out = bin_str + bin_str_out
dec_num = 0
for i in range(len(bin_str_out) / 4):
bcd_num = int(bin_str_out[(i * 4):(i + 1) * 4][::-1], 2)
if bcd_num > 9:
dec_num = -dec_num
else:
dec_num = dec_num + (bcd_num * pow(10, i))
return dec_num |
<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_gap(l, value):
""" try to find a address gap in the list of modbus registers """ |
for index in range(len(l)):
if l[index] == value:
return None
if l[index] > value:
return index |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_data(self, variable_id, value, task):
""" write value to single modbus register or coil """ |
if variable_id not in self.variables:
return False
if not self.variables[variable_id].writeable:
return False
if self.variables[variable_id].modbusvariable.function_code_read == 3:
# write register
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
if self.variables[variable_id].get_bits_by_class() / 16 == 1:
# just write the value to one register
self.slave.write_register(self.variables[variable_id].modbusvariable.address, int(value),
unit=self._unit_id)
else:
# encode it first
self.slave.write_registers(self.variables[variable_id].modbusvariable.address,
list(self.variables[variable_id].encode_value(value)),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
return False
elif self.variables[variable_id].modbusvariable.function_code_read == 1:
# write coil
if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
if self._connect():
self.slave.write_coil(self.variables[variable_id].modbusvariable.address, bool(value),
unit=self._unit_id)
self._disconnect()
return True
else:
logger.info("device with id: %d is now accessible" % self.device.pk)
return False
else:
logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
else:
logger.error('wrong type of function code %d' %
self.variables[variable_id].modbusvariable.function_code_read)
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 demonize(self):
""" do the double fork magic """ |
# check if a process is already running
if access(self.pid_file_name, F_OK):
# read the pid file
pid = self.read_pid()
try:
kill(pid, 0) # check if process is running
self.stderr.write("process is already running\n")
return False
except OSError as e:
if e.errno == errno.ESRCH:
# process is dead
self.delete_pid(force_del=True)
else:
self.stderr.write("demonize failed, something went wrong: %d (%s)\n" % (e.errno, e.strerror))
return False
try:
pid = fork()
if pid > 0:
# Exit from the first parent
timeout = time() + 60
while self.read_pid() is None:
self.stderr.write("waiting for pid..\n")
sleep(0.5)
if time() > timeout:
break
self.stderr.write("pid is %d\n" % self.read_pid())
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 1. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Decouple from parent environment
# os.chdir("/")
setsid()
umask(0)
# Do the Second fork
try:
pid = fork()
if pid > 0:
# Exit from the second parent
sys.exit(0)
except OSError as e:
self.stderr.write("demonize failed in 2. Fork: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1)
# Redirect standard file descriptors
# sys.stdout.flush()
# sys.stderr.flush()
# si = file(self.stdin, 'r')
# so = file(self.stdout, 'a+')
# se = file(self.stderr, 'a+',
# os.dup2(si.fileno(), sys.stdin.fileno())
# os.dup2(so.fileno(), sys.stdout.fileno())
# os.dup2(se.fileno(), sys.stderr.fileno())
# Write the PID file
#atexit.register(self.delete_pid)
self.write_pid()
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 delete_pid(self, force_del=False):
""" delete the pid file """ |
pid = self.read_pid()
if pid != getpid() or force_del:
logger.debug('process %d tried to delete pid' % getpid())
return False
if access(self.pid_file_name, F_OK):
try:
remove(self.pid_file_name) # remove the old pid file
logger.debug('delete pid (%d)' % getpid())
except:
logger.debug("can't delete pid file") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" start the scheduler """ |
# demonize
if self.run_as_daemon:
if not self.demonize():
self.delete_pid()
sys.exit(0)
# recreate the DB connection
if connection.connection is not None:
connection.connection.close()
connection.connection = None
master_process = BackgroundProcess.objects.filter(parent_process__isnull=True,
label=self.label,
enabled=True).first()
self.pid = getpid()
if not master_process:
self.delete_pid(force_del=True)
logger.debug('no such process in BackgroundProcesses\n')
sys.exit(0)
self.process_id = master_process.pk
master_process.pid = self.pid
master_process.last_update = now()
master_process.running_since = now()
master_process.done = False
master_process.failed = False
master_process.message = 'init master process'
master_process.save()
BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False).update(message='stopped')
for parent_process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id, done=False):
for process in BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False):
try:
kill(process.pid, 0)
except OSError as e:
if e.errno == errno.ESRCH:
process.delete()
continue
logger.debug('process %d is alive' % process.pk)
process.stop()
# clean up
BackgroundProcess.objects.filter(parent_process__pk=parent_process.pk, done=False).delete()
# register signals
[signal.signal(s, self.signal) for s in self.SIGNALS]
#signal.signal(signal.SIGCHLD, self.handle_chld)
# start the main loop
self.run()
self.delete_pid()
sys.exit(0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
""" the main loop """ |
try:
master_process = BackgroundProcess.objects.filter(pk=self.process_id).first()
if master_process:
master_process.last_update = now()
master_process.message = 'init child processes'
master_process.save()
else:
self.delete_pid(force_del=True)
self.stderr.write("no such process in BackgroundProcesses")
sys.exit(0)
self.manage_processes()
while True:
# handle signals
sig = self.SIG_QUEUE.pop(0) if len(self.SIG_QUEUE) else None
# check the DB connection
check_db_connection()
# update the P
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='running..')
if sig is None:
self.manage_processes()
elif sig not in self.SIGNALS:
logger.error('%s, unhandled signal %d' % (self.label, sig))
continue
elif sig == signal.SIGTERM:
logger.debug('%s, termination signal' % self.label)
raise StopIteration
elif sig == signal.SIGHUP:
# todo handle sighup
pass
elif sig == signal.SIGUSR1:
# restart all child processes
logger.debug('PID %d, processed SIGUSR1 (%d) signal' % (self.pid, sig))
self.restart()
elif sig == signal.SIGUSR2:
# write the process status to stdout
self.status()
pass
sleep(5)
except StopIteration:
self.stop()
self.delete_pid()
sys.exit(0)
except SystemExit:
raise
except:
logger.error('%s(%d), unhandled exception\n%s' % (self.label, getpid(), traceback.format_exc())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restart(self):
""" restart all child processes """ |
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='restarting..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
sleep(0.1)
self.kill_processes(signal.SIGKILL)
self.manage_processes()
logger.debug('BD %d: restarted'%self.process_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, sig=signal.SIGTERM):
""" stop the scheduler and stop all processes """ |
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
logger.error("can't determine process id exiting.")
return False
if self.pid != getpid():
# calling from outside the daemon instance
logger.debug('send sigterm to daemon')
try:
kill(self.pid, sig)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
logger.debug('start termination of the daemon')
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopping..')
timeout = time() + 60 # wait max 60 seconds
self.kill_processes(signal.SIGTERM)
while self.PROCESSES and time() < timeout:
self.kill_processes(signal.SIGTERM)
sleep(1)
self.kill_processes(signal.SIGKILL)
BackgroundProcess.objects.filter(pk=self.process_id).update(
last_update=now(),
message='stopped')
logger.debug('termination of the daemon done')
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 spawn_process(self, process=None):
""" spawn a new process """ |
if process is None:
return False
# start new child process
pid = fork()
if pid != 0:
# parent process
process.pid = pid
self.PROCESSES[process.process_id] = process
connections.close_all()
return True
# child process
process.pid = getpid()
# connection.connection.close()
# connection.connection = None
process.pre_init_process()
process.init_process()
process.run()
sys.exit(0) |
<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(self):
""" write the current daemon status to stdout """ |
if self.pid is None:
self.pid = self.read_pid()
if self.pid is None:
sp = BackgroundProcess.objects.filter(pk=1).first()
if sp:
self.pid = sp.pid
if self.pid is None or self.pid == 0:
self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
return False
if self.pid != getpid():
# calling from outside the daemon instance
try:
kill(self.pid, signal.SIGUSR2)
return True
except OSError as e:
if e.errno == errno.ESRCH:
return False
else:
return False
process_list = []
for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
process_list.append(process)
process_list += list(process.backgroundprocess_set.filter())
for process in process_list:
logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pk))
logger.debug('%s, process_id %d' % (self.label, self.process_id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_init_process(self):
""" will be executed after process fork """ |
db.connections.close_all()
# update process info
BackgroundProcess.objects.filter(pk=self.process_id).update(
pid=self.pid,
last_update=now(),
running_since=now(),
done=False,
failed=False,
message='init process..',
)
[signal.signal(s, signal.SIG_DFL) for s in self.SIGNALS] # reset
[signal.signal(s, self.signal) for s in self.SIGNALS] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, signum=None, frame=None):
""" handel's a termination signal """ |
BackgroundProcess.objects.filter(pk=self.process_id
).update(pid=0, last_update=now(), message='stopping..')
# run the cleanup
self.cleanup()
BackgroundProcess.objects.filter(pk=self.process_id).update(pid=0,
last_update=now(),
message='stopped') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_process(self):
""" init a standard daq process for a single device """ |
self.device = Device.objects.filter(protocol__daq_daemon=1, active=1, id=self.device_id).first()
if not self.device:
logger.error("Error init_process for %s" % self.device_id)
return False
self.dt_set = min(self.dt_set, self.device.polling_interval)
self.dt_query_data = self.device.polling_interval
try:
self.device = self.device.get_device_instance()
except:
var = traceback.format_exc()
logger.error("exception while initialisation of DAQ Process for Device %d %s %s" % (
self.device_id, linesep, var))
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 init_process(self):
""" init a standard daq process for multiple devices """ |
for item in Device.objects.filter(protocol__daq_daemon=1, active=1, id__in=self.device_ids):
try:
tmp_device = item.get_device_instance()
if tmp_device is not None:
self.devices[item.pk] = tmp_device
self.dt_set = min(self.dt_set, item.polling_interval)
self.dt_query_data = min(self.dt_query_data, item.polling_interval)
except:
var = traceback.format_exc()
logger.error("exception while initialisation of DAQ Process for Device %d %s %s" % (
item.pk, linesep, var))
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 _delete_widget_content(sender, instance, **kwargs):
""" delete the widget content instance when a WidgetContentModel is deleted """ |
if not issubclass(sender, WidgetContentModel):
return
# delete WidgetContent Entry
wcs = WidgetContent.objects.filter(
content_pk=instance.pk,
content_model=('%s' % instance.__class__).replace("<class '", '').replace("'>", ''))
for wc in wcs:
logger.debug('delete wc %r'%wc)
wc.delete() |
<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_widget_content(sender, instance, created=False, **kwargs):
""" create a widget content instance when a WidgetContentModel is deleted """ |
if not issubclass(sender, WidgetContentModel):
return
# create a WidgetContent Entry
if created:
instance.create_widget_content_entry()
return |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast_value(value, _type):
""" cast value to _type """ |
if _type.upper() == 'FLOAT64':
return float64(value)
elif _type.upper() == 'FLOAT32':
return float32(value)
elif _type.upper() == 'INT32':
return int32(value)
elif _type.upper() == 'UINT16':
return uint16(value)
elif _type.upper() == 'INT16':
return int16(value)
elif _type.upper() == 'BOOLEAN':
return uint8(value)
else:
return float64(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 loop(self):
""" check for mails and send them """ |
for mail in Mail.objects.filter(done=False, send_fail_count__lt=3):
# send all emails that are not already send or failed to send less
# then three times
mail.send_mail()
for mail in Mail.objects.filter(done=True, timestamp__lt=time() - 60 * 60 * 24 * 7):
# delete all done emails older then one week
mail.delete()
return 1, 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 normalize(l):
""" Normalizes input list. Parameters l: list The list to be normalized Returns ------- The normalized list or numpy array Raises ------ ValueError, if the list sums to zero """ |
s = float(sum(l))
if s == 0:
raise ValueError("Cannot normalize list with sum 0")
return [x / s for x in l] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def simplex_iterator(scale, boundary=True):
""" Systematically iterates through a lattice of points on the 2-simplex. Parameters scale: Int The normalized scale of the simplex, i.e. N such that points (x,y,z) satisify x + y + z == N boundary: bool, True Include the boundary points (tuples where at least one coordinate is zero) Yields ------ 3-tuples, There are binom(n+2, 2) points (the triangular number for scale + 1, less 3*(scale+1) if boundary=False """ |
start = 0
if not boundary:
start = 1
for i in range(start, scale + (1 - start)):
for j in range(start, scale + (1 - start) - i):
k = scale - i - j
yield (i, j, k) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def permute_point(p, permutation=None):
""" Permutes the point according to the permutation keyword argument. The default permutation is "012" which does not change the order of the coordinate. To rotate counterclockwise, use "120" and to rotate clockwise use "201".""" |
if not permutation:
return p
return [p[int(permutation[i])] for i in range(len(p))] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def project_sequence(s, permutation=None):
""" Projects a point or sequence of points using `project_point` to lists xs, ys for plotting with Matplotlib. Parameters s, Sequence-like The sequence of points (3-tuples) to be projected. Returns ------- xs, ys: The sequence of projected points in coordinates as two lists """ |
xs, ys = unzip([project_point(p, permutation=permutation) for p in s])
return xs, ys |
<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_coordinates(q, conversion, axisorder):
""" Convert a 3-tuple in data coordinates into to simplex data coordinates for plotting. Parameters q: 3-tuple the point to be plotted in data coordinates conversion: dict keys = ['b','l','r'] values = lambda function giving the conversion axisorder: String giving the order of the axes for the coordinate tuple e.g. 'blr' for bottom, left, right coordinates. Returns ------- p: 3-tuple The point converted to simplex coordinates. """ |
p = []
for k in range(3):
p.append(conversion[axisorder[k]](q[k]))
return tuple(p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_conversion(scale, limits):
""" Get the conversion equations for each axis. limits: dict of min and max values for the axes in the order blr. """ |
fb = float(scale) / float(limits['b'][1] - limits['b'][0])
fl = float(scale) / float(limits['l'][1] - limits['l'][0])
fr = float(scale) / float(limits['r'][1] - limits['r'][0])
conversion = {"b": lambda x: (x - limits['b'][0]) * fb,
"l": lambda x: (x - limits['l'][0]) * fl,
"r": lambda x: (x - limits['r'][0]) * fr}
return conversion |
<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_coordinates_sequence(qs, scale, limits, axisorder):
""" Take a sequence of 3-tuples in data coordinates and convert them to simplex coordinates for plotting. This is needed for custom plots where the scale of the simplex axes is set within limits rather than being defined by the scale parameter. Parameters qs, sequence of 3-tuples The points to be plotted in data coordinates. scale: int The scale parameter for the plot. limits: dict keys = ['b','l','r'] values = min,max data values for this axis. axisorder: String giving the order of the axes for the coordinate tuple e.g. 'blr' for bottom, left, right coordinates. Returns ------- s, list of 3-tuples the points converted to simplex coordinates """ |
conversion = get_conversion(scale, limits)
return [convert_coordinates(q, conversion, axisorder) for q in qs] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resize_drawing_canvas(ax, scale=1.):
""" Makes sure the drawing surface is large enough to display projected content. Parameters ax: Matplotlib AxesSubplot, None The subplot to draw on. scale: float, 1.0 Simplex scale size. """ |
ax.set_ylim((-0.10 * scale, .90 * scale))
ax.set_xlim((-0.05 * scale, 1.05 * scale)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear_matplotlib_ticks(ax=None, axis="both"):
""" Clears the default matplotlib axes, or the one specified by the axis argument. Parameters ax: Matplotlib AxesSubplot, None The subplot to draw on. axis: string, "both" The axis to clear: "x" or "horizontal", "y" or "vertical", or "both" """ |
if not ax:
return
if axis.lower() in ["both", "x", "horizontal"]:
ax.set_xticks([], [])
if axis.lower() in ["both", "y", "vertical"]:
ax.set_yticks([], []) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def scatter(points, ax=None, permutation=None, colorbar=False, colormap=None, vmin=0, vmax=1, scientific=False, cbarlabel=None, cb_kwargs=None, **kwargs):
""" Plots trajectory points where each point satisfies x + y + z = scale. First argument is a list or numpy array of tuples of length 3. Parameters points: List of 3-tuples The list of tuples to be scatter-plotted. ax: Matplotlib AxesSubplot, None The subplot to draw on. colorbar: bool, False Show colorbar. colormap: String or matplotlib.colors.Colormap, None The name of the Matplotlib colormap to use. vmin: int, 0 Minimum value for colorbar. vmax: int, 1 Maximum value for colorbar. cb_kwargs: dict Any additional kwargs to pass to colorbar kwargs: Any kwargs to pass through to matplotlib. """ |
if not ax:
fig, ax = pyplot.subplots()
xs, ys = project_sequence(points, permutation=permutation)
ax.scatter(xs, ys, vmin=vmin, vmax=vmax, **kwargs)
if colorbar and (colormap != None):
if cb_kwargs != None:
colorbar_hack(ax, vmin, vmax, colormap, scientific=scientific,
cbarlabel=cbarlabel, **cb_kwargs)
else:
colorbar_hack(ax, vmin, vmax, colormap, scientific=scientific,
cbarlabel=cbarlabel)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _en_to_enth(energy,concs,A,B,C):
"""Converts an energy to an enthalpy. Converts energy to enthalpy using the following formula: Enthalpy = energy - (energy contribution from A) - (energy contribution from B) - (energy contribution from C) An absolute value is taken afterward for convenience. Parameters energy : float The energy of the structure concs : list of floats The concentrations of each element A : float The energy of pure A B : float The energy of pure B C : float The energy of pure C Returns ------- enth : float The enthalpy of formation. """ |
enth = abs(energy - concs[0]*A -concs[1]*B -concs[2]*C)
return enth |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _energy_to_enthalpy(energy):
"""Converts energy to enthalpy. This function take the energies stored in the energy array and converts them to formation enthalpy. Parameters --------- energy : list of lists of floats Returns ------- enthalpy : list of lists containing the enthalpies. """ |
pureA = [energy[0][0],energy[0][1]]
pureB = [energy[1][0],energy[1][1]]
pureC = [energy[2][0],energy[2][1]]
enthalpy = []
for en in energy:
c = en[2]
conc = [float(i)/sum(c) for i in c]
CE = _en_to_enth(en[0],conc,pureA[0],pureB[0],pureC[0])
VASP = _en_to_enth(en[1],conc,pureA[1],pureB[1],pureC[1])
enthalpy.append([CE,VASP,c])
return enthalpy |
<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_error(vals):
"""Find the errors in the energy values. This function finds the errors in the enthalpys. Parameters vals : list of lists of floats Returns ------- err_vals : list of lists containing the errors. """ |
err_vals = []
for en in vals:
c = en[2]
conc = [float(i)/sum(c) for i in c]
err = abs(en[0]-en[1])
err_vals.append([conc,err])
return err_vals |
<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_data(fname):
"""Reads data from file. Reads the data in 'fname' into a list where each list entry contains [energy predicted, energy calculated, list of concentrations]. Parameters fname : str The name and path to the data file. Returns ------- energy : list of lists of floats A list of the energies and the concentrations. """ |
energy = []
with open(fname,'r') as f:
for line in f:
CE = abs(float(line.strip().split()[0]))
VASP = abs(float(line.strip().split()[1]))
conc = [i for i in line.strip().split()[2:]]
conc_f = []
for c in conc:
if '[' in c and ']' in c:
conc_f.append(int(c[1:-1]))
elif '[' in c:
conc_f.append(int(c[1:-1]))
elif ']' in c or ',' in c:
conc_f.append(int(c[:-1]))
else:
conc_f.append(int(c))
energy.append([CE,VASP,conc_f])
return energy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conc_err_plot(fname):
"""Plots the error in the CE data. This plots the error in the CE predictions within a ternary concentration diagram. Parameters fname : string containing the input file name. """ |
energies = _read_data(fname)
enthalpy = _energy_to_enthalpy(energies)
this_errors = _find_error(enthalpy)
points = []
colors = []
for er in this_errors:
concs = er[0]
points.append((concs[0]*100,concs[1]*100,concs[2]*100))
colors.append(er[1])
scale = 100
figure, tax = ternary.figure(scale=scale)
tax.boundary(linewidth = 1.0)
tax.set_title("Errors in Convex Hull Predictions.",fontsize=20)
tax.gridlines(multiple=10,color="blue")
tax.scatter(points,vmax=max(colors),colormap=plt.cm.viridis,colorbar=True,c=colors,cmap=plt.cm.viridis)
tax.show() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _connect_callbacks(self):
"""Connect resize matplotlib callbacks.""" |
figure = self.get_figure()
callback = partial(mpl_redraw_callback, tax=self)
event_names = ('resize_event', 'draw_event')
for event_name in event_names:
figure.canvas.mpl_connect(event_name, callback) |
<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_title(self, title, **kwargs):
"""Sets the title on the underlying matplotlib AxesSubplot.""" |
ax = self.get_axes()
ax.set_title(title, **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 left_axis_label(self, label, position=None, rotation=60, offset=0.08, **kwargs):
""" Sets the label on the left axis. Parameters label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, 60 The angle of rotation of the label offset: float, Used to compute the distance of the label from the axis kwargs: Any kwargs to pass through to matplotlib. """ |
if not position:
position = (-offset, 3./5, 2./5)
self._labels["left"] = (label, position, rotation, 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 right_axis_label(self, label, position=None, rotation=-60, offset=0.08, **kwargs):
""" Sets the label on the right axis. Parameters label: String The axis label position: 3-Tuple of floats, None The position of the text label rotation: float, -60 The angle of rotation of the label offset: float, Used to compute the distance of the label from the axis kwargs: Any kwargs to pass through to matplotlib. """ |
if not position:
position = (2. / 5 + offset, 3. / 5, 0)
self._labels["right"] = (label, position, rotation, 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 clear_matplotlib_ticks(self, axis="both"):
"""Clears the default matplotlib ticks.""" |
ax = self.get_axes()
plotting.clear_matplotlib_ticks(ax=ax, axis=axis) |
<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_ticks_from_axis_limits(self, multiple=1):
""" Taking self._axis_limits and self._boundary_scale get the scaled ticks for all three axes and store them in self._ticks under the keys 'b' for bottom, 'l' for left and 'r' for right axes. """ |
for k in ['b', 'l', 'r']:
self._ticks[k] = numpy.linspace(
self._axis_limits[k][0],
self._axis_limits[k][1],
self._boundary_scale / float(multiple) + 1
).tolist() |
<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_custom_ticks(self, locations=None, clockwise=False, multiple=1, axes_colors=None, tick_formats=None, **kwargs):
""" Having called get_ticks_from_axis_limits, set the custom ticks on the plot. """ |
for k in ['b', 'l', 'r']:
self.ticks(ticks=self._ticks[k], locations=locations,
axis=k, clockwise=clockwise, multiple=multiple,
axes_colors=axes_colors, tick_formats=tick_formats,
**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 _redraw_labels(self):
"""Redraw axis labels, typically after draw or resize events.""" |
ax = self.get_axes()
# Remove any previous labels
for mpl_object in self._to_remove:
mpl_object.remove()
self._to_remove = []
# Redraw the labels with the appropriate angles
label_data = list(self._labels.values())
label_data.extend(self._corner_labels.values())
for (label, position, rotation, kwargs) in label_data:
transform = ax.transAxes
x, y = project_point(position)
# Calculate the new angle.
position = numpy.array([x, y])
new_rotation = ax.transData.transform_angles(
numpy.array((rotation,)), position.reshape((1, 2)))[0]
text = ax.text(x, y, label, rotation=new_rotation,
transform=transform, horizontalalignment="center",
**kwargs)
text.set_rotation_mode("anchor")
self._to_remove.append(text) |
<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_coordinates(self, points, axisorder='blr'):
""" Convert data coordinates to simplex coordinates for plotting in the case that axis limits have been applied. """ |
return convert_coordinates_sequence(points,self._boundary_scale,
self._axis_limits, axisorder) |
<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_cmap(cmap=None):
""" Loads a matplotlib colormap if specified or supplies the default. Parameters cmap: string or matplotlib.colors.Colormap instance The name of the Matplotlib colormap to look up. Returns ------- The desired Matplotlib colormap Raises ------ ValueError if colormap name is not recognized by Matplotlib """ |
if isinstance(cmap, matplotlib.colors.Colormap):
return cmap
if isinstance(cmap, str):
cmap_name = cmap
else:
cmap_name = DEFAULT_COLOR_MAP_NAME
return plt.get_cmap(cmap_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def blend_value(data, i, j, k, keys=None):
"""Computes the average value of the three vertices of a triangle in the simplex triangulation, where two of the vertices are on the lower horizontal.""" |
key_size = len(list(data.keys())[0])
if not keys:
keys = triangle_coordinates(i, j, k)
# Reduce key from (i, j, k) to (i, j) if necessary
keys = [tuple(key[:key_size]) for key in keys]
# Sum over the values of the points to blend
try:
s = sum(data[key] for key in keys)
value = s / 3.
except KeyError:
value = None
return 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 alt_blend_value(data, i, j, k):
"""Computes the average value of the three vertices of a triangle in the simplex triangulation, where two of the vertices are on the upper horizontal.""" |
keys = alt_triangle_coordinates(i, j, k)
return blend_value(data, i, j, k, keys=keys) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def triangle_coordinates(i, j, k):
""" Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangules are parallel to the lower axis on the lower side. Parameters i,j,k: enumeration of the desired triangle Returns ------- A numpy array of coordinates of the hexagon (unprojected) """ |
return [(i, j, k), (i + 1, j, k - 1), (i, j + 1, k - 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 alt_triangle_coordinates(i, j, k):
""" Computes coordinates of the constituent triangles of a triangulation for the simplex. These triangules are parallel to the lower axis on the upper side. Parameters i,j,k: enumeration of the desired triangle Returns ------- A numpy array of coordinates of the hexagon (unprojected) """ |
return [(i, j + 1, k - 1), (i + 1, j, k - 1), (i + 1, j + 1, k - 2)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_hexagon_deltas():
""" Generates a dictionary of the necessary additive vectors to generate the hexagon points for the hexagonal heatmap. """ |
zero = numpy.array([0, 0, 0])
alpha = numpy.array([-1./3, 2./3, 0])
deltaup = numpy.array([1./3, 1./3, 0])
deltadown = numpy.array([2./3, -1./3, 0])
i_vec = numpy.array([0, 1./2, -1./2])
i_vec_down = numpy.array([1./2, -1./2, 0])
deltaX_vec = numpy.array([1./2, 0, -1./2])
d = dict()
# Corner Points
d["100"] = [zero, -deltaX_vec, -deltadown, -i_vec_down]
d["010"] = [zero, i_vec_down, -alpha, -i_vec]
d["001"] = [zero, i_vec, deltaup, deltaX_vec]
# On the Edges
d["011"] = [i_vec, deltaup, deltadown, -alpha, -i_vec]
d["101"] = [-deltaX_vec, -deltadown, alpha, deltaup, deltaX_vec]
d["110"] = [i_vec_down, -alpha, -deltaup, -deltadown, -i_vec_down]
# Interior point
d["111"] = [alpha, deltaup, deltadown, -alpha, -deltaup, -deltadown]
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hexagon_coordinates(i, j, k):
""" Computes coordinates of the constituent hexagons of a hexagonal heatmap. Parameters i, j, k: enumeration of the desired hexagon Returns ------- A numpy array of coordinates of the hexagon (unprojected) """ |
signature = ""
for x in [i, j, k]:
if x == 0:
signature += "0"
else:
signature += "1"
deltas = hexagon_deltas[signature]
center = numpy.array([i, j, k])
return numpy.array([center + x for x in deltas]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def polygon_generator(data, scale, style, permutation=None):
"""Generator for the vertices of the polygon to be colored and its color, depending on style. Called by heatmap.""" |
# We'll project the coordinates inside this function to prevent
# passing around permutation more than necessary
project = functools.partial(project_point, permutation=permutation)
if isinstance(data, dict):
data_gen = data.items()
else:
# Only works with style == 'h'
data_gen = data
for key, value in data_gen:
if value is None:
continue
i = key[0]
j = key[1]
k = scale - i - j
if style == 'h':
vertices = hexagon_coordinates(i, j, k)
yield (map(project, vertices), value)
elif style == 'd':
# Upright triangles
if (i <= scale) and (j <= scale) and (k >= 0):
vertices = triangle_coordinates(i, j, k)
yield (map(project, vertices), value)
# Upside-down triangles
if (i < scale) and (j < scale) and (k >= 1):
vertices = alt_triangle_coordinates(i, j, k)
value = blend_value(data, i, j, k)
yield (map(project, vertices), value)
elif style == 't':
# Upright triangles
if (i < scale) and (j < scale) and (k > 0):
vertices = triangle_coordinates(i, j, k)
value = blend_value(data, i, j, k)
yield (map(project, vertices), value)
# If not on the boundary add the upside-down triangle
if (i < scale) and (j < scale) and (k > 1):
vertices = alt_triangle_coordinates(i, j, k)
value = alt_blend_value(data, i, j, k)
yield (map(project, vertices), 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 heatmap(data, scale, vmin=None, vmax=None, cmap=None, ax=None, scientific=False, style='triangular', colorbar=True, permutation=None, use_rgba=False, cbarlabel=None, cb_kwargs=None):
""" Plots heatmap of given color values. Parameters data: dictionary A dictionary mapping the i, j polygon to the heatmap color, where i + j + k = scale. scale: Integer The scale used to partition the simplex. vmin: float, None The minimum color value, used to normalize colors. Computed if absent. vmax: float, None The maximum color value, used to normalize colors. Computed if absent. cmap: String or matplotlib.colors.Colormap, None The name of the Matplotlib colormap to use. ax: Matplotlib AxesSubplot, None The subplot to draw on. scientific: Bool, False Whether to use scientific notation for colorbar numbers. style: String, "triangular" The style of the heatmap, "triangular", "dual-triangular" or "hexagonal" colorbar: bool, True Show colorbar. permutation: string, None A permutation of the coordinates use_rgba: bool, False Use rgba color values cbarlabel: string, None Text label for the colorbar cb_kwargs: dict dict of kwargs to pass to colorbar Returns ------- ax: The matplotlib axis """ |
if not ax:
fig, ax = pyplot.subplots()
# If use_rgba, make the RGBA values numpy arrays so that they can
# be averaged.
if use_rgba:
for k, v in data.items():
data[k] = numpy.array(v)
else:
cmap = get_cmap(cmap)
if vmin is None:
vmin = min(data.values())
if vmax is None:
vmax = max(data.values())
style = style.lower()[0]
if style not in ["t", "h", 'd']:
raise ValueError("Heatmap style must be 'triangular', 'dual-triangular', or 'hexagonal'")
vertices_values = polygon_generator(data, scale, style,
permutation=permutation)
# Draw the polygons and color them
for vertices, value in vertices_values:
if value is None:
continue
if not use_rgba:
color = colormapper(value, vmin, vmax, cmap=cmap)
else:
color = value # rgba tuple (r,g,b,a) all in [0,1]
# Matplotlib wants a list of xs and a list of ys
xs, ys = unzip(vertices)
ax.fill(xs, ys, facecolor=color, edgecolor=color)
if not cb_kwargs:
cb_kwargs = dict()
if colorbar:
colorbar_hack(ax, vmin, vmax, cmap, scientific=scientific,
cbarlabel=cbarlabel, **cb_kwargs)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def svg_polygon(coordinates, color):
""" Create an svg triangle for the stationary heatmap. Parameters coordinates: list The coordinates defining the polygon color: string RGB color value e.g. #26ffd1 Returns ------- string, the svg string for the polygon """ |
coord_str = []
for c in coordinates:
coord_str.append(",".join(map(str, c)))
coord_str = " ".join(coord_str)
polygon = '<polygon points="%s" style="fill:%s;stroke:%s;stroke-width:0"/>\n' % (coord_str, color, color)
return polygon |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def line(ax, p1, p2, permutation=None, **kwargs):
""" Draws a line on `ax` from p1 to p2. Parameters ax: Matplotlib AxesSubplot, None The subplot to draw on. p1: 2-tuple The (x,y) starting coordinates p2: 2-tuple The (x,y) ending coordinates kwargs: Any kwargs to pass through to Matplotlib. """ |
pp1 = project_point(p1, permutation=permutation)
pp2 = project_point(p2, permutation=permutation)
ax.add_line(Line2D((pp1[0], pp2[0]), (pp1[1], pp2[1]), **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 horizontal_line(ax, scale, i, **kwargs):
""" Draws the i-th horizontal line parallel to the lower axis. Parameters ax: Matplotlib AxesSubplot The subplot to draw on. scale: float, 1.0 Simplex scale size. i: float The index of the line to draw kwargs: Dictionary Any kwargs to pass through to Matplotlib. """ |
p1 = (0, i, scale - i)
p2 = (scale - i, i, 0)
line(ax, p1, p2, **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 left_parallel_line(ax, scale, i, **kwargs):
""" Draws the i-th line parallel to the left axis. Parameters ax: Matplotlib AxesSubplot The subplot to draw on. scale: float Simplex scale size. i: float The index of the line to draw kwargs: Dictionary Any kwargs to pass through to Matplotlib. """ |
p1 = (i, scale - i, 0)
p2 = (i, 0, scale - i)
line(ax, p1, p2, **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 right_parallel_line(ax, scale, i, **kwargs):
""" Draws the i-th line parallel to the right axis. Parameters ax: Matplotlib AxesSubplot The subplot to draw on. scale: float Simplex scale size. i: float The index of the line to draw kwargs: Dictionary Any kwargs to pass through to Matplotlib. """ |
p1 = (0, scale - i, i)
p2 = (scale - i, 0, i)
line(ax, p1, p2, **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 boundary(ax, scale, axes_colors=None, **kwargs):
""" Plots the boundary of the simplex. Creates and returns matplotlib axis if none given. Parameters ax: Matplotlib AxesSubplot, None The subplot to draw on. scale: float Simplex scale size. kwargs: Any kwargs to pass through to matplotlib. axes_colors: dict Option for coloring boundaries different colors. e.g. {'l': 'g'} for coloring the left axis boundary green """ |
# Set default color as black.
if axes_colors is None:
axes_colors = dict()
for _axis in ['l', 'r', 'b']:
if _axis not in axes_colors.keys():
axes_colors[_axis] = 'black'
horizontal_line(ax, scale, 0, color=axes_colors['b'], **kwargs)
left_parallel_line(ax, scale, 0, color=axes_colors['l'], **kwargs)
right_parallel_line(ax, scale, 0, color=axes_colors['r'], **kwargs)
return ax |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gridlines(ax, scale, multiple=None, horizontal_kwargs=None, left_kwargs=None, right_kwargs=None, **kwargs):
""" Plots grid lines excluding boundary. Parameters ax: Matplotlib AxesSubplot, None The subplot to draw on. scale: float Simplex scale size. multiple: float, None Specifies which inner gridelines to draw. For example, if scale=30 and multiple=6, only 5 inner gridlines will be drawn. horizontal_kwargs: dict, None Any kwargs to pass through to matplotlib for horizontal gridlines left_kwargs: dict, None Any kwargs to pass through to matplotlib for left parallel gridlines right_kwargs: dict, None Any kwargs to pass through to matplotlib for right parallel gridlines kwargs: Any kwargs to pass through to matplotlib, if not using horizontal_kwargs, left_kwargs, or right_kwargs """ |
if 'linewidth' not in kwargs:
kwargs["linewidth"] = 0.5
if 'linestyle' not in kwargs:
kwargs["linestyle"] = ':'
horizontal_kwargs = merge_dicts(kwargs, horizontal_kwargs)
left_kwargs = merge_dicts(kwargs, left_kwargs)
right_kwargs = merge_dicts(kwargs, right_kwargs)
if not multiple:
multiple = 1.
## Draw grid-lines
# Parallel to horizontal axis
for i in arange(0, scale, multiple):
horizontal_line(ax, scale, i, **horizontal_kwargs)
# Parallel to left and right axes
for i in arange(0, scale + multiple, multiple):
left_parallel_line(ax, scale, i, **left_kwargs)
right_parallel_line(ax, scale, i, **right_kwargs)
return ax |
<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_next_candidates(prev_candidates, length):
""" Returns the apriori candidates as a list. Arguments: prev_candidates -- Previous candidates as a list. length -- The lengths of the next candidates. """ |
# Solve the items.
item_set = set()
for candidate in prev_candidates:
for item in candidate:
item_set.add(item)
items = sorted(item_set)
# Create the temporary candidates. These will be filtered below.
tmp_next_candidates = (frozenset(x) for x in combinations(items, length))
# Return all the candidates if the length of the next candidates is 2
# because their subsets are the same as items.
if length < 3:
return list(tmp_next_candidates)
# Filter candidates that all of their subsets are
# in the previous candidates.
next_candidates = [
candidate for candidate in tmp_next_candidates
if all(
True if frozenset(x) in prev_candidates else False
for x in combinations(candidate, length - 1))
]
return next_candidates |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_support_records(transaction_manager, min_support, **kwargs):
""" Returns a generator of support records with given transactions. Arguments: transaction_manager -- Transactions as a TransactionManager instance. min_support -- A minimum support (float). Keyword arguments: max_length -- The maximum length of relations (integer). """ |
# Parse arguments.
max_length = kwargs.get('max_length')
# For testing.
_create_next_candidates = kwargs.get(
'_create_next_candidates', create_next_candidates)
# Process.
candidates = transaction_manager.initial_candidates()
length = 1
while candidates:
relations = set()
for relation_candidate in candidates:
support = transaction_manager.calc_support(relation_candidate)
if support < min_support:
continue
candidate_set = frozenset(relation_candidate)
relations.add(candidate_set)
yield SupportRecord(candidate_set, support)
length += 1
if max_length and length > max_length:
break
candidates = _create_next_candidates(relations, length) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_ordered_statistics(transaction_manager, record):
""" Returns a generator of ordered statistics as OrderedStatistic instances. Arguments: transaction_manager -- Transactions as a TransactionManager instance. record -- A support record as a SupportRecord instance. """ |
items = record.items
for combination_set in combinations(sorted(items), len(items) - 1):
items_base = frozenset(combination_set)
items_add = frozenset(items.difference(items_base))
confidence = (
record.support / transaction_manager.calc_support(items_base))
lift = confidence / transaction_manager.calc_support(items_add)
yield OrderedStatistic(
frozenset(items_base), frozenset(items_add), confidence, lift) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_ordered_statistics(ordered_statistics, **kwargs):
""" Filter OrderedStatistic objects. Arguments: ordered_statistics -- A OrderedStatistic iterable object. Keyword arguments: min_confidence -- The minimum confidence of relations (float). min_lift -- The minimum lift of relations (float). """ |
min_confidence = kwargs.get('min_confidence', 0.0)
min_lift = kwargs.get('min_lift', 0.0)
for ordered_statistic in ordered_statistics:
if ordered_statistic.confidence < min_confidence:
continue
if ordered_statistic.lift < min_lift:
continue
yield ordered_statistic |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apriori(transactions, **kwargs):
""" Executes Apriori algorithm and returns a RelationRecord generator. Arguments: transactions -- A transaction iterable object (eg. [['A', 'B'], ['B', 'C']]). Keyword arguments: min_support -- The minimum support of relations (float). min_confidence -- The minimum confidence of relations (float). min_lift -- The minimum lift of relations (float). max_length -- The maximum length of the relation (integer). """ |
# Parse the arguments.
min_support = kwargs.get('min_support', 0.1)
min_confidence = kwargs.get('min_confidence', 0.0)
min_lift = kwargs.get('min_lift', 0.0)
max_length = kwargs.get('max_length', None)
# Check arguments.
if min_support <= 0:
raise ValueError('minimum support must be > 0')
# For testing.
_gen_support_records = kwargs.get(
'_gen_support_records', gen_support_records)
_gen_ordered_statistics = kwargs.get(
'_gen_ordered_statistics', gen_ordered_statistics)
_filter_ordered_statistics = kwargs.get(
'_filter_ordered_statistics', filter_ordered_statistics)
# Calculate supports.
transaction_manager = TransactionManager.create(transactions)
support_records = _gen_support_records(
transaction_manager, min_support, max_length=max_length)
# Calculate ordered stats.
for support_record in support_records:
ordered_statistics = list(
_filter_ordered_statistics(
_gen_ordered_statistics(transaction_manager, support_record),
min_confidence=min_confidence,
min_lift=min_lift,
)
)
if not ordered_statistics:
continue
yield RelationRecord(
support_record.items, support_record.support, ordered_statistics) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_transactions(input_file, **kwargs):
""" Load transactions and returns a generator for transactions. Arguments: input_file -- An input file. Keyword arguments: delimiter -- The delimiter of the transaction. """ |
delimiter = kwargs.get('delimiter', '\t')
for transaction in csv.reader(input_file, delimiter=delimiter):
yield transaction if transaction else [''] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_as_json(record, output_file):
""" Dump an relation record as a json value. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output. """ |
def default_func(value):
"""
Default conversion for JSON value.
"""
if isinstance(value, frozenset):
return sorted(value)
raise TypeError(repr(value) + " is not JSON serializable")
converted_record = record._replace(
ordered_statistics=[x._asdict() for x in record.ordered_statistics])
json.dump(
converted_record._asdict(), output_file,
default=default_func, ensure_ascii=False)
output_file.write(os.linesep) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_as_two_item_tsv(record, output_file):
""" Dump a relation record as TSV only for 2 item relations. Arguments: record -- A RelationRecord instance to dump. output_file -- A file to output. """ |
for ordered_stats in record.ordered_statistics:
if len(ordered_stats.items_base) != 1:
continue
if len(ordered_stats.items_add) != 1:
continue
output_file.write('{0}\t{1}\t{2:.8f}\t{3:.8f}\t{4:.8f}{5}'.format(
list(ordered_stats.items_base)[0], list(ordered_stats.items_add)[0],
record.support, ordered_stats.confidence, ordered_stats.lift,
os.linesep)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(**kwargs):
""" Executes Apriori algorithm and print its result. """ |
# For tests.
_parse_args = kwargs.get('_parse_args', parse_args)
_load_transactions = kwargs.get('_load_transactions', load_transactions)
_apriori = kwargs.get('_apriori', apriori)
args = _parse_args(sys.argv[1:])
transactions = _load_transactions(
chain(*args.input), delimiter=args.delimiter)
result = _apriori(
transactions,
max_length=args.max_length,
min_support=args.min_support,
min_confidence=args.min_confidence)
for record in result:
args.output_func(record, args.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 add_transaction(self, transaction):
""" Add a transaction. Arguments: transaction -- A transaction as an iterable object (eg. ['A', 'B']). """ |
for item in transaction:
if item not in self.__transaction_index_map:
self.__items.append(item)
self.__transaction_index_map[item] = set()
self.__transaction_index_map[item].add(self.__num_transaction)
self.__num_transaction += 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 calc_support(self, items):
""" Returns a support for items. Arguments: items -- Items as an iterable object (eg. ['A', 'B']). """ |
# Empty items is supported by all transactions.
if not items:
return 1.0
# Empty transactions supports no items.
if not self.num_transaction:
return 0.0
# Create the transaction index intersection.
sum_indexes = None
for item in items:
indexes = self.__transaction_index_map.get(item)
if indexes is None:
# No support for any set that contains a not existing item.
return 0.0
if sum_indexes is None:
# Assign the indexes on the first time.
sum_indexes = indexes
else:
# Calculate the intersection on not the first time.
sum_indexes = sum_indexes.intersection(indexes)
# Calculate and return the support.
return float(len(sum_indexes)) / self.__num_transaction |
<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_payment_form(self):
"""Display the DirectPayment for entering payment information.""" |
self.context[self.form_context_name] = self.payment_form_cls()
return TemplateResponse(self.request, self.payment_template, self.context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_payment_form(self):
"""Try to validate and then process the DirectPayment form.""" |
warn_untested()
form = self.payment_form_cls(self.request.POST)
if form.is_valid():
success = form.process(self.request, self.item)
if success:
return HttpResponseRedirect(self.success_url)
else:
self.context['errors'] = self.errors['processing']
self.context[self.form_context_name] = form
self.context.setdefault("errors", self.errors['form'])
return TemplateResponse(self.request, self.payment_template, self.context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def redirect_to_express(self):
""" First step of ExpressCheckout. Redirect the request to PayPal using the data returned from setExpressCheckout. """ |
wpp = PayPalWPP(self.request)
try:
nvp_obj = wpp.setExpressCheckout(self.item)
except PayPalFailure:
warn_untested()
self.context['errors'] = self.errors['paypal']
return self.render_payment_form()
else:
return HttpResponseRedirect(express_endpoint_for_token(nvp_obj.token)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_confirm_form(self):
""" Third and final step of ExpressCheckout. Request has pressed the confirmation but and we can send the final confirmation to PayPal using the data from the POST'ed form. """ |
wpp = PayPalWPP(self.request)
pp_data = dict(token=self.request.POST['token'], payerid=self.request.POST['PayerID'])
self.item.update(pp_data)
# @@@ This check and call could be moved into PayPalWPP.
try:
if self.is_recurring():
warn_untested()
nvp = wpp.createRecurringPaymentsProfile(self.item)
else:
nvp = wpp.doExpressCheckoutPayment(self.item)
self.handle_nvp(nvp)
except PayPalFailure:
self.context['errors'] = self.errors['processing']
return self.render_payment_form()
else:
return HttpResponseRedirect(self.success_url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init(self, request, paypal_request, paypal_response):
"""Initialize a PayPalNVP instance from a HttpRequest.""" |
if request is not None:
from paypal.pro.helpers import strip_ip_port
self.ipaddress = strip_ip_port(request.META.get('REMOTE_ADDR', ''))
if (hasattr(request, "user") and request.user.is_authenticated):
self.user = request.user
else:
self.ipaddress = ''
# No storing credit card info.
query_data = dict((k, v) for k, v in paypal_request.items() if k not in self.RESTRICTED_FIELDS)
self.query = urlencode(query_data)
self.response = urlencode(paypal_response)
# Was there a flag on the play?
ack = paypal_response.get('ack', False)
if ack != "Success":
if ack == "SuccessWithWarning":
warn_untested()
self.flag_info = paypal_response.get('l_longmessage0', '')
else:
self.set_flag(paypal_response.get('l_longmessage0', ''), paypal_response.get('l_errorcode', '')) |
<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_flag(self, info, code=None):
"""Flag this instance for investigation.""" |
self.flag = True
self.flag_info += info
if code is not None:
self.flag_code = code |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process(self, request, item):
"""Do a direct payment.""" |
warn_untested()
from paypal.pro.helpers import PayPalWPP
wpp = PayPalWPP(request)
# Change the model information into a dict that PayPal can understand.
params = model_to_dict(self, exclude=self.ADMIN_FIELDS)
params['acct'] = self.acct
params['creditcardtype'] = self.creditcardtype
params['expdate'] = self.expdate
params['cvv2'] = self.cvv2
params.update(item)
# Create recurring payment:
if 'billingperiod' in params:
return wpp.createRecurringPaymentsProfile(params, direct=True)
# Create single payment:
else:
return wpp.doDirectPayment(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def posted_data_dict(self):
""" All the data that PayPal posted to us, as a correctly parsed dictionary of values. """ |
if not self.query:
return None
from django.http import QueryDict
roughdecode = dict(item.split('=', 1) for item in self.query.split('&'))
encoding = roughdecode.get('charset', None)
if encoding is None:
encoding = DEFAULT_ENCODING
query = self.query.encode('ascii')
data = QueryDict(query, encoding=encoding)
return data.dict() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(self):
""" Verifies an IPN and a PDT. Checks for obvious signs of weirdness in the payment and flags appropriately. """ |
self.response = self._postback().decode('ascii')
self.clear_flag()
self._verify_postback()
if not self.flag:
if self.is_transaction():
if self.payment_status not in self.PAYMENT_STATUS_CHOICES:
self.set_flag("Invalid payment_status. (%s)" % self.payment_status)
if duplicate_txn_id(self):
self.set_flag("Duplicate txn_id. (%s)" % self.txn_id)
self.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify_secret(self, form_instance, secret):
"""Verifies an IPN payment over SSL using EWP.""" |
warn_untested()
if not check_secret(form_instance, secret):
self.set_flag("Invalid secret. (%s)") % secret
self.save() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize(self, request):
"""Store the data we'll need to make the postback from the request object.""" |
if request.method == 'GET':
# PDT only - this data is currently unused
self.query = request.META.get('QUERY_STRING', '')
elif request.method == 'POST':
# The following works if paypal sends an ASCII bytestring, which it does.
self.query = request.body.decode('ascii')
self.ipaddress = request.META.get('REMOTE_ADDR', '') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _encrypt(self):
"""Use your key thing to encrypt things.""" |
from M2Crypto import BIO, SMIME, X509
# Iterate through the fields and pull out the ones that have a value.
plaintext = 'cert_id=%s\n' % self.cert_id
for name, field in self.fields.items():
value = None
if name in self.initial:
value = self.initial[name]
elif field.initial is not None:
value = field.initial
if value is not None:
plaintext += u'%s=%s\n' % (name, value)
plaintext = plaintext.encode('utf-8')
# Begin crypto weirdness.
s = SMIME.SMIME()
s.load_key_bio(BIO.openfile(self.private_cert), BIO.openfile(self.public_cert))
p7 = s.sign(BIO.MemoryBuffer(plaintext), flags=SMIME.PKCS7_BINARY)
x509 = X509.load_cert_bio(BIO.openfile(self.paypal_cert))
sk = X509.X509_Stack()
sk.push(x509)
s.set_x509_stack(sk)
s.set_cipher(SMIME.Cipher('des_ede3_cbc'))
tmp = BIO.MemoryBuffer()
p7.write_der(tmp)
p7 = s.encrypt(tmp, flags=SMIME.PKCS7_BINARY)
out = BIO.MemoryBuffer()
p7.write(out)
return out.read().decode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def paypal_time(time_obj=None):
"""Returns a time suitable for PayPal time fields.""" |
warn_untested()
if time_obj is None:
time_obj = time.gmtime()
return time.strftime(PayPalNVP.TIMESTAMP_FORMAT, time_obj) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.