code stringlengths 1 18.2k |
|---|
def add_bundle(self, data: dict) -> models.Bundle: """Build a new bundle version of files. The format of the input dict is defined in the `schema` module. """ bundle_obj = self.bundle(data['name']) if bundle_obj and self.version(bundle_obj.name, data['created']): LOG.debug('version of bundle already added') return None... |
def _build_tags(self, tag_names: List[str]) -> dict: """Build a list of tag objects.""" tags = {} for tag_name in tag_names: tag_obj = self.tag(tag_name) if tag_obj is None: LOG.debug(f"create new tag: {tag_name}") tag_obj = self.new_tag(tag_name) tags[tag_name] = tag_obj return tags |
def create_comment_commit(self, body, commit_id, path, position, pr_id): """ Posts a comment to a given commit at a certain pull request. Check https://developer.github.com/v3/pulls/comments/#create-a-comment param body: str -> Comment text param commit_id: str -> SHA of the commit param path: str -> Relative path of t... |
def convert_svg_transform(self, transform): """ Converts a string representing a SVG transform into AffineTransform fields. See https://www.w3.org/TR/SVG/coords.html#TransformAttribute for the specification of the transform strings. skewX and skewY are not supported. Raises: ValueError: If transform is not a valid and ... |
c, x * (1 - c) + y * s, -x * s + y * (1 - c), ] else: raise ValueError('Unknown transformation "%s"' % transform) self._svg_transform = transform self._a00 = a[0] self._a10 = a[1] self._a01 = a[2] self._a11 = a[3] self._a02 = a[4] self._a12 = a[5] |
def run(self): """ Runs prospector in the input files and returns a json with the analysis """ arg_prospector = f'prospector --output-format json {self.repo.diff_files()}' analysis = subprocess.run(arg_prospector, stdout=subprocess.PIPE, shell=True) return json.loads(analysis.stdout) |
def execute(self, operation, parameters=()): """ Wraps execute method to record the query, execution duration and stackframe. """ __traceback_hide__ = True # NOQ # Time the exection of the query start = time.time() try: return self.cursor.execute(operation, parameters) finally: end = time.time() # Save the data data = ... |
def main(): """Collect user args and call command funct. Collect command line args and setup environment then call function for command specified in args. """ parser = parser_setup() options = parser.parse_args() debug = bool(options.debug > 0) debugall = bool(options.debug > 1) awsc.init() debg.init(debug, debugall) p... |
def parser_setup(): """Create ArgumentParser object to parse command line arguments. Returns: parser (object): containing ArgumentParser data and methods. Raises: SystemExit: if the user enters invalid args. """ parser = argparse.ArgumentParser(description="Control AWS instances from" " the command line with: list, sta... |
" If no specifications are given, " " all instances will be listed." " ex: 'awss list TEST " "-r' will list instances named 'TEST'" " that are currently running.", usage="\tawss list [none] [NAME] [-i " "ID] [-r] [-s] [OPTIONS]") parser_list.add_argument('instname', nargs='?', metavar='NAME', help='specify instance by ... |
[NAME]" " [-i ID] [-h]", description="Stop an AWS instance" " from the command line.") parser_stop.add_argument('instname', nargs='?', metavar='NAME', help='specify instance by name') parser_stop.add_argument('-i', '--id', action="store", help='specify instance-id') parser_stop.add_argument('-d', '--debug', action="cou... |
def cmd_list(options): """Gather data for instances matching args and call display func. Args: options (object): contains args and data from parser. """ (i_info, param_str) = gather_data(options) if i_info: awsc.get_all_aminames(i_info) param_str = "Instance List - " + param_str + "\n" list_instances(i_info, param_str)... |
def cmd_startstop(options): """Start or Stop the specified instance. Finds instances that match args and instance-state expected by the command. Then, the target instance is determined, the action is performed on the instance, and the eturn information is displayed. Args: options (object): contains args and data from p... |
def cmd_ssh(options): """Connect to the specified instance via ssh. Finds instances that match the user specified args that are also in the 'running' state. The target instance is determined, the required connection information is retreived (IP, key and ssh user-name), then an 'ssh' connection is made to the instance. ... |
c_itm[2])) else: debg.dprint("Connect string: ", "ssh {}@{}". format(options.user, i_info[tar_idx]['pub_dns_name'])) cmd_ssh_run += " {0}@{1}".format(options.user, i_info[tar_idx]['pub_dns_name']) print(cmd_ssh_run) subprocess.call(cmd_ssh_run, shell=True) |
def cmd_ssh_user(tar_aminame, inst_name): """Calculate instance login-username based on image-name. Args: tar_aminame (str): name of the image instance created with. inst_name (str): name of the instance. Returns: username (str): name for ssh based on AMI-name. """ if tar_aminame == "Unknown": tar_aminame = inst_name #... |
def gather_data(options): """Get Data specific for command selected. Create ec2 specific query and output title based on options specified, retrieves the raw response data from aws, then processes it into the i_info dict, which is used throughout this module. Args: options (object): contains args and data from parser, ... |
def process_results(qry_results): """Generate dictionary of results from query. Decodes the large dict recturned from the AWS query. Args: qry_results (dict): results from awsc.get_inst_info Returns: i_info (dict): information on instances and details. """ i_info = {} for i, j in enumerate(qry_results['Reservations']):... |
def process_tags(inst_tags): """Create dict of instance tags as only name:value pairs.""" tag_dict = {} for k in range(len(inst_tags)): tag_dict[inst_tags[k]['Key']] = inst_tags[k]['Value'] return tag_dict |
def qry_create(options): """Create query from the args specified and command chosen. Creates a query string that incorporates the args in the options object, and creates the title for the 'list' function. Args: options (object): contains args and data from parser Returns: qry_string (str): the query to be used against ... |
qry_string, param_str, bool(options.instname), filt_st) qry_string += ("{'Name': 'instance-state-name'," "'Values': ['%s']}" % (options.inst_state)) param_str += "state: '%s'" % (options.inst_state) filt_end = "]" param_str_default = "" qry_string += filt_end param_str += param_str_default debg.dprintx("\nQuery String"... |
def qry_helper(flag_id, qry_string, param_str, flag_filt=False, filt_st=""): """Dynamically add syntaxtical elements to query. This functions adds syntactical elements to the query string, and report title, based on the types and number of items added thus far. Args: flag_filt (bool): at least one filter item specified... |
(qry_string, param_str) |
def list_instances(i_info, param_str, numbered=False): """Display a list of all instances and their details. Iterates through all the instances in the dict, and displays information for each instance. Args: i_info (dict): information on instances and details. param_str (str): the title to display before the list. numbe... |
def list_tags(tags): """Print tags in dict so they allign with listing above.""" tags_sorted = sorted(list(tags.items()), key=operator.itemgetter(0)) tag_sec_spacer = "" c = 1 ignored_keys = ["Name", "aws:ec2spot:fleet-request-id"] pad_col = {1: 38, 2: 49} for k, v in tags_sorted: # if k != "Name": if k not in ignored_... |
def determine_inst(i_info, param_str, command): """Determine the instance-id of the target instance. Inspect the number of instance-ids collected and take the appropriate action: exit if no ids, return if single id, and call user_picklist function if multiple ids exist. Args: i_info (dict): information and details for ... |
def user_picklist(i_info, command): """Display list of instances matching args and ask user to select target. Instance list displayed and user asked to enter the number corresponding to the desired target instance, or '0' to abort. Args: i_info (dict): information on instances and details. command (str): command specif... |
def user_entry(entry_int, num_inst, command): """Validate user entry and returns index and validity flag. Processes the user entry and take the appropriate action: abort if '0' entered, set validity flag and index is valid entry, else return invalid index and the still unset validity flag. Args: entry_int (int): a numb... |
command)) sys.exit() elif entry_int >= 1 and entry_int <= num_inst: entry_idx = entry_int - 1 valid_entry = True else: print("{}Invalid entry:{} enter a number between 1" " and {}.".format(C_ERR, C_NORM, num_inst)) entry_idx = entry_int return (entry_idx, valid_entry) |
def execute(args): """ Call vswhere with the given arguments and return an array of results. `args` is a list of command line arguments to pass to vswhere. If the argument list contains '-property', this returns an array with the property value for each result. Otherwise, this returns an array of dictionaries containin... |
def find(find_all=False, latest=False, legacy=False, prerelease=False, products=None, prop=None, requires=None, requires_any=False, version=None): """ Call vswhere and return an array of the results. If `find_all` is true, finds all instances even if they are incomplete and may not launch. If `latest` is true, returns ... |
name of a property to return instead of the full installation details. Use delimiters '.', '/', or '_' to separate object and property names. Example: 'properties.nickname' will return the 'nickname' property under 'properties'. `requires` is a list of one or more workload component IDs required when finding instances.... |
def get_vswhere_path(): """ Get the path to vshwere.exe. If vswhere is not already installed as part of Visual Studio, and no alternate path is given using `set_vswhere_path()`, the latest release will be downloaded and stored alongside this script. """ if alternate_path and os.path.exists(alternate_path): return alter... |
def _download_vswhere(): """ Download vswhere to DOWNLOAD_PATH. """ print('downloading from', _get_latest_release_url()) try: from urllib.request import urlopen with urlopen(_get_latest_release_url()) as response, open(DOWNLOAD_PATH, 'wb') as outfile: shutil.copyfileobj(response, outfile) except ImportError: # Python 2... |
def _get_source(self): """ Get the lambda function source template. Strip the leading docstring. Note that it's a real module in this project so we can test it. :return: function source code, with leading docstring stripped. :rtype: str """ logger.debug('Getting module source for webhook2lambda2sqs.lambda_func') orig =... |
def _docstring(self): """ Generate a docstring for the generated source file. :return: new docstring :rtype: str """ s = '"""' + "\n" s += "webhook2lambda2sqs generated function source\n" s += "this code was generated by webhook2lambda2sqs v%s\n" % VERSION s += "<%s>\n" % PROJECT_URL s += "this project is licensed unde... |
def generate(self): """ Generate Lambda function source; return it as a string. :rtype: str :returns: lambda function source """ s = self._docstring s += self._get_source().replace( 'endpoints = {}', 'endpoints = ' + self._config_src ).replace( 'logger.setLevel(logging.INFO)', 'logger.setLevel(logging.%s)' % self.confi... |
def kem(request): """ due to the base directory settings of django, the model_path needs to be different when testing with this section. """ keyword = request.GET['keyword'] lang = request.GET['lang'] ontology = 'ontology' if 'ontology' in request.GET and bool(json.loads(request.GET['ontology'].lower())) else 'origin' ... |
def normalize_date(date): '''normalize the specified date to milliseconds since the epoch If it is a string, it is assumed to be some sort of datetime such as "2015-12-27" or "2015-12-27T11:01:20.954". If date is a naive datetime, it is assumed to be UTC. If numeric arguments are beyond 5138-11-16 (100,000,000,000 seco... |
{!r}'.format(date) raise InvalidDatalakeMetadata(msg) return Metadata._from_datetime(date) |
def amalgamate_sql(app, model, extra_fields=None, table_name=None, view_name=None): """This function returns a string, containing SQL to create a view exposing given model's content_type_id and object_id, with some extra_fields optionally. This function does *not* escape or quote its arguments. >>> print(utils.amalgama... |
'_' || %(table_name)s.id AS fake_id, U0.id AS content_type_id, %(table_name)s.id AS object_id %(extra_fields)s FROM %(table_name)s, (SELECT id FROM django_content_type WHERE app_label = '%(app)s' AND model = '%(model)s' ) U0; """ % dict(view_name=view_name, app=app, model=model, table_name=table_name, extra_fields=extr... |
def union_sql(view_name, *tables): """This function generates string containing SQL code, that creates a big VIEW, that consists of many SELECTs. >>> utils.union_sql('global', 'foo', 'bar', 'baz') 'CREATE VIEW global SELECT * FROM foo UNION SELECT * FROM bar UNION SELECT * FROM baz' """ if not tables: raise Exception("... |
def _get_output_nodes(self, output_path, error_path): """ Extracts output nodes from the standard output and standard error files. """ from pymatgen.io.nwchem import NwOutput from aiida.orm.data.structure import StructureData from aiida.orm.data.array.trajectory import TrajectoryData ret_dict = [] nwo = NwOutput(output... |
def init(context, reset, force): """Setup the database.""" store = Store(context.obj['database'], context.obj['root']) existing_tables = store.engine.table_names() if force or reset: if existing_tables and not force: message = f"Delete existing tables? [{', '.join(existing_tables)}]" click.confirm(click.style(message, ... |
def _setup_frontend(self): ''' Receiver sockets facing clients (DAQ systems) ''' self.frontends = [] self.fe_poller = zmq.Poller() for actual_frontend_address in self.frontend_address: # Subscriber or server socket actual_frontend = (actual_frontend_address, self.context.socket(self.frontend_socket_type)) # Wait 0.5 s ... |
def _setup_backend(self): ''' Send sockets facing services (e.g. online monitor, other forwarders) ''' self.backends = [] self.be_poller = zmq.Poller() for actual_backend_address in self.backend_address: # publisher or client socket actual_backend = (actual_backend_address, self.context.socket(self.backend_socket_type)... |
def send_data(self, data): ''' This function can be overwritten in derived class Std. function is to broadcast all receiver data to all backends ''' for frontend_data in data: serialized_data = self.serialize_data(frontend_data) if sys.version_info >= (3, 0): serialized_data = serialized_data.encode('utf-8') for actual... |
def load_config(config_file, default_config_file, **kwargs): '''load the configuration Configuration variables are delivered to applications exclusively through the environment. They get into the environment either from a specified configuration file, from a default configuration file, from an environment variable, or ... |
`DATALAKE_FOO`. The only exception to this is a kwarg that starts with `aws_`. That is, a kwarg called `aws_baz` would map to a configuration variable called `AWS_BAZ`. Args: - config_file: the configuration file to load. If it is None, default_config_file will be examined. If it is not None and does not exist an Insuf... |
def pre_handler(self, cmd): """Hook for logic before each handler starts.""" if self._finished: return if self.interesting_commit and cmd.name == 'commit': if cmd.mark == self.interesting_commit: print(cmd.to_string()) self._finished = True return if cmd.name in self.parsed_params: fields = self.parsed_params[cmd.name]... |
def feature_handler(self, cmd): """Process a FeatureCommand.""" feature = cmd.feature_name if feature not in commands.FEATURE_NAMES: self.warning("feature %s is not supported - parsing may fail" % (feature,)) |
def from_object(updates): "Update same name (or prefixed) settings." import sys config = sys.modules[__name__] prefix = config.__name__.split('.')[0].upper() keys = [k for k in config.__dict__ if \ k != from_object.__name__ and not k.startswith('_')] get_value = lambda c, k: hasattr(c, k) and getattr(c, k) or None for ... |
def commit_format(self): """ Formats the analysis into a simpler dictionary with the line, file and message values to be commented on a commit. Returns a list of dictionaries """ formatted_analyses = [] for analyze in self.analysis['messages']: formatted_analyses.append({ 'message': f"{analyze['source']}: {analyze['mes... |
def bundles(): """Display bundles.""" per_page = int(request.args.get('per_page', 30)) page = int(request.args.get('page', 1)) query = store.bundles() query_page = query.paginate(page, per_page=per_page) data = [] for bundle_obj in query_page.items: bundle_data = bundle_obj.to_dict() bundle_data['versions'] = [version.... |
def int_to_rgba(cls, rgba_int): """Converts a color Integer into r, g, b, a tuple.""" if rgba_int is None: return None, None, None, None alpha = rgba_int % 256 blue = rgba_int / 256 % 256 green = rgba_int / 256 / 256 % 256 red = rgba_int / 256 / 256 / 256 % 256 return (red, green, blue, alpha) |
def radii_of_curvature(self): """The radius of curvature at each point on the Polymer primitive. Notes ----- Each element of the returned list is the radius of curvature, at a point on the Polymer primitive. Element i is the radius of the circumcircle formed from indices [i-1, i, i+1] of the primitve. The first and fin... |
def format_float(x, max_width): '''format_float will ensure that a number's decimal part is truncated to fit within some bounds, unless the whole part is wider than max_width, which is a problem you need to sort out yourself. ''' # width of (whole part + 1 (to avoid zero)) + 1 because int floors, not ceils whole_width ... |
def monkey_patch_issue_25593(): """ Workaround for http://bugs.python.org/issue25593 """ save = asyncio.selector_events.BaseSelectorEventLoop._sock_connect_cb @functools.wraps(save) def patched(instance, fut, sock, address): if not fut.done(): save(instance, fut, sock, address) asyncio.selector_events.BaseSelectorEvent... |
def safe_compile(self, settings, sourcepath, destination): """ Safe compile It won't raise compile error and instead return compile success state as a boolean with a message. It will create needed directory structure first if it contain some directories that does not allready exists. Args: settings (boussole.conf.model... |
is allways in the same directory than compiled # CSS file output_filename_hint=destination, source_map_filename=source_map_destination, ) except sass.CompileError as e: return False, six.text_type(e) else: # Compiler return a tuple (css, map) if sourcemap is # enabled sourcemap = None if settings.SOURCE_MAP: content, s... |
def write_content(self, content, destination): """ Write given content to destination path. It will create needed directory structure first if it contain some directories that does not allready exists. Args: content (str): Content to write to target file. destination (str): Destination path for target file. Returns: st... |
def make_batch(size, graph): """ Split graphs into n sized chunks. See: http://stackoverflow.com/a/1915307/758157 :param size: int :param graph: graph :return: graph """ i = iter(graph) chunk = list(islice(i, size)) while chunk: yield chunk chunk = list(islice(i, size)) |
def nt_yielder(self, graph, size): """ Yield n sized ntriples for a given graph. Used in sending chunks of data to the VIVO SPARQL API. """ for grp in self.make_batch(size, graph): tmpg = Graph() # Add statements as list to tmp graph tmpg += grp yield (len(tmpg), tmpg.serialize(format='nt')) |
def bulk_update(self, named_graph, graph, size, is_add=True): """ Bulk adds or deletes. Triples are chunked into n size groups before sending to API. This prevents the API endpoint from timing out. """ context = URIRef(named_graph) total = len(graph) if total > 0: for set_size, nt in self.nt_yielder(graph, size): if is... |
def bulk_add(self, named_graph, add, size=DEFAULT_CHUNK_SIZE): """ Add batches of statements in n-sized chunks. """ return self.bulk_update(named_graph, add, size) |
def bulk_remove(self, named_graph, add, size=DEFAULT_CHUNK_SIZE): """ Remove batches of statements in n-sized chunks. """ return self.bulk_update(named_graph, add, size, is_add=False) |
def merge_uris(self, uri1, uri2, graph=DEFAULT_GRAPH): """ Generate statements to merge two URIS in a specified graph. """ rq = """ CONSTRUCT { ?uri ?p ?o . ?other ?p2 ?uri . } WHERE { GRAPH ?g { { ?uri ?p ?o } UNION { ?other ?p2 ?uri } } } """ for var in [uri1, uri2, graph]: assert type(var) == URIRef addg = Graph() r... |
def blend(c1, c2): """Alpha blends two colors, using the alpha given by c2""" return [c1[i] * (0xFF - c2[3]) + c2[i] * c2[3] >> 8 for i in range(3)] |
def gradient_list(start, end, steps): """Compute gradient colors""" delta = [end[i] - start[i] for i in range(4)] return [bytearray(start[j] + (delta[j] * i) // steps for j in range(4)) for i in range(steps + 1)] |
def rgb2rgba(rgb): """Take a row of RGB bytes, and convert to a row of RGBA bytes.""" rgba = [] for i in range(0, len(rgb), 3): rgba += rgb[i:i+3] rgba.append(255) return rgba |
def read(self, num_bytes): """Read `num_bytes` from the compressed data chunks. Data is returned as `bytes` of length `num_bytes` Will raise an EOFError if data is unavailable. Note: Will always return `num_bytes` of data (unlike the file read method). """ while len(self.decoded) < num_bytes: try: tag, data = next(self... |
def _offset(self, x, y): """Helper for internal data""" x, y = force_int(x, y) return y * self.width * 4 + x * 4 |
def point(self, x, y, color=None): """Set a pixel""" if x < 0 or y < 0 or x > self.width - 1 or y > self.height - 1: return if color is None: color = self.color o = self._offset(x, y) self.canvas[o:o + 3] = blend(self.canvas[o:o + 3], bytearray(color)) |
def rect_helper(x0, y0, x1, y1): """Rectangle helper""" x0, y0, x1, y1 = force_int(x0, y0, x1, y1) if x0 > x1: x0, x1 = x1, x0 if y0 > y1: y0, y1 = y1, y0 return x0, y0, x1, y1 |
def vertical_gradient(self, x0, y0, x1, y1, start, end): """Draw a vertical gradient""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) grad = gradient_list(start, end, y1 - y0) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): self.point(x, y, grad[y - y0]) |
def rectangle(self, x0, y0, x1, y1): """Draw a rectangle""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) self.polyline([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]]) |
def filled_rectangle(self, x0, y0, x1, y1): """Draw a filled rectangle""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): self.point(x, y, self.color) |
def copy_rect(self, x0, y0, x1, y1, dx, dy, destination): """Copy (blit) a rectangle onto another part of the image""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) dx, dy = force_int(dx, dy) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): d = destination._offset(dx + x - x0, dy + y - y0) o = self._offset(x... |
def blend_rect(self, x0, y0, x1, y1, dx, dy, destination, alpha=0xff): """Blend a rectangle onto the image""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) for x in range(x0, x1 + 1): for y in range(y0, y1 + 1): o = self._offset(x, y) rgba = self.canvas[o:o + 4] rgba[3] = alpha destination.point(dx + x - x0, dy + y... |
def line(self, x0, y0, x1, y1): """Draw a line using Xiaolin Wu's antialiasing technique""" # clean params x0, y0, x1, y1 = int(x0), int(y0), int(x1), int(y1) if y0 > y1: y0, y1, x0, x1 = y1, y0, x1, x0 dx = x1 - x0 if dx < 0: sx = -1 else: sx = 1 dx *= sx dy = y1 - y0 # 'easy' cases if dy == 0: for x in range(x0, x1, ... |
16) // dy for i in range(y0, y1 - 1): e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xFFFF if e_acc <= e_acc_temp: x0 += sx w = 0xFF-(e_acc >> 8) self.point(x0, y0, intensity(self.color, w)) y0 += 1 self.point(x0 + sx, y0, intensity(self.color, (0xFF - w))) self.point(x1, y1) return # horizontal displacement e = (dy << 16) ... |
def polyline(self, arr): """Draw a set of lines""" for i in range(0, len(arr) - 1): self.line(arr[i][0], arr[i][1], arr[i + 1][0], arr[i + 1][1]) |
def dump(self): """Dump the image data""" scan_lines = bytearray() for y in range(self.height): scan_lines.append(0) # filter type 0 (None) scan_lines.extend( self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)] ) # image represented as RGBA tuples, no interlacing return SIGNATURE + \ self.pack_chunk(b'IHDR', s... |
def pack_chunk(tag, data): """Pack a PNG chunk for serializing to disk""" to_check = tag + data return (struct.pack(b"!I", len(data)) + to_check + struct.pack(b"!I", zlib.crc32(to_check) & 0xFFFFFFFF)) |
def load(self, f): """Load a PNG image""" SUPPORTED_COLOR_TYPES = (COLOR_TYPE_TRUECOLOR, COLOR_TYPE_TRUECOLOR_WITH_ALPHA) SAMPLES_PER_PIXEL = { COLOR_TYPE_TRUECOLOR: 3, COLOR_TYPE_TRUECOLOR_WITH_ALPHA: 4 } assert f.read(8) == SIGNATURE chunks = iter(self.chunks(f)) header = next(chunks) assert header[0] == b'IHDR' (wid... |
= SAMPLES_PER_PIXEL[COLOR_TYPE_TRUECOLOR_WITH_ALPHA] * width bytes_per_scanline = bytes_per_row + 1 # Python 2 requires the encode for struct.unpack scanline_fmt = ('!%dB' % bytes_per_scanline).encode('ascii') reader = ByteReader(chunks) old_row = None cursor = 0 for row in range(height): scanline = reader.read(bytes_p... |
def defilter(cur, prev, filter_type, bpp=4): """Decode a chunk""" if filter_type == 0: # No filter return cur elif filter_type == 1: # Sub xp = 0 for xc in range(bpp, len(cur)): cur[xc] = (cur[xc] + cur[xp]) % 256 xp += 1 elif filter_type == 2: # Up for xc in range(len(cur)): cur[xc] = (cur[xc] + prev[xc]) % 256 elif f... |
= prev[xc] c = prev[xp] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: value = a elif pb <= pc: value = b else: value = c cur[xc] = (cur[xc] + value) % 256 xp += 1 else: raise ValueError('Unrecognized scanline filter type: {}'.format(filter_type)) return cur |
def chunks(f): """Split read PNG image data into chunks""" while 1: try: length = struct.unpack(b"!I", f.read(4))[0] tag = f.read(4) data = f.read(length) crc = struct.unpack(b"!I", f.read(4))[0] except struct.error: return if zlib.crc32(tag + data) & 0xFFFFFFFF != crc: raise IOError('Checksum fail') yield tag, data |
async def start(self) -> None: """Coroutine to run this server.""" if self._is_running: raise SublemonRuntimeError( 'Attempted to start an already-running `Sublemon` instance') self._poll_task = asyncio.ensure_future(self._poll()) self._is_running = True |
async def stop(self) -> None: """Coroutine to stop execution of this server.""" if not self._is_running: raise SublemonRuntimeError( 'Attempted to stop an already-stopped `Sublemon` instance') await self.block() self._poll_task.cancel() self._is_running = False with suppress(asyncio.CancelledError): await self._poll_ta... |
async def _poll(self) -> None: """Coroutine to poll status of running subprocesses.""" while True: await asyncio.sleep(self._poll_delta) for subproc in list(self._running_set): subproc._poll() |
async def iter_lines( self, *cmds: str, stream: str='both') -> AsyncGenerator[str, None]: """Coroutine to spawn commands and yield text lines from stdout.""" sps = self.spawn(*cmds) if stream == 'both': agen = amerge( amerge(*[sp.stdout for sp in sps]), amerge(*[sp.stderr for sp in sps])) elif stream == 'stdout': agen ... |
async def gather(self, *cmds: str) -> Tuple[int]: """Coroutine to spawn subprocesses and block until completion. Note: The same `max_concurrency` restriction that applies to `spawn` also applies here. Returns: The exit codes of the spawned subprocesses, in the order they were passed. """ subprocs = self.spawn(*cmds) su... |
async def block(self) -> None: """Block until all running and pending subprocesses have finished.""" await asyncio.gather( *itertools.chain( (sp.wait_done() for sp in self._running_set), (sp.wait_done() for sp in self._pending_set))) |
def spawn(self, *cmds: str) -> List[SublemonSubprocess]: """Coroutine to spawn shell commands. If `max_concurrency` is reached during the attempt to spawn the specified subprocesses, excess subprocesses will block while attempting to acquire this server's semaphore. """ if not self._is_running: raise SublemonRuntimeErr... |
def parse_filepath(self, filepath=None): """ Parse given filepath to split possible path directory from filename. * If path directory is empty, will use ``basedir`` attribute as base filepath; * If path directory is absolute, ignore ``basedir`` attribute; * If path directory is relative, join it to ``basedir`` attribut... |
def check_filepath(self, path, filename): """ Check and return the final filepath to settings Args: path (str): Directory path where to search for settings file. filename (str): Filename to use to search for settings file. Raises: boussole.exceptions.SettingsBackendError: If determined filepath does not exists or is a ... |
def open(self, filepath): """ Open settings backend to return its content Args: filepath (str): Settings object, depends from backend Returns: string: File content. """ with io.open(filepath, 'r', encoding='utf-8') as fp: content = fp.read() return content |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.