text
stringlengths
81
112k
Checks the number valiaty for the Acre state def start(st_reg_number): """Checks the number valiaty for the Acre state""" #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 = ...
load all upper parameters of object as config parameters :param object_name: the object you wanna load :return: def load_from_object(self, object_name): """ load all upper parameters of object as config parameters :param object_name: the object you wanna load :return: ...
Checks the number valiaty for the Minas Gerais state def start(st_reg_number): """Checks the number valiaty for the Minas Gerais state""" #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 = [...
Register Middleware :param middleware: The Middleware Function def use(self, *middleware: MiddlewareType) -> None: """ Register Middleware :param middleware: The Middleware Function """ for m in middleware: if is_middleware(m): self.middleware...
The handler handling each request :param request: the Request instance :return: The Response instance async def handler(self, request: Request) -> Tuple[int, str, List[Tuple[str, str]], bytes]: """ The handler handling each request :param request: the Request instance :r...
start the http server :param host: The listening host :param port: The listening port :param debug: whether it is in debug mod or not def run(self, host: str="localhost", port: int=8000, debug: bool=False): """ start the http server :param host: The listening host ...
Checks the number valiaty for the Amazonas state 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_nu...
This function is like a Facade to another modules that makes their own state validation. state_registration_number - string brazilian state registration number state_abbreviation - state abbreviation AC (Acre) AL (Alagoas) AM (Amazonas) AP (Amapá) BA (B...
Checks the number valiaty for the Alagoas state 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]...
Checks the number valiaty for the Alagoas state def start(st_reg_number): """Checks the number valiaty for the Alagoas state""" 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 au...
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 to_dict(self): """Return a dictionary repre...
Get actions filtered on a list of action types. :param a_type: argparse.Action instance name (e.g. count, append) def _filtered_actions(self, *a_types): """ Get actions filtered on a list of action types. :param a_type: argparse.Action instance name (e.g. count, append...
Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action def _input_arg(self, a): """ Ask the user for input of a single argument. :param a: argparse.Action instance :return:...
Set a single argument. :param a: argparse.Action instance :param s: config section title :param c: use class' ConfigParser instance to get parameters def _set_arg(self, a, s="main", c=False): """ Set a single argument. :param a: argparse.Action instance...
Generate the sorted list of actions based on the "last" attribute. def _sorted_actions(self): """ Generate the sorted list of actions based on the "last" attribute. """ for a in filter(lambda _: not _.last and \ not self.is_action(_, 'parsers'), self._actions): ...
Additional method for feeding input arguments from a config file. :param section: current config section name def config_args(self, section="main"): """ Additional method for feeding input arguments from a config file. :param section: current config section name ...
Additional method for replacing input arguments by demo ones. def demo_args(self): """ Additional method for replacing input arguments by demo ones. """ argv = random.choice(self.examples).replace("--demo", "") self._reparse_args['pos'] = shlex.split(argv)
Reparses new arguments when _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. def parse_args(self, args=None, namespace=None): """ Reparses new arguments when _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering inpu...
Prints a usage message incorporating the message to stderr and exits in the case when no new arguments to be reparsed, that is when no special action like _DemoAction (triggering parser.demo_args()) or _WizardAction (triggering input_args()) was called. Otherwise, it simply does not...
Add a parameter to the shared ConfigParser object. :param section: parameter's section :param name: parameter's name :param value: parameter's value def add_to_config(cls, section, name, value): """ Add a parameter to the shared ConfigParser object. ...
This decorator allows to choose to return an output as text or to save it to a file. def output(f): """ This decorator allows to choose to return an output as text or to save it to a file. """ def wrapper(self, *args, **kwargs): try: text = kwargs.get('text') or args[0] ...
Generate an HTML file from the report data. def html(self, text=TEXT): """ Generate an HTML file from the report data. """ self.logger.debug("Generating the HTML report{}..." .format(["", " (text only)"][text])) html = [] for piece in self._pieces: ...
Generate a PDF file from the report data. def pdf(self, text=TEXT): """ Generate a PDF file from the report data. """ self.logger.debug("Generating the PDF report...") html = HTML(string=self.html()) css_file = self.css or join(dirname(abspath(__file__)), ...
Generate a CSV table from the table data. 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)
Generate Markdown from the table data. def md(self, text=TEXT, float_format="%.2g"): """ Generate Markdown from the table data. """ cols = self._data.columns hl = pd.DataFrame([["---"] * len(cols)], index=["---"], columns=cols) df = pd.concat([hl, self._data]) return df.to_csv(s...
Generate an XML output from the report data. 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 += "...
retrieve a FunctionSignature object from the argspec and the annotations passed. def from_argspec(argspec): """ retrieve a FunctionSignature object from the argspec and the annotations passed. """ attributes = getattr(argspec, "args", []) + getattr(argspec, "keywords", [...
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. def split_args(self, arg_dict): """ given a dictionary of arguments, split them into args and kwargs note: this destro...
Very simple Python2/3-compatible input method. :param prompt: prompt message :param style: dictionary of ansi_wrap keyword-arguments def std_input(prompt="", style=None): """ Very simple Python2/3-compatible input method. :param prompt: prompt message :param style: dictionary of...
Python2/3-compatible input method handling choices and default value. :param prompt: prompt message :param choices: list of possible choices or lambda function :param default: default value :param required: make non-null user input mandatory :return: handled user input def user_inp...
Take the args, and kwargs that are passed them and format in a prototype style. 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(): arg...
Pretty print the XML file for rendering. def render(file): """Pretty print the XML file for rendering.""" with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') file_content = fp.read().decode(encoding) parsed_xml = xml.dom.minidom.parseString(file_content) retu...
Validate an XML file. 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('ut...
Render appropiate template with embed flag. def preview(file): """Render appropiate template with embed flag.""" return render_template( 'invenio_previewer/xml_prismjs.html', file=file, content=render(file), js_bundles=['previewer_prism_js'], css_bundles=['previewer_pris...
Prepare a context for the serialization. :param argspec: The argspec of the serialization function. :param kwargs: Dict with context :return: Keywords arguments that function can accept. def _get_context(argspec, kwargs): """Prepare a context for the serialization. :param argspec: The argspec of ...
Get an attribute from a value. :param obj: Object to get the attribute value from. :return: Value of object's attribute. def get(self, obj, **kwargs): """Get an attribute from a value. :param obj: Object to get the attribute value from. :return: Value of object's attribute. ...
Set value for obj's attribute. :param obj: Result object or dict to assign the attribute to. :param value: Value to be assigned. 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...
Get an attribute's accessor with the getter and the setter. :return: `Accessor` instance. 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 ...
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 attribute as a key. :param value: Val...
Deserialize the attribute from a HAL structure. Get the value from the HAL structure from the attribute's compartment using the attribute's name as a key, convert it using the attribute's type. Schema will either return it to parent schema or will assign to the output value if specifie...
Embedded supports curies. def key(self): """Embedded supports curies.""" if self.curie is None: return self.name return ":".join((self.curie.name, self.name))
Deserialize the HAL structure into the output value. :param value: Dict of already loaded json which will be deserialized by schema attributes. :param output: If present, the output object will be updated instead of returning the deserialized data. :returns: Dict of deserialized value for attr...
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, 'packet_type': 80, ...
Simple negative integer validation. def neg_int(i): """ Simple negative integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i > 0: raise Exception() except: raise ValueError("Not a negative integer") return...
Simple positive integer validation. def pos_int(i): """ Simple positive integer validation. """ try: if isinstance(i, string_types): i = int(i) if not isinstance(i, int) or i < 0: raise Exception() except: raise ValueError("Not a positive integer") return...
Parses a comma-separated list of ints. 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 = lis...
IP address range validation and expansion. 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 ...
Port number validation. 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
Port number range validation and expansion. def port_number_range(prange): """ Port number range validation and expansion. """ # 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 exp...
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 - packet type - packet sub-type ...
This is the entrance method for all data which is used to store the raw data and start parsing the data. :param data: The raw untouched bytearray as recieved by the RFXtrx :type data: bytearray :return: The parsed data represented in a dictionary :rtype: dict def load(self, da...
Validate a packet against this packet handler and determine if it meets the requirements. This is done by checking the following conditions are true. - The length of the packet is equal to the first byte. - The second byte is in the set of defined PACKET_TYPES for this class. - ...
It's a common mistake to not initialize a schematics class. We should handle that by just calling the default constructor. 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. ""...
Generate the result HTML. def render(file): """Generate the result HTML.""" 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_ex...
Render the IPython Notebook. def preview(file): """Render the IPython Notebook.""" body, resources = render(file) default_ipython_style = resources['inlining']['css'][1] return render_template( 'invenio_previewer/ipynb.html', file=file, content=body, style=default_ipytho...
this is the main interface to transmute. It will handle adding converting the python function into the a flask-compatible route, and adding it to the application. def transmute_route(app, fn, context=default_context): """ this is the main interface to transmute. It will handle adding converting the...
return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted to. def create_routes_and_handler(transmute_func, context): """ return back a handler that is the api generated from the transmute_func, and a list of routes it should be mounted t...
convert transmute-core's path syntax (which uses {var} as the variable wildcard) into flask's <var>. def _convert_paths_to_flask(transmute_paths): """ convert transmute-core's path syntax (which uses {var} as the variable wildcard) into flask's <var>. """ paths = [] for p in transmute_paths...
add a swagger html page, and a swagger.json generated from the routes added to the app. 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: ...
Given a list of single character strings of 1's and 0's and a list of protocol names. Log the status of each protocol where ``"1"`` is enabled and ``"0"`` is disabled. The order of the lists here is important as they need to be zipped together to create the mapping. Then return a tuple o...
Parse a 13 byte packet in the Status format. :param data: bytearray to be parsed :type data: bytearray :return: Data dictionary containing the parsed values :rtype: dict def parse(self, data): """Parse a 13 byte packet in the Status format. :param data: bytearray to b...
This function prepares the benchmark items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference def set_time_items(glob): """ This function prepares the benchmark items for inclusion in main script's global scope. :param glob: mai...
This function prepares the stepping items for inclusion in main script's global scope. :param glob: main script's global scope dictionary reference def set_step_items(glob): """ This function prepares the stepping items for inclusion in main script's global scope. :param glob: main ...
return the replacement string. this assumes the preceeding {{ has already been popped off. 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_...
Calculate the distance between two RGB sequences. 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)))
Convert an RGB colour to 8 or 16 colour ANSI graphics. 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() re...
Convert an RGB colour to 256 colour ANSI graphics. 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: grey = r <...
Get file download link. .. note:: The URI generation assumes that you can download the file using the view ``invenio_records_ui.<pid_type>_files``. def uri(self): """Get file download link. .. note:: The URI generation assumes that you can download the ...
Check if file has one of the extensions. 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
Pretty print the JSON file for rendering. def render(file): """Pretty print the JSON file for rendering.""" 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=OrderedDic...
Validate a JSON file. def validate_json(file): """Validate a 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().decode('...
Complete and denoise EDM using OptSpace algorithm. Uses OptSpace algorithm to complete and denoise EDM. The problem being solved is X,S,Y = argmin_(X,S,Y) || W ° (D - XSY') ||_F^2 :param edm_missing: EDM with 0 where no measurement was taken. :param rank: expected rank of complete EDM. :param nite...
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 EDM. :param niter: maximum number of iterations. :param edm: if given, the relative...
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 measured matrix, W is a weight matrix, and * is pointwise multiplication. Refer to paper "Eu...
Complete an denoise EDM using alternating decent. The idea here is to simply run reconstruct_acd for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: opt...
Complete an denoise EDM using dwMDS. The idea here is to simply run reconstruct_dwmds for a few iterations, yieding a position estimate, which can in turn be used to get a completed and denoised edm. :param edm: noisy matrix (NxN) :param X0: starting points (Nxd) :param W: optional weigh...
convert the transmute_path to a tornado compatible regex, and return a tornado url object. 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) ...
Initialize points according to predefined modes. :param range_:[xmin, xmax, ymin, ymax], range of point sets 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 ...
Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta. def create_theta(self): """ Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Al...
calculate angles theta_ik and theta_jk theta produce point Pk. Should give the same as get_absolute_angle! 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...
Get indices of theta vector that have k as first corner. :param k: Index of corner. :return indices_rays: Indices of ray angles in theta vector. :return indices_triangles: Indices of triangle angles in theta vector. :return corners_rays: List of corners of ray angles. :...
get G matrix from angles. def get_G(self, k, add_noise=True): """ get G matrix from angles. """ 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_indic...
:param m: size of polygones (number of corners) :return: (ordered) indices of all convex polygones of size m. 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 si...
: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 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 def get_polygon_constraints_m(self, polygons_m, print_out=False): """ :param range_polygones: list of numbers of polygones to test. :return A, b: the...
Get linear constraints on KE matrix. 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_...
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, 'packet_type': 17, ...
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 def _bytes_to_uint_48(self, bytes_): """Converts an array of 6 bytes to a 48bit integer. :param data: byte...
Parse a 18 bytes packet in the Electricity format and return a dictionary containing the data extracted. An example of a return value would be: .. code-block:: python { 'count': 3, 'current_watts': 692, 'id': "0x2EB2", ...
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 def get_key_from_path_and_site(path, site_id): ''' cache key has to be < 250 chars to avoid memcache.Client.MemcachedKeyLengthError The best a...
Return dialect information about given csv file. def validate_csv(file): """Return dialect information about given csv file.""" try: # Detect encoding and dialect with file.open() as fp: encoding = detect_encoding(fp, default='utf-8') sample = fp.read( cu...
Render appropiate template with embed flag. 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...
Create tree structure from ZIP archive. def make_tree(file): """Create tree structure from ZIP archive.""" 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...
Organize children structure. def children_to_list(node): """Organize children structure.""" if node['type'] == 'item' and len(node['children']) == 0: del node['children'] else: node['type'] = 'folder' node['children'] = list(node['children'].values()) node['children'].sort(k...
Return appropriate template and pass the file and an embed flag. 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",...
Create noisy version of edm Adds symmetric Gaussian noise to non-diagonal elements of EDM (to distances!). The output EDM is ensured to have only positive entries. :param edm: Original, noiseless EDM. :param noise: Standard deviation of Gaussian noise to be added to distances. :param n: H...
Create weight mask according to method. :param N: Dimension of square weight matrix. :param method: Method to use (default: 'all'). - none: no missing entries (only diagonal is set to 0 for dwMDS) - first: only randomly delete measurements to first point (zeros in first row/column of matrix) - all:...
describe is a decorator to customize the rest API that transmute generates, such as choosing certain arguments to be query parameters or body parameters, or a different method. :param list(str) paths: the path(s) for the handler to represent (using swagger's syntax for a path) :param list(str) met...
a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation def add_swagger(app, json_route, html_route): """ a convenience method for both adding a swagger.json route, as well as adding a page showing the html documentation """ app.router....
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. def add_swagger_api_route(app, target_route, swagger_json_route): """ mount a swagg...