output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def cache_page(page_cache, page_hash, cache_size):
"""Add a page to the page cache."""
page_cache.append(page_hash)
if len(page_cache) > cache_size:
page_cache.pop(0) | Can you create a Python 3 function that
adds a page to the page cache. | You are a Python code analyst, evaluating scripts for potential improvements. |
Filter text using regular expressions. | Can you tell what is the following Python 3 function doing
def re_filter(text, regexps):
if not regexps:
return text
matched_text = []
compiled_regexps = [re.compile(x) for x in regexps]
for line in text:
if line in matched_text:
continue
for regexp in compiled_rege... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove unnecessary whitespace while keeping logical structure. | Here you have a function in Python 3, explain what it does
def remove_whitespace(text):
clean_text = []
curr_line = ''
# Remove any newlines that follow two lines of whitespace consecutively
# Also remove whitespace at start and end of text
while text:
if not curr_line:
# Find th... | As a python code expert, you are capable of creating scripts from specifications. |
Parse text using XPath regex keywords and tag attributes. | Can you generate the documentation for the following Python 3 function
def parse_text(infile, xpath=None, filter_words=None, attributes=None):
infiles = []
text = []
if xpath is not None:
infile = parse_html(infile, xpath)
if isinstance(infile, list):
if isinstance(infile[0], lh.... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse and return text content of infiles. | Can you generate the documentation for the following Python 3 function
def get_parsed_text(args, infilename):
parsed_text = []
if infilename.endswith('.html'):
# Convert HTML to lxml object for content parsing
html = lh.fromstring(read_files(infilename))
text = None
else:
htm... | You are a Python code analyst, evaluating scripts for potential improvements. |
Filter HTML using XPath. | Can you generate the documentation for the following Python 3 function
def parse_html(infile, xpath):
if not isinstance(infile, lh.HtmlElement):
infile = lh.fromstring(infile)
infile = infile.xpath(xpath)
if not infile:
raise ValueError('XPath {0} returned no results.'.format(xpath))
ret... | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove www and fragments from internal URLs and remove www. | Can you generate a brief explanation for the following Python 3 code
def clean_url(url, base_url=None):
parsed_url = urlparse(url)
fragment = '{url.fragment}'.format(url=parsed_url)
if fragment:
url = url.split(fragment)[0]
# Identify internal URLs and fix their format
netloc = '{url.netlo... | As a Python code composer, you craft elegant and concise scripts. |
def add_url_suffix(url):
"""Add .com suffix to URL if none found."""
url = url.rstrip('/')
if not has_suffix(url):
return '{0}.com'.format(url)
return url | Implement a function in Python 3 to
add com suffix to URL if none found. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_outfilename(url, domain=None):
"""Construct the output filename from domain and end of path."""
if domain is None:
domain = get_domain(url)
path = '{url.path}'.format(url=urlparse(url))
if '.' in path:
tail_url = path.split('.')[-2]
else:
tail_url = path
if tail... | Create a Python 3 function for
constructing the output filename from domain and end of path. | As a python code expert, you are capable of creating scripts from specifications. |
def get_single_outfilename(args):
"""Use first possible entry in query as filename."""
for arg in args['query']:
if arg in args['files']:
return ('.'.join(arg.split('.')[:-1])).lower()
for url in args['urls']:
if arg.strip('/') in url:
domain = get_domain(... | Can you write a function in Python 3 where it
uses first possible entry in query as filename. | You are a Python code analyst, evaluating scripts for potential improvements. |
def modify_filename_id(filename):
"""Modify filename to have a unique numerical identifier."""
split_filename = os.path.splitext(filename)
id_num_re = re.compile('(\(\d\))')
id_num = re.findall(id_num_re, split_filename[-2])
if id_num:
new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1... | Create a Python 3 function for
modifying filename to have a unique numerical identifier. | As a Python code analyst, you investigate and solve complex coding mysteries |
If filename exists overwrite or modify it to be unique. | Explain what the following Python 3 code does
def overwrite_file_check(args, filename):
if not args['overwrite'] and os.path.exists(filename):
# Confirm overwriting of the file, or modify filename
if args['no_overwrite']:
overwrite = False
else:
try:
o... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def print_text(args, infilenames, outfilename=None):
"""Print text content of infiles to stdout.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- only used for interface purposes (None)
"""
for infilename... | Create a Python 3 function to
print text content of infiles to stdout. | As a python code expert, you are capable of creating scripts from specifications. |
def write_pdf_files(args, infilenames, outfilename):
"""Write pdf file(s) to disk using pdfkit.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output pdf file (str)
"""
if not outfilename.endswi... | Implement a Python 3 function for
writing pdf files to disk using pdfkit. | You are a Python code generator, capable of creating scripts from specifications. |
def write_csv_files(args, infilenames, outfilename):
"""Write csv file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str)
"""
def csv_convert(line):
"""Str... | Implement a Python 3 function for
writing csv files to disk. | You are a Python code generator, capable of creating scripts from specifications. |
Write text files to disk. | Can you tell what is the following Python 3 function doing
def write_text_files(args, infilenames, outfilename):
if not outfilename.endswith('.txt'):
outfilename = outfilename + '.txt'
outfilename = overwrite_file_check(args, outfilename)
all_text = [] # Text must be aggregated if writing to a sin... | You are a Python code architect, reviewing and designing scalable and efficient code |
def write_file(data, outfilename):
"""Write a single file to disk."""
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, IOError) as err... | Write a Python 3 script for
writing a single file to disk. | As a Python code composer, you craft elegant and concise scripts. |
def get_num_part_files():
"""Get the number of PART.html files currently saved to disk."""
num_parts = 0
for filename in os.listdir(os.getcwd()):
if filename.startswith('PART') and filename.endswith('.html'):
num_parts += 1
return num_parts | Can you write a function in Python 3 where it
gets the number of PART. html files currently saved to disk. | You are a Python code generator, capable of creating scripts from specifications. |
Write image files associated with a PART. html file. | Can you generate the documentation for the following Python 3 function
def write_part_images(url, raw_html, html, filename):
save_dirname = '{0}_files'.format(os.path.splitext(filename)[0])
if not os.path.exists(save_dirname):
os.makedirs(save_dirname)
images = html.xpath('//img/@src')
internal_... | You are a Python code analyst, evaluating scripts for potential improvements. |
Write a PART. html file to disk images in PART_files directory. | Can you generate the documentation for the following Python 3 function
def write_part_file(args, url, raw_html, html=None, part_num=None):
if part_num is None:
part_num = get_num_part_files() + 1
filename = 'PART{0}.html'.format(part_num)
# Decode bytes to string in Python 3 versions
if not PY2... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get numbered PART. html filenames. | How would you explain what the following Python 3 function does
def get_part_filenames(num_parts=None, start_num=0):
if num_parts is None:
num_parts = get_num_part_files()
return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+1)] | As a Python code analyst, you investigate and solve complex coding mysteries |
Read a file into memory. | How would you explain what the following Python 3 function does
def read_files(filenames):
if isinstance(filenames, list):
for filename in filenames:
with open(filename, 'r') as infile:
return infile.read()
else:
with open(filenames, 'r') as infile:
return... | As a python code expert, you are capable of creating scripts from specifications. |
def remove_part_images(filename):
"""Remove PART(#)_files directory containing images from disk."""
dirname = '{0}_files'.format(os.path.splitext(filename)[0])
if os.path.exists(dirname):
shutil.rmtree(dirname) | How would you implement a function in Python 3 that
removes PART ( # )_files directory containing images from disk. | As a Python code composer, you craft elegant and concise scripts. |
def remove_part_files(num_parts=None):
"""Remove PART(#).html files and image directories from disk."""
filenames = get_part_filenames(num_parts)
for filename in filenames:
remove_part_images(filename)
remove_file(filename) | Write a Python 3 function for
removing PART. html files and image directories from disk. | As a python code expert, you are capable of creating scripts from specifications. |
def confirm_input(user_input):
"""Check user input for yes, no, or an exit signal."""
if isinstance(user_input, list):
user_input = ''.join(user_input)
try:
u_inp = user_input.lower().strip()
except AttributeError:
u_inp = user_input
# Check for exit signal
if u_inp in ... | Write a Python 3 script to
check user input for yes no or an exit signal. | As a Python code analyst, you investigate and solve complex coding mysteries |
def mkdir_and_cd(dirname):
"""Change directory and/or create it if necessary."""
if not os.path.exists(dirname):
os.makedirs(dirname)
os.chdir(dirname)
else:
os.chdir(dirname) | Can you create a Python 3 function that
changes directory and / or create it if necessary. | As a Python code composer, you craft elegant and concise scripts. |
Converts a string representing the chemical file in in_format to out_format. | Given the following Python 3 function, write the documentation
def convert(data, in_format, out_format, name=None, pretty=False):
# Decide on a json formatter depending on desired prettiness
dumps = json.dumps if pretty else json.compress
# Shortcut for avoiding pybel dependency
if not has_ob and in_fo... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a python data structure to a Python object. | Explain what the following Python 3 code does
def json_to_pybel(data, infer_bonds=False):
obmol = ob.OBMol()
obmol.BeginModify()
for atom in data['atoms']:
obatom = obmol.NewAtom()
obatom.SetAtomicNum(table.GetAtomicNum(str(atom['element'])))
obatom.SetVector(*atom['location'])
... | As a python code expert, you are capable of creating scripts from specifications. |
def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
"""
# Save atom element type and... | Implement a function in Python 3 to
convert a pybel. Molecule to json. | As a Python code analyst, you investigate and solve complex coding mysteries |
def default(self, obj):
"""Fired when an unserializable object is hit."""
if hasattr(obj, '__dict__'):
return obj.__dict__.copy()
elif HAS_NUMPY and isinstance(obj, np.ndarray):
return obj.copy().tolist()
else:
raise TypeError(("Object of type {:s} wit... | Create a Python 3 function to
fire when an unserializable object is hit. | As a Python code analyst, you investigate and solve complex coding mysteries |
Draws an interactive 3D visualization of the inputted chemical. | How would you explain what the following Python 3 function does
def draw(data, format='auto', size=(400, 300), drawing_type='ball and stick',
camera_type='perspective', shader='lambert', display_html=True,
element_properties=None, show_save=False):
"""Draws an interactive 3D visualization of the i... | You are a Python code generator, capable of creating scripts from specifications. |
Converts input chemical formats to json and optimizes structure. | Can you generate the documentation for the following Python 3 function
def generate(data, format="auto"):
# Support both files and strings and attempt to infer file type
try:
with open(data) as in_file:
if format == 'auto':
format = data.split('.')[-1]
data = in_f... | As a python code expert, you are capable of creating scripts from specifications. |
Converts the output of generate(... ) to json. | Can you generate a brief explanation for the following Python 3 code
def to_json(data, compress=False):
return json.compress(data) if compress else json.dumps(data) | As a Python code composer, you craft elegant and concise scripts. |
Starts up the imolecule server. | Here you have a function in Python 3, explain what it does
def start_server():
parser = argparse.ArgumentParser(description="Opens a browser-based "
"client that interfaces with the "
"chemical format converter.")
parser.add_argument('--d... | As a python code expert, you are capable of creating scripts from specifications. |
def on_message(self, message):
"""Evaluates the function pointed to by json-rpc."""
json_rpc = json.loads(message)
logging.log(logging.DEBUG, json_rpc)
if self.pool is None:
self.pool = multiprocessing.Pool(processes=args.workers)
# Spawn a process to protect the se... | Write a Python 3 script to
evaluate the function pointed to by json - rpc. | As a Python code composer, you craft elegant and concise scripts. |
returns True if valA == valB and false otherwise | Can you tell what is the following Python 3 function doing
def nearly_eq(valA, valB, maxf=None, minf=None, epsilon=None):
'''
implementation based on:
http://floating-point-gui.de/errors/comparison/
'''
if valA == valB:
return True
if maxf is None:
maxf = float_info.max
i... | As a Python code composer, you craft elegant and concise scripts. |
Convert other into a Point class. | Given the following Python 3 function, write the documentation
def _convert(cls, other, ignoreScalars=False):
'''
:other: Point or point equivalent
:ignorescalars: optional boolean
:return: Point
Class private method for converting 'other' into a Point
subclasss. If 'oth... | You are a Python code analyst, evaluating scripts for potential improvements. |
def units(cls, scale=1):
'''
:scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k).
'''
return [cls(x=scale), cls(y=scale), ... | How would you implement a function in Python 3 that
returns a list of three Point objects representing the head of a unit vector. | You are a Python code generator, capable of creating scripts from specifications. |
def gaussian(cls, mu=0, sigma=1):
'''
:mu: mean
:sigma: standard deviation
:return: Point subclass
Returns a point whose coordinates are picked from a Gaussian
distribution with mean 'mu' and standard deviation 'sigma'.
See random.gauss for further explanati... | How would you implement a function in Python 3 that
returns a new Point subclass with the coordinates picked from a Gaussian distribution with mean mu and standard deviation sigma. | As a Python code analyst, you investigate and solve complex coding mysteries |
def random(cls, origin=None, radius=1):
'''
:origin: optional Point or point equivalent
:radius: optional float, radius around origin
:return: Point subclass
Returns a point with random x, y and z coordinates bounded by
the sphere defined by (origin,radius).
If ... | Implement a function in Python 3 to
return a new Point with random x y and z coordinates bounded by origin and radius around origin. | You are a Python code generator, capable of creating scripts from specifications. |
Internal function that applies a function to each coordinate and returns the result. | Can you tell what is the following Python 3 function doing
def _unary_(self, func, inplace=False):
'''
:func: unary function to apply to each coordinate
:inplace: optional boolean
:return: Point
Implementation private method.
All of the unary operations funnel thru this... | You are a Python code generator, capable of creating scripts from specifications. |
Return the cross product of two sets of points U x V. | Can you generate the documentation for the following Python 3 function
def cross(self, other):
'''
:other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Checks if the coordinates specified in axes of self to
are bounded by a and b. | Can you tell what is the following Python 3 function doing
def isBetween(self, a, b, axes='xyz'):
'''
:a: Point or point equivalent
:b: Point or point equivalent
:axis: optional string
:return: float
Checks the coordinates specified in 'axes' of 'self' to
determi... | As a Python code composer, you craft elegant and concise scripts. |
def ccw(self, b, c, axis='z'):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: float
CCW - Counter Clockwise
Returns an integer signifying the direction of rotation around 'axis... | Can you implement a function in Python 3 that
returns the angle of rotation around a given point. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns True if the angle determined by a self b c around axis is counter - clockwise rotation otherwise False. | Here you have a function in Python 3, explain what it does
def isCCW(self, b, c, axis='z'):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: boolean
True if the angle determined by a,self... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return True if self is collinear with b and c otherwise False. | How would you explain what the following Python 3 function does
def isCollinear(self, b, c):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:return: boolean
True if 'self' is collinear with 'b' and 'c', otherwise False.
'''
return all(self.ccw(b... | You are a Python code generator, capable of creating scripts from specifications. |
def rotate2d(self, theta, origin=None, axis='z', radians=False):
'''
:theta: float radians to rotate self around origin
:origin: optional Point, defaults to 0,0,0
Returns a Point rotated by :theta: around :origin:.
'''
origin = Point._convert(origin)
delta = se... | Write a Python 3 function that can
rotate the current Point around a given origin. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a Triangle initialized with points comprising the triangle
with the specified angles. | Make a summary of the following Python 3 code
def withAngles(cls, origin=None, base=1, alpha=None,
beta=None, gamma=None, inDegrees=False):
'''
:origin: optional Point
:alpha: optional float describing length of the side opposite A
:beta: optional float describing leng... | You are a Python code architect, reviewing and designing scalable and efficient code |
Computes the area of a triangle in the Heron s forumla for computing the area of a triangle. | Make a summary of the following Python 3 code
def heronsArea(self):
'''
Heron's forumla for computing the area of a triangle, float.
Performance note: contains a square root.
'''
s = self.semiperimeter
return math.sqrt(s * ((s - self.a) * (s - self.b) * (s - self.c))) | As a python code expert, you are capable of creating scripts from specifications. |
def circumradius(self):
'''
Distance from the circumcenter to all the verticies in
the Triangle, float.
'''
return (self.a * self.b * self.c) / (self.area * 4) | Can you create a Python 3 function that
returns the radius of the circumcenter of the triangle. | As a Python code composer, you craft elegant and concise scripts. |
A list of the altitudes of each vertex | Can you generate the documentation for the following Python 3 function
def altitudes(self):
'''
A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it.
'''
A = self... | You are a Python code architect, reviewing and designing scalable and efficient code |
def isIsosceles(self):
'''
True iff two side lengths are equal, boolean.
'''
return (self.a == self.b) or (self.a == self.c) or (self.b == self.c) | Write a Python 3 script for
truing iff two side lengths are equal boolean. | You are a Python code generator, capable of creating scripts from specifications. |
def center(self):
'''
Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin.
'''
try:
return self._center
except AttributeError:
pass
self._center = Point()
return self._center | Create a Python 3 function to
return the center point of the ellipse equidistant from foci Point class. | You are a Python code generator, capable of creating scripts from specifications. |
def radius(self):
'''
Radius of the ellipse, Point class.
'''
try:
return self._radius
except AttributeError:
pass
self._radius = Point(1, 1, 0)
return self._radius | Implement a function in Python 3 to
return the radius of the ellipse Point class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.x | Write a Python 3 script for
returning True if the major axis is parallel to the X axis boolean. | As a python code expert, you are capable of creating scripts from specifications. |
def xAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the X axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.x | Can you implement a function in Python 3 that
returns True if the minor axis is parallel to the X axis boolean. | As a Python code composer, you craft elegant and concise scripts. |
def yAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the Y axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.y | How would you implement a function in Python 3 that
returns True if the major axis is parallel to the Y axis boolean. | You are a Python code generator, capable of creating scripts from specifications. |
def yAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the Y axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.y | Can you create a Python 3 function that
returns True if the minor axis is parallel to the Y axis boolean. | As a Python code composer, you craft elegant and concise scripts. |
Negative antipodal point on the major axis Point class. | How would you explain what the following Python 3 function does
def a_neg(self):
'''
Negative antipodal point on the major axis, Point class.
'''
na = Point(self.center)
if self.xAxisIsMajor:
na.x -= self.majorRadius
else:
na.y -= self.majorRadiu... | As a python code expert, you are capable of creating scripts from specifications. |
Negative antipodal point on the minor axis Point class. | Can you tell what is the following Python 3 function doing
def b_neg(self):
'''
Negative antipodal point on the minor axis, Point class.
'''
nb = Point(self.center)
if self.xAxisIsMinor:
nb.x -= self.minorRadius
else:
nb.y -= self.minorRadius
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def focus0(self):
'''
First focus of the ellipse, Point class.
'''
f = Point(self.center)
if self.xAxisIsMajor:
f.x -= self.linearEccentricity
else:
f.y -= self.linearEccentricity
return f | Write a Python 3 function that can
return the first focus of the ellipse Point class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the circle that is the center of the circumcircle of the input triangle. | Make a summary of the following Python 3 code
def circumcircleForTriangle(cls, triangle):
'''
:param: triangle - Triangle class
:return: Circle class
Returns the circle where every vertex in the input triangle is
on the radius of that circle.
'''
if triangle.is... | You are a Python code architect, reviewing and designing scalable and efficient code |
def doesIntersect(self, other):
'''
:param: other - Circle class
Returns True iff:
self.center.distance(other.center) <= self.radius+other.radius
'''
otherType = type(other)
if issubclass(otherType, Ellipse):
distance = self.center.distance(other.... | Can you create a Python 3 function that
returns True iff self. center. distance ( other. center ) <= self. radius + other. radius | You are a Python code generator, capable of creating scripts from specifications. |
def normal(self):
'''
:return: Line
Returns a Line normal (perpendicular) to this Line.
'''
d = self.B - self.A
return Line([-d.y, d.x], [d.y, -d.x]) | Can you implement a function in Python 3 that
returns a Line normal to this Line. | You are a Python code architect, reviewing and designing scalable and efficient code |
Flips the positions of A and B. | Explain what the following Python 3 code does
def flip(self):
'''
:returns: None
Swaps the positions of A and B.
'''
tmp = self.A.xyz
self.A = self.B
self.B = tmp | You are a Python code architect, reviewing and designing scalable and efficient code |
def doesIntersect(self, other):
'''
:param: other - Line subclass
:return: boolean
Returns True iff:
ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0
and
ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0
'''
if s... | Create a Python 3 function for
returning True iff self and other are both Line subclasses and Line objects. | You are a Python code generator, capable of creating scripts from specifications. |
def intersection(self, other):
'''
:param: other - Line subclass
:return: Point subclass
Returns a Point object with the coordinates of the intersection
between the current line and the other line.
Will raise Parallel() if the two lines are parallel.
Will raise ... | Create a Python 3 function for
returning the intersection of two Line objects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def distanceFromPoint(self, point):
'''
:param: point - Point subclass
:return: float
Distance from the line to the given point.
'''
# XXX planar distance, doesn't take into account z ?
d = self.m
n = (d.y * point.x) - (d.x * point.y) + self.A.cross(self.... | Implement a Python 3 function for
calculating the distance from the line to the given point. | You are a Python code generator, capable of creating scripts from specifications. |
def radiansBetween(self, other):
'''
:param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi].
'''
# a dot b = |a||b| * cos(theta)
# a dot b / |a||b| = cos(theta)
# cos-... | Can you write a function in Python 3 where it
returns the angle measured between two lines in radians | As a python code expert, you are capable of creating scripts from specifications. |
Returns a property that can be used to initialize a new object variable. | Explain what the following Python 3 code does
def FloatProperty(name, default=0.0, readonly=False, docs=None):
'''
:name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initia... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a Rectangle with random size and location. | Can you tell what is the following Python 3 function doing
def randomSizeAndLocation(cls, radius, widthLimits,
heightLimits, origin=None):
'''
:param: radius - float
:param: widthLimits - iterable of floats with length >= 2
:param: heightLimits - iter... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a random Rectangle object with width and height limits. | Make a summary of the following Python 3 code
def randomSize(cls, widthLimits, heightLimits, origin=None):
'''
:param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a new Rectangle containing random locations. | How would you explain what the following Python 3 function does
def randomLocation(cls, radius, width, height, origin=None):
'''
:param: radius - float
:param: width - float
:param: height - float
:param: origin - optional Point subclass
:return: Rectangle
'''
... | As a Python code composer, you craft elegant and concise scripts. |
def origin(self):
'''
Point describing the origin of the rectangle. Defaults to (0,0,0).
'''
try:
return self._origin
except AttributeError:
pass
self._origin = Point()
return self._origin | Can you implement a function in Python 3 that
returns the origin of the rectangle. | As a python code expert, you are capable of creating scripts from specifications. |
Return a new Point object with the same coordinates as this one. | Can you generate a brief explanation for the following Python 3 code
def B(self):
'''
Point whose coordinates are (maxX,minY,origin.z), Point.
'''
return Point(self.maxX, self.minY, self.origin.z) | You are a Python code analyst, evaluating scripts for potential improvements. |
def C(self):
'''
Point whose coordinates are (maxX,maxY,origin.z), Point.
'''
return Point(self.maxX, self.maxY, self.origin.z) | Write a Python 3 script for
returning a new Point object that is the center of the current point. | You are a Python code architect, reviewing and designing scalable and efficient code |
def D(self):
'''
Point whose coordinates are (minX,maxY,origin.Z), Point.
'''
return Point(self.minX, self.maxY, self.origin.z) | Create a Python 3 function for
returning the D coordinate of the current Point. | You are a Python code analyst, evaluating scripts for potential improvements. |
def center(self):
'''
Point whose coordinates are (midX,midY,origin.z), Point.
'''
return Point(self.midX, self.midY, self.origin.z) | How would you implement a function in Python 3 that
returns the center of the current Point. | You are a Python code generator, capable of creating scripts from specifications. |
def scale(self, dx=1.0, dy=1.0):
'''
:param: dx - optional float
:param: dy - optional float
Scales the rectangle's width and height by dx and dy.
'''
self.width *= dx
self.height *= dy | Can you implement a function in Python 3 that
scales the rectangle s width and height by dx and dy. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns True if the point is contained in the rectangle or False otherwise. | Given the following Python 3 function, write the documentation
def containsPoint(self, point, Zorder=False):
'''
:param: point - Point subclass
:param: Zorder - optional Boolean
Is true if the point is contain in the rectangle or
along the rectangle's edges.
If Zorder ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def random(cls, origin=None, radius=1):
'''
:origin: - optional Point subclass
:radius: - optional float
:return: Triangle
Creates a triangle with random coordinates in the circle
described by (origin,radius). If origin is unspecified, (0,0)
is assumed. If the r... | How would you code a function in Python 3 to
return a new Triangle with random coordinates in the circle described by origin and radius. | You are a Python code architect, reviewing and designing scalable and efficient code |
def equilateral(cls, origin=None, side=1):
'''
:origin: optional Point
:side: optional float describing triangle side length
:return: Triangle initialized with points comprising a
equilateral triangle.
XXX equilateral triangle definition
'''
o =... | Implement a function in Python 3 to
return a new avec triangle initialized with points comprising a equilateral triangle. | You are a Python code generator, capable of creating scripts from specifications. |
def isosceles(cls, origin=None, base=1, alpha=90):
'''
:origin: optional Point
:base: optional float describing triangle base length
:return: Triangle initialized with points comprising a
isosceles triangle.
XXX isoceles triangle definition
'''
... | Write a Python 3 script for
returning a new isosceles triangle initialized with points comprising a . | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the Third vertex of triangle Point subclass. | How would you explain what the following Python 3 function does
def C(self):
'''
Third vertex of triangle, Point subclass.
'''
try:
return self._C
except AttributeError:
pass
self._C = Point(0, 1)
return self._C | As a python code expert, you are capable of creating scripts from specifications. |
A list of A and C vertices. | Given the following Python 3 function, write the documentation
def AC(self):
'''
Vertices A and C, list.
'''
try:
return self._AC
except AttributeError:
pass
self._AC = [self.A, self.C]
return self._AC | As a Python code analyst, you investigate and solve complex coding mysteries |
A list of all possible unique names for the current set of resources. | Can you tell what is the following Python 3 function doing
def CA(self):
'''
Vertices C and A, list.
'''
try:
return self._CA
except AttributeError:
pass
self._CA = [self.C, self.A]
return self._CA | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a list of the n - ary items that are in the order of the two sets. | How would you explain what the following Python 3 function does
def CB(self):
'''
Vertices C and B, list.
'''
try:
return self._CB
except AttributeError:
pass
self._CB = [self.C, self.B]
return self._CB | You are a Python code architect, reviewing and designing scalable and efficient code |
A list of the Triangle s line segments [ AB BC AC ] | Can you generate the documentation for the following Python 3 function
def segments(self):
'''
A list of the Triangle's line segments [AB, BC, AC], list.
'''
return [Segment(self.AB),
Segment(self.BC),
Segment(self.AC)] | As a python code expert, you are capable of creating scripts from specifications. |
Return the center of the circumscribed circle. | Make a summary of the following Python 3 code
def circumcenter(self):
'''
The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/C... | As a python code expert, you are capable of creating scripts from specifications. |
def isEquilateral(self):
'''
True if all sides of the triangle are the same length.
All equilateral triangles are also isosceles.
All equilateral triangles are also acute.
'''
if not nearly_eq(self.a, self.b):
return False
if not nearly_eq(self.b, s... | Implement a function in Python 3 to
true if all sides of the triangle are the same length. | You are a Python code architect, reviewing and designing scalable and efficient code |
def swap(self, side='AB', inplace=False):
'''
:side: - optional string
:inplace: - optional boolean
:return: Triangle with flipped side.
The optional side paramater should have one of three values:
AB, BC, or AC.
Changes the order of the triangle's points, swapp... | Create a Python 3 function for
returning a new Triangle with flipped side. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def doesIntersect(self, other):
'''
:param: other - Triangle or Line subclass
:return: boolean
Returns True iff:
Any segment in self intersects any segment in other.
'''
otherType = type(other)
if issubclass(otherType, Triangle):
for s in... | Implement a function in Python 3 to
return True iff any of the segments in self intersects any segment in other. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the total length of all sides of the current set. | How would you explain what the following Python 3 function does
def perimeter(self):
'''
Sum of the length of all sides, float.
'''
return sum([a.distance(b) for a, b in self.pairs()]) | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new DSIFT object from an image. | Given the following Python 3 function, write the documentation
def vl_dsift(data, fast=False, norm=False, bounds=None, size=3, step=1,
window_size=None, float_descriptors=False,
verbose=False, matlab_style=True):
'''
Dense sift descriptors from an image.
Returns:
frames:... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts an RGB image to grayscale using matlab s algorithm. | Can you generate a brief explanation for the following Python 3 code
def rgb2gray(img):
T = np.linalg.inv(np.array([
[1.0, 0.956, 0.621],
[1.0, -0.272, -0.647],
[1.0, -1.106, 1.703],
]))
r_c, g_c, b_c = T[0]
r, g, b = np.rollaxis(as_float_image(img), axis=-1)
return r_c * ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts an RGB image to HSV using scikit - image s algorithm. | Explain what the following Python 3 code does
def rgb2hsv(arr):
arr = np.asanyarray(arr)
if arr.ndim != 3 or arr.shape[2] != 3:
raise ValueError("the input array must have a shape == (.,.,3)")
arr = as_float_image(arr)
out = np.empty_like(arr)
# -- V channel
out_v = arr.max(-1)
# ... | As a python code expert, you are capable of creating scripts from specifications. |
def _parse_command_response(response):
"""Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The reques... | Write a Python 3 function that can
parse an SCI command response into an ElementTree Element | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse an error ElementTree Node to create an ErrorInfo object | Make a summary of the following Python 3 code
def _parse_error_tree(error):
errinf = ErrorInfo(error.get('id'), None)
if error.text is not None:
errinf.message = error.text
else:
desc = error.find('./desc')
if desc is not None:
errinf.message = desc.text
return errinf | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the contents of this file
| Can you tell what is the following Python 3 function doing
def get_data(self):
target = DeviceTarget(self.device_id)
return self._fssapi.get_file(target, self.path)[self.device_id] | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete this file from the device | Can you generate the documentation for the following Python 3 function
def delete(self):
target = DeviceTarget(self.device_id)
return self._fssapi.delete_file(target, self.path)[self.device_id] | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.