output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
This is a decorator that can customize the rest API that transmute generates.
Make a summary of the following Python 3 code def describe(**kwargs): # if we have a single method, make it a list. if isinstance(kwargs.get("paths"), string_type): kwargs["paths"] = [kwargs["paths"]] if isinstance(kwargs.get("methods"), string_type): kwargs["methods"] = [kwargs["methods"]] ...
You are a Python code generator, capable of creating scripts from specifications.
add a swagger. json route and a swagger. html route
Can you generate a brief explanation for the following Python 3 code def add_swagger(app, json_route, html_route): app.router.add_route('GET', json_route, create_swagger_json_handler(app)) add_swagger_api_route(app, html_route, json_route)
As a Python code analyst, you investigate and solve complex coding mysteries
def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagger statics page. app: the aiohttp app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. """ st...
Implement a Python 3 function for adding a route to the swagger api.
You are a Python code generator, capable of creating scripts from specifications.
def create_swagger_json_handler(app, **kwargs): """ Create a handler that returns the swagger definition for an application. This method assumes the application is using the TransmuteUrlDispatcher as the router. """ spec = get_swagger_spec(app).swagger_definition(**kwargs) encoded_spec...
Write a Python 3 function that can create a handler that returns the swagger definition for an application.
As a python code expert, you are capable of creating scripts from specifications.
def create_multispan_plots(tag_ids): """Create detail plots (first row) and total block(second row) of experiments. Args: tag_ids: list of tag-dictionaries, where the dictionaries must have fields 'name' (used for naming) and 'id' (used for numbering axis_dict) Re...
How would you implement a function in Python 3 that creates detail plots for the single - term experiment.
As a Python code composer, you craft elegant and concise scripts.
Function used by all angle conversion functions
Make a summary of the following Python 3 code def change_angles(method, theta, tol=1e-10): try: theta_new = np.zeros(theta.shape) for i, thet in enumerate(theta): try: # theta is vector theta_new[i] = method(thet, tol) except: #...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_point(theta_ik, theta_jk, Pi, Pj): """ Calculate coordinates of point Pk given two points Pi, Pj and inner angles. :param theta_ik: Inner angle at Pi to Pk. :param theta_jk: Inner angle at Pj to Pk. :param Pi: Coordinates of point Pi. :param Pj: Coordinates of point Pj. :return: Coordinate...
Can you implement a function in Python 3 that calculates coordinates of point Pk given two points Pi Pj and inner angles.
As a python code expert, you are capable of creating scripts from specifications.
return a list of the content types this set supports
Can you generate a brief explanation for the following Python 3 code def keys(self): return_value = [] for s in self.serializers: return_value += s.content_type return return_value
You are a Python code generator, capable of creating scripts from specifications.
def get_parameters(signature, transmute_attrs, arguments_to_ignore=None): """given a function, categorize which arguments should be passed by what types of parameters. The choices are: * query parameters: passed in as query parameters in the url * body parameters: retrieved from the request body (inclu...
Create a Python 3 function to give a function and a TransmuteAttributes object and a set of parameters that can be used to generate the transmute parameters for the current language.
As a python code expert, you are capable of creating scripts from specifications.
def _extract_path_parameters_from_paths(paths): """ from a list of paths, return back a list of the arguments present in those paths. the arguments available in all of the paths must match: if not, an exception will be raised. """ params = set() for path in paths: parts = PART_R...
How would you implement a function in Python 3 that extracts the parameters present in a list of paths.
As a Python code composer, you craft elegant and concise scripts.
def _build_body_schema(serializer, body_parameters): """ body is built differently, since it's a single argument no matter what. """ description = "" if isinstance(body_parameters, Param): schema = serializer.to_json_schema(body_parameters.arginfo.type) description = body_parameters.descript...
Implement a Python 3 function for building the schema for the body parameter.
As a Python code translator, you convert algorithms and pseudocode into Python.
Parses a 17 bytes packet in the Wind format and returns a dictionary containing the parsed values.
Can you generate the documentation for the following Python 3 function def parse(self, data): self.validate_packet(data) results = self.parse_header_part(data) sub_type = results['packet_subtype'] id_ = self.dump_hex(data[4:6]) direction = data[6] * 256 + data[7] if s...
You are a Python code generator, capable of creating scripts from specifications.
Fit X to an anchor set by applying optimal translation rotation and reflection.
Make a summary of the following Python 3 code def procrustes(anchors, X, scale=True, print_out=False): def centralize(X): n = X.shape[0] ones = np.ones((n, 1)) return X - np.multiply(1 / n * np.dot(ones.T, X), ones) m = anchors.shape[0] N, d = X.shape assert m >= d, 'Have to give...
You are a Python code generator, capable of creating scripts from specifications.
def reconstruct_emds(edm, Om, all_points, method=None, **kwargs): """ Reconstruct point set using E(dge)-MDS. """ from .point_set import dm_from_edm N = all_points.shape[0] d = all_points.shape[1] dm = dm_from_edm(edm) if method is None: from .mds import superMDS Xhat, __ = s...
Can you create a Python 3 function that reconstructs point set using E ( dge ) - MDS.
You are a Python code analyst, evaluating scripts for potential improvements.
Reconstruct point set from angle and distance measurements using coordinate difference matrices.
Given the following Python 3 function, write the documentation def reconstruct_cdm(dm, absolute_angles, all_points, W=None): from pylocus.point_set import dmi_from_V, sdm_from_dmi, get_V from pylocus.mds import signedMDS N = all_points.shape[0] V = get_V(absolute_angles, dm) dmx = dmi_from_V(V, 0...
You are a Python code architect, reviewing and designing scalable and efficient code
def reconstruct_mds(edm, all_points, completion='optspace', mask=None, method='geometric', print_out=False, n=1): """ Reconstruct point set using MDS and matrix completion algorithms. """ from .point_set import dm_from_edm from .mds import MDS N = all_points.shape[0] d = all_points.shape[1] ...
How would you implement a function in Python 3 that reconstructs point set using MDS and matrix completion algorithms.
As a Python code composer, you craft elegant and concise scripts.
Reconstruct point set using semi - definite rank relaxation.
Can you tell what is the following Python 3 function doing def reconstruct_sdp(edm, all_points, W=None, print_out=False, lamda=1000, **kwargs): from .edm_completion import semidefinite_relaxation edm_complete = semidefinite_relaxation( edm, lamda=lamda, W=W, print_out=print_out, **kwargs) Xhat = rec...
You are a Python code generator, capable of creating scripts from specifications.
def reconstruct_srls(edm, all_points, W=None, print_out=False, n=1, rescale=False, z=None): """ Reconstruct point set using S(quared)R(ange)L(east)S(quares) method. """ from .lateration import SRLS, get_lateration_parameters Y = all_points.copy() indices = range(n) for index...
How would you code a function in Python 3 to reconstruct the point set using S ( squared R ) L ( squares ) method.
You are a Python code generator, capable of creating scripts from specifications.
def reconstruct_acd(edm, X0, W=None, print_out=False, tol=1e-10, sweeps=10): """ Reconstruct point set using alternating coordinate descent. :param X0: Nxd matrix of starting points. :param tol: Stopping criterion: if the stepsize in all coordinate directions is less than tol for 2 consecu...
Can you create a Python 3 function that reconstructs the acd from the given ELM matrix X0 using alternating coordinate descent.
As a Python code analyst, you investigate and solve complex coding mysteries
def reconstruct_dwmds(edm, X0, W=None, n=None, r=None, X_bar=None, print_out=False, tol=1e-10, sweeps=100): """ Reconstruct point set using d(istributed)w(eighted) MDS. Refer to paper "Distributed Weighted-Multidimensional Scaling for Node Localization in Sensor Networks" for implementation details (doi.o...
Create a Python 3 function for reconstructing point set using d ( istributed ) w (eighted ) MDS.
You are a Python code architect, reviewing and designing scalable and efficient code
def parse(self, data): """Parse a 12 bytes packet in the Rain format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 11, '...
Create a Python 3 function for parsing a 12 byte packet in the Rain format and returns a dictionary containing the parsed data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get parameters relevant for lateration from full all_points edm and W.
Given the following Python 3 function, write the documentation def get_lateration_parameters(all_points, indices, index, edm, W=None): if W is None: W = np.ones(edm.shape) # delete points that are not considered anchors anchors = np.delete(all_points, indices, axis=0) r2 = np.delete(edm[index, ...
As a Python code analyst, you investigate and solve complex coding mysteries
def SRLS(anchors, w, r2, rescale=False, z=None, print_out=False): '''Squared range least squares (SRLS) Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points (Nxd) :param w: weights for the measurements (Nx1) :para...
Write a Python 3 script for squaring range least squares algorithm written by A. Beck P. Stoica in Approximate and Exact solutions of Source Localization Problems.
You are a Python code analyst, evaluating scripts for potential improvements.
Algorithm used by pozyx. io
Can you generate the documentation for the following Python 3 function def PozyxLS(anchors, W, r2, print_out=False): ''' Algorithm used by pozyx (https://www.pozyx.io/Documentation/how_does_positioning_work) :param anchors: anchor points :param r2: squared distances from anchors to point x. :returns: ...
As a python code expert, you are capable of creating scripts from specifications.
def RLS(anchors, W, r, print_out=False, grid=None, num_points=10): """ Range least squares (RLS) using grid search. Algorithm written by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points :param r2: squared distances from anchors to poi...
How would you code a function in Python 3 to range least squares algorithm.
As a Python code composer, you craft elegant and concise scripts.
def RLS_SDR(anchors, W, r, print_out=False): """ Range least squares (RLS) using SDR. Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems". :param anchors: anchor points :param r2: squared distances from anchors to point x. :return: estimated po...
Write a Python 3 script to range least squares algorithm cited by A. Beck P. Stoica in Approximate and Exact solutions of Source Localization Problems.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _join_parameters(base, nxt): """ join parameters from the lhs to the rhs, if compatible. """ if nxt is None: return base if isinstance(base, set) and isinstance(nxt, set): return base | nxt else: return nxt
Implement a function in Python 3 to join parameters from the lhs to the rhs
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_swagger_operation(self, context=default_context): """ get the swagger_schema operation representation. """ consumes = produces = context.contenttype_serializers.keys() parameters = get_swagger_parameters(self.parameters, context) responses = { "400": R...
Write a Python 3 function that can get the swagger_schema operation representation.
As a python code expert, you are capable of creating scripts from specifications.
Process a result object and return the appropriate result object.
Can you generate the documentation for the following Python 3 function def process_result(self, context, result_body, exc, content_type): return process_result(self, context, result_body, exc, content_type)
You are a Python code architect, reviewing and designing scalable and efficient code
def _parse_response_types(argspec, attrs): """ from the given parameters, return back the response type dictionaries. """ return_type = argspec.annotations.get("return") or None type_description = attrs.parameter_descriptions.get("return", "") response_types = attrs.respo...
Write a Python 3 script for parsing the response types from the given parameters and return back the response types dictionary.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a swagger. html file from the given swagger statics and swagger json path.
Explain what the following Python 3 code does def generate_swagger_html(swagger_static_root, swagger_json_url): tmpl = _get_template("swagger.html") return tmpl.render( swagger_root=swagger_static_root, swagger_json_url=swagger_json_url )
As a Python code translator, you convert algorithms and pseudocode into Python.
def add_func(self, transmute_func, transmute_context): """ add a transmute function's swagger definition to the spec """ swagger_path = transmute_func.get_swagger_path(transmute_context) for p in transmute_func.paths: self.add_path(p, swagger_path)
Write a Python 3 function that can add a transmute function to the spec
You are a Python code analyst, evaluating scripts for potential improvements.
Add the path items to the swagger file.
Make a summary of the following Python 3 code def add_path(self, path, path_item): if path not in self._swagger: self._swagger[path] = path_item else: for method, definition in path_item.items(): if definition is not None: setattr(self._swagger...
You are a Python code generator, capable of creating scripts from specifications.
def swagger_definition(self, base_path=None, **kwargs): """ return a valid swagger spec, with the values passed. """ return Swagger( { "info": Info( { key: kwargs.get(key, self.DEFAULT_INFO.get(key)) ...
Write a Python 3 function that can return a valid swagger spec with the values passed.
As a Python code analyst, you investigate and solve complex coding mysteries
Wrapper to call the spied - on function. Operates similar to the test function. Operates similar to test.
Can you tell what is the following Python 3 function doing def _call_spy(self, *args, **kwargs): ''' Wrapper to call the spied-on function. Operates similar to Expectation.test. ''' if self._spy_side_effect: if self._spy_side_effect_args or self._spy_side_effect_kwargs: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Wrap side effects for spies.
How would you explain what the following Python 3 function does def side_effect(self, func, *args, **kwargs): ''' Wrap side effects for spies. ''' self._spy_side_effect = func self._spy_side_effect_args = args self._spy_side_effect_kwargs = kwargs return self
As a Python code analyst, you investigate and solve complex coding mysteries
This function prepares the interaction items for inclusion in main script s global scope dictionary.
Can you generate the documentation for the following Python 3 function def set_interact_items(glob): a, l = glob['args'], glob['logger'] enabled = getattr(a, a._collisions.get("interact") or "interact", False) if enabled: readline.parse_and_bind('tab: complete') # InteractiveConsole as defined ...
You are a Python code generator, capable of creating scripts from specifications.
def configure_logger(glob, multi_level, relative=False, logfile=None, syslog=False): """ Logger configuration function for setting either a simple debug mode or a multi-level one. :param glob: globals dictionary :param multi_level: boolean telling if multi-level deb...
Create a Python 3 function to configure the logger for the given dictionary.
You are a Python code architect, reviewing and designing scalable and efficient code
process a result of a transmute_func call
Here you have a function in Python 3, explain what it does def process_result(transmute_func, context, result, exc, content_type): if isinstance(result, Response): response = result else: response = Response( result=result, code=transmute_func.success_code, success=True ) ...
As a Python code analyst, you investigate and solve complex coding mysteries
def opt_space(M_E, r=None, niter=50, tol=1e-6, print_out=False): ''' Implementation of the OptSpace matrix completion algorithm. An algorithm for Matrix Reconstruction from a partially revealed set. Sparse treatment of matrices are removed because of indexing problems in Python. Args: ...
Write a Python 3 function for returning a new array that is a subset of the matrix M_E.
You are a Python code generator, capable of creating scripts from specifications.
Returns the singular values of the given size in descending order.
Can you tell what is the following Python 3 function doing def svds_descending(M, k): ''' In contrast to MATLAB, numpy's svds() arranges the singular values in ascending order. In order to have matching codes, we wrap it around by a function which re-sorts the singular values and singular vecto...
You are a Python code architect, reviewing and designing scalable and efficient code
Guess the rank of the incomplete matrix M_E.
Given the following Python 3 function, write the documentation def guess_rank(M_E): '''Guess the rank of the incomplete matrix ''' n, m = M_E.shape epsilon = np.count_nonzero(M_E) / np.sqrt(m * n) _, S0, _ = svds_descending(M_E, min(100, max(M_E.shape) - 1)) S0 = np.diag(S0) S1 = S0[:-1]...
As a Python code composer, you craft elegant and concise scripts.
Compute the distortion of the current state of the tree
Can you tell what is the following Python 3 function doing def F_t(X, Y, S, M_E, E, m0, rho): ''' Compute the distortion ''' r = X.shape[1] out1 = (((np.dot(np.dot(X, S), Y.T) - M_E) * E)**2).sum() / 2 out2 = rho * G(Y, m0, r) out3 = rho * G(X, m0, r) return out1 + out2 + out3
As a Python code translator, you convert algorithms and pseudocode into Python.
Compute the gradient of the F_t function.
Explain what the following Python 3 code does def gradF_t(X, Y, S, M_E, E, m0, rho): ''' Compute the gradient. ''' n, r = X.shape m, r = Y.shape XS = np.dot(X, S) YS = np.dot(Y, S.T) XSY = np.dot(XS, Y.T) Qx = np.dot(np.dot(X.T, ((M_E - XSY) * E)), YS) / n Qy = np.dot(np...
You are a Python code architect, reviewing and designing scalable and efficient code
def getoptS(X, Y, M_E, E): ''' Find Sopt given X, Y ''' n, r = X.shape C = np.dot(np.dot(X.T, M_E), Y) C = C.flatten() A = np.zeros((r * r, r * r)) for i in range(r): for j in range(r): ind = j * r + i temp = np.dot( np.dot(X.T, np...
Implement a Python 3 function for finding Sopt given X Y M_E and E
As a Python code analyst, you investigate and solve complex coding mysteries
def MDS(D, dim, method='simple', theta=False): """ recover points from euclidean distance matrix using classic MDS algorithm. """ N = D.shape[0] if method == 'simple': d1 = D[0, :] # buf_ = d1 * np.ones([1, N]).T + (np.ones([N, 1]) * d1).T buf_ = np.broadcast_to(d1, D.shape) + n...
Can you create a Python 3 function that recovers points from euclidean distance matrix using classic MDS algorithm.
As a Python code composer, you craft elegant and concise scripts.
def superMDS(X0, N, d, **kwargs): """ Find the set of points from an edge kernel. """ Om = kwargs.get('Om', None) dm = kwargs.get('dm', None) if Om is not None and dm is not None: KE = kwargs.get('KE', None) if KE is not None: print('superMDS: KE and Om, dm given. Continu...
Can you create a Python 3 function that finds the set of points from an edge kernel.
As a python code expert, you are capable of creating scripts from specifications.
def iterativeEMDS(X0, N, d, C, b, max_it=10, print_out=False, **kwargs): """ Find the set of points from an edge kernel with geometric constraints, using iterative projection """ from pylocus.basics import mse, projection KE = kwargs.get('KE', None) KE_projected = KE.copy() d = len(X0) for ...
Write a Python 3 function that can find the set of points from an edge kernel with geometric constraints, using iterative projection
As a Python code translator, you convert algorithms and pseudocode into Python.
This function is used to find the set of points from an edge kernel with geometric constraints using convex rank relaxation.
Can you generate a brief explanation for the following Python 3 code def relaxedEMDS(X0, N, d, C, b, KE, print_out=False, lamda=10): E = C.shape[1] X = Variable((E, E), PSD=True) constraints = [C[i, :] * X == b[i] for i in range(C.shape[0])] obj = Minimize(trace(X) + lamda * norm(KE - X)) prob = P...
As a python code expert, you are capable of creating scripts from specifications.
Find the set of points from a cdm.
Can you generate a brief explanation for the following Python 3 code def signedMDS(cdm, W=None): N = cdm.shape[0] D_sym = (cdm - cdm.T) D_sym /= 2 if W is None: x_est = np.mean(D_sym, axis=1) x_est -= np.min(x_est) return x_est W_sub = W[1:, 1:] sum_W = np.sum(W[1:, :...
You are a Python code architect, reviewing and designing scalable and efficient code
Stub an attribute of an object. Will return an existing stub if there already is one.
Given the following Python 3 function, write the documentation def _stub_attr(obj, attr_name): ''' Stub an attribute of an object. Will return an existing stub if there already is one. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .m...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _stub_obj(obj): ''' Stub an object directly. ''' # Annoying circular reference requires importing here. Would like to see # this cleaned up. @AW from .mock import Mock # Return an existing stub if isinstance(obj, Stub): return obj # If a Mock object, stub its __call__ ...
Write a Python 3 script for stubbing an object directly.
You are a Python code architect, reviewing and designing scalable and efficient code
Assert that all expectations on the stub have been met.
Explain what the following Python 3 code does def unmet_expectations(self): ''' Assert that all expectations on the stub have been met. ''' unmet = [] for exp in self._expectations: if not exp.closed(with_counts=True): unmet.append(ExpectationNotSatisf...
You are a Python code generator, capable of creating scripts from specifications.
def teardown(self): ''' Clean up all expectations and restore the original attribute of the mocked object. ''' if not self._torn: self._expectations = [] self._torn = True self._teardown()
Implement a Python 3 function for cleaning up all expectations and restore the original attribute of the mocked object.
As a Python code translator, you convert algorithms and pseudocode into Python.
Add an expectation to this stub. Return the expectation.
Make a summary of the following Python 3 code def expect(self): ''' Add an expectation to this stub. Return the expectation. ''' exp = Expectation(self) self._expectations.append(exp) return exp
As a python code expert, you are capable of creating scripts from specifications.
Add a spy to this stub. Return the spy.
Here you have a function in Python 3, explain what it does def spy(self): ''' Add a spy to this stub. Return the spy. ''' spy = Spy(self) self._expectations.append(spy) return spy
As a Python code analyst, you investigate and solve complex coding mysteries
Calls the original function.
How would you explain what the following Python 3 function does def call_orig(self, *args, **kwargs): ''' Calls the original function. ''' if hasattr(self._obj, '__self__') and \ inspect.isclass(self._obj.__self__) and \ self._obj.__self__ is self._instanc...
You are a Python code analyst, evaluating scripts for potential improvements.
def _teardown(self): ''' Put the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class ...
Create a Python 3 function for putting the original method back in place. This will also handle the special case when it putting back a class method. The following code snippet best describe why it fails using settar, the class method would be replaced with a bound method not a class method. >>> class Example(object): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Replace the original method. Replace the original method. Delete the original object.
Here you have a function in Python 3, explain what it does def _teardown(self): ''' Replace the original method. ''' if not self._was_object_method: setattr(self._instance, self._attr, self._obj) else: delattr(self._instance, self._attr)
As a Python code composer, you craft elegant and concise scripts.
def call_orig(self, *args, **kwargs): ''' Calls the original function. Simulates __new__ and __init__ together. ''' rval = super(StubNew, self).call_orig(self._type) rval.__init__(*args, **kwargs) return rval
Can you write a function in Python 3 where it calls the original function. Simulates __new__ and __init__ together.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _teardown(self): ''' Overload so that we can clear out the cache after a test run. ''' # __new__ is a super-special case in that even when stubbing a class # which implements its own __new__ and subclasses object, the # "Class.__new__" reference is a staticmethod and ...
Write a Python 3 function for overloading so that we can clear out the cache after a test run.
As a python code expert, you are capable of creating scripts from specifications.
Calls the original function.
Explain what the following Python 3 code does def call_orig(self, *args, **kwargs): ''' Calls the original function. ''' return self._orig(self._obj, *args, **kwargs)
You are a Python code analyst, evaluating scripts for potential improvements.
def _setup(self): """Performs the RFXtrx initialisation protocol in a Future. Currently this is the rough workflow of the interactions with the RFXtrx. We also do a few extra things - flush the buffer, and attach readers/writers to the asyncio loop. 1. Write a RESET packet (wri...
How would you code a function in Python 3 to perform the RFXtrx initialisation protocol in a Future. Currently this is the rough workflow of the interactions with the RFXtrx. We also do a few extra things - flush the buffer, and attach readers/writers to the asyncio loop. 1. Write a RESET packet (write all zeros) 2. Wa...
You are a Python code analyst, evaluating scripts for potential improvements.
def do_callback(self, pkt): """Add the callback to the event loop, we use call soon because we just want it to be called at some point, but don't care when particularly. """ callback, parser = self.get_callback_parser(pkt) if asyncio.iscoroutinefunction(callback): se...
Create a Python 3 function for adding the callback to the event loop.
You are a Python code generator, capable of creating scripts from specifications.
Read a single packet from the device and pass to the callback.
Here you have a function in Python 3, explain what it does def read(self): data = self.dev.read() if len(data) == 0: self.log.warning("READ : Nothing received") return if data == b'\x00': self.log.warning("READ : Empty packet (Got \\x00)") retur...
You are a Python code generator, capable of creating scripts from specifications.
def delete(self, url, params=None): """ Executes an HTTP DELETE request for the given URL. ``params`` should be a dictionary """ response = self.http.delete(url, params=params, **self.requests_params) re...
How would you implement a function in Python 3 that executes an HTTP DELETE request for the given URL.
As a python code expert, you are capable of creating scripts from specifications.
Executes an HTTP GET request for the given URL.
Given the following Python 3 function, write the documentation def get(self, url, data=None): response = self.http.get(url, headers=self.headers, params=data, **self.requests_params) return self.process(re...
As a python code expert, you are capable of creating scripts from specifications.
def post(self, url, body=None): """ Executes an HTTP POST request for the given URL. """ response = self.http.post(url, headers=self.headers, data=body, **self.requests_params) return self.proc...
How would you implement a function in Python 3 that executes an HTTP POST request for the given URL.
You are a Python code architect, reviewing and designing scalable and efficient code
def put(self, url, data=None, body=None): """ Executes an HTTP PUT request for the given URL. """ response = self.http.put(url, headers=self.headers, data=body, params=data, ...
How would you code a function in Python 3 to execute an HTTP PUT request for the given URL.
As a python code expert, you are capable of creating scripts from specifications.
Returns HTTP backend agnostic Response data.
Given the following Python 3 function, write the documentation def process(self, response): try: code = response.status_code # 204 - No Content if code == 204: body = None # add an error message to 402 errors elif code == 402: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Creates an account with Zencoder no API Key necessary.
Make a summary of the following Python 3 code def create(self, email, tos=1, options=None): data = {'email': email, 'terms_of_service': str(tos)} if options: data.update(options) return self.post(self.base_url, body=json.dumps(data))
You are a Python code generator, capable of creating scripts from specifications.
Creates a new transcoding job.
Can you generate the documentation for the following Python 3 function def create(self, input=None, live_stream=False, outputs=None, options=None): data = {"input": input, "test": self.test} if outputs: data['outputs'] = outputs if options: data.update(options) ...
You are a Python code generator, capable of creating scripts from specifications.
Resubmits the given job_id.
Make a summary of the following Python 3 code def resubmit(self, job_id): url = self.base_url + '/%s/resubmit' % str(job_id) return self.put(url)
As a Python code translator, you convert algorithms and pseudocode into Python.
def cancel(self, job_id): """ Cancels the given ``job_id``. https://app.zencoder.com/docs/api/jobs/cancel """ if self.version == 'v1': verb = self.get else: verb = self.put url = self.base_url + '/%s/cancel' % str(job_id) return verb(url...
Write a Python 3 script for canceling the given job_id.
You are a Python code analyst, evaluating scripts for potential improvements.
Gets a detailed report of encoded minutes and billable minutes for a specific date range.
Here you have a function in Python 3, explain what it does def minutes(self, start_date=None, end_date=None, grouping=None): data = self.__format(start_date, end_date) url = self.base_url + '/minutes' return self.get(url, data=data)
As a Python code analyst, you investigate and solve complex coding mysteries
attach a transmute route.
Can you tell what is the following Python 3 function doing def route(app_or_blueprint, context=default_context, **kwargs): def decorator(fn): fn = describe(**kwargs)(fn) transmute_func = TransmuteFunction(fn) routes, handler = create_routes_and_handler(transmute_func, context) for r ...
You are a Python code architect, reviewing and designing scalable and efficient code
def stub(self, obj, attr=None): ''' Stub an object. If attr is not None, will attempt to stub that attribute on the object. Only required for modules and other rare cases where we can't determine the binding from the object. ''' s = stub(obj, attr) if s not in sel...
Write a Python 3 script for stubbing an object. If attr is not None, will attempt to stub that attribute on the object. Only required for modules and other rare cases where we can't determine the binding from the object.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a mock object.
Can you generate a brief explanation for the following Python 3 code def mock(self, obj=None, attr=None, **kwargs): ''' Return a mock object. ''' rval = Mock(**kwargs) if obj is not None and attr is not None: rval._object = obj rval._attr = attr ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def from_validation_exception(cls, exception, **kwargs): """Create an error from validation exception.""" errors = [] def flatten(error, path=""): if isinstance(error, halogen.exceptions.ValidationError): if not path.endswith("/"): path += "/" ...
Write a Python 3 function for creating an error from a validation exception.
You are a Python code analyst, evaluating scripts for potential improvements.
def load(raw_bytes): """ given a bytes object, should return a base python data structure that represents the object. """ try: return yaml.load(raw_bytes) except yaml.scanner.ScannerError as e: raise SerializationException(str(e))
Create a Python 3 function to give a bytes object should return a base python data structure that represents the object.
You are a Python code analyst, evaluating scripts for potential improvements.
add a transmute route to the current application
Here you have a function in Python 3, explain what it does def add_transmute_route(self, *args): if len(args) == 1: fn = args[0] elif len(args) == 3: methods, paths, fn = args fn = describe(methods=methods, paths=paths)(fn) else: raise ValueError( ...
As a Python code analyst, you investigate and solve complex coding mysteries
def can_handle(self, cls): """ this will theoretically be compatible with everything, as cattrs can handle many basic types as well. """ # cattrs uses a Singledispatch like function # under the hood. f = self._cattrs_converter._structure_func.dispatch(cls) ...
Implement a function in Python 3 to return True if the structure class can be used to handle the given class.
As a Python code analyst, you investigate and solve complex coding mysteries
Converts unstructured data into structured data recursively.
How would you explain what the following Python 3 function does def load(self, model, value): try: return self._cattrs_converter.structure(value, model) except (ValueError, TypeError) as e: raise SerializationException(str(e))
As a Python code composer, you craft elegant and concise scripts.
def dump(self, model, value): """ Convert attrs data into unstructured data with basic types, recursively: - attrs classes => dictionaries - Enumeration => values - Other types are let through without conversion, such as, int, boolean, dict, other classes. """ ...
How would you implement a function in Python 3 that converts attrs data into unstructured data with basic types recursively.
As a Python code analyst, you investigate and solve complex coding mysteries
Detect the cahracter encoding of a file pointer.
Can you generate the documentation for the following Python 3 function def detect_encoding(fp, default=None): init_pos = fp.tell() try: sample = fp.read( current_app.config.get('PREVIEWER_CHARDET_BYTES', 1024)) # Result contains 'confidence' and 'encoding' result = cchardet.d...
As a python code expert, you are capable of creating scripts from specifications.
Determine if value is an instance or subclass of the class Type.
Make a summary of the following Python 3 code def is_type(value): if isinstance(value, type): return issubclass(value, Type) return isinstance(value, Type)
As a Python code translator, you convert algorithms and pseudocode into Python.
Serialize every item of the list.
Given the following Python 3 function, write the documentation def serialize(self, value, **kwargs): return [self.item_type.serialize(val, **kwargs) for val in value]
You are a Python code generator, capable of creating scripts from specifications.
Return the dictionary representation of an Amount object.
Given the following Python 3 function, write the documentation def amount_object_to_dict(self, amount): currency, amount = ( amount.as_quantized(digits=2).as_tuple() if not isinstance(amount, dict) else (amount["currency"], amount["amount"]) ) if currency not ...
As a Python code analyst, you investigate and solve complex coding mysteries
Given a bytes object should return a base python data structure that represents the object.
Can you generate the documentation for the following Python 3 function def load(raw_bytes): try: if not isinstance(raw_bytes, string_type): raw_bytes = raw_bytes.decode() return json.loads(raw_bytes) except ValueError as e: raise SerializationException...
You are a Python code architect, reviewing and designing scalable and efficient code
def preview(pid, record, template=None, **kwargs): """Preview file for given record. Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration: .. code-block:: python RECORDS_UI_ENDPOINTS = dict( recid=dict( # ... route='/records/<pid_value/prev...
How would you implement a function in Python 3 that previews file for given record.
As a Python code composer, you craft elegant and concise scripts.
def new(template, target=None, name=None): """ Function for creating a template script or tool. :param template: template to be used ; one of TEMPLATES :param target: type of script/tool to be created :param name: name of the new script/tool """ if template not in TEMPLATES: ...
Implement a function in Python 3 to function for creating a new template script or tool.
As a Python code analyst, you investigate and solve complex coding mysteries
def add_swagger(app, json_route, html_route, **kwargs): """ a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation """ app.route(json_route)(create_swagger_json_handler(app, **kwargs)) add_swagger_api_route(app, html_route, json_route)
Create a Python 3 function for adding a swagger. json route and a swagger. html route
You are a Python code analyst, evaluating scripts for potential improvements.
def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagger statics page. app: the flask app object target_route: the path to mount the statics page. swagger_json_route: the path where the swagger json definitions is expected to be. """ static_root = get_sw...
Create a Python 3 function to add a route to the app that will serve the swagger api.
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_swagger_json_handler(app, **kwargs): """ Create a handler that returns the swagger definition for an application. This method assumes the application is using the TransmuteUrlDispatcher as the router. """ spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec()) _add_blueprint_s...
Create a Python 3 function to create a handler that returns the swagger definition for an application.
As a Python code composer, you craft elegant and concise scripts.
def fixtures(): """Command for working with test data.""" temp_path = os.path.join(os.path.dirname(__file__), 'temp') demo_files_path = os.path.join(os.path.dirname(__file__), 'demo_files') # Create location loc = Location(name='local', uri=temp_path, default=True) db.session.add(loc) db.se...
How would you implement a function in Python 3 that commands for working with test data.
As a python code expert, you are capable of creating scripts from specifications.
def render(file): """Render HTML from Markdown file content.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') result = mistune.markdown(fp.read().decode(encoding)) return result
Create a Python 3 function to render HTML from Markdown file content.
You are a Python code analyst, evaluating scripts for potential improvements.
def validate(self, value): """Validate the length of a list. :param value: List of values. :raises: :class:`halogen.exception.ValidationError` exception when length of the list is less than minimum or greater than maximum. """ try: length = len(value) ...
Write a Python 3 function that can validate the length of a list.
As a Python code composer, you craft elegant and concise scripts.
Validate value. :param value: Value which should be validated. :raises: :class:`halogen.exception.ValidationError` exception when either if value less than min in case when min is not None or if value greater than max in case when max is not None.
Can you tell what is the following Python 3 function doing def validate(self, value): if self.min is not None: min_value = self.min() if callable(self.min) else self.min if value < min_value: raise exceptions.ValidationError(self.min_err.format(val=value, min=min_value)) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
This actually executes the calls registered in the ProxyArgumentParser.
Can you generate a brief explanation for the following Python 3 code def __get_calls_from_parser(proxy_parser, real_parser): __parsers[proxy_parser] = real_parser for method, safe, args, kwargs, proxy_subparser in proxy_parser.calls: args = (__proxy_to_real_parser(v) for v in args) kwargs = {k: ...
As a Python code analyst, you investigate and solve complex coding mysteries
This recursively converts ProxyArgumentParser instances to actual parsers.
Make a summary of the following Python 3 code def __proxy_to_real_parser(value): if isinstance(value, ProxyArgumentParser): return __parsers[value] elif any(isinstance(value, t) for t in [list, tuple]): new_value = [] for subvalue in iter(value): new_value.append(__proxy_to_r...
As a python code expert, you are capable of creating scripts from specifications.