output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def clean_entries(self, source_invoice: Invoice or None, settled_invoice: Invoice or None, account: Account, **kw):
"""
This needs to be called from a derived class clean().
:param source_invoice:
:param settled_invoice:
:param account:
:return: None
"""
f... | Can you create a Python 3 function that
cleans the entries of the derived account. | As a python code expert, you are capable of creating scripts from specifications. |
Short date format.
:param obj: date or datetime or None
:return: str | Here you have a function in Python 3, explain what it does
def _format_date(self, obj) -> str:
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT') | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns aggregate sum of queryset amount field. | Make a summary of the following Python 3 code
def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal:
res = qs.aggregate(b=Sum(key))['b']
return default if res is None else res | As a Python code analyst, you investigate and solve complex coding mysteries |
def build_blueprint(self, url_prefix=''):
"""Build a blueprint that contains the endpoints for callback URLs of
the current subscriber. Only call this once per instance. Arguments:
- url_prefix; this allows you to prefix the callback URLs in your app.
"""
self.blueprint_name, s... | Implement a function in Python 3 to
build a blueprint that contains the endpoints for callback URLs of . Only call this once per instance. | As a Python code analyst, you investigate and solve complex coding mysteries |
Cancel the subscription for the given callback_id and delete the entry from the local database. | Explain what the following Python 3 code does
def unsubscribe(self, callback_id):
request = self.get_active_subscription(callback_id)
request['mode'] = 'unsubscribe'
self.subscribe_impl(callback_id, **request) | As a python code expert, you are capable of creating scripts from specifications. |
Automatically renews subscriptions that are close to expiring or have already expired. | Can you tell what is the following Python 3 function doing
def renew_close_to_expiration(self, margin_in_seconds=A_DAY):
subscriptions = self.storage.close_to_expiration(margin_in_seconds)
for subscription in subscriptions:
try:
self.subscribe_impl(**subscription)
... | As a python code expert, you are capable of creating scripts from specifications. |
def discover(url, timeout=None):
"""Discover the hub url and topic url of a given url. Firstly, by inspecting
the page's headers, secondarily by inspecting the content for link tags.
timeout determines how long to wait for the url to load. It defaults to 3.
"""
resp = get_content({'REQUEST_TIMEOUT... | Create a Python 3 function to
discover the hub url and topic url of a given url. | As a python code expert, you are capable of creating scripts from specifications. |
Context to ensure correct file permissions for certs and directories | Make a summary of the following Python 3 code
def open_tls_file(file_path, mode, private=True):
containing_dir = os.path.dirname(file_path)
fh = None
try:
if 'w' in mode:
os.chmod(containing_dir, mode=0o755)
fh = open(file_path, mode)
except OSError as e:
if 'w' in m... | As a python code expert, you are capable of creating scripts from specifications. |
def load(self):
"""Load from a file and return an x509 object"""
private = self.is_private()
with open_tls_file(self.file_path, 'r', private=private) as fh:
if private:
self.x509 = crypto.load_privatekey(self.encoding, fh.read())
else:
sel... | Can you create a Python 3 function that
loads from a file and return an x509 object | As a Python code analyst, you investigate and solve complex coding mysteries |
Persist this x509 object to disk | Can you tell what is the following Python 3 function doing
def save(self, x509):
self.x509 = x509
with open_tls_file(self.file_path, 'w',
private=self.is_private()) as fh:
fh.write(str(self)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Initializes the TLSFIle objects with the paths given to this bundle | Make a summary of the following Python 3 code
def _setup_tls_files(self, files):
for file_type in TLSFileType:
if file_type.value in files:
file_path = files[file_type.value]
setattr(self, file_type.value,
TLSFile(file_path, file_type=file_typ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Saves the x509 objects to the paths known by this bundle | Explain what the following Python 3 code does
def save_x509s(self, x509s):
for file_type in TLSFileType:
if file_type.value in x509s:
x509 = x509s[file_type.value]
if file_type is not TLSFileType.CA:
# persist this key or cert to disk
... | As a python code expert, you are capable of creating scripts from specifications. |
def to_record(self):
"""Create a CertStore record from this TLSFileBundle"""
tf_list = [getattr(self, k, None) for k in
[_.value for _ in TLSFileType]]
# If a cert isn't defined in this bundle, remove it
tf_list = filter(lambda x: x, tf_list)
files = {tf.file_... | Can you implement a function in Python 3 that
creates a CertStore record from this TLSFileBundle | You are a Python code generator, capable of creating scripts from specifications. |
Build a bundle from a CertStore record | Can you tell what is the following Python 3 function doing
def from_record(self, record):
self.record = record
self._setup_tls_files(self.record['files'])
return self | You are a Python code architect, reviewing and designing scalable and efficient code |
Write the store dict to a file specified by store_file_path | How would you explain what the following Python 3 function does
def save(self):
with open(self.store_file_path, 'w') as fh:
fh.write(json.dumps(self.store, indent=4)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Read the store dict from file | Can you generate a brief explanation for the following Python 3 code
def load(self):
with open(self.store_file_path, 'r') as fh:
self.store = json.loads(fh.read()) | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the record associated with this common name. | Can you generate a brief explanation for the following Python 3 code
def get_record(self, common_name):
try:
record = self.store[common_name]
return record
except KeyError as e:
raise CertNotFoundError(
"Unable to find record of {name}"
... | You are a Python code generator, capable of creating scripts from specifications. |
Return a bundle of TLS files associated with a common name | Can you generate the documentation for the following Python 3 function
def get_files(self, common_name):
record = self.get_record(common_name)
return TLSFileBundle(common_name).from_record(record) | As a python code expert, you are capable of creating scripts from specifications. |
def add_files(self, common_name, x509s, files=None, parent_ca='',
is_ca=False, signees=None, serial=0, overwrite=False):
"""Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these file... | Can you write a function in Python 3 where it
adds a set of files comprising a certificate to Certipy. | As a Python code composer, you craft elegant and concise scripts. |
def remove_sign_link(self, ca_name, signee_name):
"""Removes signee_name to the signee list for ca_name"""
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record['signees'] or {}
signees = Counter(signees)
if signee_name in ... | Write a Python 3 function that can
remove a signee_name from the signee list for ca_name | As a Python code analyst, you investigate and solve complex coding mysteries |
Update fields in an existing record | Explain what the following Python 3 code does
def update_record(self, common_name, **fields):
record = self.get_record(common_name)
if fields is not None:
for field, value in fields:
record[field] = value
self.save()
return record | As a python code expert, you are capable of creating scripts from specifications. |
Delete the record associated with this common name | How would you explain what the following Python 3 function does
def remove_record(self, common_name):
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Delete files and record associated with this common name | Here you have a function in Python 3, explain what it does
def remove_files(self, common_name, delete_dir=False):
record = self.remove_record(common_name)
if delete_dir:
delete_dirs = []
if 'files' in record:
key_containing_dir = os.path.dirname(record['files']['... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a public or private key pair. | Can you tell what is the following Python 3 function doing
def create_key_pair(self, cert_type, bits):
pkey = crypto.PKey()
pkey.generate_key(cert_type, bits)
return pkey | As a python code expert, you are capable of creating scripts from specifications. |
def sign(self, req, issuer_cert_key, validity_period, digest="sha256",
extensions=None, serial=0):
"""
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
... | Can you write a function in Python 3 where it
generates a certificate given a certificate request | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_ca_bundle_for_names(self, bundle_name, names):
"""Create a CA bundle to trust only certs defined in names
"""
records = [rec for name, rec
in self.store.store.items() if name in names]
return self.create_bundle(
bundle_name, names=[r['parent_ca'... | Create a Python 3 function to
create a CA bundle to trust only certs defined in names | You are a Python code analyst, evaluating scripts for potential improvements. |
def create_bundle(self, bundle_name, names=None, ca_only=True):
"""Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The ... | How would you implement a function in Python 3 that
creates a bundle of public certs for trust distribution. | You are a Python code generator, capable of creating scripts from specifications. |
def trust_from_graph(self, graph):
"""Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict com... | Create a Python 3 function to
create a set of trust bundles from a relationship graph. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048,
alt_names=None, years=5, serial=0, pathlen=0,
overwrite=False):
"""
Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of ... | Implement a function in Python 3 to
create a new CA and return a KeyCertPair object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA,
bits=2048, years=5, alt_names=None, serial=0,
overwrite=False):
"""
Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name ... | Write a Python 3 function that can
create a new key - cert pair and return it | You are a Python code analyst, evaluating scripts for potential improvements. |
5. 2 Subscription Validation | Can you tell what is the following Python 3 function doing
def subscribe(hub, callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data):
"""5.2 Subscription Validation"""
for validate in hub.validators:
error = validate(callback_url, topic_url, lease_seconds, secret,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Registers the celery tasks on the hub object. | Here you have a function in Python 3, explain what it does
def init_celery(self, celery):
count = next(self.counter)
def task_with_hub(f, **opts):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(self, *args, **kwargs)
# Make sure newer ins... | As a python code expert, you are capable of creating scripts from specifications. |
This is a decorator that is used to initialize the available publisher. | How would you explain what the following Python 3 function does
def init_publisher(app):
@app.context_processor
def inject_links():
return {
'websub_self_url': stack.top.websub_self_url,
'websub_hub_url': stack.top.websub_hub_url,
'websub_self_link': stack.top.websub_... | You are a Python code analyst, evaluating scripts for potential improvements. |
This decorator makes it easier to implement a websub publisher. | Here you have a function in Python 3, explain what it does
def publisher(self_url=None, hub_url=None):
def decorator(topic_view):
@functools.wraps(topic_view)
def wrapper(*args, **kwargs):
nonlocal hub_url, self_url
if not self_url:
self_url = request.url
... | You are a Python code generator, capable of creating scripts from specifications. |
def count_results(cube, q):
""" Get the count of records matching the query. """
q = select(columns=[func.count(True)], from_obj=q.alias())
return cube.engine.execute(q).scalar() | Write a Python 3 function for
getting the count of records matching the query. | As a Python code composer, you craft elegant and concise scripts. |
Generate the results for this query. | How would you explain what the following Python 3 function does
def generate_results(cube, q):
if q._limit is not None and q._limit < 1:
return
rp = cube.engine.execute(q)
while True:
row = rp.fetchone()
if row is None:
return
yield dict(row.items()) | You are a Python code architect, reviewing and designing scalable and efficient code |
def apply(self, q, bindings, ordering, distinct=None):
""" Sort on a set of field specifications of the type (ref, direction)
in order of the submitted list. """
info = []
for (ref, direction) in self.parse(ordering):
info.append((ref, direction))
table, column = ... | How would you code a function in Python 3 to
sort on a set of field specifications of the type ref and direction. | As a Python code analyst, you investigate and solve complex coding mysteries |
def copy(self, only=None):
'''
Returns a deep copy with all of the numpy arrays copied
If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied
'''
if only is None:
return Mesh(self)
else:
import copy
m =... | Write a Python 3 function that can
return a deep copy of the object with all of the numpy arrays copied | You are a Python code generator, capable of creating scripts from specifications. |
def concatenate(cls, *args):
"""Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces.
"""
nargs = len(args)
if nargs == 1:
return args[0]
vs = [a.v for a in args if a.v is not None]
vcs = [a.vc for a in ar... | Can you write a function in Python 3 where it
concatenates an arbitrary number of meshes. | You are a Python code architect, reviewing and designing scalable and efficient code |
Quickly Create a new connection object. | Can you tell what is the following Python 3 function doing
def getNewConnection(*args, **kargs):
kargs = dict(kargs)
if len(args) > 0:
if len(args) >= 1:
kargs['host'] = args[0]
if len(args) >= 2:
kargs['user'] = args[1]
if len(args) >= 3:
kargs['passwd'] = args[2]
if len(args) >= 4:
kargs['db'] =... | As a Python code composer, you craft elegant and concise scripts. |
Create a new PySQLQuery Class
| Can you generate a brief explanation for the following Python 3 code
def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs):
if connection is None:
return query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd)
else:
#Updated 7/24/08 to include commitOnEnd here
#-Chandler Pr... | You are a Python code architect, reviewing and designing scalable and efficient code |
def cli(username, repository, path, password, deploy, env, clipboard, env_file):
"""Encrypt passwords and environment variables for use with Travis CI.
Travis Encrypt requires as arguments the user's GitHub username and repository name.
Once the arguments are passed, a password prompt will ask for the pass... | Write a Python 3 function for
encrypting passwords and environment variables for use with Travis CI. Travis Encrypt requires as arguments the user's GitHub username and repository name. Once the arguments are passed, a password prompt will ask for the password that needs to be encrypted. The given password will then be... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def apply(self, q, bindings, fields, distinct=False):
""" Define a set of fields to return for a non-aggregated query. """
info = []
group_by = None
for field in self.parse(fields):
for concept in self.cube.model.match(field):
info.append(concept.ref)
... | Write a Python 3 function for
returning a list of fields that can be used to aggregate the query. | As a Python code analyst, you investigate and solve complex coding mysteries |
def drag(self, NewPt):
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
""" drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
"""
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular t... | Can you create a Python 3 function that
drags - drag the mouse to the new point | As a Python code analyst, you investigate and solve complex coding mysteries |
Computes the volumes of the cells in the mesh. | Here you have a function in Python 3, explain what it does
def create_cell_volumes(self):
self.cell_volumes = numpy.array(
[
abs(
self.node_coords[cell["nodes"]][1]
- self.node_coords[cell["nodes"]][0]
)
for cell... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the control volumes of all nodes in the mesh. | Can you generate a brief explanation for the following Python 3 code
def create_control_volumes(self):
self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float)
for k, cell in enumerate(self.cells):
node_ids = cell["nodes"]
self.control_volumes[node_ids] += 0.5 * sel... | As a python code expert, you are capable of creating scripts from specifications. |
Create a rectangular prism. | Can you generate a brief explanation for the following Python 3 code
def create_rectangular_prism(origin, size):
'''
Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array.
'''
from lace.topology i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a triangular prism from two points. | Explain what the following Python 3 code does
def create_triangular_prism(p1, p2, p3, height):
'''
Return a Mesh which is a triangular prism whose base is the triangle
p1, p2, p3. If the vertices are oriented in a counterclockwise
direction, the prism extends from behind them.
'''
from blmath.g... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Creates a horizontal plane. | Make a summary of the following Python 3 code
def create_horizontal_plane():
'''
Creates a horizontal plane.
'''
v = np.array([
[1., 0., 0.],
[-1., 0., 0.],
[0., 0., 1.],
[0., 0., -1.]
])
f = [[0, 1, 2], [3, 1, 0]]
return Mesh(v=v, f=f) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check if the ref matches one of the concept s aliases. | Can you tell what is the following Python 3 function doing
def match_ref(self, ref):
if ref in self.refs:
self._matched_ref = ref
return True
return False | You are a Python code architect, reviewing and designing scalable and efficient code |
def _physical_column(self, cube, column_name):
""" Return the SQLAlchemy Column object matching a given, possibly
qualified, column name (i.e.: 'table.column'). If no table is named,
the fact table is assumed. """
table_name = self.model.fact_table_name
if '.' in column_name:
... | Write a Python 3 script to
return the SQLAlchemy Table object matching a given possibly - named column name. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def bind(self, cube):
""" Map a model reference to an physical column in the database. """
table, column = self._physical_column(cube, self.column_name)
column = column.label(self.matched_ref)
column.quote = True
return table, column | Create a Python 3 function to
map a model reference to a physical column in the database. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_new_source(self, source_token, stripe_js_response=None):
"""Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be u... | How would you code a function in Python 3 to
add a new source token to the customer. | You are a Python code architect, reviewing and designing scalable and efficient code |
Update the object with data from stripe. Coupon without calling StripeCoupon. retrieve. | Make a summary of the following Python 3 code
def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])
update_data = {key: stripe_coupon[key] for key in fields_to_update}
for field in ["created", "redeem... | As a python code expert, you are capable of creating scripts from specifications. |
Save the coupon to Stripe. | Here you have a function in Python 3, explain what it does
def save(self, force_retrieve=False, *args, **kwargs):
stripe.api_key = stripe_settings.API_KEY
if self._previous_is_deleted != self.is_deleted and self.is_deleted:
try:
stripe_coupon = stripe.Coupon.retrieve(self.cou... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the signed volume of a simplex in nD. | Can you tell what is the following Python 3 function doing
def get_signed_simplex_volumes(cells, pts):
n = pts.shape[1]
assert cells.shape[1] == n + 1
p = pts[cells]
p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1)
return numpy.linalg.det(p) / math.factorial(n) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def grp_start_len(a):
"""Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this
routine returns the indices where the blocks of equal integers start and
how long the blocks are.
"""
# https://stackoverflow.com/a/50394587/353337
m = numpy.concatenate([[True], a[:-1] != a[1:], [Tru... | Implement a function in Python 3 to
give a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this routine returns the indices where the blocks of equal integers start and how long the blocks are. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej):
"""Computes the circumcenters of all given triangles.
"""
# The input argument are the dot products
#
# <e1, e2>
# <e2, e0>
# <e0, e1>
#
# of the edges
#
# e0: x1->x2,
# e1: x2->x0,
# e2: x0->x1.... | How would you implement a function in Python 3 that
computes the circumcenters of all given triangles. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_edge_mask(self, subdomain=None):
"""Get faces which are fully in subdomain.
"""
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
... | Can you create a Python 3 function that
gets edge mask of the faces which are fully in subdomain. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get faces which are fully in subdomain. | Explain what the following Python 3 code does
def get_face_mask(self, subdomain):
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _mark_vertices(self, subdomain):
"""Mark faces/edges which are fully in subdomain.
"""
if subdomain is None:
is_inside = numpy.ones(len(self.node_coords), dtype=bool)
else:
is_inside = subdomain.is_inside(self.node_coords.T).T
if subdomain.is_boun... | How would you implement a function in Python 3 that
marks faces and edges which are fully in subdomain. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
"""Dump a yaml configuration as an OrderedDict."""
class OrderedDumper(Dumper):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())
Or... | How would you implement a function in Python 3 that
dumps a yaml configuration as an OrderedDict. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _check_type(self, ref, value):
"""
Checks whether the type of the cut value matches the type of the
concept being cut, and raises a QueryException if it doesn't match
"""
if isinstance(value, list):
return [self._check_type(ref, val) for val in value]
mod... | Implement a function in Python 3 to
check whether the type of the cut value matches the type of the resource in the Cube model. | You are a Python code generator, capable of creating scripts from specifications. |
def _api_type(self, value):
"""
Returns the API type of the given value based on its python type.
"""
if isinstance(value, six.string_types):
return 'string'
elif isinstance(value, six.integer_types):
return 'integer'
elif type(value) is datetime.... | Create a Python 3 function for
returning the API type of the given value based on its python type. | You are a Python code architect, reviewing and designing scalable and efficient code |
Apply a set of filters to a query. | Can you generate a brief explanation for the following Python 3 code
def apply(self, q, bindings, cuts):
info = []
for (ref, operator, value) in self.parse(cuts):
if map_is_class and isinstance(value, map):
value = list(value)
self._check_type(ref, value)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Given an array of size NxM we accept color in the following ways. | Can you generate a brief explanation for the following Python 3 code
def colors_like(color, arr, colormap=DEFAULT_COLORMAP):
'''
Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rg... | You are a Python code analyst, evaluating scripts for potential improvements. |
Color each vertex by its height above the floor point. | Here you have a function in Python 3, explain what it does
def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument
'''
Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
thre... | As a Python code composer, you craft elegant and concise scripts. |
Color the data as a heatmap. | Explain what the following Python 3 code does
def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP):
'''
Truncate weights to the range [0, max_weight] and rescale, as you would
want for a heatmap with known scale.
'''
import numpy as np
adjusted_weig... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert quad faces to triangular faces. | Here you have a function in Python 3, explain what it does
def quads_to_tris(quads):
'''
Convert quad faces to triangular faces.
quads: An nx4 array.
Return a 2nx3 array.
'''
import numpy as np
tris = np.empty((2 * len(quads), 3))
tris[0::2, :] = quads[:, [0, 1, 2]]
tris[1::2, :] ... | You are a Python code generator, capable of creating scripts from specifications. |
def all_faces_with_verts(self, v_indices, as_boolean=False):
'''
returns all of the faces that contain at least one of the vertices in v_indices
'''
import numpy as np
included_vertices = np.zeros(self.v.shape[0], dtype=bool)
included_vertices[np.array(v_indices, dtype=np... | Implement a Python 3 function for
returning all of the faces that contain at least one of the vertices in v_indices. | You are a Python code analyst, evaluating scripts for potential improvements. |
def vertex_indices_in_segments(self, segments, ret_face_indices=False):
'''
Given a list of segment names, return an array of vertex indices for
all the vertices in those faces.
Args:
segments: a list of segment names,
ret_face_indices: if it is `True`, returns f... | Can you implement a function in Python 3 that
gives a list of segment names return an array of vertex indices for all the vertices in those faces. | You are a Python code analyst, evaluating scripts for potential improvements. |
def keep_segments(self, segments_to_keep, preserve_segmentation=True):
'''
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
'''
v_ind, f_ind = self.vertex_indices_in_segments(segments_to_k... | Write a Python 3 function that can
keep the faces and vertices for given segments discarding all others. | As a Python code analyst, you investigate and solve complex coding mysteries |
def remove_segments(self, segments_to_remove):
''' Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed
'''
v_ind = self.vertex_indices_in_segments(segments_to_remove)
self.... | Can you write a function in Python 3 where it
removes the faces and vertices for given segments keeping all others. | As a Python code composer, you craft elegant and concise scripts. |
returns array of all vertex indices common to each segment in segments | Given the following Python 3 function, write the documentation
def verts_in_common(self, segments):
verts_by_segm = self.verts_by_segm
return sorted(reduce(lambda s0, s1: s0.intersection(s1),
[set(verts_by_segm[segm]) for segm in segments])) | You are a Python code analyst, evaluating scripts for potential improvements. |
def downsampled_mesh(self, step):
"""Returns a downsampled copy of this mesh.
Args:
step: the step size for the sampling
Returns:
a new, downsampled Mesh object.
Raises:
ValueError if this Mesh has faces.
"""
from lace.mesh import Me... | Write a Python 3 script for
returning a downsampled copy of this mesh. | As a Python code analyst, you investigate and solve complex coding mysteries |
def keep_vertices(self, indices_to_keep, ret_kept_faces=False):
'''
Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining.
... | Write a Python 3 function for
keeping the given vertices and discard the others and any faces to which they may belong. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a copy of a mesh with line vertices and edges added. | Here you have a function in Python 3, explain what it does
def create_from_mesh_and_lines(cls, mesh, lines):
'''
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
'''
mesh_with_lines = mesh.copy()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_lines(self, lines):
'''
Add line vertices and edges to the mesh.
lines: A list of Polyline or Lines objects.
'''
import numpy as np
if not lines:
return
v_lines = np.vstack([l.v for l in lines])
v_index_offset = np.cumsum([0] + [len(... | Write a Python 3 script for
adding line vertices and edges to the mesh. | As a Python code composer, you craft elegant and concise scripts. |
def vert_connectivity(self):
"""Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15, 12), that means vertex 15 is connected
by an edge to vertex 12."""
import nu... | Create a Python 3 function to
return a sparse matrix where each nonzero entry is connected to vertex 12. | You are a Python code analyst, evaluating scripts for potential improvements. |
def vert_opposites_per_edge(self):
"""Returns a dictionary from vertidx-pairs to opposites.
For example, a key consist of [4, 5)] meaning the edge between
vertices 4 and 5, and a value might be [10, 11] which are the indices
of the vertices opposing this edge."""
result = {}
... | Write a Python 3 function that can
return a dictionary from vertidx - pairs to opposites. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns an Ex2 array of adjacencies between faces where each element in the array is a face index and each element in the array is a face index. Edges that are not shared by 2 faces are not included. | Make a summary of the following Python 3 code
def faces_per_edge(self):
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import col
IS = np.repeat(np.arange(len(self.f)), 3)
JS = self.f.ravel()
data = np.ones(IS.size)
f2v = sp.csc_matrix((d... | As a python code expert, you are capable of creating scripts from specifications. |
Returns an Ex2 array of adjacencies between vertices where
each element in the array is a vertex index. Each element in the array is a vertex index. Edges that are not shared by 2 faces are not included. | Make a summary of the following Python 3 code
def vertices_per_edge(self):
import numpy as np
return np.asarray([vertices_in_common(e[0], e[1]) for e in self.f[self.faces_per_edge]]) | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_vertices_to_edges_matrix(self, want_xyz=True):
"""Returns a matrix M, which if multiplied by vertices,
gives back edges (so "e = M.dot(v)"). Note that this generates
one edge per edge, *not* two edges per triangle.
Args:
want_xyz: if true, takes and returns xyz coord... | Write a Python 3 script to
return a matrix M which if multiplied by vertices gives back edges. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def remove_redundant_verts(self, eps=1e-10):
"""Given verts and faces, this remove colocated vertices"""
import numpy as np
from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module
fshape = self.f.shape
tree = cKDTree(self.v)
close_pairs = list(tree.que... | Can you write a function in Python 3 where it
gives verts and faces this remove colocated vertices | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the cardinality class of the resource. | Given the following Python 3 function, write the documentation
def cardinality_class(self):
if self.cardinality:
if self.cardinality > 1000:
return 'high'
if self.cardinality > 50:
return 'medium'
if self.cardinality > 7:
return... | As a python code expert, you are capable of creating scripts from specifications. |
def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name
'''
write_mtl: When True and mesh has a texture, includes a mtllib
reference in the .obj and writes a .mtl alongside.
'''
import os
import numpy as np... | Can you implement a function in Python 3 that
dumps a Baiji object to a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def signed_cell_areas(self):
"""Signed area of a triangle in 2D.
"""
# http://mathworld.wolfram.com/TriangleArea.html
assert (
self.node_coords.shape[1] == 2
), "Signed areas only make sense for triangles in 2D."
if self._signed_cell_areas is None:
... | How would you code a function in Python 3 to
return the signed area of a triangle in 2D. | As a python code expert, you are capable of creating scripts from specifications. |
def create_edges(self):
"""Set up edge-node and edge-cell relations.
"""
# Reshape into individual edges.
# Sort the columns to make it possible for `unique()` to identify
# individual edges.
s = self.idx_hierarchy.shape
a = numpy.sort(self.idx_hierarchy.reshape(s... | How would you implement a function in Python 3 that
creates edge - node and edge - cell relations. | You are a Python code generator, capable of creating scripts from specifications. |
def _compute_integral_x(self):
"""Computes the integral of x,
\\int_V x,
over all atomic "triangles", i.e., areas cornered by a node, an edge
midpoint, and a circumcenter.
"""
# The integral of any linear function over a triangle is the average of
# the values... | Implement a Python 3 function for
computing the integral of x over all atomic "triangles i. e. areas cornered by a node edge midpoint and a circumcenter. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the surface areas of all the nodes in the cell. | Can you tell what is the following Python 3 function doing
def _compute_surface_areas(self, cell_ids):
# Each of the three edges may contribute to the surface areas of all
# three vertices. Here, only the two adjacent nodes receive a
# contribution, but other approaches (e.g., the flat cell corr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Compute the curl of a vector field over the mesh. | Given the following Python 3 function, write the documentation
def compute_curl(self, vector_field):
# Compute the projection of A on the edge at each edge midpoint.
# Take the average of `vector_field` at the endpoints to get the
# approximate value at the edge midpoint.
A = 0.5 * numpy... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Plot the species in the 3D mesh. | Can you generate the documentation for the following Python 3 function
def plot(
self,
show_coedges=True,
show_centroids=True,
mesh_color="k",
nondelaunay_edge_color="#d62728", # mpl 2.0 default red
boundary_edge_color=None,
comesh_color=(0.8, 0.8, 0.8),
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def show_vertex(self, node_id, show_ce_ratio=True):
"""Plot the vicinity of a node and its ce_ratio.
:param node_id: Node ID of the node to be shown.
:type node_id: int
:param show_ce_ratio: If true, shows the ce_ratio of the node, too.
:type show_ce_ratio: bool, optional
... | Write a Python 3 script to
plot the vicinity of a node and its ce_ratio. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Updates all sorts of cell information for the given cell IDs. | Given the following Python 3 function, write the documentation
def _update_cell_values(self, cell_ids, interior_edge_ids):
# update idx_hierarchy
nds = self.cells["nodes"][cell_ids].T
self.idx_hierarchy[..., cell_ids] = nds[self.local_idx]
# update self.half_edge_coords
self.hal... | As a python code expert, you are capable of creating scripts from specifications. |
def _dump(f, mesh):
'''
Writes a mesh to collada file format.
'''
dae = mesh_to_collada(mesh)
dae.write(f.name) | Write a Python 3 script to
write a mesh to collada file format. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates a UTF - 8 XML string containing the mesh in collada format. | Can you generate the documentation for the following Python 3 function
def dumps(mesh):
'''
Generates a UTF-8 XML string containing the mesh, in collada format.
'''
from lxml import etree
dae = mesh_to_collada(mesh)
# Update the xmlnode.
dae.save()
return etree.tostring(dae.xmlnode, e... | As a python code expert, you are capable of creating scripts from specifications. |
def mesh_to_collada(mesh):
'''
Supports per-vertex color, but nothing else.
'''
import numpy as np
try:
from collada import Collada, scene
except ImportError:
raise ImportError("lace.serialization.dae.mesh_to_collade requires package pycollada.")
def create_material(dae):
... | Create a Python 3 function for
converting a mesh to a collada object. | As a python code expert, you are capable of creating scripts from specifications. |
Convert the mesh from one set of units to another. | Explain what the following Python 3 code does
def convert_units(self, from_units, to_units):
'''
Convert the mesh from one set of units to another.
These calls are equivalent:
- mesh.convert_units(from_units='cm', to_units='m')
- mesh.scale(.01)
'''
from blmath... | You are a Python code analyst, evaluating scripts for potential improvements. |
def predict_body_units(self):
'''
There is no prediction for united states unit system.
This may fail when a mesh is not axis-aligned
'''
longest_dist = np.max(np.max(self.v, axis=0) - np.min(self.v, axis=0))
if round(longest_dist / 1000) > 0:
return 'mm'
... | How would you implement a function in Python 3 that
predicts the unit system of the united states in the body. | You are a Python code architect, reviewing and designing scalable and efficient code |
Reorient the mesh by specifying two vectors. | Given the following Python 3 function, write the documentation
def reorient(self, up, look):
'''
Reorient the mesh by specifying two vectors.
up: The foot-to-head direction.
look: The direction the body is facing.
In the result, the up will end up along +y, and look along +z
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.