output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Try to covert val to out_type but never raise an exception.
Given the following Python 3 function, write the documentation def _safe_cast(out_type, val): if val is None: return None if out_type == int: if isinstance(val, int) or isinstance(val, float): # Just a number. return int(val) else: # Process any other...
As a python code expert, you are capable of creating scripts from specifications.
def _unpack_asf_image(data): """Unpack image data from a WM/Picture tag. Return a tuple containing the MIME type, the raw image data, a type indicator, and the image's description. This function is treated as "untrusted" and could throw all manner of exceptions (out-of-bounds, etc.). We should clea...
Create a Python 3 function for unpacking image data from a WM / Picture tag. Return a tuple containing the MIME type the raw image data a type indicator and the image s description.
You are a Python code analyst, evaluating scripts for potential improvements.
def _pack_asf_image(mime, data, type=3, description=""): """Pack image data for a WM/Picture tag. """ tag_data = struct.pack('<bi', type, len(data)) tag_data += mime.encode("utf-16-le") + b'\x00\x00' tag_data += description.encode("utf-16-le") + b'\x00\x00' tag_data += data return tag_data
Can you write a function in Python 3 where it packs image data for a WM / Picture tag.
As a Python code composer, you craft elegant and concise scripts.
def _sc_decode(soundcheck): """Convert a Sound Check bytestring value to a (gain, peak) tuple as used by ReplayGain. """ # We decode binary data. If one of the formats gives us a text # string, interpret it as UTF-8. if isinstance(soundcheck, six.text_type): soundcheck = soundcheck.encod...
Can you create a Python 3 function that converts a Sound Check bytestring value to a tuple of gain and peak.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _sc_encode(gain, peak): """Encode ReplayGain gain/peak values as a Sound Check string. """ # SoundCheck stores the peak value as the actual value of the # sample, rather than the percentage of full scale that RG uses, so # we do a simple conversion assuming 16 bit samples. peak *= 32768.0 ...
Create a Python 3 function to encode the given gain and peak values as a Sound Check string.
As a Python code analyst, you investigate and solve complex coding mysteries
def image_mime_type(data): """Return the MIME type of the image data (a bytestring). """ # This checks for a jpeg file with only the magic bytes (unrecognized by # imghdr.what). imghdr.what returns none for that type of file, so # _wider_test_jpeg is run in that case. It still returns None if it did...
Implement a Python 3 function for returning the MIME type of the image data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def deserialize(self, mutagen_value): """Given a raw value stored on a Mutagen object, decode and return the represented value. """ if self.suffix and isinstance(mutagen_value, six.text_type) \ and mutagen_value.endswith(self.suffix): return mutagen_value[:-len(sel...
How would you implement a function in Python 3 that gives a raw value stored on a Mutagen object decode and return the represented value.
As a python code expert, you are capable of creating scripts from specifications.
Assign the value for the field using this style.
Make a summary of the following Python 3 code def set(self, mutagen_file, value): self.store(mutagen_file, self.serialize(value))
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the external Python value to a type that is suitable for storing in a Mutagen file object.
Explain what the following Python 3 code does def serialize(self, value): if isinstance(value, float) and self.as_type is six.text_type: value = u'{0:.{1}f}'.format(value, self.float_places) value = self.as_type(value) elif self.as_type is six.text_type: if isinstance...
You are a Python code generator, capable of creating scripts from specifications.
Get a list of all values for the field using this style.
Can you generate a brief explanation for the following Python 3 code def get_list(self, mutagen_file): return [self.deserialize(item) for item in self.fetch(mutagen_file)]
You are a Python code architect, reviewing and designing scalable and efficient code
Set all values for the field using this style. values should be an iterable.
Make a summary of the following Python 3 code def set_list(self, mutagen_file, values): self.store(mutagen_file, [self.serialize(value) for value in values])
As a Python code analyst, you investigate and solve complex coding mysteries
def deserialize(self, apic_frame): """Convert APIC frame into Image.""" return Image(data=apic_frame.data, desc=apic_frame.desc, type=apic_frame.type)
Write a Python 3 function for converting APIC frame into Image.
You are a Python code analyst, evaluating scripts for potential improvements.
def serialize(self, image): """Return an APIC frame populated with data from ``image``. """ assert isinstance(image, Image) frame = mutagen.id3.Frames[self.key]() frame.data = image.data frame.mime = image.mime_type frame.desc = image.desc or u'' # For co...
How would you code a function in Python 3 to return an APIC frame populated with data from image.
You are a Python code generator, capable of creating scripts from specifications.
def serialize(self, image): """Turn a Image into a base64 encoded FLAC picture block. """ pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = image.desc or u'' # Encoding with base64 returns...
How would you code a function in Python 3 to turn a Image into a base64 encoded FLAC picture block.
As a Python code composer, you craft elegant and concise scripts.
def store(self, mutagen_file, pictures): """``pictures`` is a list of mutagen.flac.Picture instances. """ mutagen_file.clear_pictures() for pic in pictures: mutagen_file.add_picture(pic)
Implement a Python 3 function for storing the given pictures in the given mutagen file.
You are a Python code analyst, evaluating scripts for potential improvements.
def serialize(self, image): """Turn a Image into a mutagen.flac.Picture. """ pic = mutagen.flac.Picture() pic.data = image.data pic.type = image.type_index pic.mime = image.mime_type pic.desc = image.desc or u'' return pic
Implement a Python 3 function for turning a Image into a mutagen. flac. Picture.
As a Python code analyst, you investigate and solve complex coding mysteries
Delete all images from the file.
Given the following Python 3 function, write the documentation def delete(self, mutagen_file): for cover_tag in self.TAG_NAMES.values(): try: del mutagen_file[cover_tag] except KeyError: pass
As a Python code composer, you craft elegant and concise scripts.
def styles(self, mutagen_file): """Yields the list of storage styles of this field that can handle the MediaFile's format. """ for style in self._styles: if mutagen_file.__class__.__name__ in style.formats: yield style
Can you create a Python 3 function that yields the list of storage styles that can handle the MediaFile s format.
You are a Python code generator, capable of creating scripts from specifications.
Get an appropriate null value for this field s type.
Given the following Python 3 function, write the documentation def _none_value(self): if self.out_type == int: return 0 elif self.out_type == float: return 0.0 elif self.out_type == bool: return False elif self.out_type == six.text_type: re...
You are a Python code analyst, evaluating scripts for potential improvements.
def _get_date_tuple(self, mediafile): """Get a 3-item sequence representing the date consisting of a year, month, and day number. Each number is either an integer or None. """ # Get the underlying data and split on hyphens and slashes. datestring = super(DateField, self)....
Create a Python 3 function for getting a 3 - item sequence representing the date consisting of year month and day number. Each number is either an integer or None.
As a python code expert, you are capable of creating scripts from specifications.
def _set_date_tuple(self, mediafile, year, month=None, day=None): """Set the value of the field given a year, month, and day number. Each number can be an integer or None to indicate an unset component. """ if year is None: self.__delete__(mediafile) retur...
Write a Python 3 function for setting the value of the field given a year month and day number.
As a Python code composer, you craft elegant and concise scripts.
def fields(cls): """Get the names of all writable properties that reflect metadata tags (i.e., those that are instances of :class:`MediaField`). """ for property, descriptor in cls.__dict__.items(): if isinstance(descriptor, MediaField): if isinstance(...
Write a Python 3 function for getting the names of all writable properties that reflect metadata tags.
As a Python code composer, you craft elegant and concise scripts.
def _field_sort_name(cls, name): """Get a sort key for a field name that determines the order fields should be written in. Fields names are kept unchanged, unless they are instances of :class:`DateItemField`, in which case `year`, `month`, and `day` are replaced by `date0`, `dat...
Can you write a function in Python 3 where it gets a sort key for a field name that determines the order fields should be written in.
As a Python code composer, you craft elegant and concise scripts.
def sorted_fields(cls): """Get the names of all writable metadata fields, sorted in the order that they should be written. This is a lexicographic order, except for instances of :class:`DateItemField`, which are sorted in year-month-day order. """ for property in...
How would you code a function in Python 3 to get the names of all writable metadata fields sorted in the order that they should be written.
As a python code expert, you are capable of creating scripts from specifications.
def add_field(cls, name, descriptor): """Add a field to store custom tags. :param name: the name of the property the field is accessed through. It must not already exist on this class. :param descriptor: an instance of :class:`MediaField`. """ if not isinst...
Can you write a function in Python 3 where it adds a field to store custom tags.
You are a Python code generator, capable of creating scripts from specifications.
Updates all the fields of the MediaFile with the values from a dictionary.
Explain what the following Python 3 code does def update(self, dict): for field in self.sorted_fields(): if field in dict: if dict[field] is None: delattr(self, field) else: setattr(self, field, dict[field])
As a python code expert, you are capable of creating scripts from specifications.
def channels(self): """The number of channels in the audio (an int).""" if hasattr(self.mgfile.info, 'channels'): return self.mgfile.info.channels return 0
Can you create a Python 3 function that returns the number of channels in the audio file.
As a Python code analyst, you investigate and solve complex coding mysteries
The bitrate of the audio in the file.
How would you explain what the following Python 3 function does def bitrate(self): if hasattr(self.mgfile.info, 'bitrate') and self.mgfile.info.bitrate: # Many formats provide it explicitly. return self.mgfile.info.bitrate else: # Otherwise, we calculate bitrate from ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Reads a FITS file and returns a 2D numpy array of the data.
Here you have a function in Python 3, explain what it does def fromfits(infilename, hdu = 0, verbose = True): pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True) pixelarray = np.asarray(pixelarray).transpose() pixelarrayshape = pixelarray.shape if verbose : print "FITS impor...
As a Python code translator, you convert algorithms and pseudocode into Python.
def tofits(outfilename, pixelarray, hdr = None, verbose = True): """ Takes a 2D numpy array and write it into a FITS file. If you specify a header (pyfits format, as returned by fromfits()) it will be used for the image. You can give me boolean numpy arrays, I will convert them into 8 bit integers. ...
Create a Python 3 function to write a 2D numpy array to a FITS file.
You are a Python code generator, capable of creating scripts from specifications.
Subsample a array by 2x2
Given the following Python 3 function, write the documentation def subsample(a): # this is more a generic function then a method ... """ # Ouuwww this is slow ... outarray = np.zeros((a.shape[0]*2, a.shape[1]*2), dtype=np.float64) for i in range(a.shape[0]): for j in range(a.shape[1]): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def rebin2x2(a): """ Wrapper around rebin that actually rebins 2 by 2 """ inshape = np.array(a.shape) if not (inshape % 2 == np.zeros(2)).all(): # Modulo check to see if size is even raise RuntimeError, "I want even image shapes !" return rebin(a, inshape/2)
Create a Python 3 function for wrapping around rebin that actually rebins 2 by 2
You are a Python code architect, reviewing and designing scalable and efficient code
def labelmask(self, verbose = None): """ Finds and labels the cosmic "islands" and returns a list of dicts containing their positions. This is made on purpose for visualizations a la f2n.drawstarslist, but could be useful anyway. """ if verbose == None: verbose = self...
How would you code a function in Python 3 to label the cosmicislands and return a list of dicts containing their positions.
You are a Python code analyst, evaluating scripts for potential improvements.
def clean(self, mask = None, verbose = None): """ Given the mask, we replace the actual problematic pixels with the masked 5x5 median value. This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no readymade masked median. So for now we do a loop... ...
Write a Python 3 script to give the mask, we replace the actual problematic pixels with the masked 5x5 median value. This mimics what is done in L.A.Cosmic, but it's a bit harder to do in python, as there is no readymade masked median. So for now we do a loop... Saturated stars, if calculated, are also masked : they ar...
As a Python code analyst, you investigate and solve complex coding mysteries
def findsatstars(self, verbose = None): """ Uses the satlevel to find saturated stars (not cosmics !), and puts the result as a mask in self.satstars. This can then be used to avoid these regions in cosmic detection and cleaning procedures. Slow ... """ if verbose == None...
Can you implement a function in Python 3 that finds saturated stars in the image and store them in self. satstars.
You are a Python code generator, capable of creating scripts from specifications.
Returns the saturated stars for this instance.
Explain what the following Python 3 code does def getsatstars(self, verbose = None): if verbose == None: verbose = self.verbose if not self.satlevel > 0: raise RuntimeError, "Cannot determine satstars : you gave satlevel <= 0 !" if self.satstars == None: self...
As a Python code analyst, you investigate and solve complex coding mysteries
Guesses the background level of the current instance of the class.
Can you generate the documentation for the following Python 3 function def guessbackgroundlevel(self): if self.backgroundlevel == None: self.backgroundlevel = np.median(self.rawarray.ravel()) return self.backgroundlevel
As a Python code analyst, you investigate and solve complex coding mysteries
This function performs one iteration of the L. A. Cosmic algorithm.
Explain what the following Python 3 code does def lacosmiciteration(self, verbose = None): if verbose == None: verbose = self.verbose if verbose: print "Convolving image with Laplacian kernel ..." # We subsample, convolve, clip negative values, and rebi...
As a Python code analyst, you investigate and solve complex coding mysteries
def run(self, maxiter = 4, verbose = False): """ Full artillery :-) - Find saturated stars - Run maxiter L.A.Cosmic iterations (stops if no more cosmics are found) Stops if no cosmics are found or if maxiter is reached. """ if self.satlev...
Write a Python 3 script to run the cosmic algorithm.
As a Python code composer, you craft elegant and concise scripts.
def search_project_root(): """ Search your Django project root. returns: - path:string Django project root path """ while True: current = os.getcwd() if pathlib.Path("Miragefile.py").is_file() or pathlib.Path("Miragefile").is_file(): ...
Write a Python 3 function that can search your Django project root for Miragefile. py and Miragefile. py files.
As a Python code translator, you convert algorithms and pseudocode into Python.
def search_app_root(): """ Search your Django application root returns: - (String) Django application root path """ while True: current = os.getcwd() if pathlib.Path("apps.py").is_file(): return current elif pathl...
Write a Python 3 function that can search your Django application root for a specific locale.
As a Python code composer, you craft elegant and concise scripts.
def in_app() -> bool: """ Judge where current working directory is in Django application or not. returns: - (Bool) cwd is in app dir returns True """ try: MirageEnvironment.set_import_root() import apps if os.path.isfile("apps.py")...
Write a Python 3 function for judging where current working directory is in Django application or not.
You are a Python code architect, reviewing and designing scalable and efficient code
def update_cached_fields(*args): """ Calls update_cached_fields() for each object passed in as argument. Supports also iterable objects by checking __iter__ attribute. :param args: List of objects :return: None """ for a in args: if a is not None: if hasattr(a, '__iter__'...
Create a Python 3 function for calling update_cached_fields() for each object passed in as argument.
You are a Python code analyst, evaluating scripts for potential improvements.
Call on pre_save signal for objects to automatically refresh on save.
Can you generate a brief explanation for the following Python 3 code def update_cached_fields_pre_save(self, update_fields: list): if self.id and update_fields is None: self.update_cached_fields(commit=False, exceptions=False)
You are a Python code generator, capable of creating scripts from specifications.
Start working on a new hotfix.
Can you generate the documentation for the following Python 3 function def start(name): # type: (str) -> None """ Start working on a new hotfix. This will create a new branch off master called hotfix/<name>. Args: name (str): The name of the new feature. """ hotfix_branch =...
As a python code expert, you are capable of creating scripts from specifications.
def finish(): # type: () -> None """ Merge current feature into develop. """ pretend = context.get('pretend', False) if not pretend and (git.staged() or git.unstaged()): log.err( "You have uncommitted changes in your repo!\n" "You need to stash them before you merge the ...
How would you implement a function in Python 3 that merges current feature into develop.
As a Python code composer, you craft elegant and concise scripts.
def run(self): """ Run the shell command Returns: ShellCommand: return this ShellCommand instance for chaining """ if not self.block: self.output = [] self.error = [] self.thread = threading.Thread(target=self.run_non_blocking) ...
Create a Python 3 function to run the shell command
As a Python code analyst, you investigate and solve complex coding mysteries
def send(self, value): """ Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chain...
Write a Python 3 function for sending text to stdin. Can only be used on non blocking commands
You are a Python code architect, reviewing and designing scalable and efficient code
Append lines from stdout to self. output.
Can you generate a brief explanation for the following Python 3 code def poll_output(self): if self.block: return self.output new_list = self.output[self.old_output_size:] self.old_output_size += len(new_list) return new_list
You are a Python code analyst, evaluating scripts for potential improvements.
def poll_error(self): """ Append lines from stderr to self.errors. Returns: list: The lines added since last call """ if self.block: return self.error new_list = self.error[self.old_error_size:] self.old_error_size += len(new_list) ...
Create a Python 3 function for appending lines from stderr to self. error.
As a python code expert, you are capable of creating scripts from specifications.
def kill(self): """ Kill the current non blocking command Raises: TypeError: If command is blocking """ if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) try: self.process.kill() except ProcessLookupError as exc: ...
How would you code a function in Python 3 to kill the current non blocking command
As a Python code composer, you craft elegant and concise scripts.
Block until a pattern is found in stdout and stderr.
Given the following Python 3 function, write the documentation def wait_for(self, pattern, timeout=None): should_continue = True if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) def stop(signum, frame): # pylint: disable=W0613 nonlocal should_continue ...
You are a Python code analyst, evaluating scripts for potential improvements.
def is_running(self): """ Check if the command is currently running Returns: bool: True if running, else False """ if self.block: return False return self.thread.is_alive() or self.process.poll() is None
Can you implement a function in Python 3 that checks if the command is currently running
As a Python code composer, you craft elegant and concise scripts.
def print_live_output(self): ''' Block and print the output of the command Raises: TypeError: If command is blocking ''' if self.block: raise TypeError(NON_BLOCKING_ERROR_MESSAGE) else: while self.thread.is_alive() or self.old_output_s...
Write a Python 3 script to block and print the output of the command
As a python code expert, you are capable of creating scripts from specifications.
def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE): """ Create an instance of :class:`~ShellCommand` and run it Args: command (str): :class:`~ShellCommand` block (bool): See :class:`~ShellCommand` ...
Can you create a Python 3 function that runs a command in the current working directory.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the Bivariate Correlated Errors and intrinsic scattering of two uncertainties.
Can you tell what is the following Python 3 function doing def bces(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, model='yx', \ bootstrap=5000, verbose='normal', full_output=True): """ Bivariate, Correlated Errors and intrinsic Scatter (BCES) translated from the FORTRAN code by Christina Bird a...
As a python code expert, you are capable of creating scripts from specifications.
def scatter(slope, zero, x1, x2, x1err=[], x2err=[]): """ Used mainly to measure scatter for the BCES best-fit """ n = len(x1) x2pred = zero + slope * x1 s = sum((x2 - x2pred) ** 2) / (n - 1) if len(x2err) == n: s_obs = sum((x2err / x2) ** 2) / n s0 = s - s_obs print num...
Implement a function in Python 3 to scatter function for the BCES best fit.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns a new Kelly model with linear regression.
Can you generate the documentation for the following Python 3 function def kelly(x1, x2, x1err=[], x2err=[], cerr=[], logify=True, miniter=5000, maxiter=1e5, metro=True, silent=True): """ Python wrapper for the linear regression MCMC of Kelly (2007). Requires pidly (http://astronomy.suss...
You are a Python code architect, reviewing and designing scalable and efficient code
def mcmc(x1, x2, x1err=[], x2err=[], po=(1,1,0.5), logify=True, nsteps=5000, nwalkers=100, nburn=500, output='full'): """ Use emcee to find the best-fit linear relation or power law accounting for measurement uncertainties and intrinsic scatter Parameters ---------- x1 : array...
Can you create a Python 3 function that uses emcee to find the best-fit linear relation or power law accounting for measurement uncertainties and intrinsic scatter Parameters ---------- x1 : array of floats Independent variable, or observable x2 : array of floats Dependent variable x1err : array of floats (optional) Un...
As a python code expert, you are capable of creating scripts from specifications.
This function calculates the MLE of two sets of measurement uncertainties and returns the MLE of the two sets of free parameters.
Given the following Python 3 function, write the documentation def mle(x1, x2, x1err=[], x2err=[], cerr=[], s_int=True, po=(1,0,0.1), verbose=False, logify=True, full_output=False): """ Maximum Likelihood Estimation of best-fit parameters Parameters ---------- x1, x2 : float arrays ...
You are a Python code generator, capable of creating scripts from specifications.
Transform two linear measurements and uncertainties and transform to log values.
Can you generate a brief explanation for the following Python 3 code def to_log(x1, x2, x1err, x2err): logx1 = numpy.log10(numpy.array(x1)) logx2 = numpy.log10(numpy.array(x2)) x1err = numpy.log10(numpy.array(x1)+numpy.array(x1err)) - logx1 x2err = numpy.log10(numpy.array(x2)+numpy.array(x2err)) - logx2...
You are a Python code architect, reviewing and designing scalable and efficient code
def wrap_paths(paths): # type: (list[str]) -> str """ Put quotes around all paths and join them with space in-between. """ if isinstance(paths, string_types): raise ValueError( "paths cannot be a string. " "Use array with one element instead." ) return ' '.join('"...
Can you implement a function in Python 3 that wraps all paths in quotes and join them with space in - between.
You are a Python code architect, reviewing and designing scalable and efficient code
def filtered_walk(path, include=None, exclude=None): # type: (str, List[str], List[str]) -> Generator[str] """ Walk recursively starting at *path* excluding files matching *exclude* Args: path (str): A starting path. This has to be an existing directory. include (list[str]): ...
How would you implement a function in Python 3 that walks a directory and returns a generator yielding all the files that match any of the patterns in include and exclude.
You are a Python code generator, capable of creating scripts from specifications.
def match_globs(path, patterns): # type: (str, List[str]) -> bool """ Test whether the given *path* matches any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of glob string patterns to test against. If *path* m...
Implement a function in Python 3 to test whether the given path matches any of the given glob strings.
As a Python code analyst, you investigate and solve complex coding mysteries
Test whether the given path contains any of the given glob strings.
Make a summary of the following Python 3 code def search_globs(path, patterns): # type: (str, List[str]) -> bool """ Test whether the given *path* contains any patterns in *patterns* Args: path (str): A file path to test for matches. patterns (list[str]): A list of g...
You are a Python code analyst, evaluating scripts for potential improvements.
Writes the content of the current node to the file at the given path.
Can you tell what is the following Python 3 function doing def write_file(path, content, mode='w'): # type: (Text, Union[Text,bytes], Text) -> None """ --pretend aware file writing. You can always write files manually but you should always handle the --pretend case. Args: path (str): ...
You are a Python code generator, capable of creating scripts from specifications.
def lint_cli(ctx, exclude, skip_untracked, commit_only): # type: (click.Context, List[str], bool, bool) -> None """ Run pep8 and pylint on all project files. You can configure the linting paths using the lint.paths config variable. This should be a list of paths that will be linted. If a path to a dire...
Implement a Python 3 function for running pep8 and pylint on all project files. You can configure the linting paths using the lint.paths config variable. This should be a list of paths that will be linted. If a path to a directory is given, all files in that directory and it's subdirectories will be used. The pep8 and ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def run_command(command, timeout_sec=3600.0, output=True): """Runs a command using the subprocess module :param command: List containing the command and all args :param timeout_sec (float) seconds to wait before killing the command. :param output (bool) True collects output, False ignores outpu...
Write a Python 3 function for running a command using subprocess module .
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_ip_addresses(): """Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address """ log = logging.getLogger(mod_logger + '.get_ip_addresses') command = ['/sbin/ifconfig'] try: result = run_command(command) except CommandError: rai...
Create a Python 3 function for getting the ip addresses from ifconfig
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the Mac Address given a device index
How would you explain what the following Python 3 function does def get_mac_address(device_index=0): log = logging.getLogger(mod_logger + '.get_mac_address') command = ['ip', 'addr', 'show', 'eth{d}'.format(d=device_index)] log.info('Attempting to find a mac address at device index: {d}'.format(d=device_ind...
As a Python code analyst, you investigate and solve complex coding mysteries
def chmod(path, mode, recursive=False): """Emulates bash chmod command This method sets the file permissions to the specified mode. :param path: (str) Full path to the file or directory :param mode: (str) Mode to be set (e.g. 0755) :param recursive: (bool) Set True to make a recursive call :re...
Write a Python 3 script to emulate bash chmod command
As a Python code analyst, you investigate and solve complex coding mysteries
def mkdir_p(path): """Emulates 'mkdir -p' in bash :param path: (str) Path to create :return: None :raises CommandError """ log = logging.getLogger(mod_logger + '.mkdir_p') if not isinstance(path, basestring): msg = 'path argument is not a string' log.error(msg) raise...
Create a Python 3 function to emulate mkdir - p in bash
As a Python code analyst, you investigate and solve complex coding mysteries
Emulates source command in bash
How would you explain what the following Python 3 function does def source(script): log = logging.getLogger(mod_logger + '.source') if not isinstance(script, basestring): msg = 'script argument must be a string' log.error(msg) raise CommandError(msg) log.info('Attempting to source sc...
You are a Python code analyst, evaluating scripts for potential improvements.
This method runs the yum update command to update the packages in the system.
Explain what the following Python 3 code does def yum_update(downloadonly=False, dest_dir='/tmp'): log = logging.getLogger(mod_logger + '.yum_update') # Type checks on the args if not isinstance(dest_dir, basestring): msg = 'dest_dir argument must be a string' log.error(msg) raise C...
You are a Python code generator, capable of creating scripts from specifications.
This function installs a list of packages from yum or downloads the packages to dest_dir using the yum - y plugin.
Can you generate a brief explanation for the following Python 3 code def yum_install(packages, downloadonly=False, dest_dir='/tmp'): log = logging.getLogger(mod_logger + '.yum_install') # Type checks on the args if not isinstance(dest_dir, basestring): msg = 'dest_dir argument must be a string' ...
As a Python code composer, you craft elegant and concise scripts.
This function emulates the functionality of the bash sed command.
Make a summary of the following Python 3 code def sed(file_path, pattern, replace_str, g=0): log = logging.getLogger(mod_logger + '.sed') # Type checks on the args if not isinstance(file_path, basestring): msg = 'file_path argument must be a string' log.error(msg) raise CommandError...
As a python code expert, you are capable of creating scripts from specifications.
Creates a zip file of a directory tree
Can you tell what is the following Python 3 function doing def zip_dir(dir_path, zip_file): log = logging.getLogger(mod_logger + '.zip_dir') # Validate args if not isinstance(dir_path, basestring): msg = 'dir_path argument must be a string' log.error(msg) raise CommandError(msg) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def update_hosts_file(ip, entry): """Updates the /etc/hosts file for the specified ip This method updates the /etc/hosts file for the specified IP address with the specified entry. :param ip: (str) IP address to be added or updated :param entry: (str) Hosts file entry to be added :return: None...
Write a Python 3 function for updating the /etc/hosts file for the specified ip This method updates the /etc/hosts file for the specified IP address with the specified entry. :param ip: (str) IP address to be added or updated :param entry: (str) Hosts file entry to be added :return: None :raises CommandError
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_hostname(new_hostname, pretty_hostname=None): """Sets this hosts hostname This method updates /etc/sysconfig/network and calls the hostname command to set a hostname on a Linux system. :param new_hostname: (str) New hostname :param pretty_hostname: (str) new pretty hostname, set to the sam...
How would you code a function in Python 3 to set this hosts hostname This method updates /etc/sysconfig/network and calls the hostname command to set a hostname on a Linux system. :param new_hostname: (str) New hostname :param pretty_hostname: (str) new pretty hostname, set to the same as new_hostname if not provided :...
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the NTP server on Linux and returns None
Can you generate the documentation for the following Python 3 function def set_ntp_server(server): log = logging.getLogger(mod_logger + '.set_ntp_server') # Ensure the hostname is a str if not isinstance(server, basestring): msg = 'server argument must be a string' log.error(msg) ra...
You are a Python code generator, capable of creating scripts from specifications.
Copies an existing ifcfg network script to another ifcfg network script
Explain what the following Python 3 code does def copy_ifcfg_file(source_interface, dest_interface): log = logging.getLogger(mod_logger + '.copy_ifcfg_file') # Validate args if not isinstance(source_interface, basestring): msg = 'source_interface argument must be a string' log.error(msg) ...
As a Python code composer, you craft elegant and concise scripts.
Removes the ifcfg file at the specified device index and restarts the network service if it is still running.
Given the following Python 3 function, write the documentation def remove_ifcfg_file(device_index='0'): log = logging.getLogger(mod_logger + '.remove_ifcfg_file') if not isinstance(device_index, basestring): msg = 'device_index argument must be a string' log.error(msg) raise CommandError...
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a NAT rule to iptables .
How would you explain what the following Python 3 function does def add_nat_rule(port, source_interface, dest_interface): log = logging.getLogger(mod_logger + '.add_nat_rule') # Validate args if not isinstance(source_interface, basestring): msg = 'source_interface argument must be a string' ...
You are a Python code architect, reviewing and designing scalable and efficient code
Restarts the linux network service on linux
Explain what the following Python 3 code does def service_network_restart(): log = logging.getLogger(mod_logger + '.service_network_restart') command = ['service', 'network', 'restart'] time.sleep(5) try: result = run_command(command) time.sleep(5) code = result['code'] excep...
You are a Python code architect, reviewing and designing scalable and efficient code
def save_iptables(rules_file='/etc/sysconfig/iptables'): """Saves iptables rules to the provided rules file :return: None :raises OSError """ log = logging.getLogger(mod_logger + '.save_iptables') # Run iptables-save to get the output command = ['iptables-save'] log.debug('Running comm...
Write a Python 3 script for saving iptables rules to the provided rules file.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_remote_host_environment_variable(host, environment_variable): """Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param environment_variable: (str) variable to query :return: (str) value of the environment variable :raises: TypeE...
Create a Python 3 function for retrieving the value of an environment variable of a remote host over SSH
You are a Python code architect, reviewing and designing scalable and efficient code
Sets an environment variable on the remote host in the specified environment file
Can you generate a brief explanation for the following Python 3 code def set_remote_host_environment_variable(host, variable_name, variable_value, env_file='/etc/bashrc'): log = logging.getLogger(mod_logger + '.set_remote_host_environment_variable') if not isinstance(host, basestring): msg = 'host argum...
You are a Python code generator, capable of creating scripts from specifications.
def run_remote_command(host, command, timeout_sec=5.0): """Retrieves the value of an environment variable of a remote host over SSH :param host: (str) host to query :param command: (str) command :param timeout_sec (float) seconds to wait before killing the command. :return: (str) command output...
Implement a function in Python 3 to run a command on the specified host over SSH and returns the output of the command.
You are a Python code architect, reviewing and designing scalable and efficient code
def check_remote_host_marker_file(host, file_path): """Queries a remote host over SSH to check for existence of a marker file :param host: (str) host to query :param file_path: (str) path to the marker file :return: (bool) True if the marker file exists :raises: TypeError, CommandError """ ...
Can you write a function in Python 3 where it queries a remote host to check for existence of a marker file
You are a Python code architect, reviewing and designing scalable and efficient code
Restores and saves firewall rules from the firewall_rules file
How would you explain what the following Python 3 function does def restore_iptables(firewall_rules): log = logging.getLogger(mod_logger + '.restore_iptables') log.info('Restoring firewall rules from file: {f}'.format(f=firewall_rules)) # Ensure the firewall rules file exists if not os.path.isfile(fire...
You are a Python code generator, capable of creating scripts from specifications.
def remove_default_gateway(): """Removes Default Gateway configuration from /etc/sysconfig/network and restarts networking :return: None :raises: OSError """ log = logging.getLogger(mod_logger + '.remove_default_gateway') # Ensure the network script exists network_script = '/etc/sy...
Write a Python 3 script for removing default gateway from the system config file and restarts the network service if it is still running
As a Python code translator, you convert algorithms and pseudocode into Python.
Determines if this distro has a systemd version of the system.
Here you have a function in Python 3, explain what it does def is_systemd(): os_family = platform.system() if os_family != 'Linux': raise OSError('This method is only supported on Linux, found OS: {o}'.format(o=os_family)) linux_distro, linux_version, distro_name = platform.linux_distribution() ...
You are a Python code generator, capable of creating scripts from specifications.
def manage_service(service_name, service_action='status', systemd=None, output=True): """Use to run Linux sysv or systemd service commands :param service_name (str) name of the service to start :param service_action (str) action to perform on the service :param systemd (bool) True if the command should...
Write a Python 3 function that can manage a Linux service.
You are a Python code generator, capable of creating scripts from specifications.
Reboot the system after a specified wait time.
Can you generate the documentation for the following Python 3 function def system_reboot(wait_time_sec=20): log = logging.getLogger(mod_logger + '.system_reboot') try: wait_time_sec = int(wait_time_sec) except ValueError: raise CommandError('wait_time_sec must be an int, or a string convert...
You are a Python code analyst, evaluating scripts for potential improvements.
Logs a consistent event for easy parsing and analysis.
Can you generate a brief explanation for the following Python 3 code def log_event(name: str, request: Request=None, data=None, ip=None): log_data = {} if not ip and request: ip = get_real_ip(request) if ip: log_data['ip'] = ip if data: log_data['data'] = data msg = 'EVENT_{...
You are a Python code generator, capable of creating scripts from specifications.
AES decrypt the value with the given secret.
Can you generate the documentation for the following Python 3 function def aes_b64_decrypt(value, secret, block_size=AES.block_size): if value is not None: iv = value[:block_size] cipher = AES.new(secret[:32], AES.MODE_CFB, iv) return cipher.decrypt(b64decode( uniorbytes(value[bl...
You are a Python code generator, capable of creating scripts from specifications.
AES decrypt the value with the given secret.
Explain what the following Python 3 code does def aes_decrypt(value, secret, block_size=AES.block_size): if value is not None: cipher = AES.new(secret[:32], AES.MODE_CFB, value[:block_size]) return cipher.decrypt(uniorbytes(value[block_size * 2:], bytes))
As a Python code composer, you craft elegant and concise scripts.
Adds padding to get the correct block sizes for AES encryption
How would you explain what the following Python 3 function does def aes_pad(s, block_size=32, padding='{'): return s + (block_size - len(s) % block_size) * padding
As a Python code translator, you convert algorithms and pseudocode into Python.
def lscmp(a, b): """ Compares two strings in a cryptographically safe way: Runtime is not affected by length of common prefix, so this is helpful against timing attacks. .. from vital.security import lscmp lscmp("ringo", "starr") # -> False ls...
Write a Python 3 function that can compare two strings in a cryptographically safe way.
As a Python code translator, you convert algorithms and pseudocode into Python.
def cookie(data, key_salt='', secret=None, digestmod=None): """ Encodes or decodes a signed cookie. @data: cookie data @key_salt: HMAC key signing salt @secret: HMAC signing secret key @digestmod: hashing algorithm to sign with, recommended >=sha256 -> HMAC signed or unsigne...
Create a Python 3 function for encoding or decodes a signed or unsigned cookie.
As a python code expert, you are capable of creating scripts from specifications.