output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Executes xpath - module SQL function with given input params.
Given the following Python 3 function, write the documentation def execute_xpath(xpath_string, sql_function, uuid, version): settings = get_current_registry().settings with db_connect() as db_connection: with db_connection.cursor() as cursor: try: cursor.execute(SQL[sql_func...
As a Python code composer, you craft elegant and concise scripts.
View for the route. Determines UUID and version from input request and executes xpath_book or xpath_page.
Make a summary of the following Python 3 code def xpath(request): ident_hash = request.params.get('id') xpath_string = request.params.get('q') if not ident_hash or not xpath_string: exc = httpexceptions.HTTPBadRequest exc.explanation = 'You must supply both a UUID and an xpath' rais...
You are a Python code analyst, evaluating scripts for potential improvements.
def tree_to_html(tree): """Return html list version of book tree.""" ul = etree.Element('ul') html_listify([tree], ul) return HTML_WRAPPER.format(etree.tostring(ul))
Write a Python 3 function for returning html list version of book tree.
As a Python code composer, you craft elegant and concise scripts.
def _get_content_json(ident_hash=None): """Return a content as a dict from its ident-hash (uuid@version).""" request = get_current_request() routing_args = request and request.matchdict or {} if not ident_hash: ident_hash = routing_args['ident_hash'] as_collated = asbool(request.GET.get('as...
How would you implement a function in Python 3 that returns a content as a dict from its ident - hash.
As a Python code translator, you convert algorithms and pseudocode into Python.
Retrieve content as JSON using the ident - hash.
Can you generate the documentation for the following Python 3 function def get_content_json(request): result = _get_content_json() resp = request.response resp.status = "200 OK" resp.content_type = 'application/json' resp.body = json.dumps(result) return result, resp
You are a Python code analyst, evaluating scripts for potential improvements.
def get_content_html(request): """Retrieve content as HTML using the ident-hash (uuid@version).""" result = _get_content_json() media_type = result['mediaType'] if media_type == COLLECTION_MIMETYPE: content = tree_to_html(result['tree']) else: content = result['content'] resp =...
Write a Python 3 function for retrieving content as HTML using the ident - hash.
As a python code expert, you are capable of creating scripts from specifications.
def get_book_info(cursor, real_dict_cursor, book_id, book_version, page_id, page_version): """Return information about a given book. Return the book's title, id, shortId, authors and revised date. Raise HTTPNotFound if the page is not in the book. """ book_ident_hash = join_ident_...
Can you create a Python 3 function that returns the information about a given book.
You are a Python code generator, capable of creating scripts from specifications.
Return the portal_type of the module with the given id and version.
Make a summary of the following Python 3 code def get_portal_type(cursor, id, version): args = join_ident_hash(id, version) sql_statement = """ SELECT m.portal_type FROM modules as m WHERE ident_hash(uuid, major_version, minor_version) = %s """ cursor.execute(sql_statement, vars=(args,)) ...
You are a Python code generator, capable of creating scripts from specifications.
Return a list of book names and UUIDs that contain a given module UUID.
How would you explain what the following Python 3 function does def get_books_containing_page(cursor, uuid, version, context_uuid=None, context_version=None): """Return a list of book names and UUIDs that contain a given module UUID.""" with db_connect() as db_connection: ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_canonical_url(metadata, request): """Builds canonical in book url from a pages metadata.""" slug_title = u'/{}'.format('-'.join(metadata['title'].split())) settings = get_current_registry().settings canon_host = settings.get('canonical-hostname', re.sub('archive.',...
Can you create a Python 3 function that builds canonical in book url from a pages metadata.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_content(request): """Retrieve content using the ident-hash (uuid@version). Depending on extension or HTTP_ACCEPT header return HTML or JSON. """ ext = request.matchdict.get('ext') accept = request.headers.get('ACCEPT', '') if not ext: if ('application/xhtml+xml' in accept): ...
Write a Python 3 script for retrieving the content using the ident - hash.
You are a Python code generator, capable of creating scripts from specifications.
def get_extra(request): """Return information about a module / collection that cannot be cached.""" settings = get_current_registry().settings exports_dirs = settings['exports-directories'].split() args = request.matchdict if args['page_ident_hash']: context_id, context_version = split_ident...
Can you create a Python 3 function that returns information about a module / collection that cannot be cached.
As a Python code composer, you craft elegant and concise scripts.
def map_indices_child2parent(child, child_indices): """Map child RTDCBase event indices to parent RTDCBase Parameters ---------- child: RTDC_Hierarchy hierarchy child with `child_indices` child_indices: 1d ndarray child indices to map Returns ------- parent_indices: 1d ...
Write a Python 3 function that can map RTDCBase event indices to parent RTDCBase event indices.
As a Python code composer, you craft elegant and concise scripts.
Map RTDC_Hierarchy event indices to root RTDC_Hierarchy event indices.
Explain what the following Python 3 code does def map_indices_child2root(child, child_indices): while True: indices = map_indices_child2parent(child=child, child_indices=child_indices) if isinstance(child.hparent, RTDC_Hierarchy): child = child....
You are a Python code architect, reviewing and designing scalable and efficient code
def map_indices_parent2child(child, parent_indices): """Map parent RTDCBase event indices to RTDC_Hierarchy Parameters ---------- parent: RTDC_Hierarchy hierarchy child parent_indices: 1d ndarray hierarchy parent (`child.hparent`) indices to map Returns ------- child_in...
Write a Python 3 function for mapping parent RTDCBase event indices to RTDCBase event indices.
As a Python code translator, you convert algorithms and pseudocode into Python.
Map root RTDCBase event indices to child RTDCBase event indices.
Here you have a function in Python 3, explain what it does def map_indices_root2child(child, root_indices): # construct hierarchy tree containing only RTDC_Hierarchy instances hierarchy = [child] while True: if isinstance(child.hparent, RTDC_Hierarchy): # the parent is a hierarchy tree ...
You are a Python code generator, capable of creating scripts from specifications.
Write to self. manual and store the indices of manual events.
How would you explain what the following Python 3 function does def apply_manual_indices(self, manual_indices): if self.parent_changed: msg = "Cannot apply filter, because parent changed: " \ + "dataset {}. ".format(self.rtdc_ds) \ + "Run `RTDC_Hierarchy.apply_fil...
You are a Python code generator, capable of creating scripts from specifications.
def retrieve_manual_indices(self): """Read from self.manual Read from the boolean array `self.manual`, index all occurences of `False` and find the corresponding indices in the root hierarchy parent, return those and store them in `self._man_root_ids` as well. Notes ...
Create a Python 3 function to read from self. manual and index all occurences of False and return those and store them in self. _man_root_ids as well.
As a Python code composer, you craft elegant and concise scripts.
def apply_filter(self, *args, **kwargs): """Overridden `apply_filter` to perform tasks for hierarchy child""" if self.filter is not None: # make sure self.filter knows about root manual indices self.filter.retrieve_manual_indices() # Copy event data from hierarchy parent...
Write a Python 3 function that can override apply_filter to perform tasks for hierarchy child
You are a Python code analyst, evaluating scripts for potential improvements.
Hashes of a hierarchy child changes if the parent changes
Can you generate the documentation for the following Python 3 function def hash(self): # Do not apply filters here (speed) hph = self.hparent.hash hpfilt = hashobj(self.hparent._filter) dhash = hashobj(hph + hpfilt) return dhash
As a Python code composer, you craft elegant and concise scripts.
Tries to find a video file that belongs to an RTDC dataset returning None if no video file is found.
Make a summary of the following Python 3 code def find_video_file(rtdc_dataset): video = None if rtdc_dataset._fdir.exists(): # Cell images (video) videos = [v.name for v in rtdc_dataset._fdir.rglob("*.avi")] # Filter videos according to measurement number ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Same as __getitem__ but seek through the video beforehand This is a workaround for an all - zero image returned by imageio.
Given the following Python 3 function, write the documentation def _get_image_workaround_seek(self, idx): warnings.warn("imageio workaround used!") cap = self.video_handle mult = 50 for ii in range(idx//mult): cap.get_data(ii*mult) final = cap.get_data(idx) re...
As a Python code composer, you craft elegant and concise scripts.
def select(self, attr, default=None): """ Select a given attribute (or chain or attributes) from the objects within the list. Args: attr (str): attributes to be selected (with initial `.` omitted) default (any): value to return if given element in list doesn't co...
Create a Python 3 function to return a list of the values of the given attribute from the objects within the list.
As a Python code translator, you convert algorithms and pseudocode into Python.
def filter(self, attr, value, compare="=="): """ Filter list by a comparison of a given attribute (or chain or attributes). Args: attr (str): attributes to be compared (with initial `.` omitted) value (any): value to compare attr against compare (str): compar...
Write a Python 3 script for filtering list by a given attribute and value.
You are a Python code architect, reviewing and designing scalable and efficient code
def as_new_format(self, format="ATR"): """ Create a new disk image in the specified format """ first_data = len(self.header) raw = self.rawdata[first_data:] data = add_atr_header(raw) newraw = SegmentData(data) image = self.__class__(newraw) return image
Write a Python 3 function that can create a new disk image in the specified format
You are a Python code architect, reviewing and designing scalable and efficient code
Selects and saves source.
Can you generate a brief explanation for the following Python 3 code def set_source(self, source): route = Navigator(source=self.source).navigate_to_source(source) # Save new source self.source = source return self._send_keystroke(route, wait=True)
You are a Python code generator, capable of creating scripts from specifications.
def find_migrations_directory(): """Finds and returns the location of the database migrations directory. This function is used from a setuptools entry-point for db-migrator. """ here = os.path.abspath(os.path.dirname(__file__)) return os.path.join(here, 'sql/migrations')
Write a Python 3 script to find and returns the location of the database migrations directory.
You are a Python code analyst, evaluating scripts for potential improvements.
def declare_api_routes(config): """Declare routes, with a custom pregenerator.""" # The pregenerator makes sure we can generate a path using # request.route_path even if we don't have all the variables. # # For example, instead of having to do this: # request.route_path('resource', hash=hash...
How would you implement a function in Python 3 that declares routes with a custom pregenerator.
As a Python code analyst, you investigate and solve complex coding mysteries
def _init_lsr(n_items, alpha, initial_params): """Initialize the LSR Markov chain and the weights.""" if initial_params is None: weights = np.ones(n_items) else: weights = exp_transform(initial_params) chain = alpha * np.ones((n_items, n_items), dtype=float) return weights, chain
Implement a function in Python 3 to initialize the LSR Markov chain and the weights.
You are a Python code architect, reviewing and designing scalable and efficient code
Iteratively refine LSR estimates until converge.
Can you generate the documentation for the following Python 3 function def _ilsr(fun, params, max_iter, tol): converged = NormOfDifferenceTest(tol, order=1) for _ in range(max_iter): params = fun(initial_params=params) if converged(params): return params raise RuntimeError("Did n...
As a python code expert, you are capable of creating scripts from specifications.
Compute the LSR estimate of model parameters for a set of items in data.
Can you tell what is the following Python 3 function doing def lsr_pairwise(n_items, data, alpha=0.0, initial_params=None): weights, chain = _init_lsr(n_items, alpha, initial_params) for winner, loser in data: chain[loser, winner] += 1 / (weights[winner] + weights[loser]) chain -= np.diag(chain.sum(...
As a Python code composer, you craft elegant and concise scripts.
Compute the maximum - likelihood of the model parameters using I - LSR.
Can you generate a brief explanation for the following Python 3 code def ilsr_pairwise( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters...
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the LSR estimate of model parameters given dense data.
Can you generate the documentation for the following Python 3 function def lsr_pairwise_dense(comp_mat, alpha=0.0, initial_params=None): n_items = comp_mat.shape[0] ws, chain = _init_lsr(n_items, alpha, initial_params) denom = np.tile(ws, (n_items, 1)) chain += comp_mat.T / (denom + denom.T) chain -...
As a python code expert, you are capable of creating scripts from specifications.
def ilsr_pairwise_dense( comp_mat, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters given dense data. This function computes the maximum-likelihood (ML) estimate of model parameters given dense pairwise-comparison data. The data is describ...
Can you write a function in Python 3 where it computes the maximum - likelihood of the LSR Markov chain given a dense pairwise - comparison matrix.
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute the rank centrality estimate of model parameters.
Given the following Python 3 function, write the documentation def rank_centrality(n_items, data, alpha=0.0): _, chain = _init_lsr(n_items, alpha, None) for winner, loser in data: chain[loser, winner] += 1.0 # Transform the counts into ratios. idx = chain > 0 # Indices (i,j) of non-zero entries...
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute the LSR estimate of model parameters.
Can you generate the documentation for the following Python 3 function def lsr_rankings(n_items, data, alpha=0.0, initial_params=None): weights, chain = _init_lsr(n_items, alpha, initial_params) for ranking in data: sum_ = weights.take(ranking).sum() for i, winner in enumerate(ranking[:-1]): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the maximum - likelihood of the model parameters using I - LSR.
Can you generate a brief explanation for the following Python 3 code def ilsr_rankings( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters...
As a Python code composer, you craft elegant and concise scripts.
def lsr_top1(n_items, data, alpha=0.0, initial_params=None): """Compute the LSR estimate of model parameters. This function implements the Luce Spectral Ranking inference algorithm [MG15]_ for top-1 data (see :ref:`data-top1`). The argument ``initial_params`` can be used to iteratively refine an e...
Implement a Python 3 function for computing the LSR estimate of model parameters for the top - 1 data.
You are a Python code generator, capable of creating scripts from specifications.
def ilsr_top1( n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8): """Compute the ML estimate of model parameters using I-LSR. This function computes the maximum-likelihood (ML) estimate of model parameters given top-1 data (see :ref:`data-top1`), using the iterative Luce Sp...
Can you write a function in Python 3 where it computes the maximum - likelihood of model parameters using I - LSR.
As a python code expert, you are capable of creating scripts from specifications.
Compute a distribution of model parameters using the EP algorithm.
How would you explain what the following Python 3 function does def ep_pairwise(n_items, data, alpha, model="logit", max_iter=100, initial_state=None): """Compute a distribution of model parameters using the EP algorithm. This function computes an approximate Bayesian posterior probability distribu...
As a Python code composer, you craft elegant and concise scripts.
def _ep_pairwise( n_items, comparisons, alpha, match_moments, max_iter, initial_state): """Compute a distribution of model parameters using the EP algorithm. Raises ------ RuntimeError If the algorithm does not converge after ``max_iter`` iterations. """ # Static variable that a...
Write a Python 3 script for computing a pairwise version of the EP algorithm.
As a Python code translator, you convert algorithms and pseudocode into Python.
Stable computation of the log of the Normal CDF and its derivative.
Make a summary of the following Python 3 code def _log_phi(z): # Adapted from the GPML function `logphi.m`. if z * z < 0.0492: # First case: z close to zero. coef = -z / SQRT2PI val = functools.reduce(lambda acc, c: coef * (c + acc), CS, 0) res = -2 * val - log(2) dres = ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _init_ws(n_items, comparisons, prior_inv, tau, nu): """Initialize parameters in the weight space.""" prec = np.zeros((n_items, n_items)) xs = np.zeros(n_items) for i, (a, b) in enumerate(comparisons): prec[(a, a, b, b), (a, b, a, b)] += tau[i] * MAT_ONE_FLAT xs[a] += nu[i] x...
Write a Python 3 function that can initialize parameters in the weight space.
You are a Python code analyst, evaluating scripts for potential improvements.
Transform parameters into exp - scale weights.
Can you generate a brief explanation for the following Python 3 code def exp_transform(params): weights = np.exp(np.asarray(params) - np.mean(params)) return (len(weights) / weights.sum()) * weights
You are a Python code architect, reviewing and designing scalable and efficient code
Stable implementation of the softmax function.
Can you generate the documentation for the following Python 3 function def softmax(xs): ys = xs - np.max(xs) exps = np.exp(ys) return exps / exps.sum(axis=0)
As a Python code translator, you convert algorithms and pseudocode into Python.
Stable inverse of a positive definite matrix.
Can you generate the documentation for the following Python 3 function def inv_posdef(mat): # See: # - http://www.seas.ucla.edu/~vandenbe/103/lectures/chol.pdf # - http://scicomp.stackexchange.com/questions/3188 chol = np.linalg.cholesky(mat) ident = np.eye(mat.shape[0]) res = solve_triangular(c...
As a Python code translator, you convert algorithms and pseudocode into Python.
r Compute Spearman s footrule distance between two models.
Can you generate a brief explanation for the following Python 3 code def footrule_dist(params1, params2=None): assert params2 is None or len(params1) == len(params2) ranks1 = rankdata(params1, method="average") if params2 is None: ranks2 = np.arange(1, len(params1) + 1, dtype=float) else: ...
You are a Python code analyst, evaluating scripts for potential improvements.
r Compute the Kendall tau distance between two models.
Can you tell what is the following Python 3 function doing def kendalltau_dist(params1, params2=None): assert params2 is None or len(params1) == len(params2) ranks1 = rankdata(params1, method="ordinal") if params2 is None: ranks2 = np.arange(1, len(params1) + 1, dtype=float) else: ranks2...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the log - likelihood of model parameters.
How would you explain what the following Python 3 function does def log_likelihood_pairwise(data, params): loglik = 0 for winner, loser in data: loglik -= np.logaddexp(0, -(params[winner] - params[loser])) return loglik
As a Python code translator, you convert algorithms and pseudocode into Python.
def log_likelihood_rankings(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 params = np.asarray(params) for ranking in data: for i, winner in enumerate(ranking[:-1]): loglik -= logsumexp(params.take(ranking[i:]) - params[winner]) return loglik
Can you implement a function in Python 3 that computes the log - likelihood of model parameters.
As a python code expert, you are capable of creating scripts from specifications.
def log_likelihood_top1(data, params): """Compute the log-likelihood of model parameters.""" loglik = 0 params = np.asarray(params) for winner, losers in data: idx = np.append(winner, losers) loglik -= logsumexp(params.take(idx) - params[winner]) return loglik
Create a Python 3 function for computing the log - likelihood of model parameters.
You are a Python code generator, capable of creating scripts from specifications.
Compute the log - likelihood of the model parameters.
Can you tell what is the following Python 3 function doing def log_likelihood_network( digraph, traffic_in, traffic_out, params, weight=None): """ Compute the log-likelihood of model parameters. If ``weight`` is not ``None``, the log-likelihood is correct only up to a constant (independent of t...
As a Python code translator, you convert algorithms and pseudocode into Python.
def statdist(generator): """Compute the stationary distribution of a Markov chain. Parameters ---------- generator : array_like Infinitesimal generator matrix of the Markov chain. Returns ------- dist : numpy.ndarray The unnormalized stationary distribution of the Markov ch...
Create a Python 3 function to compute the stationary distribution of a Markov chain.
As a Python code translator, you convert algorithms and pseudocode into Python.
def generate_pairwise(params, n_comparisons=10): """Generate pairwise comparisons from a Bradley--Terry model. This function samples comparisons pairs independently and uniformly at random over the ``len(params)`` choose 2 possibilities, and samples the corresponding comparison outcomes from a Bradley-...
Implement a function in Python 3 to generate pairwise comparisons from a Bradley - Terry model.
As a Python code composer, you craft elegant and concise scripts.
Generates a random set of partial ranking items from a Plackett - Luce model.
Explain what the following Python 3 code does def generate_rankings(params, n_rankings, size=3): n = len(params) items = tuple(range(n)) params = np.asarray(params) data = list() for _ in range(n_rankings): # Pick the alternatives uniformly at random. alts = random.sample(items, size...
You are a Python code architect, reviewing and designing scalable and efficient code
Generate a comparison outcome that follows Luce s axiom.
How would you explain what the following Python 3 function does def compare(items, params, rank=False): probs = probabilities(items, params) if rank: return np.random.choice(items, size=len(items), replace=False, p=probs) else: return np.random.choice(items, p=probs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute the comparison outcome probabilities given a subset of items.
How would you explain what the following Python 3 function does def probabilities(items, params): params = np.asarray(params) return softmax(params.take(items))
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the maximum likelihood estimate of model parameters using pairwise - comparison algorithm.
Make a summary of the following Python 3 code def opt_pairwise(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameter...
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the maximum likelihood estimate of model parameters using the Scipy Optimization module.
Make a summary of the following Python 3 code def opt_rankings(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameter...
You are a Python code generator, capable of creating scripts from specifications.
def opt_top1(n_items, data, alpha=1e-6, method="Newton-CG", initial_params=None, max_iter=None, tol=1e-5): """Compute the ML estimate of model parameters using ``scipy.optimize``. This function computes the maximum-likelihood estimate of model parameters given top-1 data (see :ref:`data-top1`), usi...
Can you create a Python 3 function that computes the maximum likelihood estimate of model parameters using the Scipy Optimization module.
You are a Python code architect, reviewing and designing scalable and efficient code
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for win, los in self._data: val += np.logaddexp(0, -(params[win] - params[los])) return val
How would you code a function in Python 3 to compute the negative penalized log - likelihood.
As a Python code composer, you craft elegant and concise scripts.
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for winner, losers in self._data: idx = np.append(winner, losers) val += logsumexp(params.take(idx) - params[winner]) return val
Create a Python 3 function to compute the negative penalized log - likelihood.
As a Python code analyst, you investigate and solve complex coding mysteries
Compute the ML estimate of model parameters using the MM algorithm.
Can you generate the documentation for the following Python 3 function def mm_pairwise( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of...
As a Python code analyst, you investigate and solve complex coding mysteries
Inner loop of MM algorithm for ranking data.
Given the following Python 3 function, write the documentation def _mm_rankings(n_items, data, params): weights = exp_transform(params) wins = np.zeros(n_items, dtype=float) denoms = np.zeros(n_items, dtype=float) for ranking in data: sum_ = weights.take(ranking).sum() for i, winner in e...
As a Python code translator, you convert algorithms and pseudocode into Python.
def mm_rankings(n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the ...
Create a Python 3 function for computing the ML estimate of model parameters given a list of items and ranking data.
As a Python code composer, you craft elegant and concise scripts.
Compute the ML estimate of model parameters given a top - 1 data set.
Explain what the following Python 3 code does def mm_top1( n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given t...
As a Python code composer, you craft elegant and concise scripts.
def choicerank( digraph, traffic_in, traffic_out, weight=None, initial_params=None, alpha=1.0, max_iter=10000, tol=1e-8): """Compute the MAP estimate of a network choice model's parameters. This function computes the maximum-a-posteriori (MAP) estimate of model parameters given a network st...
Write a Python 3 function for computing the MAP estimate of a network choice model.
As a Python code translator, you convert algorithms and pseudocode into Python.
def decorate(cls, function): ''' Decorate a function so the function call is checked whenever a call is made. The calls that do not need any checks are skipped. The `function` argument is the function to be decorated. The return value will be either * the function itse...
Can you write a function in Python 3 where it decorates a function so that it is called whenever a call is made.
As a Python code composer, you craft elegant and concise scripts.
Removes validator decoration from a function.
Can you generate a brief explanation for the following Python 3 code def undecorate(cls, function): ''' Remove validator decoration from a function. The `function` argument is the function to be cleaned from the validator decorator. ''' if cls.is_function_validated(func...
As a python code expert, you are capable of creating scripts from specifications.
Validate the arguments passed to a function.
Make a summary of the following Python 3 code def validate_arguments(self, locals_dict): ''' Validate the arguments passed to a function. If an error occurred, the function will throw a TypesafetyError. The `locals_dict` argument should be the local value dictionary of the funct...
As a Python code composer, you craft elegant and concise scripts.
def validate_return_value(self, retval): ''' Validate the return value of a function call. If an error occurred, the function will throw a TypesafetyError. The `retval` should contain the return value of the function call. ''' if self.__return_annotation is None: ...
Write a Python 3 script to validate the return value of a function call.
You are a Python code analyst, evaluating scripts for potential improvements.
Uninstall the module finder.
How would you explain what the following Python 3 function does def uninstall(self): ''' Uninstall the module finder. If not installed, this will do nothing. After uninstallation, none of the newly loaded modules will be decorated (that is, everything will be back to normal). '''...
You are a Python code analyst, evaluating scripts for potential improvements.
Find the module. Required for the Python meta-loading mechanism. This will do nothing, since we use the system to locate a module.
Can you tell what is the following Python 3 function doing def find_module(self, fullname, path=None): ''' Find the module. Required for the Python meta-loading mechanism. This will do nothing, since we use the system to locate a module. ''' loader = None if self.__filt...
You are a Python code architect, reviewing and designing scalable and efficient code
Load the module. Required for the Python meta - loading mechanism.
Can you tell what is the following Python 3 function doing def load_module(self, loader): ''' Load the module. Required for the Python meta-loading mechanism. ''' modfile, pathname, description = loader.info module = imp.load_module( loader.fullname, modf...
As a Python code composer, you craft elegant and concise scripts.
def _register_event_listeners(self, cls): """ :param cls: DB class """ event.listen(cls, 'after_insert', self._new_listener) event.listen(cls, 'after_update', self._update_listener) event.listen(cls, 'after_delete', self._delete_listener)
Implement a Python 3 function for registering the event listeners for the given DB class.
As a Python code composer, you craft elegant and concise scripts.
This method is called when the session is committed.
Here you have a function in Python 3, explain what it does def after_commit_listener(self, session): log.info('Commiting indexing orders for session %s' % session) try: if not any((session.index_new[self.cls_name], session.index_dirty[self.cls_name], ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _queue_job(redis, queue_name, delegate, *args): """ creates a new job on the queue :param redis: redis :param delegate: method to be executed by the queue. Use fully qualified method name as String. :param args: arguments of the method :return: jo...
Can you implement a function in Python 3 that creates a new job on the specified queue.
You are a Python code generator, capable of creating scripts from specifications.
def after_rollback_listener(self, session): """ Rollback of the transaction, undo the indexes. If our transaction is terminated, we will reset the indexing assignments. """ log.info('Removing indexing orders.') try: session.index_new[self.cls_name].cle...
Implement a function in Python 3 to call when the transaction is terminated.
You are a Python code analyst, evaluating scripts for potential improvements.
def remove_session(self, session): """ :param sqlalchemy.session.Session session: Database session to remove """ try: del session.redis except AttributeError: pass try: del session.index_new[self.cls_name] del session.index_...
Create a Python 3 function to remove a session from the database.
As a Python code analyst, you investigate and solve complex coding mysteries
Parse a sort string for use with elasticsearch
How would you explain what the following Python 3 function does def parse_sort_string(sort): if sort is None: return ['_score'] l = sort.rsplit(',') sortlist = [] for se in l: se = se.strip() order = 'desc' if se[0:1] == '-' else 'asc' field = se[1:] if se[0:1] in ['-', '...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse query_params to a filter params dict. Merge multiple values for one key to a list.
Can you generate a brief explanation for the following Python 3 code def parse_filter_params(query_params, filterable): if query_params is not None: filter_params = {} for fq in query_params.mixed(): if fq in filterable: filter_params[fq] = query_params.mixed().get(fq) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def link_to_sibling(self, feed, sibling_type, atom_feed): """ Adding previous or next links to the given feed self._link_to_sibling(feed, 'previous', atom_feed) self._link_to_sibling(feed, 'next', atom_feed) :param feed: a feed object :param sibling_type: 'previous' or '...
Can you write a function in Python 3 where it links the given feed to the given sibling.
As a Python code translator, you convert algorithms and pseudocode into Python.
Initializes an atom feed object given a feed object
How would you explain what the following Python 3 function does def init_atom_feed(self, feed): atom_feed = FeedGenerator() atom_feed.id(id=self.request.route_url(self.get_atom_feed_url, id=feed.id)) atom_feed.link(href=self.request.route_url(self.get_atom_feed_url, id=feed.id), rel='self') ...
As a Python code analyst, you investigate and solve complex coding mysteries
A function returning a feed like feedgen. feed. FeedGenerator.
Can you generate a brief explanation for the following Python 3 code def _generate_atom_feed(self, feed): atom_feed = self.init_atom_feed(feed) atom_feed.title("Feed") return atom_feed
You are a Python code analyst, evaluating scripts for potential improvements.
Create a client for a service account.
Make a summary of the following Python 3 code def from_private_key(account_name, private_key=None, private_key_path=None, storage=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a service account. Creat...
You are a Python code architect, reviewing and designing scalable and efficient code
def from_secrets_file(client_secrets, storage=None, flags=None, storage_path=None, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a web or installed application. Create a client with a client secrets file. Args: ...
Write a Python 3 script to create a client with a client secrets file.
As a python code expert, you are capable of creating scripts from specifications.
def from_credentials_db(client_secrets, storage, api_version="v3", readonly=False, http_client=None, ga_hook=None): """Create a client for a web or installed application. Create a client with a credentials stored in stagecraft db. Args: client_secrets: dict, client secrets ...
Can you create a Python 3 function that creates a new client with a credentials stored in stagecraft db.
As a Python code analyst, you investigate and solve complex coding mysteries
def _build(credentials, api_version, http_client=None): """Build the client object.""" if not http_client: http_client = httplib2.Http() authorised_client = credentials.authorize(http_client) return build("analytics", api_version, http=authorised_client)
Write a Python 3 script to build the client object.
You are a Python code generator, capable of creating scripts from specifications.
def _prefix_ga(value): """Prefix a string with 'ga:' if it is not already Sort values may be prefixed with '-' to indicate negative sort. >>> _prefix_ga('foo') 'ga:foo' >>> _prefix_ga('ga:foo') 'ga:foo' >>> _prefix_ga('-foo') '-ga:foo' >>> _prefix_ga('-ga:foo') '-ga:foo' ""...
Create a Python 3 function to prefix a string with ga prefix.
You are a Python code generator, capable of creating scripts from specifications.
def ad_unif_inf(statistic): """ Approximates the limiting distribution to about 5 decimal digits. """ z = statistic if z < 2: return (exp(-1.2337141 / z) / sqrt(z) * (2.00012 + (.247105 - (.0649821 - (.0347962 - (.011672 - .0016...
Can you implement a function in Python 3 that computes the unifinf distribution of a given statistic.
As a Python code analyst, you investigate and solve complex coding mysteries
Corrects the limiting distribution for a finite sample size.
Given the following Python 3 function, write the documentation def ad_unif_fix(samples, pinf): n = samples c = .01265 + .1757 / n if pinf < c: return (((.0037 / n + .00078) / n + .00006) / n) * g1(pinf / c) elif pinf < .8: return ((.01365 / n + .04213) / n) * g2((pinf - c) / (.8 - c)) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Checks that all required meta - data is supplied.
Can you tell what is the following Python 3 function doing def check_metadata(self): metadata = self.distribution.metadata missing = [] for attr in ("name", "version", "url"): if not (hasattr(metadata, attr) and getattr(metadata, attr)): missing.append(attr) ...
You are a Python code generator, capable of creating scripts from specifications.
def from_url(cls, url): """ Construct a PostgresConfig from a URL. """ parsed = urlparse(url) return cls( username=parsed.username, password=parsed.password, hostname=parsed.hostname, port=parsed.port, database=parsed.pa...
Can you write a function in Python 3 where it constructs a PostgresConfig from a URL.
As a Python code translator, you convert algorithms and pseudocode into Python.
def vectorize(*args, **kwargs): """ Allows using `@vectorize` as well as `@vectorize()`. """ if args and callable(args[0]): # Guessing the argument is the method. return _vectorize(args[0]) else: # Wait for the second call. return lambda m: _vectorize(m, *args, **kwar...
Write a Python 3 script for allowing using a method or a function to vectorize a single object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a Tween that adds ETag headers and tells Pyramid to enable conditional responses where appropriate.
Here you have a function in Python 3, explain what it does def conditional_http_tween_factory(handler, registry): settings = registry.settings if hasattr(registry, 'settings') else {} not_cacheble_list = [] if 'not.cachable.list' in settings: not_cacheble_list = settings.get('not.cachable.list').spl...
As a Python code composer, you craft elegant and concise scripts.
def get_last_modified_date(filename): """ Get the last modified date of a given file :param filename: string: pathname of a file :return: Date """ if os.path.isfile(filename): t = os.path.getmtime(filename) return datetime.date.fromtimestamp(t).strftime('%d/%m/%Y') return No...
Can you implement a function in Python 3 that gets the last modified date of a given file
You are a Python code generator, capable of creating scripts from specifications.
def get_file_size(filename): """ Get the file size of a given file :param filename: string: pathname of a file :return: human readable filesize """ if os.path.isfile(filename): return convert_size(os.path.getsize(filename)) return None
Implement a function in Python 3 to get the file size of a given file
As a Python code translator, you convert algorithms and pseudocode into Python.
def convert_size(size_bytes): """ Transform bytesize to a human readable filesize :param size_bytes: bytesize :return: human readable filesize """ if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_b...
Implement a Python 3 function for transforming bytesize to a human readable filesize.
As a python code expert, you are capable of creating scripts from specifications.
def validate_all_attributes(self): """ Force validation of all traits. Useful for circumstances where an attribute won't be accessed until well after construction, but we want to fail eagerly if that attribute is passed incorrectly. Consider using ``StrictSerializable``...
Write a Python 3 function for forcing validation of all attributes of all traits.
As a Python code translator, you convert algorithms and pseudocode into Python.
def example_instance(cls, skip=()): """ Generate an example instance of a Serializable subclass. If traits have been tagged with an `example` value, then we use that value. Otherwise we fall back the default_value for the instance. Traits with names in ``skip`` will not have e...
Implement a Python 3 function for generating an example instance of a Serializable subclass.
You are a Python code generator, capable of creating scripts from specifications.