output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Checks the number valiaty for the Pernanbuco state
Here you have a function in Python 3, explain what it does def start(st_reg_number): divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False sum_total = 0 peso = 8 for i in range(len(st_reg_number)-2): sum_total = sum_total + int(st...
As a Python code analyst, you investigate and solve complex coding mysteries
def set_header(self, key: str, value: str) -> None: """ set response header :param key: the key of header :param value: the value of header """ self.headers[key] = value
Write a Python 3 function that can set response header :param key: the key of header :param value: the value of header
As a Python code translator, you convert algorithms and pseudocode into Python.
def start(st_reg_number): """Checks the number valiaty for the Bahia state""" weights_second_digit = range(len(st_reg_number)-1, 1, -1) weights_first_digit = range(len(st_reg_number), 1, -1) second_digits = st_reg_number[-1:] number_state_registration = st_reg_number[0:len(st_reg_number) - 2] d...
Create a Python 3 function to check the number valiaty for the Bahia state
As a Python code composer, you craft elegant and concise scripts.
Send an HTTP response to the writer.
Can you generate a brief explanation for the following Python 3 code async def send_http_response(writer, http_code: int, headers: List[Tuple[str, str]], content: bytes, http_status: str= None ...
As a python code expert, you are capable of creating scripts from specifications.
async def serve(http_handler: HTTP_WRAPPER_TYPE, websocket_handler=None, address: str='127.0.0.1', port: int=8000): """ start server """ return await asyncio.start_server(SocketWrapper(http_handler, websocket_handler), address, port)
How would you code a function in Python 3 to start server with websocket
You are a Python code analyst, evaluating scripts for potential improvements.
def __body_format(self, body): """ format body into different type :param body: :return: """ ctype, pdict = parse_header(self.content_type) if ctype == 'application/json': self.form = json.loads(body.decode()) elif ctype == 'application/x-www...
Can you implement a function in Python 3 that formats the body into different type
You are a Python code generator, capable of creating scripts from specifications.
def start(st_reg_number): """Checks the number valiaty for the Paraiba state""" #st_reg_number = str(st_reg_number) weights = [9, 8, 7, 6, 5, 4, 3, 2] digit_state_registration = st_reg_number[-1] if len(st_reg_number) != 9: return False sum_total = 0 for i in range(0, 8): ...
Implement a Python 3 function for checking the number valiaty for the Paraiba state
As a Python code translator, you convert algorithms and pseudocode into Python.
def start(st_reg_number): """Checks the number valiaty for the Mato Grosso state""" #st_reg_number = str(st_reg_number) weights = [3, 2, 9, 8, 7, 6, 5, 4, 3, 2] digit_state_registration = st_reg_number[-1] if len(st_reg_number) != 11: return False sum = 0 for i in range(0, 10): ...
Implement a function in Python 3 to check the number valiaty for the Mato Grosso state
You are a Python code generator, capable of creating scripts from specifications.
def start(st_reg_number): """Checks the number valiaty for the Sergipe state""" divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False sum_total = 0 peso = 9 for i in range(len(st_reg_number)-1): sum_total = sum_total + int(st...
Create a Python 3 function to check the number valiaty for the Sergipe state
You are a Python code analyst, evaluating scripts for potential improvements.
Checks the number valiaty for the Espirito Santo state
Can you generate a brief explanation for the following Python 3 code def start(st_reg_number): weights = [9, 8, 7, 6, 5, 4, 3, 2] number_state_registration = st_reg_number[0:len(st_reg_number) - 1] digit_state_registration = st_reg_number[-1] if st_reg_number[0:2] not in ['10', '11', '12']: re...
You are a Python code architect, reviewing and designing scalable and efficient code
Checks the number valiaty for the Acre state
Can you generate a brief explanation for the following Python 3 code def start(st_reg_number): #st_reg_number = str(st_reg_number) weights = [4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2] digits = st_reg_number[:len(st_reg_number) - 2] check_digits = st_reg_number[-2:] divisor = 11 if len(st_reg_number) > ...
You are a Python code architect, reviewing and designing scalable and efficient code
load all upper parameters of object as config parameters
Can you generate a brief explanation for the following Python 3 code def load_from_object(self, object_name): for key in dir(object_name): if key.isupper(): self[key] = getattr(object_name, key)
As a python code expert, you are capable of creating scripts from specifications.
Checks the number valiaty for the Minas Gerais state
Make a summary of the following Python 3 code def start(st_reg_number): #st_reg_number = str(st_reg_number) number_state_registration_first_digit = st_reg_number[0:3] + '0' + st_reg_number[3: len(st_reg_number)-2] weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2] wights_second_digit = [3, 2, 11...
You are a Python code analyst, evaluating scripts for potential improvements.
Register a set of middleware functions.
Explain what the following Python 3 code does def use(self, *middleware: MiddlewareType) -> None: for m in middleware: if is_middleware(m): self.middleware.append(m)
As a python code expert, you are capable of creating scripts from specifications.
The handler handling each request AttributeNames
Explain what the following Python 3 code does async def handler(self, request: Request) -> Tuple[int, str, List[Tuple[str, str]], bytes]: response: 'Response' = Response() handler: Callable = empty chain_reverse = self.middleware[::-1] for middleware in chain_reverse: handle...
As a Python code composer, you craft elegant and concise scripts.
Start the http server and run the loop until it is done.
Here you have a function in Python 3, explain what it does def run(self, host: str="localhost", port: int=8000, debug: bool=False): self.debug = debug loop = asyncio.get_event_loop() try: loop.run_until_complete(self.start_server(host, port)) loop.run_forever() e...
As a Python code analyst, you investigate and solve complex coding mysteries
def start(st_reg_number): """Checks the number valiaty for the Amazonas state""" weights = range(2, 10) digits = st_reg_number[0:len(st_reg_number) - 1] control_digit = 11 check_digit = st_reg_number[-1:] if len(st_reg_number) != 9: return False ...
How would you code a function in Python 3 to check the number valiaty for the Amazonas state
You are a Python code generator, capable of creating scripts from specifications.
This function is like a Facade to another modules that makes their own state validation. It is like a Facade to another modules that makes their own state validation. It is like a Facade to another modules that makes their own state validation.
Can you generate the documentation for the following Python 3 function def start(state_registration_number, state_abbreviation): state_abbreviation = state_abbreviation.upper() states_validations = { 'AC': "ac.start(" + "\"" + state_registration_number + "\"" + ")", 'AL': "al.start(" + "\"" + s...
You are a Python code architect, reviewing and designing scalable and efficient code
def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "24": return False if st_reg_number[2] not in ['0', '3', '5', '7', '8']: return...
Write a Python 3 script for checking the number valiaty for the Alagoas state
As a Python code analyst, you investigate and solve complex coding mysteries
Checks the number valiaty for the Alagoas state
Given the following Python 3 function, write the documentation def start(st_reg_number): divisor = 11 if len(st_reg_number) > 9: return False if len(st_reg_number) < 9: return False if st_reg_number[0:2] != "03": return False aux = int(st_reg_number[0:len(st_reg_number) -...
You are a Python code generator, capable of creating scripts from specifications.
def to_dict(self): """Return a dictionary representation of the error. :return: A dict with the keys: - attr: Attribute which contains the error, or "<root>" if it refers to the schema root. - errors: A list of dictionary representations of the errors. """ def ex...
Write a Python 3 function for returning a dictionary representation of the error.
You are a Python code architect, reviewing and designing scalable and efficient code
Get actions filtered on a list of action types.
Can you generate the documentation for the following Python 3 function def _filtered_actions(self, *a_types): for a in filter(lambda _: self.is_action(_, *a_types), self._actions): yield a
As a Python code analyst, you investigate and solve complex coding mysteries
def _input_arg(self, a): """ Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action """ # if action of an argument that suppresses any other, just return if a.dest == SUPPRES...
Create a Python 3 function to ask the user for input of a single argument.
As a Python code composer, you craft elegant and concise scripts.
Set a single argument.
Can you generate the documentation for the following Python 3 function def _set_arg(self, a, s="main", c=False): # if action of an argument that suppresses any other, just return if a.dest is SUPPRESS or a.default is SUPPRESS: return # check if an option string is used for this actio...
You are a Python code analyst, evaluating scripts for potential improvements.
Generate the sorted list of actions based on the last attribute.
Given the following Python 3 function, write the documentation def _sorted_actions(self): for a in filter(lambda _: not _.last and \ not self.is_action(_, 'parsers'), self._actions): yield a for a in filter(lambda _: _.last and \ not self.is_ac...
As a Python code composer, you craft elegant and concise scripts.
Feeds the input arguments from a config file.
Explain what the following Python 3 code does def config_args(self, section="main"): if self._config_parsed: return for a in self._filtered_actions("config"): for o in a.option_strings: try: i = sys.argv.index(o) sys.argv.po...
As a Python code composer, you craft elegant and concise scripts.
Additional method for replacing input arguments by demo ones.
Explain what the following Python 3 code does def demo_args(self): argv = random.choice(self.examples).replace("--demo", "") self._reparse_args['pos'] = shlex.split(argv)
As a python code expert, you are capable of creating scripts from specifications.
Reparses new arguments when the demo_args method is called.
Given the following Python 3 function, write the documentation def parse_args(self, args=None, namespace=None): if not namespace: # use the new Namespace class for handling _config namespace = Namespace(self) namespace = super(ArgumentParser, self).parse_args(args, namespace) if len...
You are a Python code generator, capable of creating scripts from specifications.
Prints a usage message incorporating the message to stderr and exits the program with an error code.
Here you have a function in Python 3, explain what it does def error(self, message): if all(len(x) == 0 for x in self._reparse_args.values()): # normal behavior with argparse self.print_usage(sys.stderr) self.exit(2, gt('%s: error: %s\n') % (self.prog, message))
You are a Python code analyst, evaluating scripts for potential improvements.
def add_to_config(cls, section, name, value): """ Add a parameter to the shared ConfigParser object. :param section: parameter's section :param name: parameter's name :param value: parameter's value """ if value: if not cls._config.has_se...
Can you implement a function in Python 3 that adds a parameter to the shared ConfigParser object.
As a python code expert, you are capable of creating scripts from specifications.
This is a decorator that can be used to save a file or text.
Here you have a function in Python 3, explain what it does def output(f): def wrapper(self, *args, **kwargs): try: text = kwargs.get('text') or args[0] except IndexError: text = True _ = f(self, *args, **kwargs) if text: return _ elif _ is ...
You are a Python code generator, capable of creating scripts from specifications.
Generate an HTML file from the report data.
How would you explain what the following Python 3 function does def html(self, text=TEXT): self.logger.debug("Generating the HTML report{}..." .format(["", " (text only)"][text])) html = [] for piece in self._pieces: if isinstance(piece, string_types): ...
You are a Python code generator, capable of creating scripts from specifications.
Generate a PDF file from the report data.
Explain what the following Python 3 code does def pdf(self, text=TEXT): self.logger.debug("Generating the PDF report...") html = HTML(string=self.html()) css_file = self.css or join(dirname(abspath(__file__)), "{}.css".format(self.theme)) css = [css_fi...
You are a Python code generator, capable of creating scripts from specifications.
def csv(self, text=TEXT, sep=',', index=True, float_fmt="%.2g"): """ Generate a CSV table from the table data. """ return self._data.to_csv(sep=sep, index=index, float_format=float_fmt)
Can you implement a function in Python 3 that generates a CSV table from the table data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate Markdown from the table data.
Given the following Python 3 function, write the documentation def md(self, text=TEXT, float_format="%.2g"): cols = self._data.columns hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols) df = pd.concat([hl, self._data]) return df.to_csv(sep='|', index=True, float_format...
As a Python code translator, you convert algorithms and pseudocode into Python.
def xml(self, text=TEXT): """ Generate an XML output from the report data. """ def convert(line): xml = " <item>\n" for f in line.index: xml += " <field name=\"%s\">%s</field>\n" % (f, line[f]) xml += " </item>\n" return xml re...
Can you create a Python 3 function that generates an XML output from the report data.
You are a Python code architect, reviewing and designing scalable and efficient code
retrieve a FunctionSignature object from the argspec and the annotations passed.
Explain what the following Python 3 code does def from_argspec(argspec): attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", []) defaults = argspec.defaults or [] arguments, keywords = [], {} attribute_list = ( attributes[: -len(defaults)] if len(defaul...
As a python code expert, you are capable of creating scripts from specifications.
def split_args(self, arg_dict): """ given a dictionary of arguments, split them into args and kwargs note: this destroys the arg_dict passed. if you need it, create a copy first. """ pos_args = [] for arg in self.args: pos_args.append(arg_dict...
Can you create a Python 3 function that gives a dictionary of arguments split them into args and kwargs
You are a Python code generator, capable of creating scripts from specifications.
A simple Python 2. 3 - compatible input method.
Make a summary of the following Python 3 code def std_input(prompt="", style=None): p = ansi_wrap(prompt, **(style or {})) try: return raw_input(p).strip() except NameError: return input(p).strip()
As a Python code translator, you convert algorithms and pseudocode into Python.
Python 2. 3 compatible user input method handling choices and default value.
Can you tell what is the following Python 3 function doing def user_input(prompt="", choices=None, default=None, choices_str="", required=False): """ Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possibl...
As a Python code translator, you convert algorithms and pseudocode into Python.
def pretty_format_args(*args, **kwargs): """ Take the args, and kwargs that are passed them and format in a prototype style. """ args = list([repr(a) for a in args]) for key, value in kwargs.items(): args.append("%s=%s" % (key, repr(value))) return "(%s)" % ", ".join([a for a in args...
Create a Python 3 function to take the args and kwargs that are passed them and format in a prototype style.
You are a Python code architect, reviewing and designing scalable and efficient code
def validate_xml(file): """Validate an XML file.""" max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: content = fp.read().decode('utf-8') xml.d...
How would you code a function in Python 3 to validate an XML file.
You are a Python code generator, capable of creating scripts from specifications.
Render appropiate template with embed flag.
Can you tell what is the following Python 3 function doing def preview(file): return render_template( 'invenio_previewer/xml_prismjs.html', file=file, content=render(file), js_bundles=['previewer_prism_js'], css_bundles=['previewer_prism_css'], )
As a python code expert, you are capable of creating scripts from specifications.
Prepare a context for the serialization function.
Make a summary of the following Python 3 code def _get_context(argspec, kwargs): if argspec.keywords is not None: return kwargs return dict((arg, kwargs[arg]) for arg in argspec.args if arg in kwargs)
As a Python code composer, you craft elegant and concise scripts.
Get an attribute from an object.
Can you generate the documentation for the following Python 3 function def get(self, obj, **kwargs): assert self.getter is not None, "Getter accessor is not specified." if callable(self.getter): return self.getter(obj, **_get_context(self._getter_argspec, kwargs)) assert isinstance(...
You are a Python code generator, capable of creating scripts from specifications.
def set(self, obj, value): """Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned. """ assert self.setter is not None, "Setter accessor is not specified." if callable(self.setter): re...
Create a Python 3 function to set value for obj s attribute.
You are a Python code generator, capable of creating scripts from specifications.
def accessor(self): """Get an attribute's accessor with the getter and the setter. :return: `Accessor` instance. """ if isinstance(self.attr, Accessor): return self.attr if callable(self.attr): return Accessor(getter=self.attr) attr = self.attr ...
Can you create a Python 3 function that gets an attribute s accessor with the getter and the setter.
You are a Python code architect, reviewing and designing scalable and efficient code
def serialize(self, value, **kwargs): """Serialize the attribute of the input data. Gets the attribute value with accessor and converts it using the type serialization. Schema will place this serialized value into corresponding compartment of the HAL structure with the name of the ...
Create a Python 3 function for serializing the attribute of the input data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Deserialize the HAL structure into the output value.
Make a summary of the following Python 3 code def deserialize(cls, value, output=None, **kwargs): errors = [] result = {} for attr in cls.__attrs__.values(): try: result[attr.name] = attr.deserialize(value, **kwargs) except NotImplementedError: ...
As a python code expert, you are capable of creating scripts from specifications.
def parse(self, data): """Parse a 9 bytes packet in the Temperature format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x2EB2", 'packet_length': 8, ...
Implement a Python 3 function for parsing a 9 bytes packet in the Temperature format and returns a dictionary containing the data extracted.
You are a Python code generator, capable of creating scripts from specifications.
def ints(l, ifilter=lambda x: x, idescr=None): """ Parses a comma-separated list of ints. """ if isinstance(l, string_types): if l[0] == '[' and l[-1] == ']': l = l[1:-1] l = list(map(lambda x: x.strip(), l.split(','))) try: l = list(map(ifilter, list(map(int, l)))) e...
Write a Python 3 script to parse a comma - separated list of ints.
As a Python code analyst, you investigate and solve complex coding mysteries
def ip_address_list(ips): """ IP address range validation and expansion. """ # first, try it as a single IP address try: return ip_address(ips) except ValueError: pass # then, consider it as an ipaddress.IPv[4|6]Network instance and expand it return list(ipaddress.ip_network(u(ip...
Implement a Python 3 function for giving a list of IP addresses return a list of all hosts in the network.
You are a Python code architect, reviewing and designing scalable and efficient code
def port_number(port): """ Port number validation. """ try: port = int(port) except ValueError: raise ValueError("Bad port number") if not 0 <= port < 2 ** 16: raise ValueError("Bad port number") return port
Can you implement a function in Python 3 that validates and return a valid port number.
As a Python code analyst, you investigate and solve complex coding mysteries
Validate and expansion of a port number range.
Can you generate a brief explanation for the following Python 3 code def port_number_range(prange): # first, try it as a normal port number try: return port_number(prange) except ValueError: pass # then, consider it as a range with the format "x-y" and expand it try: bounds =...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_header_part(self, data): """Extracts and converts the RFX common header part of all valid packets to a plain dictionary. RFX header part is the 4 bytes prior the sensor vendor specific data part. The RFX common header part contains respectively: - packet length ...
Can you create a Python 3 function that extracts and converts the RFX common header part of all valid packets to a plain dictionary.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method is used to load the raw data and start parsing the data.
Given the following Python 3 function, write the documentation def load(self, data): self.loaded_at = datetime.utcnow() self.raw = data self.data = self.parse(data) return self.data
As a python code expert, you are capable of creating scripts from specifications.
Validate a packet against this packet handler and determine if it meets the requirements.
Explain what the following Python 3 code does def validate_packet(self, data): # Validate length. # The first byte in the packet should be equal to the number of # remaining bytes (i.e. length excluding the first byte). expected_length = data[0] + 1 if len(data) != expected_len...
You are a Python code analyst, evaluating scripts for potential improvements.
def _enforce_instance(model_or_class): """ It's a common mistake to not initialize a schematics class. We should handle that by just calling the default constructor. """ if isinstance(model_or_class, type) and issubclass(model_or_class, BaseType): return model_or_class() return model...
Write a Python 3 function for enforcing an instance of the schematics class.
You are a Python code architect, reviewing and designing scalable and efficient code
Generate the result HTML.
Make a summary of the following Python 3 code def render(file): fp = file.open() content = fp.read() fp.close() notebook = nbformat.reads(content.decode('utf-8'), as_version=4) html_exporter = HTMLExporter() html_exporter.template_file = 'basic' (body, resources) = html_exporter.from_noteb...
As a Python code composer, you craft elegant and concise scripts.
Render the IPython Notebook.
How would you explain what the following Python 3 function does def preview(file): body, resources = render(file) default_ipython_style = resources['inlining']['css'][1] return render_template( 'invenio_previewer/ipynb.html', file=file, content=body, style=default_ipython_sty...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function will handle the transmute route for all the web frameworks. It will create the routes and handler for all the web frameworks.
Can you tell what is the following Python 3 function doing def transmute_route(app, fn, context=default_context): transmute_func = TransmuteFunction(fn) routes, handler = create_routes_and_handler(transmute_func, context) for r in routes: """ the route being attached is a great place to star...
As a Python code composer, you craft elegant and concise scripts.
Creates a route and handler for the given Transmute function.
Here you have a function in Python 3, explain what it does def create_routes_and_handler(transmute_func, context): @wraps(transmute_func.raw_func) def handler(): exc, result = None, None try: args, kwargs = ParamExtractorFlask().extract_params( context, transmute_func...
You are a Python code architect, reviewing and designing scalable and efficient code
converts a list of transmute - core s path syntax into flask s path syntax
Can you generate a brief explanation for the following Python 3 code def _convert_paths_to_flask(transmute_paths): paths = [] for p in transmute_paths: paths.append(p.replace("{", "<").replace("}", ">")) return paths
As a Python code composer, you craft elegant and concise scripts.
def add_swagger(app, json_route, html_route, **kwargs): """ add a swagger html page, and a swagger.json generated from the routes added to the app. """ spec = getattr(app, SWAGGER_ATTR_NAME) if spec: spec = spec.swagger_definition(**kwargs) else: spec = {} encoded_spec = ...
How would you implement a function in Python 3 that adds a swagger page to the app.
As a Python code translator, you convert algorithms and pseudocode into Python.
Log the status of each protocol where 1 is the enabled and 0 is the disabled ones.
How would you explain what the following Python 3 function does def _log_enabled_protocols(self, flags, protocols): enabled, disabled = [], [] for procol, flag in sorted(zip(protocols, flags)): if flag == '1': enabled.append(procol) status = 'Enabled' ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Parse a 13 byte packet in the Status format.
Given the following Python 3 function, write the documentation def parse(self, data): self.validate_packet(data) packet_length = data[0] packet_type = data[1] sub_type = data[2] sequence_number = data[3] command_type = data[4] transceiver_type = data[5] ...
As a python code expert, you are capable of creating scripts from specifications.
This function prepares the benchmark items for inclusion in main script s global scope dictionary.
Can you tell what is the following Python 3 function doing def set_time_items(glob): a = glob['args'] l = glob['logger'] class __TimeManager(object): def __init__(self): c = a._collisions self._stats = getattr(a, c.get("stats") or "stats", False) self._timings = ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _capture_variable(iterator, parameters): """ return the replacement string. this assumes the preceeding {{ has already been popped off. """ key = "" next_c = next(iterator) while next_c != "}": key += next_c next_c = next(iterator) # remove the final "}" next(...
Create a Python 3 function for capturing the variable in the parameters dictionary
As a Python code composer, you craft elegant and concise scripts.
Calculate the distance between two RGB sequences.
Can you generate a brief explanation for the following Python 3 code def rgb_distance(rgb1, rgb2): ''' Calculate the distance between two RGB sequences. ''' return sum(map(lambda c: (c[0] - c[1]) ** 2, zip(rgb1, rgb2)))
You are a Python code analyst, evaluating scripts for potential improvements.
Convert an RGB colour to 8 or 16 colour ANSI graphics.
How would you explain what the following Python 3 function does def rgb_reduce(r, g, b, mode=8): ''' Convert an RGB colour to 8 or 16 colour ANSI graphics. ''' colours = ANSI_COLOURS[:mode] matches = [(rgb_distance(c, map(int, [r, g, b])), i) for i, c in enumerate(colours)] matches.sort(...
As a python code expert, you are capable of creating scripts from specifications.
Convert an RGB colour to 256 colour ANSI graphics.
Can you tell what is the following Python 3 function doing def rgb256(r, g, b): ''' Convert an RGB colour to 256 colour ANSI graphics. ''' grey = False poss = True step = 2.5 while poss: # As long as the colour could be grey scale if r < step or g < step or b < step: gre...
You are a Python code architect, reviewing and designing scalable and efficient code
Get file download link.
Can you generate the documentation for the following Python 3 function def uri(self): return url_for( '.{0}_files'.format(self.pid.pid_type), pid_value=self.pid.pid_value, filename=self.file.key)
As a Python code composer, you craft elegant and concise scripts.
def has_extensions(self, *exts): """Check if file has one of the extensions.""" file_ext = splitext(self.filename)[1] file_ext = file_ext.lower() for e in exts: if file_ext == e: return True return False
Implement a Python 3 function for checking if the file has one of the extensions.
As a Python code translator, you convert algorithms and pseudocode into Python.
Pretty print the JSON file for rendering.
Here you have a function in Python 3, explain what it does def render(file): with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) json_data = json.loads(file_content, object_pairs_hook=OrderedDict) return json.dumps(json_da...
As a Python code composer, you craft elegant and concise scripts.
Validate a JSON file.
Here you have a function in Python 3, explain what it does def validate_json(file): max_file_size = current_app.config.get( 'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024) if file.size > max_file_size: return False with file.open() as fp: try: json.loads(fp.read().deco...
As a Python code composer, you craft elegant and concise scripts.
Complete and denoise EDM using OptSpace algorithm.
Make a summary of the following Python 3 code def optspace(edm_missing, rank, niter=500, tol=1e-6, print_out=False): from .opt_space import opt_space N = edm_missing.shape[0] X, S, Y, __ = opt_space(edm_missing, r=rank, niter=niter, tol=tol, print_out=print_out) edm_complete ...
As a Python code composer, you craft elegant and concise scripts.
def rank_alternation(edm_missing, rank, niter=50, print_out=False, edm_true=None): """Complete and denoise EDM using rank alternation. Iteratively impose rank and strucutre to complete marix entries :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete E...
Write a Python 3 function that can complete and denoise EDM using rank alternation.
As a Python code composer, you craft elegant and concise scripts.
def semidefinite_relaxation(edm_missing, lamda, W=None, print_out=False, **kwargs): """Complete and denoise EDM using semidefinite relaxation. Returns solution to the relaxation of the following problem: D = argmin || W * (D - edm_missing) || s.t. D is EDM where edm_missing is measure...
How would you implement a function in Python 3 that completes and denoise EDM using semidefinite relaxation.
You are a Python code analyst, evaluating scripts for potential improvements.
Complete an arbitrary denoise EDM using an iterative decent algorithm.
Here you have a function in Python 3, explain what it does def completion_acd(edm, X0, W=None, tol=1e-6, sweeps=3): from .algorithms import reconstruct_acd Xhat, costs = reconstruct_acd(edm, X0, W, tol=tol, sweeps=sweeps) return get_edm(Xhat)
As a python code expert, you are capable of creating scripts from specifications.
Complete an EDM using DWMDS.
Can you generate a brief explanation for the following Python 3 code def completion_dwmds(edm, X0, W=None, tol=1e-10, sweeps=100): from .algorithms import reconstruct_dwmds Xhat, costs = reconstruct_dwmds(edm, X0, W, n=1, tol=tol, sweeps=sweeps) return get_edm(Xhat)
You are a Python code analyst, evaluating scripts for potential improvements.
def url_spec(transmute_path, handler, *args, **kwargs): """ convert the transmute_path to a tornado compatible regex, and return a tornado url object. """ p = _to_tornado_pattern(transmute_path) for m in METHODS: method = getattr(handler, m) if hasattr(method, "transmute_func...
How would you implement a function in Python 3 that converts the transmute_path to a tornado compatible regex and return a tornado. web. URLSpec object.
As a Python code analyst, you investigate and solve complex coding mysteries
def set_points(self, mode='', points=None, range_=RANGE, size=1): """ Initialize points according to predefined modes. :param range_:[xmin, xmax, ymin, ymax], range of point sets """ if mode == 'last': if points is None: print('Error: empty last point specifi...
Create a Python 3 function to initialize points according to predefined modes.
You are a Python code architect, reviewing and designing scalable and efficient code
def create_theta(self): """ Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta. """ import itertools from pylocus.basics_angles import from_0_to_pi theta = ...
Write a Python 3 function for returning the set of inner angles between 0 and pi and the corners corresponding to each entry of theta.
As a Python code composer, you craft elegant and concise scripts.
def get_orientation(k, i, j): from pylocus.basics_angles import from_0_to_2pi """calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle! """ theta_ij = own.abs_angles[i, j] theta_ji = own.abs_angles[j, i] # complicated ...
Implement a Python 3 function for calculating angles theta_ik and theta_jk theta produce point Pk.
As a Python code analyst, you investigate and solve complex coding mysteries
Get indices of theta vector that have k as first corner.
Here you have a function in Python 3, explain what it does def get_indices(self, k): indices_rays = [] indices_triangles = [] corners_rays = [] angles_rays = [] for t, triangle in enumerate(self.corners): if triangle[0] == k: indices_rays.append(t) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
get G matrix from angles.
Make a summary of the following Python 3 code def get_G(self, k, add_noise=True): G = np.ones((self.N - 1, self.N - 1)) if (add_noise): noise = pi * 0.1 * np.random.rand( (self.N - 1) * (self.N - 1)).reshape((self.N - 1, self.N - 1)) other_indices = np.delete(range(se...
As a Python code composer, you craft elegant and concise scripts.
def get_convex_polygons(self, m, print_out=False): """ :param m: size of polygones (number of corners) :return: (ordered) indices of all convex polygones of size m. """ convex_polygons = [] for corners in itertools.combinations(np.arange(self.N), m): ...
How would you code a function in Python 3 to get all convex polygones of size m
As a Python code composer, you craft elegant and concise scripts.
def get_polygon_constraints(self, range_polygones=range(3, 5), print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the constraints on the theta-vector of the form A*theta = b ...
Write a Python 3 function that can get the constraints for the polygones
As a Python code composer, you craft elegant and concise scripts.
returns the constraints A b for each of the given set of polygones.
Explain what the following Python 3 code does def get_polygon_constraints_m(self, polygons_m, print_out=False): rows_b = [] rows_A = [] m = len(polygons_m[0]) rows_b.append((m - 2) * pi * np.ones( len(polygons_m), )) for p in polygons_m: row = np.zeros((se...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_KE_constraints(self): """Get linear constraints on KE matrix. """ C2 = np.eye(self.m) C2 = C2[:self.m - 2, :] to_be_deleted = [] for idx_vij_1 in range(self.m - 2): idx_vij_2 = idx_vij_1 + 1 C2[idx_vij_1, idx_vij_2] = -1 i1 = np...
Can you create a Python 3 function that gets linear constraints on KE matrix.
As a python code expert, you are capable of creating scripts from specifications.
def parse(self, data): """Parse a 12 bytes packet in the Lighting2 format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'id': "0x111F342", 'packet_length': 10, ...
Implement a function in Python 3 to parse a 12 byte packet in the Lighting2 format and returns a dictionary containing the parsed data.
You are a Python code architect, reviewing and designing scalable and efficient code
def _bytes_to_uint_48(self, bytes_): """Converts an array of 6 bytes to a 48bit integer. :param data: bytearray to be converted to a 48bit integer :type data: bytearray :return: the integer :rtype: int """ return ((bytes_[0] * pow(2, 40)) + (bytes_[1] * pow(2, 3...
Can you implement a function in Python 3 that converts an array of 6 bytes to a 48bit integer.
You are a Python code architect, reviewing and designing scalable and efficient code
Parses a 18 bytes packet in the Electricity format and returns a dictionary containing the data extracted.
How would you explain what the following Python 3 function does def parse(self, data): self.validate_packet(data) TOTAL_DIVISOR = 223.666 id_ = self.dump_hex(data[4:6]) count = data[6] instant = data[7:11] total = data[11:16] current_watts = self._bytes_to_uin...
You are a Python code architect, reviewing and designing scalable and efficient code
Get the cache key from a path and site ID.
Explain what the following Python 3 code does def get_key_from_path_and_site(path, site_id): ''' cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best algoritm is SHA-224 whose output (224 chars) respects this limitations ''' key = '{}_{}'.format(path, site_id) ...
As a Python code composer, you craft elegant and concise scripts.
Return dialect information about given csv file.
Explain what the following Python 3 code does def validate_csv(file): try: # Detect encoding and dialect with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') sample = fp.read( current_app.config.get('PREVIEWER_CSV_VALIDATION_BYTES', 1024)) ...
You are a Python code generator, capable of creating scripts from specifications.
def preview(file): """Render appropiate template with embed flag.""" file_info = validate_csv(file) return render_template( 'invenio_previewer/csv_bar.html', file=file, delimiter=file_info['delimiter'], encoding=file_info['encoding'], js_bundles=current_previewer.js_b...
Can you implement a function in Python 3 that renders appropiate template with embed flag.
You are a Python code architect, reviewing and designing scalable and efficient code
Create tree structure from a ZIP archive.
How would you explain what the following Python 3 function does def make_tree(file): max_files_count = current_app.config.get('PREVIEWER_ZIP_MAX_FILES', 1000) tree = {'type': 'folder', 'id': -1, 'children': {}} try: with file.open() as fp: zf = zipfile.ZipFile(fp) # Detect f...
You are a Python code architect, reviewing and designing scalable and efficient code
def preview(file): """Return appropriate template and pass the file and an embed flag.""" tree, limit_reached, error = make_tree(file) list = children_to_list(tree)['children'] return render_template( "invenio_previewer/zip.html", file=file, tree=list, limit_reached=limit...
Write a Python 3 function for returning appropriate template and pass the file and an embed flag.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create noisy version of the input EDM.
Explain what the following Python 3 code does def create_noisy_edm(edm, noise, n=None): N = edm.shape[0] if n is None: n = N found = False max_it = 100 i = 0 while not found: i += 1 dm = np.sqrt(edm) + np.random.normal(scale=noise, size=edm.shape) dm = np.triu(dm)...
You are a Python code architect, reviewing and designing scalable and efficient code
Create weight mask according to method.
Make a summary of the following Python 3 code def create_mask(N, method='all', nmissing=0): weights = np.ones((N, N)) weights[range(N), range(N)] = 0 if method == 'none': return weights # create indices object to choose from elif method == 'all': all_indices = np.triu_indices(N, 1...
As a Python code composer, you craft elegant and concise scripts.