output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Submit a coroutine as NewTask to self. loop without loop. frequencyuncy control.
Can you generate the documentation for the following Python 3 function def submit(self, coro, callback=None): callback = callback or self.default_callback if self.async_running: return self.run_coroutine_threadsafe(coro, callback=callback) else: return NewTask(coro, loop=...
As a python code expert, you are capable of creating scripts from specifications.
Return tasks in loop which its state is pending.
Given the following Python 3 function, write the documentation def todo_tasks(self): tasks = [task for task in self.all_tasks if task._state == NewTask._PENDING] return tasks
As a Python code composer, you craft elegant and concise scripts.
def done_tasks(self): """Return tasks in loop which its state is not pending.""" tasks = [task for task in self.all_tasks if task._state != NewTask._PENDING] return tasks
How would you code a function in Python 3 to return tasks in loop which its state is not pending.
As a Python code composer, you craft elegant and concise scripts.
def run(self, tasks=None, timeout=None): """Block, run loop until all tasks completed.""" timeout = self._timeout if timeout is None else timeout if self.async_running or self.loop.is_running(): return self.wait_all_tasks_done(timeout) else: tasks = tasks or self....
Create a Python 3 function for blocking run loop until all tasks completed.
As a python code expert, you are capable of creating scripts from specifications.
def wait_all_tasks_done(self, timeout=None, delay=0.5, interval=0.1): """Block, only be used while loop running in a single non-main thread.""" timeout = self._timeout if timeout is None else timeout timeout = timeout or float("inf") start_time = time.time() time.sleep(delay) ...
Create a Python 3 function to block until all tasks are done.
As a Python code translator, you convert algorithms and pseudocode into Python.
Used for await in coroutines.
Here you have a function in Python 3, explain what it does async def pendings(self, tasks=None): tasks = tasks or self.todo_tasks await asyncio.gather(*tasks, loop=self.loop)
You are a Python code architect, reviewing and designing scalable and efficient code
Ensure frequencies is dict of host - frequencies.
Can you tell what is the following Python 3 function doing def ensure_frequencies(self, frequencies): if not frequencies: return {} if not isinstance(frequencies, dict): raise ValueError("frequencies should be dict") frequencies = { host: Frequency.ensure_freq...
As a Python code composer, you craft elegant and concise scripts.
Set frequency for a given host with sem and interval.
Here you have a function in Python 3, explain what it does def set_frequency(self, host, sem=None, interval=None): # single sem or global sem sem = sem or self.sem interval = self.interval if interval is None else interval frequency = Frequency(sem, interval, host) frequencies = ...
You are a Python code generator, capable of creating scripts from specifications.
A decorator that initializes and refreshes the openstack connection.
Make a summary of the following Python 3 code def initialize_openstack(func): ''' Initialize and refresh openstack connection ''' async def wrap(self, *args, **kwargs): if not hasattr(self, 'auth') or not self.auth.is_token_valid(): self.auth = AuthPasswo...
As a Python code translator, you convert algorithms and pseudocode into Python.
Initialize static data like images and flavores and set it as object property
Here you have a function in Python 3, explain what it does async def initialize(self): ''' Initialize static data like images and flavores and set it as object property ''' flavors = await self._list_flavors() images = await self._list_images() self.flavors_map = bidict...
As a python code expert, you are capable of creating scripts from specifications.
Create VM with optional user data.
Here you have a function in Python 3, explain what it does async def create_vm(self, preset_name, image, flavor, security_groups=None, userdata=None, key_name=None, availability_zone=None, subnets=None): ''' Create VM :arg preset_name: string :arg image: strin...
As a Python code analyst, you investigate and solve complex coding mysteries
List VMs by preset name.
How would you explain what the following Python 3 function does async def list_vms(self, preset_name): ''' List VMs by preset name :arg present_name: string ''' response = await self.nova.servers.list(name=f'^{preset_name}$') result = [] for server in response['s...
As a Python code composer, you craft elegant and concise scripts.
async def terminate_vm(self, vm_id): ''' Terminate VM :arg vm_id: string ''' try: await self.nova.servers.force_delete(vm_id) except JSONDecodeError as exc: logging.info("nova sent 'content-type: application/json' but no content appeared, whateve...
Can you create a Python 3 function that terminates VM :arg vm_id: string
As a Python code translator, you convert algorithms and pseudocode into Python.
async def get_vm(self, vm_id): ''' Get VM :arg vm_id: string :returns vm: object ''' result = await self.nova.servers.get(vm_id) return self._map_vm_structure(result["server"])
How would you implement a function in Python 3 that gets VM :arg vm_id: string :returns vm: object
As a Python code translator, you convert algorithms and pseudocode into Python.
Map a vm structure to a new object.
Make a summary of the following Python 3 code def _map_vm_structure(self, vm): ''' Vm unification :arg vm: object :returns object ''' ip = self._extract_ips(vm['addresses']) created = datetime.strptime(vm['created'], '%Y-%m-%dT%H:%M:%SZ') flavor = self.fla...
As a python code expert, you are capable of creating scripts from specifications.
Map openstack status to vmshepherd status
Given the following Python 3 function, write the documentation def _map_vm_status(self, openstack_status, timed_shutdown_at=None): ''' Map openstack vm statuses to vmshepherd vm statuses openstack vm statuses: ACTIVE, BUILD, DELETED, ERROR, HARD_REBOOT, MIGRATING, PASSWORD, PAUSED, REBOOT, ...
You are a Python code generator, capable of creating scripts from specifications.
def _extract_ips(self, data): ''' Extract ip addressess from openstack structure { 'pl-krk-2-int-301-c2-int-1': [ { 'OS-EXT-IPS-MAC:mac_addr': 'fa:16:3e:29:f1:bb', 'version': 4, 'addr': '10.185.138.36', 'OS-EXT-IPS:type': '...
Can you create a Python 3 function that extracts ip addressess from openstack structure
As a python code expert, you are capable of creating scripts from specifications.
def _set_label_text(obj, text, tooltip=None, replace_all=False): """ Keep text before first colon and replace the rest with new text. If there is no colon in the :param obj: :param text: :param tooltip: :param replace_all: No colon is searched and whole text is replaced :return: """...
Can you implement a function in Python 3 that sets the text of the object to the given text.
As a Python code analyst, you investigate and solve complex coding mysteries
def __get_datafile(self, app=False): """ Draw a dialog for directory selection. """ if self.cache is not None: cache_loadfiledir = self.cache.get_or_none('loadfiledir') self.loadfiledir = str(cache_loadfiledir) if self.loadfiledir is None: se...
How would you code a function in Python 3 to draw a dialog for directory selection.
As a python code expert, you are capable of creating scripts from specifications.
def __get_datadir(self, app=False): """ Draw a dialog for directory selection. """ # if 'datadir' in self.oseg.cache.data.keys(): # if : # directory = self.oseg.input_datapath_start if self.cache is not None: cache_loaddir = self.cache.get_or_none(...
Write a Python 3 function for drawing a dialog for directory selection.
You are a Python code analyst, evaluating scripts for potential improvements.
Function is called in the end of process
Can you generate a brief explanation for the following Python 3 code def read_data_from_prepared_datapath(self): reader = datareader.DataReader() self.datap = reader.Get3DData(self.datapath, dataplus_format=True, gui=True, qt_app=self.qt_app) _set_label_text(self.text_dcm_dir, _make_text_shor...
As a python code expert, you are capable of creating scripts from specifications.
Generates the wrapper class.
Can you generate the documentation for the following Python 3 function def __generate_wrapper_class(self): routines = self._read_routine_metadata() self._write_class_header() if routines: for routine_name in sorted(routines): if routines[routine_name]['designation']...
As a python code expert, you are capable of creating scripts from specifications.
Reads the configuration file and sets the attributes of the current object.
Here you have a function in Python 3, explain what it does def _read_configuration_file(self, config_filename): config = configparser.ConfigParser() config.read(config_filename) self._parent_class_name = config.get('wrapper', 'parent_class') self._parent_class_namespace = config.get('wr...
As a Python code composer, you craft elegant and concise scripts.
Reads the metadata of stored routines.
Can you tell what is the following Python 3 function doing def _read_routine_metadata(self): metadata = {} if os.path.isfile(self._metadata_filename): with open(self._metadata_filename, 'r') as file: metadata = json.load(file) return metadata
As a Python code analyst, you investigate and solve complex coding mysteries
Generates a class header for the stored routine wrapper.
Explain what the following Python 3 code does def _write_class_header(self): self._write_line('from {0!s} import {1!s}'.format(self._parent_class_namespace, self._parent_class_name)) self._write_line() self._write_line() self._write_line('# ' + ('-' * 118)) self._write_line('clas...
As a Python code translator, you convert algorithms and pseudocode into Python.
def _write_line(self, text=''): """ Writes a line with Python code to the generate code buffer. :param str text: The line with Python code. """ if text: self._code += str(text) + "\n" else: self._code += "\n"
Write a Python 3 script to write a line with Python code to the generate code buffer.
You are a Python code analyst, evaluating scripts for potential improvements.
def get_results_generator(future_list, timeout=None, sort_by_completed=False): """Return as a generator of tasks order by completed sequence.""" try: # python2 not support yield from if sort_by_completed: for future in as_completed(future_list, timeout=timeout): yield...
Can you create a Python 3 function that returns as a generator of tasks order by completed sequence.
You are a Python code generator, capable of creating scripts from specifications.
Run the function after seconds asynchronously.
Given the following Python 3 function, write the documentation def run_after_async(seconds, func, *args, **kwargs): t = Timer(seconds, func, args, kwargs) t.daemon = True t.start() return t
As a Python code translator, you convert algorithms and pseudocode into Python.
Decorator for let a normal function return the NewFuture
Can you generate a brief explanation for the following Python 3 code def async_func(self, function): @wraps(function) def wrapped(*args, **kwargs): return self.submit(function, *args, **kwargs) return wrapped
As a Python code composer, you craft elegant and concise scripts.
def _get_cpu_count(self): """Get the cpu count.""" try: from multiprocessing import cpu_count return cpu_count() except Exception as e: Config.main_logger.error("_get_cpu_count failed for %s" % e)
Create a Python 3 function to get the cpu count.
You are a Python code analyst, evaluating scripts for potential improvements.
def submit(self, func, *args, **kwargs): """Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`""" with self._shutdown_lock: if self._shutdown: raise RuntimeError("cannot schedule new futures after shutdown") callback = kwargs.pop("callback", ...
Write a Python 3 script for submitting a function to the pool.
As a Python code translator, you convert algorithms and pseudocode into Python.
def submit(self, func, *args, **kwargs): """Submit a function to the pool, `self.submit(function,arg1,arg2,arg3=3)`""" with self._shutdown_lock: if PY3 and self._broken: raise BrokenProcessPool( "A child process terminated " "abruptly,...
Implement a function in Python 3 to submit a function to the pool.
You are a Python code architect, reviewing and designing scalable and efficient code
def _invoke_callbacks(self): """Record the task_end_time & task_cost_time, set result for self._callback_result.""" self.task_end_time = time.time() self.task_cost_time = self.task_end_time - self.task_start_time with self._condition: for callback in self._done_callbacks: ...
Implement a function in Python 3 to invoke all the callbacks that have been set for this instance.
You are a Python code generator, capable of creating scripts from specifications.
def callback_result(self): """Block the main thead until future finish, return the future.callback_result.""" if self._state in [PENDING, RUNNING]: self.x if self._user_callbacks: return self._callback_result else: return self.x
Implement a Python 3 function for blocking the main thead until the future finish return the future. callback_result.
As a python code expert, you are capable of creating scripts from specifications.
def x(self): """Block the main thead until future finish, return the future.result().""" with self._condition: result = None if not self.done(): self._condition.wait(self._timeout) if not self.done(): # timeout self.set_...
Can you implement a function in Python 3 that blocks the main thead until the future finish return the future. result method.
As a Python code analyst, you investigate and solve complex coding mysteries
def close(self, wait=False): """Close session, shutdown pool.""" self.session.close() self.pool.shutdown(wait=wait)
Write a Python 3 function that can close session shutdown pool.
As a Python code analyst, you investigate and solve complex coding mysteries
Similar to requests. request but return as NewFuture.
How would you explain what the following Python 3 function does def request(self, method, url, callback=None, retry=0, **kwargs): return self.pool.submit( self._request, method=method, url=url, retry=retry, callback=callback or self.default_callback, ...
You are a Python code architect, reviewing and designing scalable and efficient code
Similar to requests. get but return as NewFuture.
Can you generate the documentation for the following Python 3 function def get(self, url, params=None, callback=None, retry=0, **kwargs): kwargs.setdefault("allow_redirects", True) return self.request( "get", url=url, params=params, callback=callback, retry=retry, **kwargs )
As a Python code translator, you convert algorithms and pseudocode into Python.
Similar to requests. post but return as NewFuture.
Here you have a function in Python 3, explain what it does def post(self, url, data=None, json=None, callback=None, retry=0, **kwargs): return self.request( "post", url=url, data=data, json=json, callback=callback, retry=retry, ...
You are a Python code generator, capable of creating scripts from specifications.
Execute GetInfo action to get basic WAN link information s.
Explain what the following Python 3 code does def getLinkInfo(self, wanInterfaceId=1, timeout=1): namespace = Wan.getServiceType("getLinkInfo") + str(wanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetInfo", timeout=timeout) return WanLinkInf...
As a Python code translator, you convert algorithms and pseudocode into Python.
Execute GetCommonLinkProperties action to get WAN link properties.
Can you generate the documentation for the following Python 3 function def getLinkProperties(self, wanInterfaceId=1, timeout=1): namespace = Wan.getServiceType("getLinkProperties") + str(wanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetCommonLinkPro...
You are a Python code architect, reviewing and designing scalable and efficient code
def getADSLInfo(self, wanInterfaceId=1, timeout=1): """Execute GetInfo action to get basic ADSL information's. :param int wanInterfaceId: the id of the WAN device :param float timeout: the timeout to wait for the action to be executed :return: ADSL informations. :rtype: ADSLInfo...
Write a Python 3 function for executing GetInfo action to get basic ADSL information s.
As a python code expert, you are capable of creating scripts from specifications.
Execute GetEthernetLinkStatus action to get the status of the ethernet link.
Can you tell what is the following Python 3 function doing def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1): namespace = Wan.getServiceType("getEthernetLinkStatus") + str(wanInterfaceId) uri = self.getControlURL(namespace) results = self.execute(uri, namespace, "GetEthernetLinkStatu...
You are a Python code analyst, evaluating scripts for potential improvements.
def getByteStatistic(self, wanInterfaceId=1, timeout=1): """Execute GetTotalBytesSent&GetTotalBytesReceived actions to get WAN statistics. :param int wanInterfaceId: the id of the WAN device :param float timeout: the timeout to wait for the action to be executed :return: a tuple of two ...
Write a Python 3 script to execute GetTotalBytesSent & GetTotalBytesReceived actions to get WAN statistics.
As a Python code composer, you craft elegant and concise scripts.
def getConnectionInfo(self, wanInterfaceId=1, timeout=1): """Execute GetInfo action to get WAN connection information's. :param int wanInterfaceId: the id of the WAN device :param float timeout: the timeout to wait for the action to be executed :return: WAN connection information's. ...
Write a Python 3 script for executing GetInfo action to get WAN connection information s.
As a python code expert, you are capable of creating scripts from specifications.
Set enable status for a WAN interface.
How would you explain what the following Python 3 function does def setEnable(self, status, wanInterfaceId=1, timeout=1): namespace = Wan.getServiceType("setEnable") + str(wanInterfaceId) uri = self.getControlURL(namespace) if status: setStatus = 1 else: setStatu...
You are a Python code generator, capable of creating scripts from specifications.
def requestConnection(self, wanInterfaceId=1, timeout=1): """Request the connection to be established :param int wanInterfaceId: the id of the WAN interface :param float timeout: the timeout to wait for the action to be executed """ namespace = Wan.getServiceType("requestConnect...
Implement a Python 3 function for requesting the connection to be established
You are a Python code architect, reviewing and designing scalable and efficient code
def write_config(filename, config, mode="w"): '''use configparser to write a config object to filename ''' with open(filename, mode) as filey: config.write(filey) return filename
Can you implement a function in Python 3 that writes a config object to filename
As a Python code analyst, you investigate and solve complex coding mysteries
generate a temporary file in base directory with a particular extension
Can you generate a brief explanation for the following Python 3 code def generate_temporary_file(folder='/tmp', prefix='helpme', ext='json'): '''write a temporary file, in base directory with a particular extension. Parameters ========== folder: the base directory to write in. pr...
You are a Python code architect, reviewing and designing scalable and efficient code
def copyfile(source, destination, force=True): '''copy a file from a source to its destination. ''' if os.path.exists(destination) and force is True: os.remove(destination) shutil.copyfile(source, destination) return destination
Implement a function in Python 3 to copy a file from a source to its destination.
As a Python code translator, you convert algorithms and pseudocode into Python.
def full_inventory(self): """ Returns a full inventory Some additional work required to provide consistent and consumable output. Inventory output only contains values, no keys - Add the keys to the output so that it can be consumed more easily. """ if sel...
Can you create a Python 3 function that returns a full inventory with all the keys and values
As a Python code composer, you craft elegant and concise scripts.
def self_inventory(self): """ Inventory output will only contain the server name and the session ID when a key is provided. Provide the same format as with the full inventory instead for consistency. """ if self.api_key is None: return {} if self._sel...
Write a Python 3 script to get the self - inventory for the current API key.
As a Python code analyst, you investigate and solve complex coding mysteries
def _ssid_inventory(self, inventory, ssid): """ Filters an inventory to only return servers matching ssid """ matching_hosts = {} for host in inventory: if inventory[host]['comment'] == ssid: matching_hosts[host] = inventory[host] return match...
Can you implement a function in Python 3 that filters an inventory to only return servers matching ssid
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a node inventory.
Can you tell what is the following Python 3 function doing def inventory(self, all=False, ssid=None): if all or self.api_key is None: if ssid is not None: return self._ssid_inventory(self.full_inventory, ssid) else: return self.full_inventory else:...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the hosts and ssid of the nodes with the provided parameters.
Given the following Python 3 function, write the documentation def node_get(self, arch=None, ver=None, flavor=None, count=1, retry_count=1, retry_interval=10): """ Requests specified number of nodes with the provided parameters. :param arch: Server architecture (ex: x86_64) ...
As a python code expert, you are capable of creating scripts from specifications.
def node_done(self, ssid=None): """ Release the servers for the specified ssid. The API doesn't provide any kind of output, try to be helpful by providing the list of servers to be released. :param ssid: ssid of the server pool :return: [ requested_hosts ] """ ...
Create a Python 3 function for releasing the servers for the specified ssid.
As a Python code translator, you convert algorithms and pseudocode into Python.
def update_redis(project: str, environment: str, feature: str, state: str) \ -> None: """ Update redis state for a feature flag. :param project: LaunchDarkly project key. :param environment: LaunchDarkly environment key. :param feature: LaunchDarkly feature key. :param state: State for ...
Can you create a Python 3 function that updates Redis state for a feature flag.
You are a Python code architect, reviewing and designing scalable and efficient code
def update_ld_api(project: str, environment: str, feature: str, state: str): """ Execute command against the LaunchDarkly API. This command is generally not used directly, instead it is called as a part of running the ``playback()`` function. :param project: LaunchDarkly project key. :param en...
How would you implement a function in Python 3 that executes command against the LaunchDarkly API.
You are a Python code analyst, evaluating scripts for potential improvements.
def generate_relay_config(project): """ Generate Relay Proxy Configuration. Generate a ld-relay.conf file to quickly spin up a relay proxy. Right now this is mostly used for integration testing. :param project: LaunchDarkly project key """ ld_api = LaunchDarklyApi( os.environ.get('...
How would you implement a function in Python 3 that generates Relay Proxy Configuration.
As a Python code analyst, you investigate and solve complex coding mysteries
Get information about series in dir
Make a summary of the following Python 3 code def dicomdir_info(dirpath, *args, **kwargs): dr = DicomReader(dirpath=dirpath, *args, **kwargs) info = dr.dicomdirectory.get_stats_of_series_in_dir() return info
You are a Python code generator, capable of creating scripts from specifications.
Check if in dir is one or more dicom files.
Can you generate a brief explanation for the following Python 3 code def is_dicom_dir(datapath): # Second tries open files # with dicom module. retval = False datapath = op.expanduser(datapath) for f in os.listdir(datapath): if f.endswith((".dcm", ".DCM")): retval = True ...
As a Python code analyst, you investigate and solve complex coding mysteries
def files_in_dir(dirpath, wildcard="*", startpath=None): """ Function generates list of files from specific dir files_in_dir(dirpath, wildcard="*.*", startpath=None) dirpath: required directory wilcard: mask for files startpath: start for relative path Example files_in_dir('medical/ja...
Can you write a function in Python 3 where it functions generates list of files from specific directory
You are a Python code generator, capable of creating scripts from specifications.
get location of the slice in a single object
Can you generate the documentation for the following Python 3 function def get_slice_location(dcmdata, teil=None): slice_location = None if hasattr(dcmdata, 'SliceLocation'): # print(dcmdata.SliceLocation) # print(type(dcmdata.SliceLocation)) try: slice_location = float(dcmda...
You are a Python code generator, capable of creating scripts from specifications.
def attr_to_dict(obj, attr, dct): """ Add attribute to dict if it exists. :param dct: :param obj: object :param attr: object attribute name :return: dict """ if hasattr(obj, attr): dct[attr] = getattr(obj, attr) return dct
Write a Python 3 function for adding attribute to dict if it exists.
You are a Python code analyst, evaluating scripts for potential improvements.
Select the series number that is used for liver.
Can you generate a brief explanation for the following Python 3 code def get_series_number_by_guess_for_liver(dcmreader, counts, bins, qt_app=None): series_info = dcmreader.dicomdirectory.get_stats_of_series_in_dir() print(dcmreader.print_series_info(series_info)) import pandas as pd df = pd.DataFrame(l...
You are a Python code generator, capable of creating scripts from specifications.
def get_overlay(self): """ Function make 3D data from dicom file slices. There are usualy more overlays in the data. """ overlay = {} dcmlist = self.files_in_serie for i in range(len(dcmlist)): onefile = dcmlist[i] logger.info("reading '%s...
How would you implement a function in Python 3 that functions make 3D data from dicom file slices.
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_3Ddata(self, start=0, stop=None, step=1): """ Function make 3D data from dicom file slices """ data3d = [] dcmlist = self.files_in_serie # print('stsp ', start, stop, step) # raw_max = None # raw_min = None # slope = None # inter =...
Can you implement a function in Python 3 that functions make 3D data from dicom files
You are a Python code architect, reviewing and designing scalable and efficient code
Read DICOMDIR crate if necessary.
How would you explain what the following Python 3 function does def get_standard_dicomdir_info(self): dicomdir_filepath = os.path.join(self.dirpath, self.standard_dicomdir_filename) if not os.path.exists(dicomdir_filepath): self.create_standard_dicomdir() return self.read_standard_di...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return series metadata. Output condatin information about voxelsize_mm, series_number and modality. If it is possible, the ImageComment, AcquisitionDate and few other dicom tags are also in output dict. :param series_number: :return: metadata dict with voxelsize_mm, SeriesNumber and othe...
Make a summary of the following Python 3 code def get_metadata_new(self, series_number): # TODO implement simplier metadata function # automatic test is prepared files, files_with_info = self.get_sorted_series_files(series_number=series_number, return_files_with_info=True) metadata = { ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_metaData(self, dcmlist, series_number): """ Get metadata. Voxel size is obtained from PixelSpacing and difference of SliceLocation of two neighboorhoding slices (first have index ifile). Files in are used. """ # if dcmlist is None: # dcmlist = ...
Write a Python 3 script for getting metadata for a neighboorhoding slice.
As a Python code composer, you craft elegant and concise scripts.
get series staticstics from dicomdir
Explain what the following Python 3 code does def get_stats_of_series_in_dir(self, study_id=None): if study_id is not None: logger.error("study_id tag is not implemented yet") return import numpy as np dcmdir = self.files_with_info # get series number # vy...
As a Python code translator, you convert algorithms and pseudocode into Python.
Print series_info from dcmdirstats
Explain what the following Python 3 code does def print_series_info(self, series_info, minimal_series_number=1): strinfo = '' if len(series_info) > minimal_series_number: for serie_number in series_info.keys(): strl = get_one_serie_info(series_info, serie_number) ...
You are a Python code analyst, evaluating scripts for potential improvements.
def __prepare_info_from_dicomdir_file(self, writedicomdirfile=True): """ Check if exists dicomdir file and load it or cerate it dcmdir = get_dir(dirpath) dcmdir: list with filenames, SeriesNumber and SliceLocation """ createdcmdir = True dicomdirfile = os.path....
Write a Python 3 script to prepare info from dicomdir file
As a Python code composer, you craft elegant and concise scripts.
return list of series names and counts of all files in dirpath
Explain what the following Python 3 code does def series_in_dir(self): # none_count = 0 countsd = {} # dcmdirseries = [] for line in self.files_with_info: if "SeriesNumber" in line: sn = line['SeriesNumber'] else: sn = None ...
You are a Python code architect, reviewing and designing scalable and efficient code
Function returns sorted list of dicom files.
How would you explain what the following Python 3 function does def get_sorted_series_files(self, startpath="", series_number=None, return_files_with_info=False, sort_keys="SliceLocation", return_files=True, remove_doubled_slice_locations=True): """ Function returns sorte...
You are a Python code generator, capable of creating scripts from specifications.
Function crates list of all files in dicom dir with all IDs
Make a summary of the following Python 3 code def _create_dicomdir_info(self): filelist = files_in_dir(self.dirpath) files = [] metadataline = {} for filepath in filelist: head, teil = os.path.split(filepath) dcmdata = None if os.path.isdir(filepath)...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_one(seq, default=None, skip_string_iter=True): """ Return one item from seq or None(by default). """ if skip_string_iter and isinstance(seq, (str, unicode, bytes, bytearray)): return seq if not seq: return '' try: return next(iter(seq)) except TypeError: ...
How would you code a function in Python 3 to return one item from seq or None by default.
You are a Python code architect, reviewing and designing scalable and efficient code
def ensure_list(obj): """ null obj -> return []; str, unicode, bytes, bytearray -> [obj]; else -> list(obj) """ if not obj: return [] elif isinstance(obj, (str, unicode, bytes, bytearray)): return [obj] elif hasattr(obj, '__iter_...
Implement a Python 3 function for ensuring that the object is a list of the available cache entries.
As a Python code analyst, you investigate and solve complex coding mysteries
def python_parser(self, obj, *args): """operate a python obj""" attr, args = args[0], args[1:] item = getattr(obj, attr) if callable(item): item = item(*args) return [item]
Can you create a Python 3 function that operates a python obj
As a python code expert, you are capable of creating scripts from specifications.
parse a single HTML code into a list of items
Here you have a function in Python 3, explain what it does def html_parser(self, scode, *args): allow_method = ('text', 'html', 'xml') css_path, method = args assert method in allow_method or method.startswith( '@'), 'method allow: %s or @attr' % allow_method result = self.en...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse the XML code.
Here you have a function in Python 3, explain what it does def xml_parser(self, scode, *args): allow_method = ('text', 'html', 'xml') xpath_string, method = args assert method in allow_method, 'method allow: %s' % allow_method result = self.ensure_list( self._fromstring(scode...
You are a Python code architect, reviewing and designing scalable and efficient code
def parse(self, scode, args_chain=None, join_with=None, default=''): """ single arg: [one_to_many, parser_name, *args] args_chain: [['1-n', 're', 'search', '(<.*?>)', '\\1']] [['1-n', 'html', 'p', 'html'], ['n-n', 'html', 'p', 'text']] """ ass...
Write a Python 3 function for parsing the scode and return a list of objects.
You are a Python code architect, reviewing and designing scalable and efficient code
Parses the CSS contents and returns the cleaned CSS as a string
Can you tell what is the following Python 3 function doing def parse(self): # Build the HTML tree self.tree = self._build_tree(self.html_contents) # Parse the CSS contents self.stylesheet = self.parser.parse_stylesheet(self.css_contents) # Get the cleaned CSS contents s...
You are a Python code architect, reviewing and designing scalable and efficient code
Converts relative links from css contents to absolute links .
Can you generate the documentation for the following Python 3 function def rel_to_abs(self, base_url): self.cleaned_css = self.rel_to_abs_re.sub( lambda match: "url('%s')" % urljoin( base_url, match.group('path').strip('\'"')), self.cleaned_css)
As a python code expert, you are capable of creating scripts from specifications.
def _clean_css(self): """ Returns the cleaned CSS :param stylesheet: The Stylesheet object to parse :type stylesheet: tinycss.css21.Stylesheet """ # Init the cleaned CSS rules and contents string css_rules = [] # For every rule in the CSS for rul...
How would you code a function in Python 3 to clean the CSS rules and contents of the tree and return the cleaned CSS
As a Python code analyst, you investigate and solve complex coding mysteries
Returns True if the token list matches the HTML tree
Here you have a function in Python 3, explain what it does def _token_list_matches_tree(self, token_list): try: parsed_selector = cssselect.parse( ''.join(token.as_css() for token in token_list))[0] return bool( self.tree.xpath( self.x...
As a Python code analyst, you investigate and solve complex coding mysteries
def _rule_as_string(self, rule): """ Converts a tinycss rule to a formatted CSS string :param rule: The rule to format :type rule: tinycss Rule object :returns: The Rule as a CSS string :rtype: str """ if isinstance(rule, RuleSet): # Simple CS...
How would you implement a function in Python 3 that converts a tinycss rule to a formatted CSS string
You are a Python code generator, capable of creating scripts from specifications.
def _selector_as_string(self, selector): """ Returns a selector as a CSS string :param selector: A list of tinycss Tokens :type selector: list :returns: The CSS string for the selector :rtype: str """ return ','.join( ''.join(token.as_css() fo...
Create a Python 3 function to return a selector as a CSS string for the selector
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a list of declarations as a formatted CSS string for the keys in the list.
Can you tell what is the following Python 3 function doing def _declarations_as_string(self, declarations): return ''.join('%s:%s%s;' % ( d.name, d.value.as_css(), ' !' + d.priority if d.priority else '') for d in declarations)
You are a Python code analyst, evaluating scripts for potential improvements.
def envars_to_markdown(envars, title = "Environment"): '''generate a markdown list of a list of environment variable tuples Parameters ========== title: A title for the section (defaults to "Environment" envars: a list of tuples for the environment, e.g.: [('TERM', 'xterm-2...
Create a Python 3 function to generate a markdown list of a list of environment variables
As a python code expert, you are capable of creating scripts from specifications.
Create a new server.
Here you have a function in Python 3, explain what it does async def create_vm(self, preset_name: str, image: str, flavor: str, security_groups: List=None, userdata: Dict=None, key_name: str=None, availability_zone: str=None, subnets: List=None) -> Any: """ ...
As a Python code composer, you craft elegant and concise scripts.
Returns the default commands of this application.
Can you generate a brief explanation for the following Python 3 code def get_default_commands(self): commands = Application.get_default_commands(self) self.add(ConstantsCommand()) self.add(LoaderCommand()) self.add(PyStratumCommand()) self.add(WrapperCommand()) return c...
You are a Python code architect, reviewing and designing scalable and efficient code
Discover UPnP devices in the local network.
Make a summary of the following Python 3 code def discover(service="ssdp:all", timeout=1, retries=2, ipAddress="239.255.255.250", port=1900): socket.setdefaulttimeout(timeout) messages = [] if isinstance(service, str): services = [service] elif isinstance(service, list): ...
You are a Python code architect, reviewing and designing scalable and efficient code
Discover a particular host and find the most specific response.
Can you tell what is the following Python 3 function doing def discoverParticularHost(host, service="ssdp:all", deviceDefinitionURL=None, timeout=1, retries=2, ipAddress="239.255.255.250", port=1900, proxies=None): """Discover a particular host and find the best response. ...
You are a Python code generator, capable of creating scripts from specifications.
def rateServiceTypeInResult(discoveryResponse): """Gives a quality rating for a given service type in a result, higher is better. Several UpnP devices reply to a discovery request with multiple responses with different service type announcements. To find the most specific one we need to be able...
Write a Python 3 function for rating the service type in a result.
You are a Python code architect, reviewing and designing scalable and efficient code
def download(self, url, file_name, headers=None, show_progress=True): '''stream to a temporary file, rename on successful completion Parameters ========== file_name: the file name to stream to url: the url to stream from ...
How would you implement a function in Python 3 that downloads the image from the url and return the name of the downloaded file
As a Python code translator, you convert algorithms and pseudocode into Python.
def stream_response(self, response, stream_to=None): ''' stream response is one level higher up than stream, starting with a response object and then performing the stream without making the requests.get. The expectation is that the request was successful (status code 20*). Par...
How would you code a function in Python 3 to stream the response to a file.
As a Python code composer, you craft elegant and concise scripts.
def getSCDPURL(self, serviceType, default=None): """Returns the SCDP (Service Control Protocol Document) URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace th...
Can you write a function in Python 3 where it returns the SCDP URL for a given service type and namespace. If no SCDP URL is given the default value is returned.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the control URL for a given service type and namespace.
Make a summary of the following Python 3 code def getControlURL(self, serviceType, default=None): if serviceType in self.__deviceServiceDefinitions.keys(): return self.__deviceServiceDefinitions[serviceType]["controlURL"] # check if definitions have been loaded, then dont return the default...
As a Python code translator, you convert algorithms and pseudocode into Python.
def getEventSubURL(self, serviceType, default=None): """Returns the event URL for a given service type. When the device definitions have been loaded with :meth:`~simpletr64.DeviceTR64.loadDeviceDefinitions` this method returns for a given service type/namespace the associated event URL. If the ...
Can you create a Python 3 function that returns the event URL for a given service type and namespace. If no event URL is given the associated event URL is returned. If no event URL is given the associated event URL is returned.
As a python code expert, you are capable of creating scripts from specifications.