output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Compute specified symmetric confidence interval for empirical sample.
Can you generate a brief explanation for the following Python 3 code def empirical_confidence_interval(sample, interval=0.95): # Sort sample in increasing order. sample = np.sort(sample) # Determine sample size. N = len(sample) # Compute low and high indices. low_index = int(np.round((N-1) * (...
As a Python code composer, you craft elegant and concise scripts.
Generates LaTeX table for the given SampledHMM.
Can you tell what is the following Python 3 function doing def generate_latex_table(sampled_hmm, conf=0.95, dt=1, time_unit='ms', obs_name='force', obs_units='pN', caption='', outfile=None): """ Generate a LaTeX column-wide table showing various computed properties and uncertainties. ...
You are a Python code analyst, evaluating scripts for potential improvements.
def confidence_interval(data, alpha): """ Computes the mean and alpha-confidence interval of the given sample set Parameters ---------- data : ndarray a 1D-array of samples alpha : float in [0,1] the confidence level, i.e. percentage of data included in the interval ...
Can you create a Python 3 function that computes the mean and alpha - confidence interval of the given sample set.
You are a Python code architect, reviewing and designing scalable and efficient code
def status(self, remote=False): """ Return the connection status, both locally and remotely. The local connection status is a dictionary that gives: * the count of multiple queries sent to the server. * the count of single queries sent to the server. * the count of actio...
Write a Python 3 script to return the connection status both locally and remotely.
You are a Python code analyst, evaluating scripts for potential improvements.
Query for a single object.
Here you have a function in Python 3, explain what it does def query_single(self, object_type, url_params, query_params=None): # type: (str, list, dict) -> dict """ Query for a single object. :param object_type: string query type (e.g., "users" or "groups") :param url_params: req...
As a Python code translator, you convert algorithms and pseudocode into Python.
Query for multiple objects.
Here you have a function in Python 3, explain what it does def query_multiple(self, object_type, page=0, url_params=None, query_params=None): # type: (str, int, list, dict) -> tuple """ Query for a page of objects. Defaults to the (0-based) first page. Sadly, the sort order is undetermi...
You are a Python code generator, capable of creating scripts from specifications.
def execute_single(self, action, immediate=False): """ Execute a single action (containing commands on a single object). Normally, since actions are batched so as to be most efficient about execution, but if you want this command sent immediately (and all prior queued commands se...
Implement a function in Python 3 to execute a single action on a single object.
As a Python code analyst, you investigate and solve complex coding mysteries
def execute_multiple(self, actions, immediate=True): """ Execute multiple Actions (each containing commands on a single object). Normally, the actions are sent for execution immediately (possibly preceded by earlier queued commands), but if you are going for maximum efficiency yo...
Can you write a function in Python 3 where it executes multiple actions on a single object.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _execute_batch(self, actions): """ Execute a single batch of Actions. For each action that has a problem, we annotate the action with the error information for that action, and we return the number of successful actions in the batch. :param actions: the list of Action...
Can you write a function in Python 3 where it executes a batch of Actions.
As a Python code translator, you convert algorithms and pseudocode into Python.
Make a single UMAPI call with error handling and retry on temporary failure.
Given the following Python 3 function, write the documentation def make_call(self, path, body=None, delete=False): if body: request_body = json.dumps(body) def call(): return self.session.post(self.endpoint + path, auth=self.auth, data=request_body, timeout=self.timeout) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Paginate through all results of a UMAPI query
Make a summary of the following Python 3 code def paginate(query, org_id, max_pages=maxsize, max_records=maxsize): page_count = 0 record_count = 0 records = [] while page_count < max_pages and record_count < max_records: res = make_call(query, org_id, page_count) page_count += 1 ...
You are a Python code analyst, evaluating scripts for potential improvements.
def make_call(query, org_id, page): """ Make a single UMAPI call with error handling and server-controlled throttling. (Adapted from sample code at https://www.adobe.io/products/usermanagement/docs/samples#retry) :param query: a query method from a UMAPI instance (callable as a function) :param org_...
Write a Python 3 script to make a single UMAPI call with error handling and server - controlled throttling.
As a Python code composer, you craft elegant and concise scripts.
This method is used to add commands to the list of available user - defined commands.
Explain what the following Python 3 code does def do(self, **kwargs): # add "create" / "add" / "removeFrom" first for k, v in list(six.iteritems(kwargs)): if k.startswith("create") or k.startswith("addAdobe") or k.startswith("removeFrom"): self.commands.append({k: v}) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Split this action into an equivalent list of actions each of which have at most max_commands commands.
Explain what the following Python 3 code does def split(self, max_commands): a_prior = Action(**self.frame) a_prior.commands = list(self.commands) self.split_actions = [a_prior] while len(a_prior.commands) > max_commands: a_next = Action(**self.frame) a_prior.comm...
You are a Python code generator, capable of creating scripts from specifications.
def append(self, **kwargs): """ Add commands at the end of the sequence. Be careful: because this runs in Python 2.x, the order of the kwargs dict may not match the order in which the args were specified. Thus, if you care about specific ordering, you must make multiple calls t...
Write a Python 3 function that can add commands at the end of the sequence.
You are a Python code architect, reviewing and designing scalable and efficient code
Insert commands at the beginning of the sequence.
Can you generate a brief explanation for the following Python 3 code def insert(self, **kwargs): for k, v in six.iteritems(kwargs): self.commands.insert(0, {k: v}) return self
As a Python code analyst, you investigate and solve complex coding mysteries
def report_command_error(self, error_dict): """ Report a server error executing a command. We keep track of the command's position in the command list, and we add annotation of what the command was, to the error. :param error_dict: The server's error dict for the error encounter...
How would you code a function in Python 3 to report a server error executing a command.
As a Python code translator, you convert algorithms and pseudocode into Python.
def execution_errors(self): """ Return a list of commands that encountered execution errors, with the error. Each dictionary entry gives the command dictionary and the error dictionary :return: list of commands that gave errors, with their error information """ if self.s...
Write a Python 3 function that can return a list of commands that encountered execution errors with the error.
You are a Python code analyst, evaluating scripts for potential improvements.
Check if group lists in add or remove directives should be split and split them if needed.
Can you generate the documentation for the following Python 3 function def maybe_split_groups(self, max_groups): split_commands = [] # return True if we split at least once maybe_split = False valid_step_keys = ['add', 'addRoles', 'remove'] for command in self.commands: ...
You are a Python code architect, reviewing and designing scalable and efficient code
Reload the results from the server side.
Given the following Python 3 function, write the documentation def reload(self): self._results = [] self._next_item_index = 0 self._next_page_index = 0 self._last_page_seen = False
As a Python code composer, you craft elegant and concise scripts.
def _next_page(self): """ Fetch the next page of the query. """ if self._last_page_seen: raise StopIteration new, self._last_page_seen = self.conn.query_multiple(self.object_type, self._next_page_index, self...
How would you code a function in Python 3 to fetch the next page of the query.
You are a Python code architect, reviewing and designing scalable and efficient code
Eagerly fetch all the results.
Explain what the following Python 3 code does def all_results(self): while not self._last_page_seen: self._next_page() self._next_item_index = len(self._results) return list(self._results)
As a python code expert, you are capable of creating scripts from specifications.
Fetch the object from the server.
Given the following Python 3 function, write the documentation def _fetch_result(self): self._result = self.conn.query_single(self.object_type, self.url_params, self.query_params)
As a Python code composer, you craft elegant and concise scripts.
Create a user on the Adobe back end.
Given the following Python 3 function, write the documentation def create(self, first_name=None, last_name=None, country=None, email=None, on_conflict=IfAlreadyExistsOptions.ignoreIfAlreadyExists): """ Create the user on the Adobe back end. See [Issue 32](https://github.com/adobe-...
As a Python code translator, you convert algorithms and pseudocode into Python.
def update(self, email=None, username=None, first_name=None, last_name=None, country=None): """ Update values on an existing user. See the API docs for what kinds of update are possible. :param email: new email for this user :param username: new username for this user :param fir...
Write a Python 3 script for updating the user s attributes.
As a Python code composer, you craft elegant and concise scripts.
def add_to_groups(self, groups=None, all_groups=False, group_type=None): """ Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the u...
Create a Python 3 function for adding user to some groups.
As a python code expert, you are capable of creating scripts from specifications.
Removes a user from some PLC groups or all of them.
Make a summary of the following Python 3 code def remove_from_groups(self, groups=None, all_groups=False, group_type=None): if all_groups: if groups or group_type: raise ArgumentError("When removing from all groups, do not specify specific groups or types") glist = "all" ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a role to a user
Given the following Python 3 function, write the documentation def add_role(self, groups=None, role_type=RoleTypes.admin): if not groups: raise ArgumentError("You must specify groups to which to add the role for this user") if role_type in RoleTypes.__members__: role_type = RoleT...
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes a user from a role of some groups.
Given the following Python 3 function, write the documentation def remove_role(self, groups=None, role_type=RoleTypes.admin): if not groups: raise ArgumentError("You must specify groups from which to remove the role for this user") if role_type in RoleTypes.__members__: role_type...
You are a Python code analyst, evaluating scripts for potential improvements.
Removes a user from the organization s list of visible users.
Can you tell what is the following Python 3 function doing def remove_from_organization(self, delete_account=False): self.append(removeFromOrg={"deleteAccount": True if delete_account else False}) return None
As a Python code translator, you convert algorithms and pseudocode into Python.
Deletes a user s account.
Here you have a function in Python 3, explain what it does def delete_account(self): if self.id_type == IdentityTypes.adobeID: raise ArgumentError("You cannot delete an Adobe ID account.") self.append(removeFromDomain={}) return None
As a python code expert, you are capable of creating scripts from specifications.
def _validate(cls, group_name): """ Validates the group name Input values must be strings (standard or unicode). Throws ArgumentError if any input is invalid :param group_name: name of group """ if group_name and not cls._group_name_regex.match(group_name): r...
How would you code a function in Python 3 to validate the group name
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a user group to some product license configuration groups or all of them.
Can you generate the documentation for the following Python 3 function def add_to_products(self, products=None, all_products=False): if all_products: if products: raise ArgumentError("When adding to all products, do not specify specific products") plist = "all" el...
As a Python code translator, you convert algorithms and pseudocode into Python.
Removes a user group from some product license configuration groups or all of them.
Given the following Python 3 function, write the documentation def remove_from_products(self, products=None, all_products=False): if all_products: if products: raise ArgumentError("When removing from all products, do not specify specific products") plist = "all" e...
As a Python code composer, you craft elegant and concise scripts.
Adds users to the user group.
Can you generate the documentation for the following Python 3 function def add_users(self, users=None): if not users: raise ArgumentError("You must specify emails for users to add to the user group") ulist = {"user": [user for user in users]} return self.append(add=ulist)
As a Python code analyst, you investigate and solve complex coding mysteries
Removes users from the user group.
Given the following Python 3 function, write the documentation def remove_users(self, users=None): if not users: raise ArgumentError("You must specify emails for users to remove from the user group") ulist = {"user": [user for user in users]} return self.append(remove=ulist)
As a Python code composer, you craft elegant and concise scripts.
Returns the scale of the image in x - plane.
How would you explain what the following Python 3 function does def scale2x(self, surface): assert(self._scale == 2) return self._pygame.transform.scale2x(surface)
As a python code expert, you are capable of creating scripts from specifications.
def smoothscale(self, surface): """ Smooth scaling using MMX or SSE extensions if available """ return self._pygame.transform.smoothscale(surface, self._output_size)
How would you implement a function in Python 3 that smooths scaling using MMX or SSE extensions.
As a Python code analyst, you investigate and solve complex coding mysteries
def identity(self, surface): """ Fast scale operation that does not sample the results """ return self._pygame.transform.scale(surface, self._output_size)
Can you write a function in Python 3 where it returns the identity of the current object.
As a Python code analyst, you investigate and solve complex coding mysteries
Transforms the input surface into an LED matrix.
Can you generate a brief explanation for the following Python 3 code def led_matrix(self, surface): scale = self._led_on.get_width() w, h = self._input_size pix = self._pygame.PixelArray(surface) img = self._pygame.Surface((w * scale, h * scale)) for y in range(h): f...
As a Python code composer, you craft elegant and concise scripts.
def rgb2short(r, g, b): """ Converts RGB values to the nearest equivalent xterm-256 color. """ # Using list of snap points, convert RGB value to cube indexes r, g, b = [len(tuple(s for s in snaps if s < x)) for x in (r, g, b)] # Simple colorcube transform return (r * 36) + (g * 6) + b + 16
Can you implement a function in Python 3 that converts RGB values to nearest equivalent xterm - 256 color.
You are a Python code analyst, evaluating scripts for potential improvements.
Converts a Pillow. Image into a pygame. Surface.
Here you have a function in Python 3, explain what it does def to_surface(self, image, alpha=1.0): assert(0.0 <= alpha <= 1.0) if alpha < 1.0: im = image.convert("RGBA") black = Image.new(im.mode, im.size, "black") im = Image.blend(black, im, alpha) else: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Takes a : py : mod : PIL. Image and dumps it to a numbered PNG file.
Make a summary of the following Python 3 code def display(self, image): assert(image.size == self.size) self._last_image = image self._count += 1 filename = self._file_template.format(self._count) image = self.preprocess(image) surface = self.to_surface(image, alpha=self...
You are a Python code architect, reviewing and designing scalable and efficient code
Displays an image in the current thread.
Make a summary of the following Python 3 code def display(self, image): assert(image.size == self.size) self._last_image = image image = self.preprocess(image) surface = self.to_surface(image, alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to a pygame display surface. """ assert(image.size == self.size) self._last_image = image image = self.preprocess(image) self._clock.tick(self._fps) self._pygame.event.pump() ...
Can you write a function in Python 3 where it displays the image to the pygame display surface.
You are a Python code analyst, evaluating scripts for potential improvements.
def _char_density(self, c, font=ImageFont.load_default()): """ Count the number of black pixels in a rendered character. """ image = Image.new('1', font.getsize(c), color=255) draw = ImageDraw.Draw(image) draw.text((0, 0), c, fill="white", font=font) return collec...
How would you code a function in Python 3 to count the number of black pixels in a rendered character.
You are a Python code generator, capable of creating scripts from specifications.
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ # Characters aren't square, so scale the output by the aspect ratio of a charater height = int(height * self._char_width / float(self._char_height)) image = image.resize...
How would you implement a function in Python 3 that generates an ascii art.
You are a Python code architect, reviewing and designing scalable and efficient code
Displays an image as ASCII - art.
How would you explain what the following Python 3 function does def display(self, image): assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes = self._pygame.image.tostring(surface, "RGB", False) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def _generate_art(self, image, width, height): """ Return an iterator that produces the ascii art. """ image = image.resize((width, height), Image.ANTIALIAS).convert("RGB") pixels = list(image.getdata()) for y in range(0, height - 1, 2): for x in range(width)...
Write a Python 3 function for generating an ascii art.
You are a Python code architect, reviewing and designing scalable and efficient code
def _CSI(self, cmd): """ Control sequence introducer """ sys.stdout.write('\x1b[') sys.stdout.write(cmd)
How would you implement a function in Python 3 that prints the CSI command.
As a python code expert, you are capable of creating scripts from specifications.
def display(self, image): """ Takes a :py:mod:`PIL.Image` and renders it to the current terminal as ASCII-blocks. """ assert(image.size == self.size) self._last_image = image surface = self.to_surface(self.preprocess(image), alpha=self._contrast) rawbytes...
Can you write a function in Python 3 where it displays the image as an ASCII - block.
As a Python code translator, you convert algorithms and pseudocode into Python.
def chunk_sequence(sequence, chunk_length): """Yield successive n-sized chunks from l.""" for index in range(0, len(sequence), chunk_length): yield sequence[index:index + chunk_length]
Implement a Python 3 function for yielding successive n - sized chunks from l.
You are a Python code architect, reviewing and designing scalable and efficient code
def _filter_invalid_routes(routes, board, railroad): """ Given a collection of routes, returns a new set containing only valid routes. Invalid routes removed: - contain less than 2 cities, or - go through Chicago using an impassable exit - only contain Chicago as a station, but don't use the correct...
Write a Python 3 function for giving a collection of routes returns a new set containing only valid routes.
As a Python code analyst, you investigate and solve complex coding mysteries
Find a log file.
Here you have a function in Python 3, explain what it does def find(path, level=None, message=None, time_lower=None, time_upper=None, case_sensitive=False): # pragma: no cover """ Filter log message. **中文文档** 根据level名称, message中的关键字, 和log的时间的区间, 筛选出相关的日志 """ ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a logger by name.
Can you generate the documentation for the following Python 3 function def get_logger_by_name(name=None, rand_name=False, charset=Charset.HEX): if rand_name: name = rand_str(charset) logger = logging.getLogger(name) return logger
You are a Python code generator, capable of creating scripts from specifications.
invoke self. logger. debug
Given the following Python 3 function, write the documentation def debug(self, msg, indent=0, **kwargs): return self.logger.debug(self._indent(msg, indent), **kwargs)
You are a Python code architect, reviewing and designing scalable and efficient code
invoke self. info. debug
Can you tell what is the following Python 3 function doing def info(self, msg, indent=0, **kwargs): return self.logger.info(self._indent(msg, indent), **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
invoke self. logger. warning
Here you have a function in Python 3, explain what it does def warning(self, msg, indent=0, **kwargs): return self.logger.warning(self._indent(msg, indent), **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def error(self, msg, indent=0, **kwargs): """invoke ``self.logger.error``""" return self.logger.error(self._indent(msg, indent), **kwargs)
Write a Python 3 script for invoking self. logger. error
As a Python code translator, you convert algorithms and pseudocode into Python.
invoke self. logger. critical
Explain what the following Python 3 code does def critical(self, msg, indent=0, **kwargs): return self.logger.critical(self._indent(msg, indent), **kwargs)
As a python code expert, you are capable of creating scripts from specifications.
def show(self, msg, indent=0, style="", **kwargs): """ Print message to console, indent format may apply. """ if self.enable_verbose: new_msg = self.MessageTemplate.with_style.format( indent=self.tab * indent, style=style, msg=m...
Create a Python 3 function to print a message to console indent format may apply.
As a Python code composer, you craft elegant and concise scripts.
Remove all file handlers associated with this logger.
Explain what the following Python 3 code does def remove_all_handler(self): for handler in self.logger.handlers[:]: self.logger.removeHandler(handler) self._handler_cache.append(handler)
As a Python code composer, you craft elegant and concise scripts.
Re - add all file handlers that have been removed from the logger.
Can you tell what is the following Python 3 function doing def recover_all_handler(self): for handler in self._handler_cache: self.logger.addHandler(handler) self._handler_cache = list()
As a Python code composer, you craft elegant and concise scripts.
Constructor from protobuf. :param proto: protobuf structure :type proto: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto :return: the LinkItem :rtype: ~unidown.plugin.link_item.LinkItem :raises ValueError: name of LinkItem does not exist inside the protobuf or is empty
Can you generate the documentation for the following Python 3 function def from_protobuf(cls, proto: LinkItemProto) -> LinkItem: if proto.name == '': raise ValueError("name of LinkItem does not exist or is empty inside the protobuf.") return cls(proto.name, Timestamp.ToDatetime(proto.time))
You are a Python code analyst, evaluating scripts for potential improvements.
Create protobuf item. :return: protobuf structure :rtype: ~unidown.plugin.protobuf.link_item_pb2.LinkItemProto
Can you generate a brief explanation for the following Python 3 code def to_protobuf(self) -> LinkItemProto: result = LinkItemProto() result.name = self._name result.time.CopyFrom(datetime_to_timestamp(self._time)) return result
You are a Python code architect, reviewing and designing scalable and efficient code
Adds a handler to save to a file. Includes debug stuff.
Can you generate the documentation for the following Python 3 function def update(self, fname): ltfh = FileHandler(fname) self._log.addHandler(ltfh)
As a python code expert, you are capable of creating scripts from specifications.
Delete a folder recursively.
Can you generate a brief explanation for the following Python 3 code def delete_dir_rec(path: Path): if not path.exists() or not path.is_dir(): return for sub in path.iterdir(): if sub.is_dir(): delete_dir_rec(sub) else: sub.unlink() path.rmdir()
You are a Python code architect, reviewing and designing scalable and efficient code
Create a folder recursively.
Can you tell what is the following Python 3 function doing def create_dir_rec(path: Path): if not path.exists(): Path.mkdir(path, parents=True, exist_ok=True)
As a python code expert, you are capable of creating scripts from specifications.
def datetime_to_timestamp(time: datetime) -> Timestamp: """ Convert datetime to protobuf.timestamp. :param time: time :type time: ~datetime.datetime :return: protobuf.timestamp :rtype: ~google.protobuf.timestamp_pb2.Timestamp """ protime = Timestamp() protime.FromDatetime(time) ...
Can you write a function in Python 3 where it converts datetime to protobuf. timestamp. Timestamp
As a Python code composer, you craft elegant and concise scripts.
def print_plugin_list(plugins: Dict[str, pkg_resources.EntryPoint]): """ Prints all registered plugins and checks if they can be loaded or not. :param plugins: plugins :type plugins: Dict[str, ~pkg_resources.EntryPoint] """ for trigger, entry_point in plugins.items(): try: p...
Write a Python 3 script to print all registered plugins and checks if they can be loaded or not.
You are a Python code architect, reviewing and designing scalable and efficient code
def overlap(xl1, yl1, nx1, ny1, xl2, yl2, nx2, ny2): """ Determines whether two windows overlap """ return (xl2 < xl1+nx1 and xl2+nx2 > xl1 and yl2 < yl1+ny1 and yl2+ny2 > yl1)
Write a Python 3 script to determine whether two windows overlap.
As a Python code composer, you craft elegant and concise scripts.
Saves the current setup in JSON compatible dictionary format to disk.
Given the following Python 3 function, write the documentation def saveJSON(g, data, backup=False): if not backup: fname = filedialog.asksaveasfilename( defaultextension='.json', filetypes=[('json files', '.json'), ], initialdir=g.cpars['app_directory'] ) ...
As a python code expert, you are capable of creating scripts from specifications.
def postJSON(g, data): """ Posts the current setup to the camera and data servers. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. """ g.clog.debug('Entering postJSON') # encode data as json json_dat...
Write a Python 3 function for posting the current setup to the camera and data servers.
As a python code expert, you are capable of creating scripts from specifications.
Create JSON compatible dictionary from current settings
Given the following Python 3 function, write the documentation def createJSON(g, full=True): data = dict() if 'gps_attached' not in g.cpars: data['gps_attached'] = 1 else: data['gps_attached'] = 1 if g.cpars['gps_attached'] else 0 data['appdata'] = g.ipars.dumpJSON() data['user'] = g...
As a python code expert, you are capable of creating scripts from specifications.
def insertFITSHDU(g): """ Uploads a table of TCS data to the servers, which is appended onto a run. Arguments --------- g : hcam_drivers.globals.Container the Container object of application globals """ if not g.cpars['hcam_server_on']: g.clog.warn('insertFITSHDU: servers ar...
Implement a function in Python 3 to upload a table of TCS data to the server and returns True if successful False otherwise
As a Python code analyst, you investigate and solve complex coding mysteries
def execCommand(g, command, timeout=10): """ Executes a command by sending it to the rack server Arguments: g : hcam_drivers.globals.Container the Container object of application globals command : (string) the command (see below) Possible commands are: start : s...
Can you implement a function in Python 3 that executes a command on the NGC controller and returns True if the command was successful False otherwise
As a Python code analyst, you investigate and solve complex coding mysteries
Checks if a run is active
Here you have a function in Python 3, explain what it does def isRunActive(g): if g.cpars['hcam_server_on']: url = g.cpars['hipercam_server'] + 'summary' response = urllib.request.urlopen(url, timeout=2) rs = ReadServer(response.read(), status_msg=True) if not rs.ok: rais...
You are a Python code analyst, evaluating scripts for potential improvements.
def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO...
Write a Python 3 script to poll the data server to find the current frame number.
You are a Python code generator, capable of creating scripts from specifications.
def getRunNumber(g): """ Polls the data server to find the current run number. Throws exceptions if it can't determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'summary' response = url...
Write a Python 3 function that can poll the data server to find the current run number. Throws exceptions if it can t determine it.
You are a Python code architect, reviewing and designing scalable and efficient code
Sends a request to Simbad to check whether a target is recognised. Returns with a list of results or raises an exception if it times out.
Make a summary of the following Python 3 code def checkSimbad(g, target, maxobj=5, timeout=5): url = 'http://simbad.u-strasbg.fr/simbad/sim-script' q = 'set limit ' + str(maxobj) + \ '\nformat object form1 "Target: %IDLIST(1) | %COO(A D;ICRS)"\nquery ' \ + target query = urllib.parse.urlenco...
You are a Python code architect, reviewing and designing scalable and efficient code
def run(self): """ Version of run that traps Exceptions and stores them in the fifo """ try: threading.Thread.run(self) except Exception: t, v, tb = sys.exc_info() error = traceback.format_exception_only(t, v)[0][:-1] tback ...
Create a Python 3 function for running the thread and stores the tracebacks and the exception in the fifo.
As a python code expert, you are capable of creating scripts from specifications.
Adds the styles of the GUI element w to the global fonts and colours.
Given the following Python 3 function, write the documentation def addStyle(w): # access global container in root widget root = get_root(w) g = root.globals fsize = g.cpars['font_size'] family = g.cpars['font_family'] # Default font g.DEFAULT_FONT = font.nametofont("TkDefaultFont") g.DE...
You are a Python code analyst, evaluating scripts for potential improvements.
Initialize the _downloader. TODO. :param main_dir: main directory :type main_dir: ~pathlib.Path :param logfile_path: logfile path :type logfile_path: ~pathlib.Path :param log_level: logging level :type log_level: str
Make a summary of the following Python 3 code def init(main_dir: Path, logfile_path: Path, log_level: str): dynamic_data.reset() dynamic_data.init_dirs(main_dir, logfile_path) dynamic_data.check_dirs() tools.create_dir_rec(dynamic_data.MAIN_DIR) tools.create_dir_rec(dynamic_data.TEMP_DIR) tool...
As a Python code translator, you convert algorithms and pseudocode into Python.
Download and check if all data is downloaded and if so update the site with the latest update time.
Can you tell what is the following Python 3 function doing def download_from_plugin(plugin: APlugin): # get last update date plugin.log.info('Get last update') plugin.update_last_update() # load old save state save_state = plugin.load_save_state() if plugin.last_update <= save_state.last_update:...
As a Python code analyst, you investigate and solve complex coding mysteries
Runs a plugin so use the download routine and clean up after.
Can you generate the documentation for the following Python 3 function def run(plugin_name: str, options: List[str] = None) -> PluginState: if options is None: options = [] if plugin_name not in dynamic_data.AVAIL_PLUGINS: msg = 'Plugin ' + plugin_name + ' was not found.' logging.error(...
You are a Python code analyst, evaluating scripts for potential improvements.
def check_update(): """ Check for app updates and print/log them. """ logging.info('Check for app updates.') try: update = updater.check_for_app_updates() except Exception: logging.exception('Check for updates failed.') return if update: print("!!! UPDATE AVAI...
Write a Python 3 function for checking for app updates and print them if they are available.
As a Python code composer, you craft elegant and concise scripts.
def get_newest_app_version() -> Version: """ Download the version tag from remote. :return: version from remote :rtype: ~packaging.version.Version """ with urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where()) as p_man: pypi_json = p_man.urlopen('GET', static_data.PYP...
Write a Python 3 script for downloading the version tag from remote and return the newest version.
As a Python code analyst, you investigate and solve complex coding mysteries
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( numexp=self.number.value(), app=self.a...
Write a Python 3 function for dumping current parameters to JSON compatible dictionary.
You are a Python code generator, capable of creating scripts from specifications.
Load the current state from a JSON string.
Make a summary of the following Python 3 code def loadJSON(self, json_string): g = get_root(self).globals data = json.loads(json_string)['appdata'] # first set the parameters which change regardless of mode # number of exposures numexp = data.get('numexp', 0) if numexp ==...
You are a Python code analyst, evaluating scripts for potential improvements.
Checks validity of the instrument parameters.
Can you generate the documentation for the following Python 3 function def check(self, *args): status = True g = get_root(self).globals # clear errors on binning (may be set later if FF) xbinw, ybinw = self.wframe.xbin, self.wframe.ybin xbinw.config(bg=g.COL['main']) ybi...
As a python code expert, you are capable of creating scripts from specifications.
def freeze(self): """ Freeze all settings so they cannot be altered """ self.app.disable() self.clear.disable() self.nod.disable() self.led.disable() self.dummy.disable() self.readSpeed.disable() self.expose.disable() self.number.di...
Can you implement a function in Python 3 that freezes all settings so they cannot be altered
As a Python code composer, you craft elegant and concise scripts.
def getRtplotWins(self): """" Returns a string suitable to sending off to rtplot when it asks for window parameters. Returns null string '' if the windows are not OK. This operates on the basis of trying to send something back, even if it might not be OK as a window setup...
Can you write a function in Python 3 where it returns a string suitable to send off to rtplot when the current window parameters are OK. Returns null string if the current window parameters are not OK.
As a Python code analyst, you investigate and solve complex coding mysteries
Return a tuple of the current set of timing information for the current set of instrument parameters.
Here you have a function in Python 3, explain what it does def timing(self): # drift mode y/n? isDriftMode = self.isDrift() # FF y/n? isFF = self.isFF() # Set the readout speed readSpeed = self.readSpeed() if readSpeed == 'Fast' and self.dummy(): vid...
You are a Python code architect, reviewing and designing scalable and efficient code
Sets the values of the run parameters given a JSON string
How would you explain what the following Python 3 function does def loadJSON(self, json_string): g = get_root(self).globals user = json.loads(json_string)['user'] def setField(widget, field): val = user.get(field) if val is not None: widget.set(val) ...
You are a Python code generator, capable of creating scripts from specifications.
Dumps current parameters to JSON compatible dictionary.
Given the following Python 3 function, write the documentation def dumpJSON(self): g = get_root(self).globals dtype = g.observe.rtype() if dtype == 'bias': target = 'BIAS' elif dtype == 'flat': target = 'FLAT' elif dtype == 'dark': target = 'DA...
You are a Python code architect, reviewing and designing scalable and efficient code
def check(self, *args): """ Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False. """ ok = True msg = '' g = get_root(self).globals dtype = g.observe.rtyp...
Write a Python 3 function that can check the validity of the run parameters. Returns True if the flag is False otherwise.
You are a Python code generator, capable of creating scripts from specifications.
Freeze all settings so that they can t be altered
Explain what the following Python 3 code does def freeze(self): self.target.disable() self.filter.configure(state='disable') self.prog_ob.configure(state='disable') self.pi.configure(state='disable') self.observers.configure(state='disable') self.comment.configure(state='...
You are a Python code analyst, evaluating scripts for potential improvements.
Unfreeze all settings so that they can be altered
Given the following Python 3 function, write the documentation def unfreeze(self): g = get_root(self).globals self.filter.configure(state='normal') dtype = g.observe.rtype() if dtype == 'data caution' or dtype == 'data' or dtype == 'technical': self.prog_ob.configure(state='n...
You are a Python code analyst, evaluating scripts for potential improvements.
def checkUpdate(self, *args): """ Updates values after first checking instrument parameters are OK. This is not integrated within update to prevent ifinite recursion since update gets called from ipars. """ g = get_root(self).globals if not self.check(): ...
Create a Python 3 function for checking if the current observing parameters are OK.
You are a Python code generator, capable of creating scripts from specifications.
def check(self): """ Checks values """ status = True g = get_root(self).globals if self.mag.ok(): self.mag.config(bg=g.COL['main']) else: self.mag.config(bg=g.COL['warn']) status = False if self.airmass.ok(): ...
Implement a Python 3 function for checking if the current instance of the assessment is OK.
As a Python code composer, you craft elegant and concise scripts.