output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def index_registry(args, reg, ts=None, idx=None): """ Index into a :class:`~simkit.core.Registry` to return arguments from :class:`~simkit.core.data_sources.DataRegistry` and :class:`~simkit.core.outputs.OutputRegistry` based on the calculation parameter file. :param args: Arguments field from ...
How would you code a function in Python 3 to index into a :class:`~simkit.core.Registry` to return arguments from :class:`~simkit.core.data_sources.DataRegistry` and :class:`~simkit.core.outputs.OutputRegistry` based on the calculation parameter file. :param args: Arguments field from the calculation parameter file. :p...
As a Python code composer, you craft elegant and concise scripts.
Get the covariance matrix of the data and output.
Given the following Python 3 function, write the documentation def get_covariance(datargs, outargs, vargs, datvar, outvar): # number of formula arguments that are not constant argn = len(vargs) # number of observations must be the same for all vargs nobs = 1 for m in xrange(argn)...
As a Python code composer, you craft elegant and concise scripts.
Calculate the keys for a given time - interval.
Can you generate the documentation for the following Python 3 function def calculate(cls, calc, formula_reg, data_reg, out_reg, timestep=None, idx=None): """ Execute calculation :param calc: calculation, with formula, args and return keys :type calc: dict :para...
As a Python code analyst, you investigate and solve complex coding mysteries
def check_photometry_categorize(x, y, levels, tags=None): '''Put every point in its category. levels must be sorted.''' x = numpy.asarray(x) y = numpy.asarray(y) ys = y.copy() ys.sort() # Mean of the upper half m = ys[len(ys) // 2:].mean() y /= m m = 1.0 s = ys[len(ys) // 2:...
Create a Python 3 function to put every point in its category. levels must be sorted.
You are a Python code architect, reviewing and designing scalable and efficient code
Do client authentication :param endpoint_context: A :py:class:`oidcendpoint.endpoint_context.SrvInfo` instance :param request: Parsed request, a self.request_cls class instance :param authn: Authorization info :return: client_id or raise and exception
Explain what the following Python 3 code does def client_authentication(self, request, auth=None, **kwargs): return verify_client(self.endpoint_context, request, auth)
You are a Python code generator, capable of creating scripts from specifications.
def construct(self, response_args, request, **kwargs): """ Construct the response :param response_args: response arguments :param request: The parsed request, a self.request_cls class instance :param kwargs: Extra keyword arguments :return: An instance of the self.respon...
Can you create a Python 3 function that constructs the response object for the response_args request and kwargs.
You are a Python code generator, capable of creating scripts from specifications.
Set wavelength calibration parameters for rectified images.
Can you tell what is the following Python 3 function doing def set_wv_parameters(filter_name, grism_name): # protections if filter_name not in EMIR_VALID_FILTERS: raise ValueError('Unexpected filter_name:', filter_name) if grism_name not in EMIR_VALID_GRISMS: raise ValueError('Unexpected gr...
As a Python code translator, you convert algorithms and pseudocode into Python.
Creates list of input elements
Explain what the following Python 3 code does def inputs(form_args): element = [] for name, value in form_args.items(): element.append( '<input type="hidden" name="{}" value="{}"/>'.format(name, value)) return "\n".join(element)
As a Python code analyst, you investigate and solve complex coding mysteries
Verify that the URI is faulty.
How would you explain what the following Python 3 function does def verify_uri(endpoint_context, request, uri_type, client_id=None): try: _cid = request["client_id"] except KeyError: _cid = client_id if not _cid: logger.error('No client id found') raise UnknownClient('No cli...
You are a Python code analyst, evaluating scripts for potential improvements.
verify that the redirect URI is reasonable
Can you generate a brief explanation for the following Python 3 code def get_uri(endpoint_context, request, uri_type): if uri_type in request: verify_uri(endpoint_context, request, uri_type) uri = request[uri_type] else: try: _specs = endpoint_context.cdb[ str...
As a Python code composer, you craft elegant and concise scripts.
Things that are done after a successful authentication. :param user: :param request: :param sid: :param kwargs: :return: A dictionary with 'response_args'
Make a summary of the following Python 3 code def post_authentication(self, user, request, sid, **kwargs): response_info = {} # Do the authorization try: permission = self.endpoint_context.authz( user, client_id=request['client_id']) except ToOld as err: ...
As a Python code composer, you craft elegant and concise scripts.
This function is called by the client when the user is authenticated.
Can you generate a brief explanation for the following Python 3 code def authz_part2(self, user, authn_event, request, **kwargs): sid = setup_session(self.endpoint_context, request, user, authn_event=authn_event) try: resp_info = self.post_authentication(user, re...
You are a Python code architect, reviewing and designing scalable and efficient code
This method is called by the client to process the request and returns the response as a dictionary.
Can you tell what is the following Python 3 function doing def process_request(self, request_info=None, **kwargs): if isinstance(request_info, AuthorizationErrorResponse): return request_info _cid = request_info["client_id"] cinfo = self.endpoint_context.cdb[_cid] try: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def setup_session(endpoint_context, areq, uid, client_id='', acr='', salt='salt', authn_event=None): """ Setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnE...
Create a Python 3 function for setting up a user session :param endpoint_context: :param areq: :param uid: :param acr: :param client_id: :param salt: :param authn_event: A already made AuthnEvent :return:
As a python code expert, you are capable of creating scripts from specifications.
def dict_match(a, b): """ Check if all attribute/value pairs in a also appears in b :param a: A dictionary :param b: A dictionary :return: True/False """ res = [] for k, v in a.items(): try: res.append(b[k] == v) except KeyError: pass return a...
Can you implement a function in Python 3 that checks if all attribute value pairs in a also appears in b.
You are a Python code generator, capable of creating scripts from specifications.
def mint_sub(client_salt, sector_id="", subject_type="public", uid='', user_salt=''): """ Mint a new sub (subject identifier) :param authn_event: Authentication event information :param client_salt: client specific salt - used in pairwise :param sector_id: Possible sector identifier ...
Implement a Python 3 function for minting a new sub - subject identifier
As a python code expert, you are capable of creating scripts from specifications.
Update a special session with the specified attributes.
Can you tell what is the following Python 3 function doing def update(self, sid, **kwargs): item = self[sid] for attribute, value in kwargs.items(): item[attribute] = value self[sid] = item
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the session info by token
Here you have a function in Python 3, explain what it does def update_by_token(self, token, **kwargs): _sid = self.handler.sid(token) return self.update(_sid, **kwargs)
As a Python code translator, you convert algorithms and pseudocode into Python.
def replace_token(self, sid, sinfo, token_type): """ Replace an old refresh_token with a new one :param sid: session ID :param sinfo: session info :param token_type: What type of tokens should be replaced :return: Updated session info """ try: ...
Can you implement a function in Python 3 that replaces an old refresh_token with a new one
As a Python code analyst, you investigate and solve complex coding mysteries
def refresh_token(self, token, new_refresh=False): """ Issue a new access token using a valid refresh token :param token: Refresh token :param new_refresh: Whether a new refresh token should be minted or not :return: Dictionary with session info :raises: ExpiredToken for...
Write a Python 3 function for issuing a new access token using a valid refresh token
As a Python code translator, you convert algorithms and pseudocode into Python.
Checks validity of a given token
How would you explain what the following Python 3 function does def is_token_valid(self, token): try: _tinfo = self.handler.info(token) except KeyError: return False if is_expired(int(_tinfo['exp'])) or _tinfo['black_listed']: return False # Depende...
You are a Python code architect, reviewing and designing scalable and efficient code
def revoke_token(self, token, token_type=''): """ Revokes access token :param token: access token """ if token_type: self.handler[token_type].black_list(token) else: self.handler.black_list(token)
Write a Python 3 script for revoking the token from the cache.
You are a Python code architect, reviewing and designing scalable and efficient code
def revoke_session(self, sid='', token=''): """ Mark session as revoked but also explicitly revoke all issued tokens :param token: any token connected to the session :param sid: Session identifier """ if not sid: if token: sid = self.handler.s...
Create a Python 3 function for revoking a session by explicitly revoking all issued tokens
As a Python code translator, you convert algorithms and pseudocode into Python.
def rectwv_coeff_add_longslit_model(rectwv_coeff, geometry, debugplot=0): """Compute longslit_model coefficients for RectWaveCoeff object. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for a particular CSU configuration...
Write a Python 3 script for computing the longslit model coefficients for a specific RectWaveCoeff instance.
You are a Python code analyst, evaluating scripts for potential improvements.
def pick_auth(endpoint_context, areq, all=False): """ Pick authentication method :param areq: AuthorizationRequest instance :return: A dictionary with the authentication method and its authn class ref """ acrs = [] try: if len(endpoint_context.authn_broker) == 1: return...
Write a Python 3 function that can pick the authentication method and its authn class ref from the AuthN broker.
You are a Python code analyst, evaluating scripts for potential improvements.
Generator that returns all registered authenticators based on a specific authentication class.
Can you generate the documentation for the following Python 3 function def get_method(self, cls_name): for id, spec in self.db.items(): if spec["method"].__class__.__name__ == cls_name: yield spec["method"]
As a Python code translator, you convert algorithms and pseudocode into Python.
Given the authentication context find zero or more authn methods that could be used.
Can you generate the documentation for the following Python 3 function def pick(self, acr=None): if acr is None: # Anything else doesn't make sense return self.db.values() else: return self._pick_by_class_ref(acr)
As a Python code analyst, you investigate and solve complex coding mysteries
def setup(self, path=None): """ Look for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed. """ # -- Finding sextractor program an...
Can you write a function in Python 3 where it looks for SExtractor program ('sextractor', or 'sex'). If a full path is provided, only this path is checked. Raise a SExtractorException if it failed. Return program and version if it succeed.
As a Python code analyst, you investigate and solve complex coding mysteries
Update the in - memory SExtractor configuration files according to the current in - memory SExtractor configuration.
Make a summary of the following Python 3 code def update_config(self): # -- Write filter configuration file # First check the filter itself filter = self.config['FILTER_MASK'] rows = len(filter) cols = len(filter[0]) # May raise ValueError, OK filter_f = __builtin__...
As a Python code analyst, you investigate and solve complex coding mysteries
def run(self, file, updateconfig=True, clean=False, path=None): """ Run SExtractor. If updateconfig is True (default), the configuration files will be updated before running SExtractor. If clean is True (default: False), configuration files (if any) will be deleted afte...
Implement a function in Python 3 to run the SExtractor command line and return the current version of the SExtractor.
As a Python code translator, you convert algorithms and pseudocode into Python.
Read the output catalog produced by the last SExtractor run.
Explain what the following Python 3 code does def catalog(self): output_f = SExtractorfile(self.config['CATALOG_NAME'], 'r') c = output_f.read() output_f.close() return c
You are a Python code architect, reviewing and designing scalable and efficient code
def clean(self, config=True, catalog=False, check=False): """ Remove the generated SExtractor files (if any). If config is True, remove generated configuration files. If catalog is True, remove the output catalog. If check is True, remove output check image. """ ...
Write a Python 3 script for removing the generated SExtractor files and the generated configuration files.
As a Python code composer, you craft elegant and concise scripts.
Refine rectification and wavelength calibration coefficients for a particular CSU configuration.
Explain what the following Python 3 code does def refine_rectwv_coeff(input_image, rectwv_coeff, refine_wavecalib_mode, minimum_slitlet_width_mm, maximum_slitlet_width_mm, save_intermediate_results=False, ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Select unrectified slitlet from the image2d.
Can you generate the documentation for the following Python 3 function def select_unrectified_slitlet(image2d, islitlet, csu_bar_slit_center, params, parmodel, maskonly): """Returns image with the indicated slitlet (zero anywhere else). Parameters ---------- image2d : num...
You are a Python code generator, capable of creating scripts from specifications.
def rectwv_coeff_from_arc_image(reduced_image, bound_param, lines_catalog, args_nbrightlines=None, args_ymargin_bb=2, args_remove_sp_background=True, ...
Can you implement a function in Python 3 that evaluates rect.+wavecal. coefficients from arc image.
You are a Python code architect, reviewing and designing scalable and efficient code
Compute offsets between frames using WCS information.
How would you explain what the following Python 3 function does def offsets_from_wcs(frames, pixref): '''Compute offsets between frames using WCS information. :parameter frames: sequence of FITS filenames or file descriptors :parameter pixref: numpy array used as reference pixel The sky world coordina...
You are a Python code generator, capable of creating scripts from specifications.
Compute reference pixels between frames using WCS information.
Explain what the following Python 3 code does def reference_pix_from_wcs(frames, pixref, origin=1): result = [] with frames[0].open() as hdulist: wcsh = wcs.WCS(hdulist[0].header) skyref = wcsh.wcs_pix2world([pixref], origin) result.append(pixref) for idx, frame in enumerate(frame...
You are a Python code architect, reviewing and designing scalable and efficient code
Compute reference pixels between frames using WCS information.
Here you have a function in Python 3, explain what it does def reference_pix_from_wcs_imgs(imgs, pixref, origin=1): result = [] refimg = imgs[0] wcsh = wcs.WCS(refimg[0].header) skyref = wcsh.wcs_pix2world([pixref], origin) result.append(pixref) for idx, img in enumerate(imgs[1:]): w...
As a Python code analyst, you investigate and solve complex coding mysteries
def process_request(self, request=None, cookie=None, **kwargs): """ Perform user logout :param request: :param cookie: :param kwargs: :return: """ _cntx = self.endpoint_context _sdb = _cntx.sdb if 'post_logout_redirect_uri' in request: ...
Can you create a Python 3 function that processes the request and return the user s session id and session id.
As a Python code translator, you convert algorithms and pseudocode into Python.
def rectwv_coeff_from_mos_library(reduced_image, master_rectwv, ignore_dtu_configuration=True, debugplot=0): """Evaluate rect.+wavecal. coefficients from MOS library Parameters ---------- reduced_image...
Implement a function in Python 3 to evaluate rect.+wavecal. coefficients from MOS library.
You are a Python code generator, capable of creating scripts from specifications.
Compute the median spectrum of each slitlet in the input image.
How would you explain what the following Python 3 function does def median_slitlets_rectified( input_image, mode=0, minimum_slitlet_width_mm=EMIR_MINIMUM_SLITLET_WIDTH_MM, maximum_slitlet_width_mm=EMIR_MAXIMUM_SLITLET_WIDTH_MM, debugplot=0 ): """Compute median spectrum fo...
As a python code expert, you are capable of creating scripts from specifications.
def get_networks(self): """Get the networks assoiated with the resource description. Returns list of tuple roles, network """ networks = self.c_resources["networks"] result = [] for net in networks: _c_network = net.get("_c_network") i...
Can you create a Python 3 function that gets the networks assoiated with the resource description.
You are a Python code generator, capable of creating scripts from specifications.
Get the roles associated with the hosts.
Make a summary of the following Python 3 code def get_roles(self): machines = self.c_resources["machines"] result = {} for desc in machines: roles = utils.get_roles_as_list(desc) hosts = self._denormalize(desc) for role in roles: result.setdef...
As a Python code translator, you convert algorithms and pseudocode into Python.
async def start_client(self, sock: anyio.abc.SocketStream, addr, path: str, headers: Optional[List] = None, subprotocols: Optional[List[str]] = None): """Start a client WS conne...
Write a Python 3 script for starting a client WS connection.
As a Python code composer, you craft elegant and concise scripts.
async def start_server(self, sock: anyio.abc.SocketStream, filter=None): # pylint: disable=W0622 """Start a server WS connection on this socket. Filter: an async callable that gets passed the initial Request. It may return an AcceptConnection message, a bool, or a string (the subprotoc...
Can you implement a function in Python 3 that starts a server WS connection on this socket.
You are a Python code analyst, evaluating scripts for potential improvements.
async def _next_event(self): """ Gets the next event. """ while True: for event in self._connection.events(): if isinstance(event, Message): # check if we need to buffer if event.message_finished: ...
Can you write a function in Python 3 where it gets the next event from the queue.
As a Python code analyst, you investigate and solve complex coding mysteries
Sends some data down the connection.
Can you generate the documentation for the following Python 3 function async def send(self, data: Union[bytes, str], final: bool = True): MsgType = TextMessage if isinstance(data, str) else BytesMessage data = MsgType(data=data, message_finished=final) data = self._connection.send(event=data) ...
You are a Python code architect, reviewing and designing scalable and efficient code
Buffers an event to the internal buffer.
Can you generate a brief explanation for the following Python 3 code def _buffer(self, event: Message): if isinstance(event, BytesMessage): self._byte_buffer.write(event.data) elif isinstance(event, TextMessage): self._string_buffer.write(event.data)
You are a Python code generator, capable of creating scripts from specifications.
Gathers all the data from a buffer.
Can you tell what is the following Python 3 function doing def _gather_buffers(self, event: Message): if isinstance(event, BytesMessage): buf = self._byte_buffer else: buf = self._string_buffer # yay for code shortening buf.write(event.data) buf.seek(0) ...
You are a Python code analyst, evaluating scripts for potential improvements.
Wraps data into the right event.
Here you have a function in Python 3, explain what it does def _wrap_data(data: Union[str, bytes]): MsgType = TextMessage if isinstance(data, str) else BytesMessage return MsgType(data=data, frame_finished=True, message_finished=True)
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_field_SQL(self, field_name, field): """ returns the SQL for a given field with full type information http://www.sqlite.org/datatype3.html field_name -- string -- the field's name field -- Field() -- the set options for the field return -- string -- the field ty...
Write a Python 3 function that can return the SQL for a given field with full type information.
You are a Python code architect, reviewing and designing scalable and efficient code
Set the table in the database.
Make a summary of the following Python 3 code def _set_table(self, schema, **kwargs): query_str = [] query_str.append("CREATE TABLE {} (".format(self._normalize_table_name(schema))) query_fields = [] for field_name, field in schema.fields.items(): query_fields.append(' {}'....
As a Python code analyst, you investigate and solve complex coding mysteries
def _set_index(self, schema, name, fields, **index_options): """ https://www.sqlite.org/lang_createindex.html """ query_str = "CREATE {}INDEX IF NOT EXISTS '{}_{}' ON {} ({})".format( 'UNIQUE ' if index_options.get('unique', False) else '', schema, nam...
Can you create a Python 3 function that creates an index for the current record.
You are a Python code generator, capable of creating scripts from specifications.
return all the indexes for the given schema
Can you generate a brief explanation for the following Python 3 code def _get_indexes(self, schema, **kwargs): # http://www.sqlite.org/pragma.html#schema # http://www.mail-archive.com/sqlite-users@sqlite.org/msg22055.html # http://stackoverflow.com/questions/604939/ ret = {} rs =...
As a python code expert, you are capable of creating scripts from specifications.
def _get_fields(self, table_name, **kwargs): """return all the fields for the given table""" ret = {} query_str = 'PRAGMA table_info({})'.format(self._normalize_table_name(table_name)) fields = self._query(query_str, **kwargs) #pout.v([dict(d) for d in fields]) query_str...
Write a Python 3 function that can return all the fields for the given table
As a Python code analyst, you investigate and solve complex coding mysteries
allow extracting information from date http://www. sqlite. org / lang_datefunc. html
How would you explain what the following Python 3 function does def _normalize_date_SQL(self, field_name, field_kwargs, symbol): fstrs = [] k_opts = { 'day': "CAST(strftime('%d', {}) AS integer)", 'hour': "CAST(strftime('%H', {}) AS integer)", 'doy': "CAST(strftime('%...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function returns a SQL sort string and a list of query arguments.
Can you generate the documentation for the following Python 3 function def _normalize_sort_SQL(self, field_name, field_vals, sort_dir_str): fvi = None if sort_dir_str == 'ASC': fvi = (t for t in enumerate(field_vals)) else: fvi = (t for t in enumerate(reversed(field_val...
You are a Python code analyst, evaluating scripts for potential improvements.
def register(self, new_calc, *args, **kwargs): """ Register calculations and meta data. * ``dependencies`` - list of prerequisite calculations * ``always_calc`` - ``True`` if calculation ignores thresholds * ``frequency`` - frequency of calculation in intervals or units of time ...
Create a Python 3 function to register new calculations and meta data.
As a python code expert, you are capable of creating scripts from specifications.
Transform fiber traces to ds9 - region format.
Can you generate a brief explanation for the following Python 3 code def slits_to_ds9_reg(ds9reg, slits): # open output file and insert header ds9reg.write('# Region file format: DS9 version 4.1\n') ds9reg.write( 'global color=green dashlist=8 3 width=1 font="helvetica 10 ' 'normal roman" ...
As a python code expert, you are capable of creating scripts from specifications.
Makes an ID from the object s class name and the datetime now in ISO format.
Can you generate the documentation for the following Python 3 function def id_maker(obj): dtfmt = '%Y%m%d-%H%M%S' return '%s-%s' % (obj.__class__.__name__, datetime.now().strftime(dtfmt))
As a python code expert, you are capable of creating scripts from specifications.
register simulation and metadata.
Here you have a function in Python 3, explain what it does def register(self, sim, *args, **kwargs): kwargs.update(zip(self.meta_names, args)) # call super method, now meta can be passed as args or kwargs. super(SimRegistry, self).register(sim, **kwargs)
As a Python code analyst, you investigate and solve complex coding mysteries
def check_data(self, data): """ Check if data loaded for all sources in data layer. :param data: data layer from model :type data: :class:`~simkit.core.layer.Data` :return: dictionary of data sources and objects or `None` if not loaded """ data_objs = { ...
Write a Python 3 function for checking if data loaded for all sources in data layer.
As a python code expert, you are capable of creating scripts from specifications.
Initializes the simulation by dependency.
Make a summary of the following Python 3 code def initialize(self, calc_reg): self._isinitialized = True # TODO: if calculations are edited, loaded, added, etc. then reset self.calc_order = topological_sort(calc_reg.dependencies)
As a Python code analyst, you investigate and solve complex coding mysteries
Generator that returns the index of the items in the index.
Can you tell what is the following Python 3 function doing def index_iterator(self): idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 if new_idx: idx = new_idx - 1
You are a Python code generator, capable of creating scripts from specifications.
def start(self, model, progress_hook=None): """ Start the simulation from time zero. :param model: Model with layers and registries containing parameters :type: :class:`~simkit.core.models.Model` :param progress_hook: A function that receives either a string or a lis...
Can you write a function in Python 3 where it starts the simulation from time zero.
As a Python code analyst, you investigate and solve complex coding mysteries
def pause(self, progress_hook=None): """ Pause the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? ...
Can you create a Python 3 function that pauses the simulation. How is this different from stopping it? Maintain info sufficient to restart simulation. Sets ``is_paused`` to True. Will this state allow analysis? changing parameters? What can you do with a paused simulation? Should be capable of saving paused simulation ...
As a Python code analyst, you investigate and solve complex coding mysteries
def save_ds9(output, filename): """Save ds9 region output info filename. Parameters ---------- output : str String containing the full output to be exported as a ds9 region file. filename : str Output file name. """ ds9_file = open(filename, 'wt') ds9_file.writ...
Write a Python 3 function for saving ds9 region output info filename.
As a Python code composer, you craft elegant and concise scripts.
Save the 4 possible ds9 region files.
Can you tell what is the following Python 3 function doing def save_four_ds9(rectwv_coeff, debugplot=0): for limits, rectified, suffix in zip( ['frontiers', 'frontiers', 'boundaries', 'boundaries'], [False, True, False, True], ['rawimage', 'rectified', 'rawimage', 'rectified'] ): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a DS9 region file from a RectWaveCoeff instance.
Here you have a function in Python 3, explain what it does def rectwv_coeff_to_ds9(rectwv_coeff, limits=None, rectified=False, numpix=100): """Generate ds9 region output with requested slitlet limits Parameters ---------- rectwv_co...
As a Python code composer, you craft elegant and concise scripts.
def save_spectral_lines_ds9(rectwv_coeff, debugplot=0): """Save expected location of arc and OH airglow to ds9 region files. Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients for the particular CSU configuration. debugp...
Can you write a function in Python 3 where it saves expected location of arc OH airglow to ds9 region files.
You are a Python code architect, reviewing and designing scalable and efficient code
def spectral_lines_to_ds9(rectwv_coeff, spectral_lines=None, rectified=False): """Generate ds9 region output with requested spectral lines Parameters ---------- rectwv_coeff : RectWaveCoeff instance Rectification and wavelength calibration coefficients fo...
Can you create a Python 3 function that generates a ds9 region output with requested spectral lines.
You are a Python code architect, reviewing and designing scalable and efficient code
Dynamically create the provider info response from the capabilities
Can you tell what is the following Python 3 function doing def create_providerinfo(self, capabilities): _pinfo = self.package_capabilities() not_supported = {} for key, val in capabilities.items(): try: allowed = _pinfo[key] except KeyError: ...
As a python code expert, you are capable of creating scripts from specifications.
def _write_utf8(write, value): """Writes a length-prefixed UTF-8 string.""" write('h', len(value)) write.io.write(value.encode('utf-8'))
Implement a function in Python 3 to write a length - prefixed UTF - 8 string.
As a Python code composer, you craft elegant and concise scripts.
def read(cls, read, has_name=True): """ Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name. """ name = cls._read_utf8(read) if has_name else None if cls is TAG_Compound: # A TAG_Compound is almost identical to Python's ...
Write a Python 3 script to read the tag in using the reader rd.
As a Python code translator, you convert algorithms and pseudocode into Python.
Saves the NBTFile to io.
Make a summary of the following Python 3 code def save(self, io, little_endian=False): if little_endian: write = lambda fmt, *args: io.write(pack('<' + fmt, *args)) else: write = lambda fmt, *args: io.write(pack('>' + fmt, *args)) write.io = io self.write(write)
You are a Python code analyst, evaluating scripts for potential improvements.
def factory(ec, code=None, token=None, refresh=None, **kwargs): """ Create a token handler :param code: :param token: :param refresh: :return: TokenHandler instance """ TTYPE = {'code': 'A', 'token': 'T', 'refresh': 'R'} args = {} if code: args['code_handler'] = init_...
Write a Python 3 function for creating a token handler
As a Python code analyst, you investigate and solve complex coding mysteries
def key(self, user="", areq=None): """ Return a key (the session id) :param user: User id :param areq: The authorization request :return: An ID """ csum = hashlib.new('sha224') csum.update(rndstr(32).encode('utf-8')) return csum.hexdigest()
Write a Python 3 script for returning a key that can be used to access the session id.
You are a Python code architect, reviewing and designing scalable and efficient code
Return token information. :param token: A token :return: dictionary with info about the token
How would you explain what the following Python 3 function does def info(self, token): _res = dict(zip(['_id', 'type', 'sid', 'exp'], self.split_token(token))) if _res['type'] != self.type: raise WrongTokenType(_res['type']) else: _res['handler'] =...
You are a Python code analyst, evaluating scripts for potential improvements.
Processes element with a wildcard weight fraction and returns a balanced fraction.
Here you have a function in Python 3, explain what it does def process_wildcard(fractions): wildcard_zs = set() total_fraction = 0.0 for z, fraction in fractions.items(): if fraction == '?': wildcard_zs.add(z) else: total_fraction += fraction if not wildcard_zs: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def convert_mass_to_atomic_fractions(mass_fractions): """ Converts a mass fraction :class:`dict` to an atomic fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The composition is specified by a dictionary. The keys are atomic numbers and the v...
Write a Python 3 function for converting a mass fraction to an atomic fraction.
As a python code expert, you are capable of creating scripts from specifications.
Converts an atomic fraction to a mass fraction.
Here you have a function in Python 3, explain what it does def convert_atomic_to_mass_fractions(atomic_fractions): # Calculate total atomic mass atomic_masses = {} total_atomic_mass = 0.0 for z, atomic_fraction in atomic_fractions.items(): atomic_mass = pyxray.element_atomic_weight(z) at...
As a python code expert, you are capable of creating scripts from specifications.
Converts a chemical formula to an atomic fractions.
Can you generate the documentation for the following Python 3 function def convert_formula_to_atomic_fractions(formula): mole_fractions = {} total_mole_fraction = 0.0 for match in CHEMICAL_FORMULA_PATTERN.finditer(formula): symbol, mole_fraction = match.groups() z = pyxray.element_atomic_n...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates a name from the composition.
Explain what the following Python 3 code does def generate_name(atomic_fractions): if not atomic_fractions: return '' if len(atomic_fractions) == 1: z = list(atomic_fractions.keys())[0] return pyxray.element_symbol(z) symbols = [] fractions = [] for z in sorted(atomic_fract...
You are a Python code generator, capable of creating scripts from specifications.
def from_pure(cls, z): """ Creates a pure composition. Args: z (int): atomic number """ return cls(cls._key, {z: 1.0}, {z: 1.0}, pyxray.element_symbol(z))
Can you write a function in Python 3 where it creates a pure composition.
You are a Python code architect, reviewing and designing scalable and efficient code
def from_mass_fractions(cls, mass_fractions, formula=None): """ Creates a composition from a mass fraction :class:`dict`. Args: mass_fractions (dict): mass fraction :class:`dict`. The keys are atomic numbers and the values weight fractions. Wildcard a...
Implement a Python 3 function for creating a new composition from a mass fractions.
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a composition from an atomic fractions dictionary.
Explain what the following Python 3 code does def from_atomic_fractions(cls, atomic_fractions, formula=None): atomic_fractions = process_wildcard(atomic_fractions) mass_fractions = convert_atomic_to_mass_fractions(atomic_fractions) if not formula: formula = generate_name(atomic_fract...
You are a Python code analyst, evaluating scripts for potential improvements.
Collect the sample from the server.
Explain what the following Python 3 code does async def _collect_sample(self, url, url_pattern): samples = [] urls = [self.path_generator.generate_url(url, url_pattern) for _ in range(self.confirmation_factor)] iterator = asyncio.as_completed([self._fetch_sample(url) for url in urls]) ...
As a python code expert, you are capable of creating scripts from specifications.
Return the path part of the URL with the last element replaced with its pattern.
Explain what the following Python 3 code does def get_pattern(self, url): path = urlparse(url).path directories, filename = os.path.split(path) if len(filename) > 0: pattern = self.get_pattern_for_filename(filename) if directories[-1] != "/": directories +...
As a python code expert, you are capable of creating scripts from specifications.
def get_boundaries(bounddict_file, slitlet_number): """Read the bounddict json file and return the polynomial boundaries. Parameters ---------- bounddict_file : file handler File containing the bounddict JSON data. slitlet_number : int Number of slitlet. Returns ------- ...
Can you implement a function in Python 3 that reads the bounddict json file and return the polynomial boundaries.
You are a Python code generator, capable of creating scripts from specifications.
def _to_enos_roles(roles): """Transform the roles to use enoslib.host.Host hosts. Args: roles (dict): roles returned by :py:func:`enoslib.infra.provider.Provider.init` """ def to_host(h): extra = {} # create extra_vars for the nics # network_role = ethX ...
How would you code a function in Python 3 to transform the roles to use enoslib. host. Host hosts.
You are a Python code architect, reviewing and designing scalable and efficient code
Transform the networks returned by deploy5k. to enos.
Can you generate a brief explanation for the following Python 3 code def _to_enos_networks(networks): nets = [] for roles, network in networks: nets.append(network.to_enos(roles)) logger.debug(nets) return nets
You are a Python code generator, capable of creating scripts from specifications.
Reserve and deploys the nodes according to the resources section.
Explain what the following Python 3 code does def init(self, force_deploy=False, client=None): _force_deploy = self.provider_conf.force_deploy self.provider_conf.force_deploy = _force_deploy or force_deploy self._provider_conf = self.provider_conf.to_dict() r = api.Resources(self._provid...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _find_wikipedia_names(self, name_en): """ Finds all Wikipedia pages referring to the specified name in English and returns a dictionary where the keys are the language code and the values are the titles of the corresponding pages. """ url = 'https://en.wikipedia.org/w...
Create a Python 3 function for finding all Wikipedia pages referring to the specified name in English and return a dictionary where the keys are the language code and the values are the titles of the corresponding pages.
As a Python code composer, you craft elegant and concise scripts.
Append the response to the stack of responses.
Given the following Python 3 function, write the documentation def append_response(self, response): self._responses.append(response) if 'Warning' in response.headers: LOGGER.warning( 'HTTP %s %s Warning (%s): %s (attempt %s)', response.request.method, response...
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the HTTP response body deserialized if possible.
Can you tell what is the following Python 3 function doing def body(self): if not self._responses: return None if self._responses[-1].code >= 400: return self._error_message() return self._deserialize()
You are a Python code architect, reviewing and designing scalable and efficient code
def links(self): """Return the parsed link header if it was set, returning a list of the links as a dict. :rtype: list(dict()) or None """ if not self._responses: return None if 'Link' in self._responses[-1].headers: links = [] for l ...
Can you implement a function in Python 3 that returns the parsed link header if it was set returning a list of dicts.
You are a Python code generator, capable of creating scripts from specifications.
def _decode(self, value): """Decode bytes to UTF-8 strings as a singe value, list, or dict. :param mixed value: The value to decode :rtype: mixed """ if isinstance(value, list): return [self._decode(v) for v in value] elif isinstance(value, dict): ...
Can you create a Python 3 function that decodes bytes to UTF - 8 strings as a singe value list or dict.
As a python code expert, you are capable of creating scripts from specifications.
Try and deserialize a response body based upon the specified content type.
Explain what the following Python 3 code does def _deserialize(self): if not self._responses or not self._responses[-1].body: return None if 'Content-Type' not in self._responses[-1].headers: return self._responses[-1].body try: content_type = algorithms.selec...
You are a Python code generator, capable of creating scripts from specifications.
def _error_message(self): """Try and extract the error message from a HTTP error response. :rtype: str """ body = self._deserialize() return body.get('message', body) if isinstance(body, dict) else body
Implement a function in Python 3 to try and extract the error message from a HTTP error response.
You are a Python code architect, reviewing and designing scalable and efficient code
Perform a HTTP request.
How would you explain what the following Python 3 function does async def http_fetch(self, url, method='GET', request_headers=None, body=None, content_type=CONTENT_TYPE_MSGPACK, follow_redirects=...
As a Python code translator, you convert algorithms and pseudocode into Python.