output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Returns the version storage for the given version file.
How would you explain what the following Python 3 function does def get_version_storage(): # type: () -> VersionStorage """ Get version storage for the given version file. The storage engine used depends on the extension of the *version_file*. """ version_file = conf.get_path('version_file', 'VERSI...
As a Python code translator, you convert algorithms and pseudocode into Python.
def read(self): # type: () -> Optional[str] """ Read the project version from .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and read the version string. """ with open(self.version_file) as fp: content = fp.read() ...
Create a Python 3 function for reading the project version from. py file.
You are a Python code analyst, evaluating scripts for potential improvements.
Writes the project version to. py file.
Make a summary of the following Python 3 code def write(self, version): # type: (str) -> None """ Write the project version to .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and substitute the version string for the new version. """ ...
You are a Python code architect, reviewing and designing scalable and efficient code
def read(self): # type: () -> Optional[str] """ Read the project version from .py file. This will regex search in the file for a ``__version__ = VERSION_STRING`` and read the version string. """ with open(self.version_file) as fp: version = fp.read().strip() ...
Write a Python 3 function for reading the project version from. py file.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a nimage object from a FITS file.
Here you have a function in Python 3, explain what it does def fromfits(infile, hdu = 0, verbose = True): pixelarray, hdr = ft.getdata(infile, hdu, header=True) pixelarray = np.asarray(pixelarray).transpose() #print pixelarray pixelarrayshape = pixelarray.shape if verbose : print "...
You are a Python code generator, capable of creating scripts from specifications.
Auxiliary function to rebin ndarray data.
Explain what the following Python 3 code does def rebin(a, newshape): shape = a.shape lenShape = len(shape) factor = np.asarray(shape)/np.asarray(newshape) #print factor evList = ['a.reshape('] + \ ['newshape[%d],factor[%d],'%(i,i) for i in xrange(lenShape)] + \ ...
As a Python code composer, you craft elegant and concise scripts.
def compose(f2nimages, outfile): """ Takes f2nimages and writes them into one single png file, side by side. f2nimages is a list of horizontal lines, where each line is a list of f2nimages. For instance : [ [image1, image2], [image3, image4] ] The sizes of these images have to "match...
Write a Python 3 function that can take f2nimages and writes them into one png file side by side.
As a Python code analyst, you investigate and solve complex coding mysteries
Crops the image. Two points : - We use numpy conventions xa = 200 and xb = 400 will give you a width of 200 pixels ! - We crop relative to the current array (i.e. not necessarily to the original array !) This means you can crop several times in a row wit...
How would you explain what the following Python 3 function does def crop(self, xa, xb, ya, yb): if self.pilimage != None: raise RuntimeError, "Cannot crop anymore, PIL image already exists !" if self.verbose: print "Cropping : [%i:%i, %i:%i]" % (xa, xb, ya, yb) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Crop the image with the given irafcropstring.
Given the following Python 3 function, write the documentation def irafcrop(self, irafcropstring): irafcropstring = irafcropstring[1:-1] # removing the [ ] ranges = irafcropstring.split(",") xr = ranges[0].split(":") yr = ranges[1].split(":") xmin = int(xr[0]) xmax = int(...
As a Python code translator, you convert algorithms and pseudocode into Python.
def makepilimage(self, scale = "log", negative = False): """ Makes a PIL image out of the array, respecting the z1 and z2 cutoffs. By default we use a log scaling identical to iraf's, and produce an image of mode "L", i.e. grayscale. But some drawings or colourscales will change the mode...
Create a Python 3 function for making a PIL image out of the array.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method shows the cutoffs of the related image.
Can you generate a brief explanation for the following Python 3 code def showcutoffs(self, redblue = False): highmask = self.numpyarray > self.z2 lowmask = self.numpyarray < self.z1 if redblue == False : if self.negative : self.drawmask(highmask, colour = 255...
As a python code expert, you are capable of creating scripts from specifications.
Auxiliary method to make a draw object.
How would you explain what the following Python 3 function does def makedraw(self): if self.draw == None: self.draw = imdw.Draw(self.pilimage)
You are a Python code architect, reviewing and designing scalable and efficient code
Loads the title font from the file system.
How would you explain what the following Python 3 function does def loadtitlefont(self): if self.titlefont == None: # print 'the bloody fonts dir is????', fontsdir # print 'pero esto que hace??', os.path.join(fontsdir, "courR18.pil") # /home/vital/Workspace/pyResources/Scient...
As a python code expert, you are capable of creating scripts from specifications.
Auxiliary method to load label font if not yet done.
Explain what the following Python 3 code does def loadlabelfont(self): if self.labelfont == None: self.labelfont = imft.load_path(os.path.join(fontsdir, "courR10.pil"))
As a Python code translator, you convert algorithms and pseudocode into Python.
Change the colour mode of the current image.
Explain what the following Python 3 code does def changecolourmode(self, newcolour): if type(newcolour) != type(0) and self.pilimage.mode != "RGB": if self.verbose : print "Switching to RGB !" self.pilimage = self.pilimage.convert("RGB") self.draw = None # imp...
As a python code expert, you are capable of creating scripts from specifications.
def pilcoords(self, (x,y)): """ Converts the coordinates (x,y) of the original array or FITS file to the current coordinates of the PIL image, respecting cropping, rebinning, and upsampling. This is only used once the PIL image is available, for drawing. Note that we also have to...
Can you implement a function in Python 3 that converts the coordinates x y of the original array or FITS file to the current coordinates of the PIL image.
You are a Python code generator, capable of creating scripts from specifications.
def pilscale(self, r): """ Converts a "scale" (like an aperture radius) of the original array or FITS file to the current PIL coordinates. """ return r * float(self.upsamplefactor) / float(self.binfactor)
Create a Python 3 function for converting a scale from the original array or FITS file to the current PIL coordinates.
You are a Python code architect, reviewing and designing scalable and efficient code
def drawpoint(self, x, y, colour = None): """ Most elementary drawing, single pixel, used mainly for testing purposes. Coordinates are those of your initial image ! """ self.checkforpilimage() colour = self.defaultcolour(colour) self.changecolourmode(colour) ...
Write a Python 3 function that can draw a point on the current image.
As a Python code analyst, you investigate and solve complex coding mysteries
def drawcircle(self, x, y, r = 10, colour = None, label = None): """ Draws a circle centered on (x, y) with radius r. All these are in the coordinates of your initial image ! You give these x and y in the usual ds9 pixels, (0,0) is bottom left. I will convert this into the right PIL coor...
How would you code a function in Python 3 to draw a circle centered on x y with radius r.
As a Python code analyst, you investigate and solve complex coding mysteries
def drawrectangle(self, xa, xb, ya, yb, colour=None, label = None): """ Draws a 1-pixel wide frame AROUND the region you specify. Same convention as for crop(). """ self.checkforpilimage() colour = self.defaultcolour(colour) self.changecolourmode(colour) ...
Create a Python 3 function for drawing a 1 - pixel wide frame AROUND the region you specify.
As a Python code composer, you craft elegant and concise scripts.
Writes a title on the image.
Can you generate the documentation for the following Python 3 function def writetitle(self, titlestring, colour = None): self.checkforpilimage() colour = self.defaultcolour(colour) self.changecolourmode(colour) self.makedraw() self.loadtitlefont() ...
You are a Python code generator, capable of creating scripts from specifications.
def writeinfo(self, linelist, colour = None): """ We add a longer chunk of text on the upper left corner of the image. Provide linelist, a list of strings that will be written one below the other. """ self.checkforpilimage() colour = self.defaultcolour(colour) ...
Create a Python 3 function to write some info on the image.
You are a Python code generator, capable of creating scripts from specifications.
def drawstarslist(self, dictlist, r = 10, colour = None): """ Calls drawcircle and writelable for an list of stars. Provide a list of dictionnaries, where each dictionnary contains "name", "x", and "y". """ self.checkforpilimage() colour = self.defaultco...
Write a Python 3 function for calling drawcircle and writelable for an list of stars.
As a Python code analyst, you investigate and solve complex coding mysteries
def tonet(self, outfile): """ Writes the PIL image into a png. We do not want to flip the image at this stage, as you might have written on it ! """ self.checkforpilimage() if self.verbose : print "Writing image to %s...\n%i x %i pixels, mode %s" % (o...
Create a Python 3 function for writing the PIL image into a png file.
As a Python code analyst, you investigate and solve complex coding mysteries
Sets up the CORS headers response based on the settings used for the API.
Can you tell what is the following Python 3 function doing def cors_setup(self, request): def cors_headers(request, response): if request.method.lower() == 'options': response.headers.update({ '-'.join([p.capitalize() for p in k.split('_')]): v ...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a new service for the given request.
Make a summary of the following Python 3 code def factory(self, request, parent=None, name=None): traverse = request.matchdict['traverse'] # show documentation at the root path if not traverse: return {} else: service = {} name = name or traverse[0] ...
You are a Python code analyst, evaluating scripts for potential improvements.
def register(self, service, name=''): """ Exposes a given service to this API. """ # expose a sub-factory if isinstance(service, ApiFactory): self.services[name] = (service.factory, None) # expose a module dynamically as a service elif inspect.ismodul...
Can you create a Python 3 function that registers a given service to this API.
You are a Python code architect, reviewing and designing scalable and efficient code
Serves this API from the inputted root path
Make a summary of the following Python 3 code def serve(self, config, path, route_name=None, permission=None, **view_options): route_name = route_name or path.replace('/', '.').strip('.') path = path.strip('/') + '*traverse' self.route_name = route_name self.base_permission = permission...
You are a Python code analyst, evaluating scripts for potential improvements.
Prints a line from the terminal.
Make a summary of the following Python 3 code def line(separator="-·-", color=None, padding=None, num=1): for x in range(num): columns = get_terminal_width() separator = "".join( separator for x in range(floor(columns/len(separator)))) print(padd(colorize(separator.st...
As a python code expert, you are capable of creating scripts from specifications.
Adds extra new lines to the top bottom or all of a String .
Can you generate the documentation for the following Python 3 function def padd(text, padding="top", size=1): if padding: padding = padding.lower() pad_all = padding == 'all' padding_top = "" if padding and (padding == 'top' or pad_all): padding_top = "".join("\n" for x i...
As a Python code composer, you craft elegant and concise scripts.
Colorizes the text for terminal outputs.
Make a summary of the following Python 3 code def colorize(text, color="BLUE", close=True): if color: color = getattr(colors, color.upper()) return color + uncolorize(str(text)) + (colors.RESET if close else "") return text
As a python code expert, you are capable of creating scripts from specifications.
Bolds text for terminal outputs
Can you tell what is the following Python 3 function doing def bold(text, close=True): return getattr(colors, "BOLD") + str(text) + \ (colors.RESET if close else "")
As a Python code translator, you convert algorithms and pseudocode into Python.
def cut(text, length=50, replace_with="…"): """ Shortens text to @length, appends @replace_with to end of string if the string length is > @length @text: #str text to shortens @length: #int max length of string @replace_with: #str to replace chars beyond @length with .. ...
Create a Python 3 function to shorten text to length appends replace_with to end of string
As a Python code composer, you craft elegant and concise scripts.
def flag(text=None, color=None, padding=None, show=True, brackets='⸨⸩'): """ Wraps @text in parentheses (), optionally colors and pads and prints the text. @text: #str text to (flag) @color: #str color to :func:colorize the text within @padding: #str location of padding from :func:p...
Write a Python 3 script for wrapping @text in parentheses (), optionally colors and pads and prints the text. @text: #str text to (flag) @color: #str color to :func:colorize the text within @padding: #str location of padding from :func:padd @show: #bool whether or not to print the text in addition to returning it -> #s...
You are a Python code analyst, evaluating scripts for potential improvements.
Generates a random string from the specified random module.
Make a summary of the following Python 3 code def gen_rand_str(*size, use=None, keyspace=None): keyspace = keyspace or (string.ascii_letters + string.digits) keyspace = [char for char in keyspace] use = use or _random use.seed() if size: size = size if len(size) == 2 else (size[0], size[0]) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_parent_name(obj): """ Gets the name of the object containing @obj and returns as a string @obj: any python object -> #str parent object name or None .. from vital.debug import get_parent_name get_parent_name(get_parent_name) # -> 'vital.debug' ...
Implement a Python 3 function for getting the name of the object containing the object and returns as a string
As a Python code analyst, you investigate and solve complex coding mysteries
Gets the class object which defined a given method.
How would you explain what the following Python 3 function does def get_class_that_defined_method(meth): if inspect.ismethod(meth): for cls in inspect.getmro(meth.__self__.__class__): if cls.__dict__.get(meth.__name__) is meth: return cls meth = meth.__func__ # fallback ...
You are a Python code architect, reviewing and designing scalable and efficient code
Gets the name of the object containing obj and returns as a string ..
Here you have a function in Python 3, explain what it does def get_parent_obj(obj): try: cls = get_class_that_defined_method(obj) if cls and cls != obj: return cls except AttributeError: pass if hasattr(obj, '__module__') and obj.__module__: try: modul...
You are a Python code architect, reviewing and designing scalable and efficient code
def format_obj_name(obj, delim="<>"): """ Formats the object name in a pretty way @obj: any python object @delim: the characters to wrap a parent object name in -> #str formatted name .. from vital.debug import format_obj_name format_obj_name(vital.debug.Ti...
Can you write a function in Python 3 where it formats the object name in a pretty way that contains a parent object name.
You are a Python code analyst, evaluating scripts for potential improvements.
Creates prettier object representations
Here you have a function in Python 3, explain what it does def preprX(*attributes, address=True, full_name=False, pretty=False, keyless=False, **kwargs): """ `Creates prettier object representations` @*attributes: (#str) instance attributes within the object you wish to display. Attr...
As a Python code composer, you craft elegant and concise scripts.
Adds attributes to the __repr__ string
Can you tell what is the following Python 3 function doing def add_attrs(self, *args, _order=[], **kwargs): for arg in args: if isinstance(arg, (tuple, list)): key, color = arg self.attrs[key] = (None, color) else: self.attrs[arg] = (None, ...
As a Python code composer, you craft elegant and concise scripts.
Formats the attributes of the current object.
Explain what the following Python 3 code does def _format_attrs(self): _bold = bold _colorize = colorize if not self.pretty: _bold = lambda x: x _colorize = lambda x, c: x attrs = [] add_attr = attrs.append if self.doc and hasattr(self.obj, "__doc_...
As a Python code analyst, you investigate and solve complex coding mysteries
def format(self): """ Formats the __repr__ string -> #str containing __repr__ output """ _bold = bold _break = "\n " if not self.pretty: _bold = lambda x: x # Attach memory address and return _attrs = self._format_attrs() parent_...
How would you implement a function in Python 3 that formats the __repr__ string containing __repr__ output
As a Python code analyst, you investigate and solve complex coding mysteries
def randstr(self): """ -> #str result of :func:gen_rand_str """ return gen_rand_str( 4, 10, use=self.random, keyspace=list(string.ascii_letters))
Can you implement a function in Python 3 that generates random string from the current system.
As a python code expert, you are capable of creating scripts from specifications.
def randbytes(self): """ -> #bytes result of bytes-encoded :func:gen_rand_str """ return gen_rand_str( 10, 30, use=self.random, keyspace=list(self.keyspace) ).encode("utf-8")
Write a Python 3 script for returning a random bytes - encoded version of the current n - z instance.
As a Python code analyst, you investigate and solve complex coding mysteries
def randdomain(self): """ -> a randomized domain-like name """ return '.'.join( rand_readable(3, 6, use=self.random, density=3) for _ in range(self.random.randint(1, 2)) ).lower()
Write a Python 3 function that can return a randomized domain - like name
As a Python code composer, you craft elegant and concise scripts.
def randpath(self): """ -> a random URI-like #str path """ return '/'.join( gen_rand_str(3, 10, use=self.random, keyspace=list(self.keyspace)) for _ in range(self.random.randint(0, 3)))
Implement a Python 3 function for returning a random URI - like path
You are a Python code generator, capable of creating scripts from specifications.
def randtld(self): """ -> a random #str tld via :mod:tlds """ self.tlds = tuple(tlds.tlds) if not self.tlds else self.tlds return self.random.choice(self.tlds)
Write a Python 3 function for returning a random tld from the set of TLDs
As a Python code translator, you convert algorithms and pseudocode into Python.
def randurl(self): """ -> a random url-like #str via :prop:randdomain, :prop:randtld, and :prop:randpath """ return "{}://{}.{}/{}".format( self.random.choice(("http", "https")), self.randdomain, self.randtld, self.randpath)
Write a Python 3 function for returning a random url - like string via Random.
As a Python code composer, you craft elegant and concise scripts.
Returns a random tuple of random integers
Explain what the following Python 3 code does def randtuple(self): return tuple( self.randint for x in range(0, self.random.randint(3, 10)))
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a deque of random integers.
How would you explain what the following Python 3 function does def randdeque(self): return deque( self.randint for x in range(0, self.random.randint(3, 10)))
As a Python code translator, you convert algorithms and pseudocode into Python.
def randdict(self): """ -> a #dict of |{random_string: random_int}| """ return { self.randstr: self._map_type(int) for x in range(self.random.randint(3, 10))}
Can you write a function in Python 3 where it returns a random dictionary of the class
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a set of random integers
Can you tell what is the following Python 3 function doing def randset(self): return { self._map_type(int) for x in range(self.random.randint(3, 10))}
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a dict of random items for the current tree depth.
Explain what the following Python 3 code does def dict(self, key_depth=1000, tree_depth=1): if not tree_depth: return self._map_type() return { self.randstr: self.dict(key_depth, tree_depth-1) for x in range(key_depth)}
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates a dictionary of random values for the available node types.
Given the following Python 3 function, write the documentation def defaultdict(self, key_depth=1000, tree_depth=1): if not tree_depth: return self._map_type() _dict = defaultdict() _dict.update({ self.randstr: self.defaultdict(key_depth, tree_depth-1) for x in...
As a python code expert, you are capable of creating scripts from specifications.
def tuple(self, size=1000, tree_depth=1): """ Creates a random #tuple @size: #int number of random values to include in each @tree_depth @tree_depth: #int dict tree dimensions size, i.e. 1=|(value1, value2)| 2=|((value1, value2), (value1, value2))| ...
How would you code a function in Python 3 to create a random tuple of size and tree_depth
You are a Python code architect, reviewing and designing scalable and efficient code
Creates a random generator for the size of the items in the tree_depth.
How would you explain what the following Python 3 function does def generator(self, size=1000, tree_depth=1): if not tree_depth: return self._map_type() return (self.generator(size, tree_depth-1) for x in range(size))
You are a Python code generator, capable of creating scripts from specifications.
def sequence(self, struct, size=1000, tree_depth=1, append_callable=None): """ Generates random values for sequence-like objects @struct: the sequence-like structure you want to fill with random data @size: #int number of random values to include in each @tree_depth ...
Write a Python 3 function for generating random values for the sequence - like objects in the specified structure.
As a Python code translator, you convert algorithms and pseudocode into Python.
def mapping(self, struct, key_depth=1000, tree_depth=1, update_callable=None): """ Generates random values for dict-like objects @struct: the dict-like structure you want to fill with random data @size: #int number of random values to include in each @tree_depth ...
How would you code a function in Python 3 to generate random values for the dict - like object in the tree.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _dict_prefix(self, key, value, i, dj=0, color=None, separator=":"): just = self._justify if i > 0 else dj key = cut(str(key), self._key_maxlen).rjust(just) key = colorize(key, color=color) pref = "{}{} {}".format(key, separator, value) """pref = "{}{} {}".format(colorize(str(...
Can you create a Python 3 function that returns a string that is prefixed with the key and value.
As a Python code analyst, you investigate and solve complex coding mysteries
def objname(self, obj=None): """ Formats object names in a pretty fashion """ obj = obj or self.obj _objname = self.pretty_objname(obj, color=None) _objname = "'{}'".format(colorize(_objname, "blue")) return _objname
How would you code a function in Python 3 to format object names in a pretty fashion
As a Python code analyst, you investigate and solve complex coding mysteries
def pretty(self, obj=None, display=True): """ Formats @obj or :prop:obj @obj: the object you'd like to prettify -> #str pretty object """ ret = self._format_obj(obj if obj is not None else self.obj) if display: print(ret) else: re...
Implement a Python 3 function for formatting the object in a pretty format.
You are a Python code architect, reviewing and designing scalable and efficient code
def _format_obj(self, item=None): """ Determines the type of the object and maps it to the correct formatter """ # Order here matters, odd behavior with tuples if item is None: return getattr(self, 'number')(item) elif isinstance(item, self.str_): ...
Write a Python 3 function that can format the object to the correct format for the
As a python code expert, you are capable of creating scripts from specifications.
Sets the loglevel to the given level.
Given the following Python 3 function, write the documentation def set_level(self, level): if not level: return None self.levelmap = set() for char in level: self.levelmap = self.levelmap.union(self.levels[char]) self.loglevel = level return self.loglevel
You are a Python code generator, capable of creating scripts from specifications.
def log(self, flag_message=None, padding=None, color=None, force=False): """ Log Level: :attr:LOG @flag_message: #str flags the message with the given text using :func:flag @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area wit...
Implement a function in Python 3 to log the message with the given text using the given color.
You are a Python code generator, capable of creating scripts from specifications.
Log the message with the given text and padding.
Make a summary of the following Python 3 code def success(self, flag_message="Success", padding=None, force=False): if self.should_log(self.SUCCESS) or force: self._print_message( flag_message=flag_message, color=colors.success_color, padding=padding)
As a python code expert, you are capable of creating scripts from specifications.
def complete(self, flag_message="Complete", padding=None, force=False): """ Log Level: :attr:COMPLETE @flag_message: #str flags the message with the given text using :func:flag @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area...
Create a Python 3 function for logging the message with the given text and flag the message with the given text using the given padding.
As a Python code analyst, you investigate and solve complex coding mysteries
def notice(self, flag_message="Notice", padding=None, force=False): """ Log Level: :attr:NOTICE @flag_message: #str flags the message with the given text using :func:flag @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area with ...
Write a Python 3 function for logging a notice message to the log file.
As a Python code composer, you craft elegant and concise scripts.
def warning(self, flag_message="Warning", padding=None, force=False): """ Log Level: :attr:WARNING @flag_message: #str flags the message with the given text using :func:flag @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area wi...
Create a Python 3 function to log a warning message to the log file.
You are a Python code architect, reviewing and designing scalable and efficient code
Log an error message for the current object.
Can you generate the documentation for the following Python 3 function def error(self, flag_message="Error", padding=None, force=False): if self.should_log(self.ERROR) or force: self._print_message( flag_message=flag_message, color=colors.error_color, padding=padding)
You are a Python code generator, capable of creating scripts from specifications.
Log a timing message to the log file.
Can you generate the documentation for the following Python 3 function def timing(self, flag_message, padding=None, force=False): if self.should_log(self.TIMING) or force: self._print_message( flag_message=Timer.format_time(flag_message), padding=padding, reverse=True...
You are a Python code generator, capable of creating scripts from specifications.
def count(self, flag_message, padding=None, force=False): """ Log Level: :attr:COUNT @flag_message: time-like #float @padding: #str 'top', 'bottom' or 'all', adds a new line to the specified area with :func:padd @force: #bool whether or not to force the messa...
Write a Python 3 function that can count the number of available log entries in the available log files.
As a Python code translator, you convert algorithms and pseudocode into Python.
def format_message(self, message): """ Formats a message with :class:Look """ look = Look(message) return look.pretty(display=False)
Can you implement a function in Python 3 that formats a message with a Look object
As a Python code composer, you craft elegant and concise scripts.
Formats several messages with the same class and encodes them with stdout_encode
Can you generate a brief explanation for the following Python 3 code def format_messages(self, messages): mess = "" for message in self.message: if self.pretty: mess = "{}{}".format(mess, self.format_message(message)) else: mess += str(message) ...
As a python code expert, you are capable of creating scripts from specifications.
def _print_message(self, flag_message=None, color=None, padding=None, reverse=False): """ Outputs the message to the terminal """ if flag_message: flag_message = stdout_encode(flag(flag_message, color=color if self.pretty e...
How would you implement a function in Python 3 that outputs the message to the terminal
You are a Python code architect, reviewing and designing scalable and efficient code
def format_bar(self): """ Builds the progress bar """ pct = floor(round(self.progress/self.size, 2)*100) pr = floor(pct*.33) bar = "".join( ["‒" for x in range(pr)] + ["↦"] + [" " for o in range(self._barsize-pr-1)]) subprogress = self.format_parent_bar() ...
Write a Python 3 function that can build the progress bar
As a Python code composer, you craft elegant and concise scripts.
def finish(self): """ Resets the progress bar and clears it from the terminal """ pct = floor(round(self.progress/self.size, 2)*100) pr = floor(pct*.33) bar = "".join([" " for x in range(pr-1)] + ["↦"]) subprogress = self.format_parent_bar() if self.parent_bar else "" fin...
Create a Python 3 function to print the progress bar and clears it from the terminal
As a Python code composer, you craft elegant and concise scripts.
Updates the progress bar with the given value.
How would you explain what the following Python 3 function does def update(self, progress=0): self.progress += (progress or 1) if self.visible: if self.progress % self._mod == 1 or\ self.progress == self.size - 1: print(self.format_bar(), end="\r") ...
As a Python code analyst, you investigate and solve complex coding mysteries
def stop(self, precision=0): """ Stops the timer, adds it as an interval to :prop:intervals @precision: #int number of decimal places to round to -> #str formatted interval time """ self._stop = time.perf_counter() return self.add_interval(precision)
How would you implement a function in Python 3 that stops the timer and adds it as an interval to the intervals property
You are a Python code architect, reviewing and designing scalable and efficient code
Pretty - formats a given time in a readable manner.
Given the following Python 3 function, write the documentation def format_time(self, sec): # µsec if sec < 0.001: return "{}{}".format( colorize(round(sec*1000000, 2), "purple"), bold("µs")) # ms elif sec < 1.0: return "{}{}".format( ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Adds an interval to the list of intervals and returns a formatted string.
Can you generate a brief explanation for the following Python 3 code def add_interval(self, precision=0): precision = precision or self.precision interval = round((self._stop - self._start), precision) self.intervals.append(interval) self._intervals_len += 1 self._start = time.pe...
You are a Python code analyst, evaluating scripts for potential improvements.
Measure the execution time of the function for the given number of intervals.
Here you have a function in Python 3, explain what it does def time(self, intervals=1, *args, _show_progress=True, _print=True, _collect_garbage=True, _quiet=True, **kwargs): """ Measures the execution time of :prop:_callable for @intervals @intervals: #int number of intervals to measu...
You are a Python code generator, capable of creating scripts from specifications.
Returns the mean value of the time intervals
Here you have a function in Python 3, explain what it does def mean(self): return round(np.mean(self.array), self.precision)\ if len(self.array) else None
You are a Python code generator, capable of creating scripts from specifications.
Returns the median value of the time intervals
Here you have a function in Python 3, explain what it does def median(self): return round(float(np.median(self.array)), self.precision)\ if len(self.array) else None
As a Python code composer, you craft elegant and concise scripts.
Returns the maximum value of the resource in the array
Here you have a function in Python 3, explain what it does def max(self): return round(np.max(self.array), self.precision)\ if len(self.array) else None
As a Python code composer, you craft elegant and concise scripts.
def min(self): """ -> #float :func:numpy.min of the timing intervals """ return round(np.min(self.array), self.precision)\ if len(self.array) else None
Write a Python 3 function that can return the minimum value of the resource class
As a Python code composer, you craft elegant and concise scripts.
Returns the standard deviation of the time intervals
Can you generate the documentation for the following Python 3 function def stdev(self): return round(np.std(self.array), self.precision)\ if len(self.array) else None
As a Python code analyst, you investigate and solve complex coding mysteries
def stats(self): """ -> :class:collections.OrderedDict of stats about the time intervals """ return OrderedDict([ ("Intervals", len(self.array)), ("Mean", self.format_time(self.mean or 0)), ("Min", self.format_time(self.min or 0)), ("Median", self....
Implement a Python 3 function for returning an OrderedDict of stats about the time intervals
You are a Python code architect, reviewing and designing scalable and efficient code
Calculates and colorizes the percent difference between the best and other cluster keys.
Can you generate a brief explanation for the following Python 3 code def _pct_diff(self, best, other): return colorize("{}%".format( round(((best-other)/best)*100, 2)).rjust(10), "red")
As a Python code analyst, you investigate and solve complex coding mysteries
Prints and formats the results of the timing .
Make a summary of the following Python 3 code def info(self, verbose=None): if self.name: flag(bold(self.name)) flag("Results after {} intervals".format( bold(self.num_intervals, close=False)), colors.notice_color, padding="top") line("‒") verbose = ve...
As a Python code translator, you convert algorithms and pseudocode into Python.
Loads Finnish monetary institution codes and BICs from CSV format.
Make a summary of the following Python 3 code def fi_iban_load_map(filename: str) -> dict: out = {} with open(filename, 'rt') as fp: lines = [line.strip().split(',') for line in fp.readlines()] ver = lines.pop(0) head = lines.pop(0) if head != ['National ID', 'BIC Code', 'Financi...
As a Python code translator, you convert algorithms and pseudocode into Python.
A decorator that returns an asynchronous LRU cache for Python 3. 5.
Can you generate the documentation for the following Python 3 function def async_lru(size=100): cache = collections.OrderedDict() def decorator(fn): @wraps(fn) @asyncio.coroutine def memoizer(*args, **kwargs): key = str((args, kwargs)) try: result...
As a Python code composer, you craft elegant and concise scripts.
Returns the label of the object in the choices list.
Can you tell what is the following Python 3 function doing def choices_label(choices: tuple, value) -> str: for key, label in choices: if key == value: return label return ''
As a Python code composer, you craft elegant and concise scripts.
Print sys message to stdout.
Given the following Python 3 function, write the documentation def info(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Print sys message to stdout. System messages should inform about the flow of the script. This should be a major milestones during the build. """ if len(args) or len(...
You are a Python code analyst, evaluating scripts for potential improvements.
def is_username(string, minlen=1, maxlen=15): """ Determines whether the @string pattern is username-like @string: #str being tested @minlen: minimum required username length @maxlen: maximum username length -> #bool """ if string: string = string.strip() ret...
Write a Python 3 script to determine whether the string pattern is username - like .
As a Python code analyst, you investigate and solve complex coding mysteries
def bigint_to_string(val): """ Converts @val to a string if it is a big integer (|>2**53-1|) @val: #int or #float -> #str if @val is a big integer, otherwise @val """ if isinstance(val, _NUMBERS) and not abs(val) <= 2**53-1: return str(val) return val
Write a Python 3 function for converting a big integer to a string if it is a big integer.
As a Python code analyst, you investigate and solve complex coding mysteries
def remove_blank_lines(string): """ Removes all blank lines in @string -> #str without blank lines """ return "\n".join(line for line in string.split("\n") if len(line.strip()))
Can you create a Python 3 function that removes all blank lines in the string
As a Python code translator, you convert algorithms and pseudocode into Python.
def _manage_cmd(cmd, settings=None): # type: () -> None """ Run django ./manage.py command manually. This function eliminates the need for having ``manage.py`` (reduces file clutter). """ import sys from os import environ from peltak.core import conf from peltak.core import context ...
How would you implement a function in Python 3 that runs django. manage. py command manually.
You are a Python code analyst, evaluating scripts for potential improvements.
def current_branch(): # type: () -> BranchDetails """ Return the BranchDetails for the current branch. Return: BranchDetails: The details of the current branch. """ cmd = 'git symbolic-ref --short HEAD' branch_name = shell.run( cmd, capture=True, never_pretend=Tr...
Write a Python 3 script for returning the BranchDetails for the current branch.
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the names of branches that this commit belongs to.
Can you generate the documentation for the following Python 3 function def commit_branches(sha1): # type: (str) -> List[str] """ Get the name of the branches that this commit belongs to. """ cmd = 'git branch --contains {}'.format(sha1) return shell.run( cmd, capture=True, never_...
You are a Python code architect, reviewing and designing scalable and efficient code