output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns if this object is peregrine.
Given the following Python 3 function, write the documentation def isPeregrine(self): return isPeregrine(self.obj.id, self.obj.sign, self.obj.signlon)
You are a Python code architect, reviewing and designing scalable and efficient code
def nextSolarReturn(chart, date): """ Returns the solar return of a Chart after a specific date. """ sun = chart.getObject(const.SUN) srDate = ephem.nextSolarReturn(date, sun.lon) return _computeChart(chart, srDate)
Write a Python 3 function that can return the solar return of a Chart after a specific date.
As a Python code composer, you craft elegant and concise scripts.
Creates the planetary hour table for a date and position.
Can you generate a brief explanation for the following Python 3 code def hourTable(date, pos): lastSunrise = ephem.lastSunrise(date, pos) middleSunset = ephem.nextSunset(lastSunrise, pos) nextSunrise = ephem.nextSunrise(date, pos) table = [] # Create diurnal hour sequence length = (mid...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns an HourTable object for the given date and position.
Can you generate the documentation for the following Python 3 function def getHourTable(date, pos): table = hourTable(date, pos) return HourTable(table, date)
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the index of a date in the table.
Given the following Python 3 function, write the documentation def index(self, date): for (i, (start, end, ruler)) in enumerate(self.table): if start <= date.jd <= end: return i return None
You are a Python code architect, reviewing and designing scalable and efficient code
Returns information about a specific planetary time.
Given the following Python 3 function, write the documentation def indexInfo(self, index): entry = self.table[index] info = { # Default is diurnal 'mode': 'Day', 'ruler': self.dayRuler(), 'dayRuler': self.dayRuler(), 'nightRuler': self.nightRul...
You are a Python code generator, capable of creating scripts from specifications.
def compute(chart, date, fixedObjects=False): """ Returns a profection chart for a given date. Receives argument 'fixedObjects' to fix chart objects in their natal locations. """ sun = chart.getObject(const.SUN) prevSr = ephem.prevSolarReturn(date, sun.lon) nextSr = ephem.nextSolar...
Implement a Python 3 function for computing a profection chart for a given date.
As a Python code analyst, you investigate and solve complex coding mysteries
def _merge(listA, listB): """ Merges two list of objects removing repetitions. """ listA = [x.id for x in listA] listB = [x.id for x in listB] listA.extend(listB) set_ = set(listA) return list(set_)
How would you implement a function in Python 3 that merges two list of objects removing repetitions.
As a Python code translator, you convert algorithms and pseudocode into Python.
def compute(chart): """ Computes the behavior. """ factors = [] # Planets in House1 or Conjunct Asc house1 = chart.getHouse(const.HOUSE1) planetsHouse1 = chart.objects.getObjectsInHouse(house1) asc = chart.getAngle(const.ASC) planetsConjAsc = chart.objects.getObjectsAspecting(asc, ...
Implement a Python 3 function for computing the behavior of the current object.
As a python code expert, you are capable of creating scripts from specifications.
Returns a list with the absolute longitude of all terms.
Explain what the following Python 3 code does def termLons(TERMS): res = [] for i, sign in enumerate(SIGN_LIST): termList = TERMS[sign] res.extend([ ID, sign, start + 30 * i, ] for (ID, start, end) in termList) return res
As a Python code translator, you convert algorithms and pseudocode into Python.
def compute(chart): """ Computes the Almutem table. """ almutems = {} # Hylegic points hylegic = [ chart.getObject(const.SUN), chart.getObject(const.MOON), chart.getAngle(const.ASC), chart.getObject(const.PARS_FORTUNA), chart.getObject(const.SYZYGY) ] ...
How would you implement a function in Python 3 that computes the Almutem table.
You are a Python code analyst, evaluating scripts for potential improvements.
def get(self, resource_id=None, resource_action=None, resource_cls=None, single_resource=False): """ Gets the details for one or more resources by ID Args: cls - gophish.models.Model - The resource class resource_id - str - The end...
Create a Python 3 function for getting the details for one or more resources by ID.
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates a new instance of the resource.
Given the following Python 3 function, write the documentation def post(self, resource): response = self.api.execute( "POST", self.endpoint, json=(resource.as_dict())) if not response.ok: raise Error.parse(response.json()) return self._cls.parse(response.json())
As a Python code analyst, you investigate and solve complex coding mysteries
def put(self, resource): """ Edits an existing resource Args: resource - gophish.models.Model - The resource instance """ endpoint = self.endpoint if resource.id: endpoint = self._build_url(endpoint, resource.id) response = self.api.execute("PU...
Implement a function in Python 3 to edit an existing resource instance
You are a Python code architect, reviewing and designing scalable and efficient code
Deletes an existing resource in the cluster.
Given the following Python 3 function, write the documentation def delete(self, resource_id): endpoint = '{}/{}'.format(self.endpoint, resource_id) response = self.api.execute("DELETE", endpoint) if not response.ok: raise Error.parse(response.json()) return self._cls.pars...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a dict representation of the resource.
Explain what the following Python 3 code does def as_dict(self): result = {} for key in self._valid_properties: val = getattr(self, key) if isinstance(val, datetime): val = val.isoformat() # Parse custom classes elif val and not Model._is_b...
As a python code expert, you are capable of creating scripts from specifications.
Executes a request to a given endpoint returning the response
Can you generate a brief explanation for the following Python 3 code def execute(self, method, path, **kwargs): url = "{}{}".format(self.host, path) kwargs.update(self._client_kwargs) response = requests.request( method, url, headers={"Authorization": "Bearer...
You are a Python code analyst, evaluating scripts for potential improvements.
Complete an existing campaign
How would you explain what the following Python 3 function does def complete(self, campaign_id): return super(API, self).get( resource_id=campaign_id, resource_action='complete')
As a Python code composer, you craft elegant and concise scripts.
Returns the summary of the current user s infrastructure.
Given the following Python 3 function, write the documentation def summary(self, campaign_id=None): resource_cls = CampaignSummary single_resource = False if not campaign_id: resource_cls = CampaignSummaries single_resource = True return super(API, self).get( ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns just the results for a given campaign
How would you explain what the following Python 3 function does def results(self, campaign_id): return super(API, self).get( resource_id=campaign_id, resource_action='results', resource_cls=CampaignResults)
You are a Python code generator, capable of creating scripts from specifications.
Set the path of the database.
Can you tell what is the following Python 3 function doing def set_path(self, file_path): if not file_path: self.read_data = self.memory_read self.write_data = self.memory_write elif not is_valid(file_path): self.write_data(file_path, {}) self.path = file_pat...
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes the specified key from the database.
How would you explain what the following Python 3 function does def delete(self, key): obj = self._get_content() obj.pop(key, None) self.write_data(self.path, obj)
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the content of the entry in the database.
How would you explain what the following Python 3 function does def data(self, **kwargs): key = kwargs.pop('key', None) value = kwargs.pop('value', None) dictionary = kwargs.pop('dictionary', None) # Fail if a key and a dictionary or a value and a dictionary are given if (key i...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of objects based on a dictionary of filter parameters.
Can you generate a brief explanation for the following Python 3 code def filter(self, filter_arguments): results = self._get_content() # Filter based on a dictionary of search parameters if isinstance(filter_arguments, dict): for item, content in iteritems(self._get_content()): ...
You are a Python code architect, reviewing and designing scalable and efficient code
def drop(self): """ Remove the database by deleting the JSON file. """ import os if self.path: if os.path.exists(self.path): os.remove(self.path) else: # Clear the in-memory data if there is no file path self._data = {}
Create a Python 3 function for dropping the database by deleting the JSON file.
You are a Python code architect, reviewing and designing scalable and efficient code
Reads a file and returns a json encoded representation of the file.
Make a summary of the following Python 3 code def read_data(file_path): if not is_valid(file_path): write_data(file_path, {}) db = open_file_for_reading(file_path) content = db.read() obj = decode(content) db.close() return obj
As a Python code analyst, you investigate and solve complex coding mysteries
Writes a dictionary to a file and returns the updated file content.
Explain what the following Python 3 code does def write_data(path, obj): with open_file_for_writing(path) as db: db.write(encode(obj)) return obj
As a Python code translator, you convert algorithms and pseudocode into Python.
def is_valid(file_path): """ Check to see if a file exists or is empty. """ from os import path, stat can_open = False try: with open(file_path) as fp: can_open = True except IOError: return False is_file = path.isfile(file_path) return path.exists(fil...
Write a Python 3 script for checking to see if a file exists or is empty.
You are a Python code generator, capable of creating scripts from specifications.
Refines a mesh by inserting nodes at all edge midpoints and make four triangular elements where there was one.
Given the following Python 3 function, write the documentation def _refine(node_coords, cells_nodes, edge_nodes, cells_edges): num_nodes = len(node_coords) num_new_nodes = len(edge_nodes) # new_nodes = numpy.empty(num_new_nodes, dtype=numpy.dtype((float, 2))) node_coords.resize(num_nodes + num_new_node...
As a Python code translator, you convert algorithms and pseudocode into Python.
Create edge - node and edge - cell relations. Adapted from voropy.
How would you explain what the following Python 3 function does def create_edges(cells_nodes): # Create the idx_hierarchy (nodes->edges->cells), i.e., the value of # `self.idx_hierarchy[0, 2, 27]` is the index of the node of cell 27, edge # 2, node 0. The shape of `self.idx_hierarchy` is `(2, 3, n)`, where ...
As a Python code composer, you craft elegant and concise scripts.
Plot a 2D mesh using matplotlib.
Given the following Python 3 function, write the documentation def plot2d(points, cells, mesh_color="k", show_axes=False): import matplotlib.pyplot as plt from matplotlib.collections import LineCollection fig = plt.figure() ax = fig.gca() plt.axis("equal") if not show_axes: ax.set_axis_...
As a Python code translator, you convert algorithms and pseudocode into Python.
def put(self, job, result): "Perform a job by a member in the pool and return the result." self.job.put(job) r = result.get() return r
Can you create a Python 3 function that performs a job by a member in the pool and return the result.
You are a Python code architect, reviewing and designing scalable and efficient code
def contract(self, jobs, result): """ Perform a contract on a number of jobs and block until a result is retrieved for each job. """ for j in jobs: WorkerPool.put(self, j) r = [] for i in xrange(len(jobs)): r.append(result.get()) ...
Implement a function in Python 3 to perform a contract on a number of jobs and block until a result is retrieved for each job.
You are a Python code analyst, evaluating scripts for potential improvements.
Canonical tetrahedrization of the cube.
Make a summary of the following Python 3 code def cube( xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, zmin=0.0, zmax=1.0, nx=11, ny=11, nz=11 ): """Canonical tetrahedrization of the cube. Input: Edge lenghts of the cube Number of nodes along the edges. """ # Generate suitable ranges for parametriz...
As a Python code composer, you craft elegant and concise scripts.
def grow(self): "Add another worker to the pool." t = self.worker_factory(self) t.start() self._size += 1
How would you code a function in Python 3 to add another worker to the pool.
As a Python code analyst, you investigate and solve complex coding mysteries
Get rid of one worker from the pool. Raises IndexError if empty.
Can you generate the documentation for the following Python 3 function def shrink(self): "Get rid of one worker from the pool. Raises IndexError if empty." if self._size <= 0: raise IndexError("pool is already empty") self._size -= 1 self.put(SuicideJob())
As a Python code composer, you craft elegant and concise scripts.
def map(self, fn, *seq): "Perform a map operation distributed among the workers. Will " "block until done." results = Queue() args = zip(*seq) for seq in args: j = SimpleJob(results, fn, seq) self.put(j) # Aggregate results r = [] ...
Write a Python 3 script for performing a map operation distributed among the workers. Will " "block until done.
You are a Python code generator, capable of creating scripts from specifications.
def moebius( num_twists=1, # How many twists are there in the 'paper'? nl=60, # Number of nodes along the length of the strip nw=11, # Number of nodes along the width of the strip (>= 2) mode="classical", ): """Creates a simplistic triangular mesh on a slightly Möbius strip. The Möbius strip ...
How would you implement a function in Python 3 that returns a Möbius strip as a simplistic triangular mesh.
You are a Python code analyst, evaluating scripts for potential improvements.
Get jobs from the queue and perform them as they arrive.
Make a summary of the following Python 3 code def run(self): "Get jobs from the queue and perform them as they arrive." while 1: # Sleep until there is a job to perform. job = self.jobs.get() # Yawn. Time to get some work done. try: job.ru...
As a python code expert, you are capable of creating scripts from specifications.
def display(contents, domain=DEFAULT_DOMAIN, force_gist=False): """ Open a web browser pointing to geojson.io with the specified content. If the content is large, an anonymous gist will be created on github and the URL will instruct geojson.io to download the gist data and then display. If the cont...
Write a Python 3 script for displaying a single object in a web browser pointing to geojson. io with the specified content.
As a Python code translator, you convert algorithms and pseudocode into Python.
def embed(contents='', width='100%', height=512, *args, **kwargs): """ Embed geojson.io in an iframe in Jupyter/IPython notebook. Parameters ---------- contents - see make_url() width - string, default '100%' - width of the iframe height - string / int, default 512 - height of the iframe ...
Write a Python 3 function that can embed geojson. io in an iframe in Jupyter notebook.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the URL to open given the domain and contents.
Given the following Python 3 function, write the documentation def make_url(contents, domain=DEFAULT_DOMAIN, force_gist=False, size_for_gist=MAX_URL_LEN): """ Returns the URL to open given the domain and contents. If the file contents are large, an anonymous gist will be created. Paramete...
You are a Python code analyst, evaluating scripts for potential improvements.
def make_geojson(contents): """ Return a GeoJSON string from a variety of inputs. See the documentation for make_url for the possible contents input. Returns ------- GeoJSON string """ if isinstance(contents, six.string_types): return contents if hasattr(contents, '__g...
Write a Python 3 function that can return a GeoJSON string from a variety of inputs.
As a python code expert, you are capable of creating scripts from specifications.
def data_url(contents, domain=DEFAULT_DOMAIN): """ Return the URL for embedding the GeoJSON data in the URL hash Parameters ---------- contents - string of GeoJSON domain - string, default http://geojson.io """ url = (domain + '#data=data:application/json,' + urllib.parse.qu...
Implement a function in Python 3 to return the URL for embedding the GeoJSON data in the URL hash
As a Python code translator, you convert algorithms and pseudocode into Python.
Create and return an anonymous gist with a single file and specified contents
Here you have a function in Python 3, explain what it does def _make_gist(contents, description='', filename='data.geojson'): ghapi = github3.GitHub() files = {filename: {'content': contents}} gist = ghapi.create_gist(description, files) return gist
As a Python code translator, you convert algorithms and pseudocode into Python.
Clenshaw s algorithm for evaluating the kth orthogonal polynomial defined by the recurrence coefficients alpha and beta.
Can you generate the documentation for the following Python 3 function def clenshaw(a, alpha, beta, t): n = len(alpha) assert len(beta) == n assert len(a) == n + 1 try: b = numpy.empty((n + 1,) + t.shape) except AttributeError: # 'float' object has no attribute 'shape' b = numpy.em...
You are a Python code analyst, evaluating scripts for potential improvements.
Recurrence coefficients for generalized Laguerre polynomials. Set alpha=0 (default) to get classical Laguerre.
Here you have a function in Python 3, explain what it does def tree(X, n, alpha=0, symbolic=False): args = recurrence_coefficients(n, alpha=alpha, symbolic=symbolic) return line_tree(X, *args)
As a Python code composer, you craft elegant and concise scripts.
def recurrence_coefficients(n, alpha, standardization="normal", symbolic=False): """Recurrence coefficients for generalized Laguerre polynomials. vals_k = vals_{k-1} * (t*a_k - b_k) - vals{k-2} * c_k """ S = sympy.S if symbolic else lambda x: x sqrt = sympy.sqrt if symbolic else numpy.sqrt ...
How would you code a function in Python 3 to return the recurrence coefficients for generalized Laguerre polynomials.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate the recurrence coefficients a_k b_k c_k for the Jacobi polynomials which are orthogonal on [ 1 - 1 ).
Can you generate the documentation for the following Python 3 function def jacobi(n, alpha, beta, standardization, symbolic=False): gamma = sympy.gamma if symbolic else lambda x: scipy.special.gamma(float(x)) def rational(x, y): # <https://github.com/sympy/sympy/pull/13670> return ( ...
As a Python code analyst, you investigate and solve complex coding mysteries
Plot function over a disk.
Can you generate the documentation for the following Python 3 function def plot(f, lcar=1.0e-1): import matplotlib import matplotlib.pyplot as plt import pygmsh geom = pygmsh.built_in.Geometry() geom.add_circle([0.0, 0.0, 0.0], 1.0, lcar, num_sections=4, compound=True) points, cells, _, _, _ = ...
As a python code expert, you are capable of creating scripts from specifications.
def tree(X, n, symbolic=False): """Evaluates the entire tree of orthogonal polynomials for the n-cube The computation is organized such that tree returns a list of arrays, L={0, ..., dim}, where each level corresponds to the polynomial degree L. Further, each level is organized like a discrete (dim-1)-...
Write a Python 3 function that can evaluate the entire tree of orthogonal polynomials for the n - cube X.
As a Python code analyst, you investigate and solve complex coding mysteries
Evaluate the orthogonal polynomial defined by its recurrence coefficients a b and c at the point s.
How would you explain what the following Python 3 function does def line_evaluate(t, p0, a, b, c): vals1 = numpy.zeros_like(t, dtype=int) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_like(t) * p0 for a_k, b_k, c_k in zip(a, b, c): va...
As a Python code analyst, you investigate and solve complex coding mysteries
Plot function over a triangle.
Make a summary of the following Python 3 code def plot(corners, f, n=100): import matplotlib.tri import matplotlib.pyplot as plt # discretization points def partition(boxes, balls): # <https://stackoverflow.com/a/36748940/353337> def rec(boxes, balls, parent=tuple()): if box...
As a Python code composer, you craft elegant and concise scripts.
Case - insensitive search for key within keys of lookup_dict.
Here you have a function in Python 3, explain what it does def _iget(key, lookup_dict): for k, v in lookup_dict.items(): if k.lower() == key.lower(): return v return None
You are a Python code analyst, evaluating scripts for potential improvements.
Try to lookup a Language object by name e. g. English in internal language list.
Here you have a function in Python 3, explain what it does def getlang_by_name(name): direct_match = _iget(name, _LANGUAGE_NAME_LOOKUP) if direct_match: return direct_match else: simple_name = name.split(',')[0] # take part before comma simple_name = simple_name.split...
You are a Python code architect, reviewing and designing scalable and efficient code
Try to lookup a Language object by native name e. g. English in internal language list.
Explain what the following Python 3 code does def getlang_by_native_name(native_name): direct_match = _iget(native_name, _LANGUAGE_NATIVE_NAME_LOOKUP) if direct_match: return direct_match else: simple_native_name = native_name.split(',')[0] # take part before comma si...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a Language object for the language code code.
Explain what the following Python 3 code does def getlang_by_alpha2(code): # Handle special cases for language codes returned by YouTube API if code == 'iw': # handle old Hebrew code 'iw' and return modern code 'he' return getlang('he') elif 'zh-Hans' in code: return getlang('zh-CN') # u...
As a Python code composer, you craft elegant and concise scripts.
Write a function f defined in terms of spherical coordinates to a file.
Given the following Python 3 function, write the documentation def write(filename, f): import meshio import meshzoo points, cells = meshzoo.iso_sphere(5) # get spherical coordinates from points polar = numpy.arccos(points[:, 2]) azimuthal = numpy.arctan2(points[:, 1], points[:, 0]) vals = f...
You are a Python code architect, reviewing and designing scalable and efficient code
def tree_sph(polar, azimuthal, n, standardization, symbolic=False): """Evaluate all spherical harmonics of degree at most `n` at angles `polar`, `azimuthal`. """ cos = numpy.vectorize(sympy.cos) if symbolic else numpy.cos # Conventions from # <https://en.wikipedia.org/wiki/Spherical_harmonics#O...
Can you write a function in Python 3 where it evaluates all spherical harmonics of degree at most n at angles polar and azimuthal.
As a python code expert, you are capable of creating scripts from specifications.
Evaluates the entire tree of associated Legendre polynomials up to depth n.
Can you generate the documentation for the following Python 3 function def tree_alp( x, n, standardization, phi=None, with_condon_shortley_phase=True, symbolic=False ): """Evaluates the entire tree of associated Legendre polynomials up to depth n. There are many recurrence relations that can be used to ...
As a python code expert, you are capable of creating scripts from specifications.
Evaluates the entire tree of orthogonal polynomials on the unit disk.
Can you tell what is the following Python 3 function doing def tree(X, n, symbolic=False): frac = sympy.Rational if symbolic else lambda x, y: x / y sqrt = sympy.sqrt if symbolic else numpy.sqrt pi = sympy.pi if symbolic else numpy.pi mu = frac(1, 2) p0 = 1 / sqrt(pi) def alpha(n): re...
You are a Python code generator, capable of creating scripts from specifications.
def tree(bary, n, standardization, symbolic=False): """Evaluates the entire tree of orthogonal triangle polynomials. The return value is a list of arrays, where `out[k]` hosts the `2*k+1` values of the `k`th level of the tree (0, 0) (0, 1) (1, 1) (0, 2) (1, 2) (2, 2) ...
Write a Python 3 script to evaluate the entire tree of orthogonal triangle polynomials.
You are a Python code analyst, evaluating scripts for potential improvements.
Check if the given filename actually exists and if it s a directory and if it s not a file
Can you generate the documentation for the following Python 3 function def check_if_this_file_exist(filename): #get the absolute path filename = os.path.abspath(filename) #Boolean this_file_exist = os.path.exists(filename) a_directory = os.path.isdir(filename) result = this_file_exist and not ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def command_line(cmd): """Handle the command line call keyword arguments: cmd = a list return 0 if error or a string for the command line output """ try: s = subprocess.Popen(cmd, stdout=subprocess.PIPE) s = s.stdout.read() return s.strip() except subproce...
How would you implement a function in Python 3 that handles the command line call keyword arguments return 0 if error or a string for the command line output
As a python code expert, you are capable of creating scripts from specifications.
def information(filename): """Returns the file exif""" check_if_this_file_exist(filename) filename = os.path.abspath(filename) result = get_json(filename) result = result[0] return result
How would you implement a function in Python 3 that returns the exif of a file
You are a Python code analyst, evaluating scripts for potential improvements.
def get_json(filename): """ Return a json value of the exif Get a filename and return a JSON object Arguments: filename {string} -- your filename Returns: [JSON] -- Return a JSON object """ check_if_this_file_exist(filename) #Process this function filename = os.path.a...
Implement a function in Python 3 to return a json value of the exif
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a csv representation of the exif get a filename and returns a unicode string with a csv format
Can you generate the documentation for the following Python 3 function def get_csv(filename): check_if_this_file_exist(filename) #Process this function filename = os.path.abspath(filename) s = command_line(['exiftool', '-G', '-csv', '-sort', filename]) if s: #convert bytes to string ...
As a Python code analyst, you investigate and solve complex coding mysteries
This function will output a message in a header
Can you generate the documentation for the following Python 3 function def print_a_header(message="-"): print("-".center(60,'-')) print(message.center(60,'-')) print("-".center(60,'-')) print()
As a python code expert, you are capable of creating scripts from specifications.
Checks if Exiftool is installed on your system and returns True if it is otherwise False
How would you explain what the following Python 3 function does def check_if_exiftool_is_already_installed(): result = 1; command = ["exiftool", "-ver"] with open(os.devnull, "w") as fnull: result = subprocess.call( command, stdout = fnull, stderr = fnull ...
You are a Python code analyst, evaluating scripts for potential improvements.
Render the message with the provided context.
Can you generate the documentation for the following Python 3 function def render(self, context=None, clean=False): # Load template if it is not loaded yet. if not self.template: self.load_template(self.template_name) # The signature of the `render()` method was changed in Django 1.7...
As a python code expert, you are capable of creating scripts from specifications.
def send(self, *args, **kwargs): """ Send email message, render if it is not rendered yet. Note ---- Any extra arguments are passed to :class:`EmailMultiAlternatives.send() <django.core.mail.EmailMessage>`. Keyword Arguments ----------------- cle...
Implement a function in Python 3 to send the message to the related object.
You are a Python code architect, reviewing and designing scalable and efficient code
This function is a convenience function for sending an email message to a list of recipients.
Can you generate the documentation for the following Python 3 function def send_mail(template_name, context, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, **kwargs): """ Easy wrapper for sending a single email message to a recip...
You are a Python code generator, capable of creating scripts from specifications.
def silhouette_score(X, labels, metric='euclidean', sample_size=None, random_state=None, **kwds): """Compute the mean Silhouette Coefficient of all samples. The Silhouette Coefficient is calculated using the mean intra-cluster distance (``a``) and the mean nearest-cluster distance (``b...
Create a Python 3 function to compute the mean Silhouette Coefficient of all samples.
You are a Python code analyst, evaluating scripts for potential improvements.
def silhouette_samples(X, labels, metric='euclidean', **kwds): """Compute the Silhouette Coefficient for each sample. The Silhouette Coefficient is a measure of how well samples are clustered with samples that are similar to themselves. Clustering models with a high Silhouette Coefficient are said to b...
Write a Python 3 script for computing the Silhouette Coefficient for each sample in X.
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the Calinski and Harabaz score.
Can you tell what is the following Python 3 function doing def calinski_harabaz_score(X, labels): X, labels = check_X_y(X, labels) le = LabelEncoder() labels = le.fit_transform(labels) n_samples, _ = X.shape n_labels = len(le.classes_) check_number_of_labels(n_labels, n_samples) extra_dis...
As a python code expert, you are capable of creating scripts from specifications.
def handle_zeros_in_scale(scale, copy=True): ''' Makes sure that whenever scale is zero, we handle it correctly. This happens in most scalers when we have constant features. Adapted from sklearn.preprocessing.data''' # if we are fitting on 1D arrays, scale might be a scalar if np.isscalar(scale): ...
Write a Python 3 function for handling zeroes in a single scale.
You are a Python code generator, capable of creating scripts from specifications.
def _joint_probabilities(distances, desired_perplexity, verbose): """Compute joint probabilities p_ij from distances. Parameters ---------- distances : array, shape (n_samples * (n_samples-1) / 2,) Distances of samples are stored as condensed matrices, i.e. we omit the diagonal and dupl...
Write a Python 3 function for computing joint probabilities p_ij from distances.
You are a Python code architect, reviewing and designing scalable and efficient code
Compute joint probabilities p_ij from distances using just nearest - neighbors.
Can you generate a brief explanation for the following Python 3 code def _joint_probabilities_nn(distances, neighbors, desired_perplexity, verbose): t0 = time() # Compute conditional probabilities such that they approximately match # the desired perplexity n_samples, k = neighbors.shape distances = ...
You are a Python code generator, capable of creating scripts from specifications.
t - SNE objective function for Kullback - Leibler divergence of p_ij and q_ij.
Make a summary of the following Python 3 code def _kl_divergence(params, P, degrees_of_freedom, n_samples, n_components, skip_num_points=0): """t-SNE objective function: gradient of the KL divergence of p_ijs and q_ijs and the absolute error. Parameters ---------- params : array,...
You are a Python code architect, reviewing and designing scalable and efficient code
Batch gradient descent for a given parameter vector.
How would you explain what the following Python 3 function does def _gradient_descent(objective, p0, it, n_iter, n_iter_check=1, n_iter_without_progress=300, momentum=0.8, learning_rate=200.0, min_gain=0.01, min_grad_norm=1e-7, verbose=0, args=None, kwar...
As a Python code analyst, you investigate and solve complex coding mysteries
def trustworthiness(X, X_embedded, n_neighbors=5, precomputed=False): """Expresses to what extent the local structure is retained. The trustworthiness is within [0, 1]. It is defined as .. math:: T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} \sum_{j \in U^{(k)}_i} (r(i, j) - k) ...
How would you implement a function in Python 3 that returns the trustworthiness of the local structure.
You are a Python code analyst, evaluating scripts for potential improvements.
Fit the model using X as training data.
Can you tell what is the following Python 3 function doing def _fit(self, X, skip_num_points=0): if self.method not in ['barnes_hut', 'exact']: raise ValueError("'method' must be 'barnes_hut' or 'exact'") if self.angle < 0.0 or self.angle > 1.0: raise ValueError("'angle' must be ...
You are a Python code analyst, evaluating scripts for potential improvements.
def _tsne(self, P, degrees_of_freedom, n_samples, random_state, X_embedded, neighbors=None, skip_num_points=0): """Runs t-SNE.""" # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P # and the Student's t-distributions Q. The optimization algorithm that # we ...
Write a Python 3 script to run t - SNE.
As a python code expert, you are capable of creating scripts from specifications.
Fit X into an embedded space and return that transformed .
Here you have a function in Python 3, explain what it does def fit_transform(self, X, y=None): embedding = self._fit(X) self.embedding_ = embedding return self.embedding_
As a Python code translator, you convert algorithms and pseudocode into Python.
Integrate and batch correct a list of data sets.
Can you tell what is the following Python 3 function doing def correct(datasets_full, genes_list, return_dimred=False, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, return_dense=False, hvg=None, union=False, ...
As a Python code composer, you craft elegant and concise scripts.
Integrate a list of data sets and correct a list of genes.
Here you have a function in Python 3, explain what it does def integrate(datasets_full, genes_list, batch_size=BATCH_SIZE, verbose=VERBOSE, ds_names=None, dimred=DIMRED, approx=APPROX, sigma=SIGMA, alpha=ALPHA, knn=KNN, geosketch=False, geosketch_max=20000, n_iter=1, union=Fals...
As a Python code composer, you craft elegant and concise scripts.
def correct_scanpy(adatas, **kwargs): """Batch correct a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate and/or correct. kwargs : `dict` See documentation for the `correct()` method for a full list of paramet...
Can you create a Python 3 function that batches correct a list of scanpy. api. AnnData.
You are a Python code architect, reviewing and designing scalable and efficient code
def integrate_scanpy(adatas, **kwargs): """Integrate a list of `scanpy.api.AnnData`. Parameters ---------- adatas : `list` of `scanpy.api.AnnData` Data sets to integrate. kwargs : `dict` See documentation for the `integrate()` method for a full list of parameters to use for ...
Write a Python 3 function that can integrate a list of scanpy. api. AnnData objects.
You are a Python code analyst, evaluating scripts for potential improvements.
Augment a knot vector with a new order.
How would you explain what the following Python 3 function does def augknt(knots, order): if isinstance(knots, np.ndarray) and knots.ndim > 1: raise ValueError("knots must be a list or a rank-1 array") knots = list(knots) # ensure Python list # One copy of knots[0] and knots[-1] will come from "...
As a Python code analyst, you investigate and solve complex coding mysteries
def aveknt(t, k): """Compute the running average of `k` successive elements of `t`. Return the averaged array. Parameters: t: Python list or rank-1 array k: int, >= 2, how many successive elements to average Returns: rank-1 array, averaged data. If k > len(t), returns a zero-length arr...
Write a Python 3 script for computing the running average of k successive elements of t. Return the averaged array.
As a Python code composer, you craft elegant and concise scripts.
Create an acceptable knot vector.
Can you generate the documentation for the following Python 3 function def aptknt(tau, order): tau = np.atleast_1d(tau) k = order + 1 if tau.ndim > 1: raise ValueError("tau must be a list or a rank-1 array") # emulate MATLAB behavior for the "k" parameter # # See # https://se.m...
You are a Python code generator, capable of creating scripts from specifications.
def knt2mlt(t): """Count multiplicities of elements in a sorted list or rank-1 array. Minimal emulation of MATLAB's ``knt2mlt``. Parameters: t: Python list or rank-1 array. Must be sorted! Returns: out rank-1 array such that out[k] = #{ t[i] == t[k] for i < k } Example: If ``...
Create a Python 3 function for counting multiplicities of elements in a sorted list or rank - 1 array.
You are a Python code architect, reviewing and designing scalable and efficient code
Return collocation matrix. spcol is the minimum emulation of MATLAB s pcol.
Explain what the following Python 3 code does def spcol(knots, order, tau): m = knt2mlt(tau) B = bspline.Bspline(knots, order) dummy = B(0.) nbasis = len(dummy) # perform dummy evaluation to get number of basis functions A = np.empty( (tau.shape[0], nbasis), dtype=dummy.dtype ) for i,item in ...
You are a Python code generator, capable of creating scripts from specifications.
Order zero basis ( for internal use.
How would you explain what the following Python 3 function does def __basis0(self, xi): return np.where(np.all([self.knot_vector[:-1] <= xi, xi < self.knot_vector[1:]],axis=0), 1.0, 0.0)
As a Python code translator, you convert algorithms and pseudocode into Python.
Convenience function to compute first derivative of basis functions. Memoized for speed.
Here you have a function in Python 3, explain what it does def d(self, xi): return self.__basis(xi, self.p, compute_derivatives=True)
As a Python code analyst, you investigate and solve complex coding mysteries
def plot(self): """Plot basis functions over full range of knots. Convenience function. Requires matplotlib. """ try: import matplotlib.pyplot as plt except ImportError: from sys import stderr print("ERROR: matplotlib.pyplot not found, matplo...
Write a Python 3 script to plot basis functions over full range of knots. Convenience function. Requires matplotlib.
As a Python code translator, you convert algorithms and pseudocode into Python.
def __diff_internal(self): """Differentiate a B-spline once, and return the resulting coefficients and Bspline objects. This preserves the Bspline object nature of the data, enabling recursive implementation of higher-order differentiation (see `diff`). The value of the first derivative of `B` at a point `x` ...
Implement a function in Python 3 to differentiate a B - spline once and return the resulting coefficients and Bspline objects.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a function that evaluates the order - th derivative of a B - spline.
Can you tell what is the following Python 3 function doing def diff(self, order=1): order = int(order) if order < 0: raise ValueError("order must be >= 0, got %d" % (order)) if order == 0: return self.__call__ if order > self.p: # identically zero, but force t...
As a Python code analyst, you investigate and solve complex coding mysteries
Compute collocation matrix for the given set of functions.
Can you generate the documentation for the following Python 3 function def collmat(self, tau, deriv_order=0): # get number of basis functions and output dtype dummy = self.__call__(0.) nbasis = dummy.shape[0] tau = np.atleast_1d(tau) if tau.ndim > 1: raise ValueError...
You are a Python code architect, reviewing and designing scalable and efficient code
Build a dictionary of methods that are used by the method.
Here you have a function in Python 3, explain what it does def build_interfaces_by_method(interfaces): def traverse(block, parts): try: method = block['method'].lower() except KeyError: for k, v in compat.iteritems(block): traverse(v, parts + [k]) else...
You are a Python code generator, capable of creating scripts from specifications.