output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Check if a re pattern expression matches an entire string.
Here you have a function in Python 3, explain what it does def _is_pattern_match(re_pattern, s): match = re.match(re_pattern, s, re.I) return match.group() == s if match else False
As a Python code analyst, you investigate and solve complex coding mysteries
def is_pinyin(s): """Check if *s* consists of valid Pinyin.""" re_pattern = ('(?:%(word)s|[ \t%(punctuation)s])+' % {'word': zhon.pinyin.word, 'punctuation': zhon.pinyin.punctuation}) return _is_pattern_match(re_pattern, s)
Write a Python 3 script to check if *s* consists of valid Pinyin.
You are a Python code architect, reviewing and designing scalable and efficient code
def is_zhuyin_compatible(s): """Checks if *s* is consists of Zhuyin-compatible characters. This does not check if *s* contains valid Zhuyin syllables; for that see :func:`is_zhuyin`. Besides Zhuyin characters and tone marks, spaces are also accepted. This function checks that all characters in *s*...
Create a Python 3 function for checking if a string s contains Zhuyin - compatible characters.
As a python code expert, you are capable of creating scripts from specifications.
def is_ipa(s): """Check if *s* consists of valid Chinese IPA.""" re_pattern = ('(?:%(syllable)s|[ \t%(punctuation)s])+' % {'syllable': _IPA_SYLLABLE, 'punctuation': zhon.pinyin.punctuation}) return _is_pattern_match(re_pattern, s)
Write a Python 3 function that can check if *s* consists of valid Chinese IPA.
As a Python code composer, you craft elegant and concise scripts.
def identify(s): """Identify a given string's transcription system. *s* is the string to identify. The string is checked to see if its contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`, :data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the string's identity. If *s* ...
Create a Python 3 function for identifying a given string s transcription system.
As a Python code translator, you convert algorithms and pseudocode into Python.
def prepare(self, f): """Accept an objective function for optimization.""" self.g = autograd.grad(f) self.h = autograd.hessian(f)
Create a Python 3 function to accept an objective function for optimization.
You are a Python code architect, reviewing and designing scalable and efficient code
Calculate an optimum argument of an objective function.
Can you generate the documentation for the following Python 3 function def optimize(self, x0, target): x = x0 for _ in range(self.maxiter): delta = np.linalg.solve(self.h(x, target), -self.g(x, target)) x = x + delta if np.linalg.norm(delta) < self.tol: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def optimize(self, x0, target): """Calculate an optimum argument of an objective function.""" x = x0 for i in range(self.maxiter): g = self.g(x, target) h = self.h(x, target) if i == 0: alpha = 0 m = g else: ...
Can you create a Python 3 function that calculates an optimum argument of an objective function.
You are a Python code architect, reviewing and designing scalable and efficient code
def optimize(self, angles0, target): """Calculate an optimum argument of an objective function.""" def new_objective(angles): return self.f(angles, target) return scipy.optimize.minimize( new_objective, angles0, **self.optimizer_opt).x
How would you code a function in Python 3 to calculate an optimum argument of an objective function.
You are a Python code analyst, evaluating scripts for potential improvements.
def optimize(self, angles0, target): """Calculate an optimum argument of an objective function.""" def new_objective(angles): a = angles - angles0 if isinstance(self.smooth_factor, (np.ndarray, list)): if len(a) == len(self.smooth_factor): retu...
How would you implement a function in Python 3 that calculates an optimum argument of an objective function.
As a Python code translator, you convert algorithms and pseudocode into Python.
def solve(self, angles): """Calculate a position of the end-effector and return it.""" return reduce( lambda a, m: np.dot(m, a), reversed(self._matrices(angles)), np.array([0., 0., 0., 1.]) )[:3]
Can you create a Python 3 function that calculates a position of the end - effector and return it.
As a Python code composer, you craft elegant and concise scripts.
def solve(self, angles0, target): """Calculate joint angles and returns it.""" return self.optimizer.optimize(np.array(angles0), target)
Can you create a Python 3 function that calculates joint angles and returns it.
You are a Python code analyst, evaluating scripts for potential improvements.
Return translation matrix in homogeneous coordinates.
Explain what the following Python 3 code does def matrix(self, _): x, y, z = self.coord return np.array([ [1., 0., 0., x], [0., 1., 0., y], [0., 0., 1., z], [0., 0., 0., 1.] ])
As a Python code composer, you craft elegant and concise scripts.
Return rotation matrix in homogeneous coordinates.
Explain what the following Python 3 code does def matrix(self, angle): _rot_mat = { 'x': self._x_rot, 'y': self._y_rot, 'z': self._z_rot } return _rot_mat[self.axis](angle)
As a Python code composer, you craft elegant and concise scripts.
def set_logger(self, logger): """ Set a logger to send debug messages to Parameters ---------- logger : `Logger <http://docs.python.org/2/library/logging.html>`_ A python logger used to get debugging output from this module. """ self.__logger = logger...
Implement a Python 3 function for setting a logger to send debug messages to the current session
You are a Python code generator, capable of creating scripts from specifications.
Returns the version number of the Lending Club Investor tool Returns ------- string A version number of the Lending Club Investor tool
Can you tell what is the following Python 3 function doing def version(self): this_path = os.path.dirname(os.path.realpath(__file__)) version_file = os.path.join(this_path, 'VERSION') return open(version_file).read().strip()
As a Python code translator, you convert algorithms and pseudocode into Python.
def authenticate(self, email=None, password=None): """ Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns -...
Can you create a Python 3 function that attempts to authenticate the user.
You are a Python code architect, reviewing and designing scalable and efficient code
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
Can you write a function in Python 3 where it returns the cash balance available for investing the account.
As a python code expert, you are capable of creating scripts from specifications.
def get_portfolio_list(self, names_only=False): """ Get your list of named portfolios from the lendingclub.com Parameters ---------- names_only : boolean, optional If set to True, the function will return a list of portfolio names, instead of portfolio objects ...
Write a Python 3 function that can get your list of named portfolios from the lendingclub. com base object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Assign a note to a named portfolio.
Explain what the following Python 3 code does def assign_to_portfolio(self, portfolio_name, loan_id, order_id): response = None assert type(loan_id) == type(order_id), "Both loan_id and order_id need to be the same type" assert type(loan_id) in (int, list), "loan_id and order_id can only be int...
As a Python code translator, you convert algorithms and pseudocode into Python.
def search(self, filters=None, start_index=0, limit=100): """ Search for a list of notes that can be invested in. (similar to searching for notes in the Browse section on the site) Parameters ---------- filters : lendingclub.filters.*, optional The filter to ...
How would you implement a function in Python 3 that searches for a list of notes that can be invested in.
You are a Python code architect, reviewing and designing scalable and efficient code
def build_portfolio(self, cash, max_per_note=25, min_percent=0, max_percent=20, filters=None, automatically_invest=False, do_not_clear_staging=False): """ Returns a list of loan notes that are diversified by your min/max percent request and filters. One way to invest in these loan notes, is to s...
Create a Python 3 function to build a list of loan notes that are diversified by your min_percent request and max_percent request.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a specific loan note by ID.
Here you have a function in Python 3, explain what it does def get_note(self, note_id): index = 0 while True: notes = self.my_notes(start_index=index, sort_by='noteId') if notes['result'] != 'success': break # If the first note has a higher ID, we'v...
You are a Python code generator, capable of creating scripts from specifications.
def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None): """ Search for notes you are invested in. Use the parameters to define how to search. Passing no parameters is the same as calling `my_notes(get_all=True)` Parameters ...
Can you write a function in Python 3 where it searches for the notes that are invested in.
As a Python code analyst, you investigate and solve complex coding mysteries
Add a loan and amount to your order.
Can you generate a brief explanation for the following Python 3 code def add(self, loan_id, amount): assert amount > 0 and amount % 25 == 0, 'Amount must be a multiple of 25' assert type(amount) in (float, int), 'Amount must be a number' if type(loan_id) is dict: loan = loan_id ...
As a Python code composer, you craft elegant and concise scripts.
Adds a batch of loans to your order.
How would you explain what the following Python 3 function does def add_batch(self, loans, batch_amount=None): assert batch_amount is None or batch_amount % 25 == 0, 'batch_amount must be a multiple of 25' # Add each loan assert type(loans) is list, 'The loans property must be a list. (not {0})...
You are a Python code analyst, evaluating scripts for potential improvements.
Place the order with LendingClub and assign the loan notes to the portfolio.
Can you tell what is the following Python 3 function doing def execute(self, portfolio_name=None): assert self.order_id == 0, 'This order has already been place. Start a new order.' assert len(self.loans) > 0, 'There aren\'t any loans in your order' # Place the order self.__stage_order(...
You are a Python code analyst, evaluating scripts for potential improvements.
def assign_to_portfolio(self, portfolio_name=None): """ Assign all the notes in this order to a portfolio Parameters ---------- portfolio_name -- The name of the portfolio to assign it to (new or existing) Raises ------ LendingClubError Retu...
Can you write a function in Python 3 where it assigns all the notes in this order to a portfolio.
You are a Python code architect, reviewing and designing scalable and efficient code
def __stage_order(self): """ Add all the loans to the LC order session """ # Skip staging...probably not a good idea...you've been warned if self.__already_staged is True and self.__i_know_what_im_doing is True: self.__log('Not staging the order...I hope you know wha...
How would you code a function in Python 3 to stage all the loans in the batch to the order session
You are a Python code architect, reviewing and designing scalable and efficient code
def __get_strut_token(self): """ Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value ...
Write a Python 3 script for getting the struts token from the place order HTML.
You are a Python code architect, reviewing and designing scalable and efficient code
def __place_order(self, token): """ Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID. """ ...
Can you write a function in Python 3 where it places the order in the struts token.
You are a Python code analyst, evaluating scripts for potential improvements.
def __continue_session(self): """ Check if the time since the last HTTP request is under the session timeout limit. If it's been too long since the last request attempt to authenticate again. """ now = time.time() diff = abs(now - self.last_request_time) t...
Can you write a function in Python 3 where it checks if the time since the last HTTP request is under the session timeout limit. If it is too long since the last HTTP request attempt to authenticate again.
You are a Python code generator, capable of creating scripts from specifications.
Builds a LendingClub URL from a path.
Can you generate a brief explanation for the following Python 3 code def build_url(self, path): url = '{0}{1}'.format(self.base_url, path) url = re.sub('([^:])//', '\\1/', url) # Remove double slashes return url
You are a Python code analyst, evaluating scripts for potential improvements.
Authenticate with LendingClub and preserve the user session for future requests.
Can you tell what is the following Python 3 function doing def authenticate(self, email=None, password=None): # Get email and password if email is None: email = self.email else: self.email = email if password is None: password = self.__pass e...
You are a Python code generator, capable of creating scripts from specifications.
Returns True if we can access the site with the given ID.
Given the following Python 3 function, write the documentation def is_site_available(self): try: response = requests.head(self.base_url) status = response.status_code return 200 <= status < 400 # Returns true if the status code is greater than 200 and less than 400 e...
As a python code expert, you are capable of creating scripts from specifications.
Send a HTTP request to the LendingClub.
How would you explain what the following Python 3 function does def request(self, method, path, query=None, data=None, redirects=True): # Check session time self.__continue_session() try: url = self.build_url(path) method = method.upper() self.__log('{0} re...
You are a Python code analyst, evaluating scripts for potential improvements.
def post(self, path, query=None, data=None, redirects=True): """ POST request wrapper for :func:`request()` """ return self.request('POST', path, query, data, redirects)
Create a Python 3 function to wrap for request function for POST requests.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get(self, path, query=None, redirects=True): """ GET request wrapper for :func:`request()` """ return self.request('GET', path, query, None, redirects)
How would you implement a function in Python 3 that wraps for request method for GET requests.
As a Python code composer, you craft elegant and concise scripts.
HEAD request wrapper for the request method.
Here you have a function in Python 3, explain what it does def head(self, path, query=None, data=None, redirects=True): return self.request('HEAD', path, query, None, redirects)
You are a Python code analyst, evaluating scripts for potential improvements.
Check the JSON response object for the success flag
Can you generate the documentation for the following Python 3 function def json_success(self, json): if type(json) is dict and 'result' in json and json['result'] == 'success': return True return False
As a Python code analyst, you investigate and solve complex coding mysteries
def __merge_values(self, from_dict, to_dict): """ Merge dictionary objects recursively, by only updating keys existing in to_dict """ for key, value in from_dict.iteritems(): # Only if the key already exists if key in to_dict: # Make sure the val...
Write a Python 3 function for merging dictionary objects recursively, by only updating keys existing in to_dict
You are a Python code architect, reviewing and designing scalable and efficient code
Adjust the grades list.
How would you explain what the following Python 3 function does def __normalize_grades(self): if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: self['grades']['All'] = False ...
As a Python code composer, you craft elegant and concise scripts.
def __normalize_progress(self): """ Adjust the funding progress filter to be a factor of 10 """ progress = self['funding_progress'] if progress % 10 != 0: progress = round(float(progress) / 10) progress = int(progress) * 10 self['funding_prog...
How would you code a function in Python 3 to adjust the funding progress filter to be a factor of 10
You are a Python code analyst, evaluating scripts for potential improvements.
Adjusts the values of the filters to be correct.
Given the following Python 3 function, write the documentation def __normalize(self): # Don't normalize if we're already normalizing or intializing if self.__normalizing is True or self.__initialized is False: return self.__normalizing = True self.__normalize_grades() ...
As a python code expert, you are capable of creating scripts from specifications.
Validate a single loan record against the filters.
Explain what the following Python 3 code does def validate_one(self, loan): assert type(loan) is dict, 'loan parameter must be a dictionary object' # Map the loan value keys to the filter keys req = { 'loanGUID': 'loan_id', 'loanGrade': 'grade', 'loanLength':...
As a Python code translator, you convert algorithms and pseudocode into Python.
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compil...
Implement a function in Python 3 to return the JSON string that LendingClub expects for it s search
As a Python code composer, you craft elegant and concise scripts.
Get a list of all your saved filters
Make a summary of the following Python 3 code def all_filters(lc): filters = [] response = lc.session.get('/browse/getSavedFiltersAj.action') json_response = response.json() # Load all filters if lc.session.json_success(json_response): for saved in json_response['fi...
As a python code expert, you are capable of creating scripts from specifications.
Load the filter from the server and store it in the self. name attribute.
Can you tell what is the following Python 3 function doing def load(self): # Attempt to load the saved filter payload = { 'id': self.id } response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload) self.response = response json_response =...
As a python code expert, you are capable of creating scripts from specifications.
Analyze the filter JSON and attempt to parse out the individual filters.
Can you generate the documentation for the following Python 3 function def __analyze(self): filter_values = {} # ID to filter name mapping name_map = { 10: 'grades', 11: 'loan_purpose', 13: 'approved', 15: 'funding_progress', 38: 'excl...
You are a Python code architect, reviewing and designing scalable and efficient code
Copy origin to out and return it.
Can you generate a brief explanation for the following Python 3 code def _float_copy_to_out(out, origin): if out is None: out = origin / 1 # The division forces cast to a floating point type elif out is not origin: np.copyto(out, origin) return out
You are a Python code analyst, evaluating scripts for potential improvements.
Real implementation of u_centered.
Given the following Python 3 function, write the documentation def _u_centered_imp(a, out=None): out = _float_copy_to_out(out, a) dim = np.size(a, 0) u_mu = np.sum(a) / ((dim - 1) * (dim - 2)) sum_cols = np.sum(a, 0, keepdims=True) sum_rows = np.sum(a, 1, keepdims=True) u_mu_cols = np.ones((di...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the inner product of two arrays a and b.
Make a summary of the following Python 3 code def u_product(a, b): n = np.size(a, 0) return np.sum(a * b) / (n * (n - 3))
You are a Python code architect, reviewing and designing scalable and efficient code
r Returns the orthogonal projection function over a matrix.
Given the following Python 3 function, write the documentation def u_complementary_projection(a): proj = u_projection(a) def projection(a): """ Orthogonal projection over the complementary space. This function was returned by :code:`u_complementary_projection`. The complete usa...
As a Python code composer, you craft elegant and concise scripts.
Compute a centered distance matrix given a matrix.
Here you have a function in Python 3, explain what it does def _distance_matrix_generic(x, centering, exponent=1): _check_valid_dcov_exponent(exponent) x = _transform_to_2d(x) # Calculate distance matrices a = distances.pairwise_distances(x, exponent=exponent) # Double centering a = centering...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _af_inv_scaled(x): """Scale a random vector for using the affinely invariant measures""" x = _transform_to_2d(x) cov_matrix = np.atleast_2d(np.cov(x, rowvar=False)) cov_matrix_power = _mat_sqrt_inv(cov_matrix) return x.dot(cov_matrix_power)
Create a Python 3 function to scale a random vector for using the affinely invariant measures
As a Python code translator, you convert algorithms and pseudocode into Python.
def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------...
Implement a function in Python 3 to compute the partial distance covariance estimator for the given random vectors x y and z.
You are a Python code analyst, evaluating scripts for potential improvements.
Partial distance correlation estimator.
Can you tell what is the following Python 3 function doing def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) aa = u_product(a, a) bb = u_product(b, b) cc = u_product(c, c) ab = u_product...
You are a Python code generator, capable of creating scripts from specifications.
Compute energy distance with precalculated distance matrices.
Can you tell what is the following Python 3 function doing def _energy_distance_from_distance_matrices( distance_xx, distance_yy, distance_xy): """Compute energy distance with precalculated distance matrices.""" return (2 * np.mean(distance_xy) - np.mean(distance_xx) - np.mean(distance_yy))
As a Python code composer, you craft elegant and concise scripts.
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product, exponent=1): """Compute generic squared stats.""" a = matrix_centered(x, exponent=exponent) b = matrix_centered(y, exponent=exponent) covariance_xy_sqr = product(a, b) variance_x_sqr = produc...
How would you implement a function in Python 3 that computes generic squared stats.
As a Python code translator, you convert algorithms and pseudocode into Python.
Biased distance correlation estimator between two matrices.
Can you generate the documentation for the following Python 3 function def _distance_correlation_sqr_naive(x, y, exponent=1): return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, exponent=exponent).correlation_xy
As a Python code translator, you convert algorithms and pseudocode into Python.
Bias - correcteded distance correlation estimator between two matrices.
Can you generate the documentation for the following Python 3 function def _u_distance_correlation_sqr_naive(x, y, exponent=1): return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_matrix, product=u_product, exponent=exponent).correlation_xy
As a Python code analyst, you investigate and solve complex coding mysteries
Check if the fast algorithm for distance stats can be used.
Explain what the following Python 3 code does def _can_use_fast_algorithm(x, y, exponent=1): return (_is_random_variable(x) and _is_random_variable(y) and x.shape[0] > 3 and y.shape[0] > 3 and exponent == 1)
You are a Python code generator, capable of creating scripts from specifications.
Fast algorithm for the squared distance covariance.
Make a summary of the following Python 3 code def _distance_covariance_sqr_fast_generic( x, y, unbiased=False): # pylint:disable=too-many-locals # This function has many locals so it can be compared # with the original algorithm. """Fast algorithm for the squared distance covariance.""" x = np....
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the distance stats using the fast algorithm.
How would you explain what the following Python 3 function does def _distance_stats_sqr_fast_generic(x, y, dcov_function): covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denomi...
You are a Python code generator, capable of creating scripts from specifications.
Calculates the squared distance covariance between two random vectors.
Can you generate the documentation for the following Python 3 function def distance_covariance_sqr(x, y, **kwargs): if _can_use_fast_algorithm(x, y, **kwargs): return _distance_covariance_sqr_fast(x, y) else: return _distance_covariance_sqr_naive(x, y, **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
This function computes the squared distance covariance and squared distance correlation between two random vectors and the individual squared distance variances.
Given the following Python 3 function, write the documentation def distance_stats_sqr(x, y, **kwargs): if _can_use_fast_algorithm(x, y, **kwargs): return _distance_stats_sqr_fast(x, y) else: return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix,...
You are a Python code architect, reviewing and designing scalable and efficient code
This function computes the unbiased un
How would you explain what the following Python 3 function does def u_distance_stats_sqr(x, y, **kwargs): if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_stats_sqr_fast(x, y) else: return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_u_distance_...
You are a Python code analyst, evaluating scripts for potential improvements.
This function computes the distance covariance and distance correlation between two random vectors and the individual distance variances.
Can you generate a brief explanation for the following Python 3 code def distance_stats(x, y, **kwargs): return Stats(*[_sqrt(s) for s in distance_stats_sqr(x, y, **kwargs)])
You are a Python code generator, capable of creating scripts from specifications.
Returns the squared distance correlation between two random vectors.
Can you tell what is the following Python 3 function doing def u_distance_correlation_sqr(x, y, **kwargs): if _can_use_fast_algorithm(x, y, **kwargs): return _u_distance_correlation_sqr_fast(x, y) else: return _u_distance_correlation_sqr_naive(x, y, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
Calculates the squared affinely invariant distance correlation between two random vectors.
Given the following Python 3 function, write the documentation def distance_correlation_af_inv_sqr(x, y): x = _af_inv_scaled(x) y = _af_inv_scaled(y) correlation = distance_correlation_sqr(x, y) return 0 if np.isnan(correlation) else correlation
As a Python code analyst, you investigate and solve complex coding mysteries
A function that computes the dependency measure between each pair of elements.
Explain what the following Python 3 code does def pairwise(function, x, y=None, **kwargs): return _pairwise_imp(function, x, y, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
Compile a function using a jit compiler.
Make a summary of the following Python 3 code def _jit(function): import sys compiled = numba.jit(function) if hasattr(sys, '_called_from_test'): return function else: # pragma: no cover return compiled
You are a Python code analyst, evaluating scripts for potential improvements.
def _sqrt(x): """ Return square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method. """ x = np.clip(x, a_min=0, a_max=None) try: return np.sqrt(x) except AttributeError: exponen...
Can you write a function in Python 3 where it returns square root of an ndarray. This sqrt function for ndarrays tries to use the exponentiation operator if the objects stored do not supply a sqrt method.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert vectors to column matrices to always have a 2d shape.
Explain what the following Python 3 code does def _transform_to_2d(t): t = np.asarray(t) dim = len(t.shape) assert dim <= 2 if dim < 2: t = np.atleast_2d(t).T return t
As a Python code analyst, you investigate and solve complex coding mysteries
Return True if the array can be safely converted to double.
Can you generate a brief explanation for the following Python 3 code def _can_be_double(x): return ((np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize <= np.dtype(float).itemsize) or (np.issubdtype(x.dtype, np.signedinteger) and np.can_cast(x, float)))
As a Python code composer, you craft elegant and concise scripts.
Pairwise distance between the points in two sets.
Can you generate a brief explanation for the following Python 3 code def _cdist_scipy(x, y, exponent=1): metric = 'euclidean' if exponent != 1: metric = 'sqeuclidean' distances = _spatial.distance.cdist(x, y, metric=metric) if exponent != 1: distances **= exponent / 2 return dist...
You are a Python code analyst, evaluating scripts for potential improvements.
Pairwise distance between points in a set.
Can you tell what is the following Python 3 function doing def _pdist(x, exponent=1): if _can_be_double(x): return _pdist_scipy(x, exponent) else: return _cdist_naive(x, x, exponent)
As a python code expert, you are capable of creating scripts from specifications.
Pairwise distance between points in two sets.
Make a summary of the following Python 3 code def _cdist(x, y, exponent=1): if _can_be_double(x) and _can_be_double(y): return _cdist_scipy(x, y, exponent) else: return _cdist_naive(x, y, exponent)
You are a Python code analyst, evaluating scripts for potential improvements.
This method generates the response header for the current resource.
How would you explain what the following Python 3 function does def respond(self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None): """ Respond to the request. This generates the :attr:`mohawk.Receiv...
As a python code expert, you are capable of creating scripts from specifications.
Calculates a hash for a given payload.
Explain what the following Python 3 code does def calculate_payload_hash(payload, algorithm, content_type): p_hash = hashlib.new(algorithm) parts = [] parts.append('hawk.' + str(HAWK_VER) + '.payload\n') parts.append(parse_content_type(content_type) + '\n') parts.append(payload or '') parts.app...
As a Python code composer, you craft elegant and concise scripts.
def calculate_mac(mac_type, resource, content_hash): """Calculates a message authorization code (MAC).""" normalized = normalize_string(mac_type, resource, content_hash) log.debug(u'normalized resource for mac calc: {norm}' .format(norm=normalized)) digestmod = getattr(hashlib, resource.cr...
Write a Python 3 function for calculating a message authorization code ( MAC ).
As a Python code composer, you craft elegant and concise scripts.
def calculate_ts_mac(ts, credentials): """Calculates a message authorization code (MAC) for a timestamp.""" normalized = ('hawk.{hawk_ver}.ts\n{ts}\n' .format(hawk_ver=HAWK_VER, ts=ts)) log.debug(u'normalized resource for ts mac calc: {norm}' .format(norm=normalized)) dig...
Write a Python 3 script to calculate a message authorization code for a timestamp.
You are a Python code architect, reviewing and designing scalable and efficient code
def normalize_string(mac_type, resource, content_hash): """Serializes mac_type and resource into a HAWK string.""" normalized = [ 'hawk.' + str(HAWK_VER) + '.' + mac_type, normalize_header_attr(resource.timestamp), normalize_header_attr(resource.nonce), normalize_header_attr(res...
Can you create a Python 3 function that serializes mac_type and resource into a HAWK string.
As a python code expert, you are capable of creating scripts from specifications.
def parse_authorization_header(auth_header): """ Example Authorization header: 'Hawk id="dh37fgj492je", ts="1367076201", nonce="NPHgnG", ext="and welcome!", mac="CeWHy4d9kbLGhDlkyw2Nh3PJ7SDOdZDa267KH4ZaNMY="' """ if len(auth_header) > MAX_LENGTH: raise BadHeaderValue('Header exc...
Create a Python 3 function to parse an authorization header into a single object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_bewit(resource): """ Returns a bewit identifier for the resource as a string. :param resource: Resource to generate a bewit for :type resource: `mohawk.base.Resource` """ if resource.method != 'GET': raise ValueError('bewits can only be generated for GET requests') i...
Write a Python 3 function for returning a bewit identifier for the resource as a string.
As a Python code composer, you craft elegant and concise scripts.
def parse_bewit(bewit): """ Returns a `bewittuple` representing the parts of an encoded bewit string. This has the following named attributes: (id, expiration, mac, ext) :param bewit: A base64 encoded bewit string :type bewit: str """ decoded_bewit = b64decode(bewit).decode(...
Write a Python 3 script for parsing a base64 encoded bewit string into a bewittuple.
As a python code expert, you are capable of creating scripts from specifications.
Strips the bewit parameter out of a url.
Explain what the following Python 3 code does def strip_bewit(url): m = re.search('[?&]bewit=([^&]+)', url) if not m: raise InvalidBewit('no bewit data found') bewit = m.group(1) stripped_url = url[:m.start()] + url[m.end():] return bewit, stripped_url
You are a Python code architect, reviewing and designing scalable and efficient code
def check_bewit(url, credential_lookup, now=None): """ Validates the given bewit. Returns True if the resource has a valid bewit parameter attached, or raises a subclass of HawkFail otherwise. :param credential_lookup: Callable to look up the credentials dict by sender ID. The cred...
Write a Python 3 script for checking if a given bewit is valid and raises a subclass of HawkFail otherwise.
As a Python code analyst, you investigate and solve complex coding mysteries
def accept_response(self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds...
Write a Python 3 function for accepting a response to the Hawk server.
You are a Python code analyst, evaluating scripts for potential improvements.
def current_state(self): """ Returns a ``field -> value`` dict of the current state of the instance. """ field_names = set() [field_names.add(f.name) for f in self._meta.local_fields] [field_names.add(f.attname) for f in self._meta.local_fields] return dict([(fiel...
How would you implement a function in Python 3 that returns a dict of the current state of the instance.
You are a Python code architect, reviewing and designing scalable and efficient code
def was_persisted(self): """ Returns true if the instance was persisted (saved) in its old state. Examples:: >>> user = User() >>> user.save() >>> user.was_persisted() False >>> user = User.objects.get(pk=1) >>> u...
How would you implement a function in Python 3 that returns True if the user was persisted in its old state.
You are a Python code architect, reviewing and designing scalable and efficient code
Removes trailing colons from the URI back to the first non - colon.
Can you generate the documentation for the following Python 3 function def _trim(cls, s): reverse = s[::-1] idx = 0 for i in range(0, len(reverse)): if reverse[i] == ":": idx += 1 else: break # Return the substring after all traili...
As a python code expert, you are capable of creating scripts from specifications.
def _create_cpe_parts(self, system, components): """ Create the structure to store the input type of system associated with components of CPE Name (hardware, operating system and software). :param string system: type of system associated with CPE Name :param dict components: CPE...
How would you implement a function in Python 3 that creates the structure to store the input type of system associated with CPE Name components of CPE Name.
As a Python code composer, you craft elegant and concise scripts.
def _get_attribute_components(self, att): """ Returns the component list of input attribute. :param string att: Attribute name to get :returns: List of Component objects of the attribute in CPE Name :rtype: list :exception: ValueError - invalid attribute name """...
Implement a Python 3 function for returning the list of Component objects of the attribute in CPE Name
As a python code expert, you are capable of creating scripts from specifications.
def _pack_edition(self): """ Pack the values of the five arguments into the simple edition component. If all the values are blank, just return a blank. :returns: "edition", "sw_edition", "target_sw", "target_hw" and "other" attributes packed in a only value :rtype: s...
Create a Python 3 function to pack the values of the five arguments into the simple edition component and return the string representation of the edition attribute.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the CPE Name as URI string of version 2. 3.
Here you have a function in Python 3, explain what it does def as_uri_2_3(self): uri = [] uri.append("cpe:/") ordered_comp_parts = { 0: CPEComponent.ATT_PART, 1: CPEComponent.ATT_VENDOR, 2: CPEComponent.ATT_PRODUCT, 3: CPEComponent.ATT_VERSION, ...
You are a Python code architect, reviewing and designing scalable and efficient code
def as_wfn(self): """ Returns the CPE Name as Well-Formed Name string of version 2.3. :return: CPE Name as WFN string :rtype: string :exception: TypeError - incompatible version """ from .cpe2_3_wfn import CPE2_3_WFN wfn = [] wfn.append(CPE2_3_W...
Write a Python 3 script for returning the CPE Name as Well - Formed Name string of version 2. 3.
As a python code expert, you are capable of creating scripts from specifications.
def as_fs(self): """ Returns the CPE Name as formatted string of version 2.3. :returns: CPE Name as formatted string :rtype: string :exception: TypeError - incompatible version """ fs = [] fs.append("cpe:2.3:") for i in range(0, len(CPEComponent...
Can you create a Python 3 function that returns the CPE Name as formatted string of version 2. 3.
As a Python code composer, you craft elegant and concise scripts.
def _is_alphanum(cls, c): """ Returns True if c is an uppercase letter, a lowercase letter, a digit or an underscore, otherwise False. :param string c: Character to check :returns: True if char is alphanumeric or an underscore, False otherwise :rtype: boolean...
Write a Python 3 script for checking if the character c is an alphanumeric character.
As a Python code composer, you craft elegant and concise scripts.
Return the appropriate percent - encoding of character c.
Given the following Python 3 function, write the documentation def _pct_encode_uri(cls, c): CPEComponentSimple.spechar_to_pce['-'] = c # bound without encoding CPEComponentSimple.spechar_to_pce['.'] = c # bound without encoding return CPEComponentSimple.spechar_to_pce[c]
As a Python code analyst, you investigate and solve complex coding mysteries