output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def processes_with_env_psutil(env_name, env_value): """ Find PIDs of processes having environment variable matching given one. Internally it uses `psutil` library. :param str env_name: name of environment variable to be found :param str env_value: environment variable value prefix :return: pro...
Write a Python 3 script to find processes with environment variable matching given one.
As a Python code analyst, you investigate and solve complex coding mysteries
def processes_with_env_ps(env_name, env_value): """ Find PIDs of processes having environment variable matching given one. It uses `$ ps xe -o pid,cmd` command so it works only on systems having such command available (Linux, MacOS). If not available function will just log error. :param str en...
Write a Python 3 script for finding processes with environment variable matching given one.
As a Python code composer, you craft elegant and concise scripts.
def _ncc_c(x, y): """ >>> _ncc_c([1,2,3,4], [1,2,3,4]) array([ 0.13333333, 0.36666667, 0.66666667, 1. , 0.66666667, 0.36666667, 0.13333333]) >>> _ncc_c([1,1,1], [1,1,1]) array([ 0.33333333, 0.66666667, 1. , 0.66666667, 0.33333333]) >>> _ncc_c([1,2,3], [-1,-1,-1...
Can you write a function in Python 3 where it computes the NCC of a 2D array.
You are a Python code architect, reviewing and designing scalable and efficient code
Variant of NCCc that operates with 2 dimensional X arrays and 1 dimensional y vector Returns a 2 dimensional array of normalized fourier transforms
Given the following Python 3 function, write the documentation def _ncc_c_2dim(x, y): den = np.array(norm(x, axis=1) * norm(y)) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1 << (2*x_len-1).bit_length() cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size))) cc = np.concatenate((cc[:,-(...
As a python code expert, you are capable of creating scripts from specifications.
Variant of NCCc that operates with 2 dimensional X arrays and 2 dimensional y vector Returns a 3 dimensional array of normalized fourier transforms
Make a summary of the following Python 3 code def _ncc_c_3dim(x, y): den = norm(x, axis=1)[:, None] * norm(y, axis=1) den[den == 0] = np.Inf x_len = x.shape[-1] fft_size = 1 << (2*x_len-1).bit_length() cc = ifft(fft(x, fft_size) * np.conj(fft(y, fft_size))[:, None]) cc = np.concatenate((cc[:,:,-...
You are a Python code analyst, evaluating scripts for potential improvements.
Compute the SVD distance and yshift for a single node.
Make a summary of the following Python 3 code def _sbd(x, y): ncc = _ncc_c(x, y) idx = ncc.argmax() dist = 1 - ncc[idx] yshift = roll_zeropad(y, (idx + 1) - max(len(x), len(y))) return dist, yshift
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the shape of the array of the array of the array at the given index.
Can you generate the documentation for the following Python 3 function def _extract_shape(idx, x, j, cur_center): _a = [] for i in range(len(idx)): if idx[i] == j: if cur_center.sum() == 0: opt_x = x[i] else: _, opt_x = _sbd(cur_center, x[i]) ...
As a Python code composer, you craft elegant and concise scripts.
Returns k - size of the randomized k - array
Can you tell what is the following Python 3 function doing def _kshape(x, k): m = x.shape[0] idx = randint(0, k, size=m) centroids = np.zeros((k, x.shape[1])) distances = np.empty((m, k)) for _ in range(100): old_idx = idx for j in range(k): centroids[j] = _extract_shape...
You are a Python code generator, capable of creating scripts from specifications.
def get_version_by_version_id(version_id): """ Get the internal version ID be the version. :param Tuple version_id: Major and minor version number :return: Internal version ID :rtype: Integer|None """ for ver in registry.version_info: if ver.version_id == version_id: ret...
Write a Python 3 function that can get the internal version ID be the version.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_version_name(version_id): """ Get the name of a protocol version by the internal version ID. :param Integer version_id: Internal protocol version ID :return: Name of the version :rtype: String """ ver = registry.version_info.get(version_id) if ver: return ver.name r...
Write a Python 3 script for getting the name of a protocol version by the internal version ID.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_version_id(protocol_version): """ Get a tuple with major and minor version number :param Integer protocol_version: Internal version ID :return: Tuple of major and minor protocol version :rtype: Tuple """ ver = registry.version_info.get(protocol_version) if ver: return ve...
Write a Python 3 function that can get a tuple with major and minor protocol version number.
You are a Python code analyst, evaluating scripts for potential improvements.
Compress data given in b returning compressed result either from this function or writing to fp.
How would you explain what the following Python 3 function does def update(self, b): # pylint: disable=method-hidden,invalid-name with self.__lock: output = compress_update(self.__ctx, b) if self.__write: self.__write(self.__header) self.__header = None ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Finalise lz4 frame by writing any remaining as return from this function.
How would you explain what the following Python 3 function does def end(self): with self.__lock: if self.__write: self.__write(compress_end(self.__ctx)) else: return compress_end(self.__ctx)
As a Python code analyst, you investigate and solve complex coding mysteries
Get the name of the value of the n - A A
Can you tell what is the following Python 3 function doing def get_value_name(self, pretty=False): if pretty: return "%s (%x)" % ( self.enums.get(self._value, "n/a"), self._value ) return self.enums.get(self._value, "n/a")
You are a Python code architect, reviewing and designing scalable and efficient code
Set the value of the attribute.
Explain what the following Python 3 code does def set_value(self, value, force=False): if force: self._value = value return if value is None: self._value = value return if isinstance(value, six.integer_types): self._value = value ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Dissect the field value from the given bytes.
Given the following Python 3 function, write the documentation def dissect(self, data): size = struct.calcsize("B") if len(data) < size: raise NotEnoughData( "Not enough data to decode field '%s' value" % self.name ) curve_type = struct.unpack("B", data[...
As a Python code analyst, you investigate and solve complex coding mysteries
Compute an WAMP - CRA authentication signature from an authentication challenge and a derived key.
Given the following Python 3 function, write the documentation def compute_wcs(key, challenge): key = key.encode('utf8') challenge = challenge.encode('utf8') sig = hmac.new(key, challenge, hashlib.sha256).digest() return binascii.b2a_base64(sig).strip()
As a Python code analyst, you investigate and solve complex coding mysteries
def _register_procedure(self, procedure_name, invocation_policy="single"): """ Register a "procedure" on a Client as callable over the Router. """ options = {"invoke": invocation_policy} message = Register(procedure=procedure_name, options=options) request_id = message.request_id...
Implement a function in Python 3 to register a procedure on a Client over the Router.
As a Python code translator, you convert algorithms and pseudocode into Python.
Start the Crossbar. io process.
Can you tell what is the following Python 3 function doing def start(self): if self.started is True: raise WampyError("Router already started") # will attempt to connect or start up the CrossBar crossbar_config_path = self.config_path cbdir = self.crossbar_directory ...
As a Python code composer, you craft elegant and concise scripts.
Return the HTTP upgrade handshake headers.
Explain what the following Python 3 code does def _get_handshake_headers(self, upgrade): headers = [] # https://tools.ietf.org/html/rfc6455 headers.append("GET {} HTTP/1.1".format(self.websocket_location)) headers.append("Host: {}:{}".format(self.host, self.port)) headers.append(...
As a Python code analyst, you investigate and solve complex coding mysteries
def parse_url(self): """ Parses a URL of the form: - ws://host[:port][path] - wss://host[:port][path] - ws+unix:///path/to/my.socket """ self.scheme = None self.resource = None self.host = None self.port = None if self.url is None: ...
How would you code a function in Python 3 to parse a URL into a set of attributes.
You are a Python code analyst, evaluating scripts for potential improvements.
def generate_mask(cls, mask_key, data): """ Mask data. :Parameters: mask_key: byte string 4 byte string(byte), e.g. '\x10\xc6\xc4\x16' data: str data to mask """ # Masking of WebSocket traffic from client to server is required ...
How would you code a function in Python 3 to generate a mask for the given key and data.
You are a Python code generator, capable of creating scripts from specifications.
Generate the bytes for the current state of the entry in the cache.
Can you tell what is the following Python 3 function doing def generate_bytes(cls, payload, fin_bit, opcode, mask_payload): # the first byte contains the FIN bit, the 3 RSV bits and the # 4 opcode bits and for a client will *always* be 1000 0001 (or 129). # so we want the first byte to look like...
As a Python code analyst, you investigate and solve complex coding mysteries
def add_edge(self, edge): """ Add edge (u, v) to the graph. Raises InvariantError if adding the edge would form a cycle. """ u, v = edge both_exist = u in self.vertices and v in self.vertices # Using `is` because if they belong to the same component, they MUST ...
How would you code a function in Python 3 to add an edge to the internal set.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a set of edges in canonical order.
How would you explain what the following Python 3 function does def edges(self): canonical_edges = set() for v1, neighbours in self._vertices.items(): for v2 in neighbours: edge = self.canonical_order((v1, v2)) canonical_edges.add(edge) return canonica...
As a python code expert, you are capable of creating scripts from specifications.
Returns the sequence with the duplicates removed preserving input order.
How would you explain what the following Python 3 function does def ordered_deduplicate(sequence): seen = set() # Micro optimization: each call to seen_add saves an extra attribute # lookup in most iterations of the loop. seen_add = seen.add return tuple(x for x in sequence if not (x in seen or se...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a CzechHashBuilder object that can be used to generate the hash parameters for the given set of words.
How would you explain what the following Python 3 function does def hash_parameters(words, minimize_indices=False): # Ensure that we have an indexable sequence. words = tuple(words) # Delegate to the hash builder. return CzechHashBuilder(words).hash_info
You are a Python code generator, capable of creating scripts from specifications.
def make_pickable_hash(words, *args, **kwargs): """ Creates an ordered, minimal perfect hash function for the given sequence of words. >>> hf = make_pickable_hash(['sun', 'mon', 'tue', 'wed', 'thu', ... 'fri', 'sat']) >>> hf('fri') 5 >>> hf('sun') 0 """ ...
Write a Python 3 script for creating a pickable hash function for the given sequence of words.
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a dictionary from a sequence of words.
How would you explain what the following Python 3 function does def make_dict(name, words, *args, **kwargs): info = CzechHashBuilder(words, *args, **kwargs) # Create a docstring that at least describes where the class came from... doc = """ Dictionary-like object that uses minimal perfect hashing,...
You are a Python code architect, reviewing and designing scalable and efficient code
def hash_function(self): """ Returns the hash function proper. Ensures that `self` is not bound to the returned closure. """ assert hasattr(self, 'f1') and hasattr(self, 'f2') # These are not just convenient aliases for the given # attributes; if `self` would cre...
Create a Python 3 function to return the hash function proper for the given object.
You are a Python code architect, reviewing and designing scalable and efficient code
def generate_acyclic_graph(self): """ Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object. """ # Maximum length of each table, respectively. # Hardcoded n = cm, where c = 3 # There might be a good way...
Create a Python 3 function to generate an acyclic graph for the given words.
As a Python code composer, you craft elegant and concise scripts.
def generate_random_table(self): """ Generates random tables for given word lists. """ table = list(range(0, self.n)) random.shuffle(table) return table
Implement a function in Python 3 to generate random tables for given word lists.
As a Python code composer, you craft elegant and concise scripts.
Generates a random mini - hashing function.
How would you explain what the following Python 3 function does def generate_func(self, table): # Ensure that `self` isn't suddenly in the closure... n = self.n def func(word): return sum(x * ord(c) for x, c in zip(table, word)) % n return func
As a Python code composer, you craft elegant and concise scripts.
def create_dict_subclass(name, hash_func, slots, doc): """ Creates a dict subclass named name, using the hash_function to index hash_length items. Doc should be any additional documentation added to the class. """ hash_length = len(slots) # Returns array index -- raises a KeyError if the k...
Write a Python 3 function that can create a dict subclass with the given name and hash_function and the given slots and documentation.
As a Python code analyst, you investigate and solve complex coding mysteries
def validate(data, skiperrors=False, fixerrors=True): """Checks that the geojson data is a feature collection, that it contains a proper "features" attribute, and that all features are valid too. Returns True if all goes well. - skiperrors will throw away any features that fail to validate. - fixer...
Write a Python 3 function for checking that the geojson data is a feature collection and that all features are valid.
You are a Python code architect, reviewing and designing scalable and efficient code
Validates that the geometry is correctly formatted according to the geometry type and coordinates.
How would you explain what the following Python 3 function does def validate(self, fixerrors=True): # validate nullgeometry or has type and coordinates keys if not self._data: # null geometry, no further checking needed return True elif "type" not in self._data or "coord...
You are a Python code architect, reviewing and designing scalable and efficient code
Validates that the feature is correctly formatted.
Can you generate the documentation for the following Python 3 function def validate(self, fixerrors=True): if not "type" in self._data or self._data["type"] != "Feature": if fixerrors: self._data["type"] = "Feature" else: raise Exception("A geojson feature...
As a Python code translator, you convert algorithms and pseudocode into Python.
def all_attributes(self): """ Collect and return a list of all attributes/properties/fields used in any of the features. """ features = self._data["features"] if not features: return [] elif len(features) == 1: return features[0]["properties"].keys() else: ...
Implement a function in Python 3 to collect and return a list of all attributes and properties used in any of the features.
As a Python code composer, you craft elegant and concise scripts.
Collect and return a list of attributes and properties common to all features.
Can you generate a brief explanation for the following Python 3 code def common_attributes(self): features = self._data["features"] if not features: return [] elif len(features) == 1: return features[0]["properties"].keys() else: fields = set(features[0]["properties"].keys())...
You are a Python code analyst, evaluating scripts for potential improvements.
Adds a given feature to the internal data structure.
Explain what the following Python 3 code does def add_feature(self, obj=None, geometry=None, properties=None): properties = properties or {} if isinstance(obj, Feature): # instead of creating copy, the original feat should reference the same one that was added here feat = obj._da...
As a Python code analyst, you investigate and solve complex coding mysteries
Define the coordinate reference system for the geojson file.
How would you explain what the following Python 3 function does def define_crs(self, type, name=None, link=None, link_type=None): if not type in ("name","link"): raise Exception("type must be either 'name' or 'link'") crs = self._data["crs"] = {"type":type, "properties":{} } if type == "name": ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Recalculates the bbox region attribute for the entire file.
Given the following Python 3 function, write the documentation def update_bbox(self): xmins, ymins, xmaxs, ymaxs = zip(*(feat.geometry.bbox for feat in self if feat.geometry.type != "Null")) bbox = [min(xmins), min(ymins), max(xmaxs), max(ymaxs)] self._data["bbox"] = bbox
You are a Python code generator, capable of creating scripts from specifications.
Adds a unique id property to each feature.
Explain what the following Python 3 code does def add_unique_id(self): uid = 0 for feature in self._data["features"]: if feature["properties"].get("id"): raise Exception("one of the features already had an id field") feature["properties"]["id"] = uid ...
As a Python code composer, you craft elegant and concise scripts.
def add_all_bboxes(self): """ Calculates and adds a bbox attribute to the geojson entry of all feature geometries, updating any existing ones. """ for feature in self: if feature.geometry.type != "Null": feature.geometry._data["bbox"] = Feature(feature).geomet...
Write a Python 3 function for calculating and adds a bbox attribute to the geojson entry of all features in the archive.
As a python code expert, you are capable of creating scripts from specifications.
def save(self, savepath, **kwargs): """ Saves the geojson instance to file. To save with a different text encoding use the 'encoding' argument. Parameters: - **savepath**: Filepath to save the file. """ self.update_bbox() tempfile = open(savepath,"w") ...
Write a Python 3 script for saving the object to a file.
You are a Python code generator, capable of creating scripts from specifications.
This loads a geojson file into a python dict using the json module.
How would you explain what the following Python 3 function does def _loadfilepath(self, filepath, **kwargs): with open(filepath, "r") as f: data = json.load(f, **kwargs) return data
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds potentially missing items to the geojson dictionary
Given the following Python 3 function, write the documentation def _prepdata(self): # if missing, compute and add bbox if not self._data.get("bbox"): self.update_bbox() # if missing, set crs to default crs (WGS84), see http://geojson.org/geojson-spec.html if not sel...
As a Python code composer, you craft elegant and concise scripts.
Calculates the parameters for a perfect hash.
Can you generate a brief explanation for the following Python 3 code def hash_parameters(keys, minimize=True, to_int=None): # If to_int is not assigned, simply use the identity function. if to_int is None: to_int = __identity key_to_original = {to_int(original): original for original in keys} ...
As a Python code composer, you craft elegant and concise scripts.
Place items in a square of a tree.
Explain what the following Python 3 code does def place_items_in_square(items, t): # A minheap (because that's all that heapq supports :/) # of the length of each row. Why this is important is because # we'll be popping the largest rows when figuring out row displacements. # Each item is a tuple of (t ...
As a Python code analyst, you investigate and solve complex coding mysteries
def arrange_rows(row_queue, t): """ Takes a priority queue as generated by place_items_in_square(). Arranges the items from its conceptual square to one list. Returns both the resultant vector, plus the displacement vector, to be used in the final output hash function. >>> rows = [(2, 1, [(0, ...
How would you implement a function in Python 3 that arranges the items from its conceptual square to one list.
As a python code expert, you are capable of creating scripts from specifications.
Find the first index that the row can fit in.
Here you have a function in Python 3, explain what it does def find_first_fit(unoccupied_columns, row, row_length): for free_col in unoccupied_columns: # The offset is that such that the first item goes in the free column. first_item_x = row[0][0] offset = free_col - first_item_x if ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks if all the occupied columns in the row fit in the indices
Can you tell what is the following Python 3 function doing def check_columns_fit(unoccupied_columns, row, offset, row_length): for index, item in row: adjusted_index = (index + offset) % row_length # Check if the index is in the appropriate place. if adjusted_index not in unoccupied_columns...
You are a Python code architect, reviewing and designing scalable and efficient code
Prints a row queue as its conceptual square array.
Can you generate a brief explanation for the following Python 3 code def print_square(row_queue, t): occupied_rows = {y: row for _, y, row in row_queue} empty_row = ', '.join('...' for _ in range(t)) for y in range(t): print('|', end=' ') if y not in occupied_rows: print(empty_r...
As a Python code analyst, you investigate and solve complex coding mysteries
def trim_nones_from_right(xs): """ Returns the list without all the Nones at the right end. >>> trim_nones_from_right([1, 2, None, 4, None, 5, None, None]) [1, 2, None, 4, None, 5] """ # Find the first element that does not contain none. for i, item in enumerate(reversed(xs)): if i...
Write a Python 3 function that can return the list with all the Nones at the right end.
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a hash function from the given keys.
Can you tell what is the following Python 3 function doing def make_hash(keys, **kwargs): params = hash_parameters(keys, **kwargs) t = params.t r = params.r offset = params.offset to_int = params.to_int if params.to_int else __identity def perfect_hash(x): val = to_int(x) + offset ...
As a Python code composer, you craft elegant and concise scripts.
def make_dict(name, keys, **kwargs): """ Creates a dictionary-like mapping class that uses perfect hashing. ``name`` is the proper class name of the returned class. See ``hash_parameters()`` for documentation on all arguments after ``name``. >>> MyDict = make_dict('MyDict', '+-<>[],.', to_int=o...
Create a Python 3 function for creating a dictionary - like mapping class that uses perfect hashing.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_timestamp(dirname_full, remove): """ Get the timestamp from the timestamp file. Optionally mark it for removal if we're going to write another one. """ record_filename = os.path.join(dirname_full, RECORD_FILENAME) if not os.path.exists(record_filename): return None mtime ...
Implement a Python 3 function for getting the timestamp from the timestamp file.
As a Python code composer, you craft elegant and concise scripts.
def _get_timestamp_cached(dirname_full, remove): """ Get the timestamp from the cache or fill the cache Much quicker than reading the same files over and over """ if dirname_full not in TIMESTAMP_CACHE: mtime = _get_timestamp(dirname_full, remove) TIMESTAMP_CACHE[dirname_full] = mtim...
Create a Python 3 function to get the timestamp of a node in the cache or fill it if it doesn t exist
You are a Python code architect, reviewing and designing scalable and efficient code
def _max_timestamps(dirname_full, remove, compare_tstamp): """Compare a timestamp file to one passed in. Get the max.""" tstamp = _get_timestamp_cached(dirname_full, remove) return max_none((tstamp, compare_tstamp))
Implement a function in Python 3 to compare a timestamp file to one passed in. Get the max.
As a python code expert, you are capable of creating scripts from specifications.
Get the parent timestamp of the passed in directory tree.
Can you tell what is the following Python 3 function doing def _get_parent_timestamp(dirname, mtime): parent_pathname = os.path.dirname(dirname) # max between the parent timestamp the one passed in mtime = _max_timestamps(parent_pathname, False, mtime) if dirname != os.path.dirname(parent_pathname): ...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the mtime of the file after the given file.
Make a summary of the following Python 3 code def get_walk_after(filename, optimize_after=None): if Settings.optimize_after is not None: return Settings.optimize_after dirname = os.path.dirname(filename) if optimize_after is None: optimize_after = _get_parent_timestamp(dirname, optimize_aft...
As a Python code translator, you convert algorithms and pseudocode into Python.
Record the timestamp of running in a dotfile.
Explain what the following Python 3 code does def record_timestamp(pathname_full): if Settings.test or Settings.list_only or not Settings.record_timestamp: return if not Settings.follow_symlinks and os.path.islink(pathname_full): if Settings.verbose: print('Not setting timestamp beca...
You are a Python code analyst, evaluating scripts for potential improvements.
def walk_comic_archive(filename_full, image_format, optimize_after): """ Optimize a comic archive. This is done mostly inline to use the master processes process pool for workers. And to avoid calling back up into walk from a dedicated module or format processor. It does mean that we block on uncom...
Write a Python 3 script to optimize a comic archive.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _is_skippable(filename_full): """Handle things that are not optimizable files.""" # File types if not Settings.follow_symlinks and os.path.islink(filename_full): return True if os.path.basename(filename_full) == timestamp.RECORD_FILENAME: return True if not os.path.exists(filena...
Write a Python 3 script for handling things that are not optimizable files.
As a Python code translator, you convert algorithms and pseudocode into Python.
Optimize an individual file.
Explain what the following Python 3 code does def walk_file(filename, walk_after, recurse=None, archive_mtime=None): filename = os.path.normpath(filename) result_set = set() if _is_skippable(filename): return result_set walk_after = timestamp.get_walk_after(filename, walk_after) # File i...
You are a Python code generator, capable of creating scripts from specifications.
Recursively optimize a directory.
How would you explain what the following Python 3 function does def walk_dir(dir_path, walk_after, recurse=None, archive_mtime=None): if recurse is None: recurse = Settings.recurse result_set = set() if not recurse: return result_set for root, _, filenames in os.walk(dir_path): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Walks all files in the current directory tree and returns a set of records.
Can you tell what is the following Python 3 function doing def _walk_all_files(): # Init records record_dirs = set() result_set = set() for filename in Settings.paths: # Record dirs to put timestamps in later filename_full = os.path.abspath(filename) if Settings.recurse and os.p...
As a python code expert, you are capable of creating scripts from specifications.
Use preconfigured settings to optimize files.
Given the following Python 3 function, write the documentation def run(): # Setup Multiprocessing # manager = multiprocessing.Manager() Settings.pool = multiprocessing.Pool(Settings.jobs) # Optimize Files record_dirs, bytes_in, bytes_out, nag_about_gifs, errors = \ _walk_all_files() # ...
As a Python code analyst, you investigate and solve complex coding mysteries
Replace the file extention.
Here you have a function in Python 3, explain what it does def replace_ext(filename, new_ext): filename_base = os.path.splitext(filename)[0] new_filename = '{}.{}'.format(filename_base, new_ext) return new_filename
As a Python code translator, you convert algorithms and pseudocode into Python.
Remove old file with better one or discard new wasteful file.
Can you tell what is the following Python 3 function doing def _cleanup_after_optimize_aux(filename, new_filename, old_format, new_format): """ Replace old file with better one or discard new wasteful file. """ bytes_in = 0 bytes_out = 0 final_filename = filename ...
You are a Python code architect, reviewing and designing scalable and efficient code
Clean up the file after optimisation.
Make a summary of the following Python 3 code def cleanup_after_optimize(filename, new_filename, old_format, new_format): final_filename, bytes_in, bytes_out = _cleanup_after_optimize_aux( filename, new_filename, old_format, new_format) return stats.ReportStats(final_filename, bytes_count=(bytes_in, byt...
You are a Python code generator, capable of creating scripts from specifications.
def parse_reqs(filename): """Parse setup requirements from a requirements.txt file.""" install_reqs = parse_requirements(filename, session=False) return [str(ir.req) for ir in install_reqs]
Create a Python 3 function to parse setup requirements from a requirements. txt file.
As a python code expert, you are capable of creating scripts from specifications.
Get the requirements by weather we re building develop or not.
Can you generate the documentation for the following Python 3 function def get_req_list(): req_list = parse_reqs(REQUIREMENTS['prod']) if len(sys.argv) > 2 and sys.argv[2] == ('develop'): req_list += parse_reqs(REQUIREMENTS['dev']) return req_list
As a Python code translator, you convert algorithms and pseudocode into Python.
Return the comic format if it is a comic archive.
Can you tell what is the following Python 3 function doing def get_comic_format(filename): image_format = None filename_ext = os.path.splitext(filename)[-1].lower() if filename_ext in _COMIC_EXTS: if zipfile.is_zipfile(filename): image_format = _CBZ_FORMAT elif rarfile.is_rarfile...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the name of the working dir to use for this filename.
Make a summary of the following Python 3 code def _get_archive_tmp_dir(filename): head, tail = os.path.split(filename) return os.path.join(head, _ARCHIVE_TMP_DIR_TEMPLATE.format(tail))
You are a Python code generator, capable of creating scripts from specifications.
Uncompress a comic archive into a temporary directory.
Can you generate the documentation for the following Python 3 function def comic_archive_uncompress(filename, image_format): if not Settings.comics: report = ['Skipping archive file: {}'.format(filename)] return None, ReportStats(filename, report=report) if Settings.verbose: truncated_f...
As a Python code composer, you craft elegant and concise scripts.
def _comic_archive_write_zipfile(new_filename, tmp_dir): """Zip up the files in the tempdir into the new filename.""" if Settings.verbose: print('Rezipping archive', end='') with zipfile.ZipFile(new_filename, 'w', compression=zipfile.ZIP_DEFLATED) as new_zf: root_len...
Write a Python 3 script for zipping up the files in the tempdir into the new filename.
As a Python code analyst, you investigate and solve complex coding mysteries
def comic_archive_compress(args): """ Called back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up. """ try: filename, old_format, settings, nag_about_gifs = args Settings.update(settings) tmp_dir = _get_archive_tmp...
Write a Python 3 function for calling back by every optimization inside a comic archive. When they're all done it creates the new archive and cleans up.
You are a Python code generator, capable of creating scripts from specifications.
Create argument list for mozjpeg.
How would you explain what the following Python 3 function does def mozjpeg(ext_args): args = copy.copy(_MOZJPEG_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] args += ['-outfile'] args += [ext_args.new_filename, ext_args.old_filename] ...
As a Python code composer, you craft elegant and concise scripts.
Create argument list for jpegtran.
Explain what the following Python 3 code does def jpegtran(ext_args): args = copy.copy(_JPEGTRAN_ARGS) if Settings.destroy_metadata: args += ["-copy", "none"] else: args += ["-copy", "all"] if Settings.jpegtran_prog: args += ["-progressive"] args += ['-outfile'] args += [...
As a Python code translator, you convert algorithms and pseudocode into Python.
def jpegrescan(ext_args): """Run the EXTERNAL program jpegrescan.""" args = copy.copy(_JPEGRESCAN_ARGS) if Settings.jpegrescan_multithread: args += ['-t'] if Settings.destroy_metadata: args += ['-s'] args += [ext_args.old_filename, ext_args.new_filename] extern.run_ext(args) ...
Implement a function in Python 3 to run the EXTERNAL program jpegrescan.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_arguments(args): """Parse the command line.""" usage = "%(prog)s [arguments] [image files]" programs_str = ', '.join([prog.__name__ for prog in PROGRAMS]) description = "Uses "+programs_str+" if they are on the path." parser = argparse.ArgumentParser(usage=usage, description=description) ...
Write a Python 3 function that can parse the command line arguments.
As a Python code analyst, you investigate and solve complex coding mysteries
def run(args): """Process command line arguments and walk inputs.""" raw_arguments = get_arguments(args[1:]) process_arguments(raw_arguments) walk.run() return True
Implement a Python 3 function for processing command line arguments and walk inputs.
As a Python code analyst, you investigate and solve complex coding mysteries
def does_external_program_run(prog, verbose): """Test to see if the external programs can be run.""" try: with open('/dev/null') as null: subprocess.call([prog, '-h'], stdout=null, stderr=null) result = True except OSError: if verbose > 1: print("couldn't run ...
Write a Python 3 function that can test to see if the external programs can be run.
As a python code expert, you are capable of creating scripts from specifications.
Return a humanized string representation of a number of num_bytes.
Given the following Python 3 function, write the documentation def _humanize_bytes(num_bytes, precision=1): if num_bytes == 0: return 'no bytes' if num_bytes == 1: return '1 byte' factored_bytes = 0 factor_suffix = 'bytes' for factor, suffix in ABBREVS: if num_bytes >= facto...
You are a Python code architect, reviewing and designing scalable and efficient code
def new_percent_saved(report_stats): """Spit out how much space the optimization saved.""" size_in = report_stats.bytes_in if size_in > 0: size_out = report_stats.bytes_out ratio = size_out / size_in kb_saved = _humanize_bytes(size_in - size_out) else: ratio = 0 k...
Create a Python 3 function for spitting out how much space the optimization saved.
You are a Python code generator, capable of creating scripts from specifications.
Remove the cwd from the full filename.
Given the following Python 3 function, write the documentation def truncate_cwd(full_filename): if full_filename.startswith(os.getcwd()): truncated_filename = full_filename.split(os.getcwd(), 1)[1] truncated_filename = truncated_filename.split(os.sep, 1)[1] else: truncated_filename = ful...
You are a Python code analyst, evaluating scripts for potential improvements.
def report_saved(report_stats): """Record the percent saved & print it.""" if Settings.verbose: report = '' truncated_filename = truncate_cwd(report_stats.final_filename) report += '{}: '.format(truncated_filename) total = new_percent_saved(report_stats) if total: ...
Create a Python 3 function for recording the percent saved & print it.
You are a Python code analyst, evaluating scripts for potential improvements.
def report_totals(bytes_in, bytes_out, nag_about_gifs, errors): """Report the total number and percent of bytes saved.""" if bytes_in: bytes_saved = bytes_in - bytes_out percent_bytes_saved = bytes_saved / bytes_in * 100 msg = '' if Settings.test: if percent_bytes_sav...
Can you implement a function in Python 3 that reports the total number and percent of bytes saved.
You are a Python code architect, reviewing and designing scalable and efficient code
def skip(type_name, filename): """Provide reporting statistics for a skipped file.""" report = ['Skipping {} file: {}'.format(type_name, filename)] report_stats = ReportStats(filename, report=report) return report_stats
Implement a Python 3 function for providing reporting statistics for a skipped file.
As a Python code analyst, you investigate and solve complex coding mysteries
Run the EXTERNAL program gifsicle.
Here you have a function in Python 3, explain what it does def gifsicle(ext_args): args = _GIFSICLE_ARGS + [ext_args.new_filename] extern.run_ext(args) return _GIF_FORMAT
As a Python code analyst, you investigate and solve complex coding mysteries
def _optimize_image_external(filename, func, image_format, new_ext): """Optimize the file with the external function.""" new_filename = filename + TMP_SUFFIX + new_ext new_filename = os.path.normpath(new_filename) shutil.copy2(filename, new_filename) ext_args = ExtArgs(filename, new_filename) n...
Write a Python 3 script to optimize the file with the external function.
As a python code expert, you are capable of creating scripts from specifications.
def _optimize_with_progs(format_module, filename, image_format): """ Use the correct optimizing functions in sequence. And report back statistics. """ filesize_in = os.stat(filename).st_size report_stats = None for func in format_module.PROGRAMS: if not getattr(Settings, func.__nam...
Can you create a Python 3 function that optimizes the image with the correct optimizing functions in sequence.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _get_format_module(image_format): """Get the format module to use for optimizing the image.""" format_module = None nag_about_gifs = False if detect_format.is_format_selected(image_format, Settings.to_png_formats, png.P...
How would you implement a function in Python 3 that gets the format module to use for optimizing the image.
As a Python code analyst, you investigate and solve complex coding mysteries
Optimize a given image from a filename.
Explain what the following Python 3 code does def optimize_image(arg): try: filename, image_format, settings = arg Settings.update(settings) format_module, nag_about_gifs = _get_format_module(image_format) if format_module is None: if Settings.verbose > 1: ...
As a python code expert, you are capable of creating scripts from specifications.
Determine if the program is enabled in the settings.
Can you generate a brief explanation for the following Python 3 code def _is_program_selected(progs): mode = False for prog in progs: if getattr(Settings, prog.__name__): mode = True break return mode
As a python code expert, you are capable of creating scripts from specifications.
def is_format_selected(image_format, formats, progs): """Determine if the image format is selected by command line arguments.""" intersection = formats & Settings.formats mode = _is_program_selected(progs) result = (image_format in intersection) and mode return result
Write a Python 3 script for determining if the image format is selected by command line arguments.
As a Python code translator, you convert algorithms and pseudocode into Python.
Determine if the image is a sequenced image.
Can you generate a brief explanation for the following Python 3 code def _is_image_sequenced(image): try: image.seek(1) image.seek(0) result = True except EOFError: result = False return result
As a python code expert, you are capable of creating scripts from specifications.
def get_image_format(filename): """Get the image format.""" image = None bad_image = 1 image_format = NONE_FORMAT sequenced = False try: bad_image = Image.open(filename).verify() image = Image.open(filename) image_format = image.format sequenced = _is_image_sequen...
Can you create a Python 3 function that gets the image format.
You are a Python code generator, capable of creating scripts from specifications.
Detect the image format and return the appropriate comic archive type.
Can you generate a brief explanation for the following Python 3 code def detect_file(filename): image_format = get_image_format(filename) if image_format in Settings.formats: return image_format if image_format in (NONE_FORMAT, ERROR_FORMAT): return None if Settings.verbose > 1 and no...
You are a Python code generator, capable of creating scripts from specifications.