output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def create_back_links(env): """ Create back-links in all found needs. But do this only once, as all needs are already collected and this sorting is for all needs and not only for the ones of the current document. :param env: sphinx enviroment :return: None """ if env.needs_workflow['bac...
Can you create a Python 3 function that creates back - links in all found needs.
You are a Python code generator, capable of creating scripts from specifications.
Constructs the node - structure for the headline container.
Given the following Python 3 function, write the documentation def construct_headline(need_data, app): # need title calculation title_type = '{}: '.format(need_data["type_name"]) title_headline = need_data["title"] title_id = "{}".format(need_data["id"]) title_spacer = " " # need title node...
As a Python code analyst, you investigate and solve complex coding mysteries
Constructs the node - structure for the status container
Make a summary of the following Python 3 code def construct_meta(need_data, env): hide_options = env.config.needs_hide_options if not isinstance(hide_options, list): raise SphinxError('Config parameter needs_hide_options must be of type list') node_meta = nodes.line_block(classes=['needs_meta']) ...
As a Python code translator, you convert algorithms and pseudocode into Python.
This function fixes the list of dynamic function fragments in a list.
Here you have a function in Python 3, explain what it does def _fix_list_dyn_func(list): open_func_string = False new_list = [] for element in list: if '[[' in element: open_func_string = True new_link = [element] elif ']]' in element: new_link.append(elem...
As a Python code analyst, you investigate and solve complex coding mysteries
Add any extra options introduced via options_ext to needs_info
Can you generate the documentation for the following Python 3 function def merge_extra_options(self, needs_info): extra_keys = set(self.options.keys()).difference(set(needs_info.keys())) for key in extra_keys: needs_info[key] = self.options[key] # Finally add all not used extra opti...
As a Python code composer, you craft elegant and concise scripts.
def merge_global_options(self, needs_info): """Add all global defined options to needs_info""" global_options = getattr(self.env.app.config, 'needs_global_options', None) if global_options is None: return for key, value in global_options.items(): # If key already...
Create a Python 3 function to add all global options to needs_info
As a Python code translator, you convert algorithms and pseudocode into Python.
Determines the full title for the need in order of precedence.
Make a summary of the following Python 3 code def _get_full_title(self): if len(self.arguments) > 0: # a title was passed if 'title_from_content' in self.options: self.log.warning( 'Needs: need "{}" has :title_from_content: set, ' 'but a title...
As a python code expert, you are capable of creating scripts from specifications.
def process_needlist(app, doctree, fromdocname): """ Replace all needlist nodes with a list of the collected needs. Augment each need with a backlink to the original location. """ env = app.builder.env for node in doctree.traverse(Needlist): if not app.config.needs_include_needs: ...
Implement a Python 3 function for processing all needlists in the doctree.
As a Python code analyst, you investigate and solve complex coding mysteries
def parse_version(version: str) -> tuple: """Parse a string formatted X[.Y.Z] version number into a tuple >>> parse_version('10.2.3') (10, 2, 3) >>> parse_version('12') (12, 0, 0) """ if not version: return None parts = version.split('.') missing = 3 - len(parts) return...
Write a Python 3 function that can parse a string formatted X. Y. Z version number into a tuple of integers.
As a Python code analyst, you investigate and solve complex coding mysteries
Parse a tablename into a tuple of schema and table name.
Can you generate the documentation for the following Python 3 function def parse_table(fq_table: str) -> Tuple[str, str]: parts = fq_table.split('.') if len(parts) == 1: return 'doc', parts[0] elif len(parts) == 2: return parts[0], parts[1] else: raise ValueError
As a Python code translator, you convert algorithms and pseudocode into Python.
Yields a list of tuples grouped by stmt into a list of args grouped by stmt.
Can you generate a brief explanation for the following Python 3 code def as_bulk_queries(queries, bulk_size): stmt_dict = defaultdict(list) for stmt, args in queries: bulk_args = stmt_dict[stmt] bulk_args.append(args) if len(bulk_args) == bulk_size: yield stmt, bulk_args ...
As a python code expert, you are capable of creating scripts from specifications.
Create an iterator that returns the lines of a utf - 8 encoded file.
Can you tell what is the following Python 3 function doing def get_lines(filename: str) -> Iterator[str]: if filename.endswith('.gz'): with gzip.open(filename, 'r') as f: for line in f: yield line.decode('utf-8') else: with open(filename, 'r', encoding='utf-8') as f: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Create an iterator that transforms lines into sql statements.
Here you have a function in Python 3, explain what it does def as_statements(lines: Iterator[str]) -> Iterator[str]: lines = (l.strip() for l in lines if l) lines = (l for l in lines if l and not l.startswith('--')) parts = [] for line in lines: parts.append(line.rstrip(';')) if line.end...
As a Python code analyst, you investigate and solve complex coding mysteries
Break an iterable on the item that matches the predicate into lists.
Make a summary of the following Python 3 code def break_iterable(iterable, pred): sublist = [] for i in iterable: if pred(i): yield sublist sublist = [] else: sublist.append(i) yield sublist
As a Python code translator, you convert algorithms and pseudocode into Python.
def create_bag(dir_bag): """ Create a Bag out of given files. :param str dir_bag: Directory that contains csv, jsonld, and changelog files. :return obj: Bag """ logger_bagit.info("enter create_bag") # if not dir_bag: # dir_bag = os.getcwd() try: bag = bagit.make_bag(dir_b...
Implement a Python 3 function for creating a Bag out of a directory.
You are a Python code analyst, evaluating scripts for potential improvements.
def open_bag(dir_bag): """ Open Bag at the given path :param str dir_bag: Path to Bag :return obj: Bag """ logger_bagit.info("enter open_bag") try: bag = bagit.Bag(dir_bag) logger_bagit.info("opened bag") return bag except Exception as e: print("Error: fai...
How would you implement a function in Python 3 that opens a Bag at the given path
You are a Python code analyst, evaluating scripts for potential improvements.
Check if Bag is valid and print out entries and md5
Can you tell what is the following Python 3 function doing def validate_md5(bag): logger_bagit.info("validate_md5") if bag.is_valid(): print("Valid md5") # for path, fixity in bag.entries.items(): # print("path:{}\nmd5:{}\n".format(path, fixity["md5"])) else: print("Inval...
You are a Python code analyst, evaluating scripts for potential improvements.
def resolved_flag(bag): """ Check DOI flag in bag.info to see if doi_resolver has been previously run :param obj bag: Bag :return bool: Flag """ if 'DOI-Resolved' in bag.info: logger_bagit.info("bagit resolved_flag: true") return True logger_bagit.info("bagit resolved_flag: f...
How would you implement a function in Python 3 that checks if DOI - Resolved flag in bag. info to see if doi_resolver has been previously run
As a Python code composer, you craft elegant and concise scripts.
Closes steps for creating a bag and saves it
How would you explain what the following Python 3 function does def finish_bag(dir_bag): logger_bagit.info("enter finish_bag") # Create a bag for the 3 files new_bag = create_bag(dir_bag) open_bag(dir_bag) new_bag.save(manifests=True) logger_bagit.info("exit finish_bag") return
You are a Python code generator, capable of creating scripts from specifications.
Ask user if they want to load in one file or do a batch process of a whole directory.
Can you generate the documentation for the following Python 3 function def _ask_how_many(): batch = True invalid = True _option = "" try: while invalid: print("\nChoose a loading option:\n1. Select specific file(s)\n2. Load entire folder") _option = input("Option: ") ...
You are a Python code architect, reviewing and designing scalable and efficient code
Open a GUI browse dialog window and let to user pick a target directory.
Given the following Python 3 function, write the documentation def browse_dialog_dir(): _go_to_package() logger_directory.info("enter browse_dialog") _path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False) _path = _fix_path_bytes(_path_bytes, file=False) if len(_path) >= ...
As a python code expert, you are capable of creating scripts from specifications.
Open a GUI browse dialog window and let to select one or more files
Here you have a function in Python 3, explain what it does def browse_dialog_file(): logger_directory.info("enter browse_dialog") # We make files a list, because the user can multi-select files. _files = [] _path = "" try: _go_to_package() _path_bytes = subprocess.check_output(['pyt...
You are a Python code generator, capable of creating scripts from specifications.
Check if the target file has an older creation date than X amount of time.
Can you generate the documentation for the following Python 3 function def check_file_age(filename, days): logger_directory.info("enter check_file_age") # Multiply days given by time for one day. t = days * 60 * 60 * 24 now = time.time() specified_time = now - t try: if os.path.getctime(...
You are a Python code analyst, evaluating scripts for potential improvements.
Collect all files from a given path and return one list for each type
Make a summary of the following Python 3 code def collect_metadata_files(cwd, new_files, existing_files): obj = {} try: os.chdir(cwd) # Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths. if new_files: for full_path in new_files: ...
As a python code expert, you are capable of creating scripts from specifications.
def collect_metadata_file(full_path): """ Create the file metadata and add it to the appropriate section by file-type :param str full_path: :param dict existing_files: :return dict existing files: """ fne = os.path.basename(full_path) fn = os.path.splitext(fne)[0] obj = {"full_path":...
Can you create a Python 3 function that creates the file metadata and add it to the appropriate section by file - type
You are a Python code generator, capable of creating scripts from specifications.
def dir_cleanup(dir_bag, dir_data): """ Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with the data files, so we don't need the other text files and such. :param str dir_bag: Path to root of Bag :param str dir_data: Path to Bag /data subdi...
Can you create a Python 3 function that deletes all the data files in the data directory and the metadata bag.
As a python code expert, you are capable of creating scripts from specifications.
def filename_from_path(path): """ Extract the file name from a given file path. :param str path: File path :return str: File name with extension """ head, tail = ntpath.split(path) return head, tail or ntpath.basename(head)
Implement a Python 3 function for extracting the file name from a given file path.
You are a Python code analyst, evaluating scripts for potential improvements.
def find_files(): """ Search for the directory containing jsonld and csv files. chdir and then quit. :return none: """ _dir = os.getcwd() _files = os.listdir() # Look for a jsonld file for _file in _files: if _file.endswith(".jsonld"): return os.getcwd() # No json...
Can you implement a function in Python 3 that searches for the directory containing jsonld and csv files. chdir and then quit.
You are a Python code analyst, evaluating scripts for potential improvements.
Get the filenames that the LiPD utilities has generated.
Given the following Python 3 function, write the documentation def get_filenames_generated(d, name="", csvs=""): filenames = [] try: filenames = d.keys() if name: filenames = [os.path.join(name, "data", filename) for filename in filenames] if csvs: lst = [i for i ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_filenames_in_lipd(path, name=""): """ List all the files contained in the LiPD archive. Bagit, JSON, and CSV :param str path: Directory to be listed :param str name: LiPD dataset name, if you want to prefix it to show file hierarchy :return list: Filenames found """ _filenames = [] ...
Create a Python 3 function for getting all the files contained in the LiPD archive. Bagit JSON and CSV files are included in the LiPD archive.
You are a Python code generator, capable of creating scripts from specifications.
def get_src_or_dst_prompt(mode): """ String together the proper prompt based on the mode :param str mode: "read" or "write" :return str prompt: The prompt needed """ _words = {"read": "from", "write": "to"} # print(os.getcwd()) prompt = "Where would you like to {} your file(s) {}?\n" \ ...
How would you implement a function in Python 3 that returns the proper prompt for reading or writing a file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the path to the source directory or destination directory.
Make a summary of the following Python 3 code def get_src_or_dst_path(prompt, count): _path = "" print(prompt) option = input("Option: ") print("\n") if option == '1': # Set the path to the system desktop folder. logger_directory.info("1: desktop") _path = os.path.expanduser(...
You are a Python code architect, reviewing and designing scalable and efficient code
Lists files in given path of the X type.
Explain what the following Python 3 code does def list_files(x, path=""): logger_directory.info("enter list_files") file_list = [] if path: # list files from target directory files = os.listdir(path) for file in files: if file.endswith(x) and not file.startswith(("$", "~"...
As a Python code analyst, you investigate and solve complex coding mysteries
Removes all files within a directory but does not delete the directory
Explain what the following Python 3 code does def rm_files_in_dir(path): for f in os.listdir(path): try: os.remove(f) except PermissionError: os.chmod(f, 0o777) try: os.remove(f) except Exception: pass return
You are a Python code generator, capable of creating scripts from specifications.
def rm_file_if_exists(path, filename): """ Remove a file if it exists. Useful for when we want to write a file, but it already exists in that locaiton. :param str filename: Filename :param str path: Directory :return none: """ _full_path = os.path.join(path, filename) if os.path.exists(_...
Create a Python 3 function to remove a file if it exists in the specified directory.
You are a Python code generator, capable of creating scripts from specifications.
def regenerate(location='http://www.iana.org/assignments/language-subtag-registry', filename=None, default_encoding='utf-8'): """ Generate the languages Python module. """ paren = re.compile('\([^)]*\)') # Get the language list. data = urllib2.urlopen(location) if ('content-t...
Write a Python 3 function for generating the languages Python module.
As a Python code analyst, you investigate and solve complex coding mysteries
def give_repr(cls): # pragma: no cover r"""Patch a class to give it a generic __repr__ method that works by inspecting the instance dictionary. Parameters ---------- cls: type The class to add a generic __repr__ to. Returns ------- cls: type The passed class is returne...
Write a Python 3 script for patching a class to give it a generic __repr__ method that works by inspecting the instance dictionary.
You are a Python code analyst, evaluating scripts for potential improvements.
r This function is used to compute the elementary symmetric polynomial of the roots of the input polynomial of a single variable.
Can you tell what is the following Python 3 function doing def vietes(coefficients): r''' Given the coefficients of a polynomial of a single variable, compute an elementary symmetric polynomial of the roots of the input polynomial by Viete's Formula: .. math:: \sum_{1\le i_1<i_2<...<i_k \le...
You are a Python code generator, capable of creating scripts from specifications.
Calculates the maximum number of isotopic variants that could be produced by a .
How would you explain what the following Python 3 function does def max_variants(composition): max_n_variants = 0 for element, count in composition.items(): if element == "H+": continue try: max_n_variants += count * periodic_table[element].max_neutron_shift() ex...
As a Python code analyst, you investigate and solve complex coding mysteries
Compute a peak list representing theoretical isotopic cluster for a given composition.
Given the following Python 3 function, write the documentation def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON): ''' Compute a peak list representing the theoretical isotopic cluster for `composition`. Parameters ---------- composition : Mapping Any Mapping t...
You are a Python code generator, capable of creating scripts from specifications.
Execute command line helper.
Make a summary of the following Python 3 code def call(): args = get_arguments() # Set up logging if args.debug: log_level = logging.DEBUG elif args.quiet: log_level = logging.WARN else: log_level = logging.INFO setup_logging(log_level) skybell = None try: ...
You are a Python code analyst, evaluating scripts for potential improvements.
This function trims and upsamples PET images from the input images in a NIfTI file.
Make a summary of the following Python 3 code def trimim( fims, affine=None, scale=2, divdim = 8**2, int_order=0, fmax = 0.05, outpath='', fname='', fcomment='', store_avg=False, store_img_intrmd=Fal...
As a Python code translator, you convert algorithms and pseudocode into Python.
def psf_general(vx_size=(1,1,1), fwhm=(5, 5, 6), hradius=8, scale=2): ''' Separable kernels for convolution executed on the GPU device The outputted kernels are in this order: z, y, x ''' xSig = (scale*fwhm[0]/vx_size[0]) / (2*(2*np.log(2))**.5) ySig = (scale*fwhm[1]/vx_size[1]) / (2*(2*np.log(2...
Can you write a function in Python 3 where it generalizes convolution function for the GPU device.
You are a Python code generator, capable of creating scripts from specifications.
This function is used to perform partial volume correction of the PET data using iterative Yang method.
Can you generate a brief explanation for the following Python 3 code def pvc_iyang( petin, mridct, Cnt, pvcroi, krnl, itr=5, tool='niftyreg', faff='', outpath='', fcomment='', store_img=False, store_rois=False, ): ''...
You are a Python code analyst, evaluating scripts for potential improvements.
def ct2mu(im): '''HU units to 511keV PET mu-values https://link.springer.com/content/pdf/10.1007%2Fs00259-002-0796-3.pdf C. Burger, et al., PET attenuation coefficients from CT images, ''' # convert nans to -1024 for the HU values only im[np.isnan(im)] = -1024 # constants muwat...
Write a Python 3 function for converting CT image to mu - values
As a python code expert, you are capable of creating scripts from specifications.
Calculates the centre of mass of an image along each axes.
How would you explain what the following Python 3 function does def centre_mass_img(imdct): ''' Calculate the centre of mass of an image along each axes (x,y,z), separately. Arguments: imdct - the image dictionary with the image and header data. Output the list of the centre of mass ...
You are a Python code architect, reviewing and designing scalable and efficient code
def nii_modify( nii, fimout = '', outpath = '', fcomment = '', voxel_range=[]): ''' Modify the NIfTI image given either as a file path or a dictionary, obtained by nimpa.getnii(file_path). ''' if isinstance(nii, basestring) and os.path.isfile(nii): d...
Implement a Python 3 function for modifying the NIfTI image given either as a file path or a dictionary of NIfTI images obtained by nimpa. getnii.
You are a Python code generator, capable of creating scripts from specifications.
def bias_field_correction( fmr, fimout = '', outpath = '', fcomment = '_N4bias', executable = '', exe_options = [], sitk_image_mask = True, verbose = False,): ''' Correct for bias field in MR image(s) given in <fmr> as a string (single file) o...
How would you implement a function in Python 3 that corrects for bias field in MR image(s) given in <fmr> as a string (single file) or as a list of strings (multiple files). Output dictionary with the bias corrected file names. Options: - fimout: The name (with path) of the output file. It's ignored when multiple files...
As a Python code composer, you craft elegant and concise scripts.
def roi_extraction(imdic, amyroi, datain, Cnt, use_stored=False): ''' Extracting ROI values of upsampled PET. If not provided it will be upsampled. imdic: dictionary of all image parts (image, path to file and affine transformation) > fpet: file name for quantitative PET > faff: file name and...
Write a Python 3 script to extract ROI values of upsampled PET. If not provided it will be upsampled. imdic: dictionary of all image parts (image, path to file and affine transformation) > fpet: file name for quantitative PET > faff: file name and path to the affine (rigid) transformations, most likely for upscaled PET...
You are a Python code generator, capable of creating scripts from specifications.
def getnii(fim, nan_replace=None, output='image'): '''Get PET image from NIfTI file. fim: input file name for the nifty image nan_replace: the value to be used for replacing the NaNs in the image. by default no change (None). output: option for choosing output: image, affine matri...
How would you code a function in Python 3 to get PET image from NIfTI file.
As a Python code composer, you craft elegant and concise scripts.
def getnii_descr(fim): ''' Extracts the custom description header field to dictionary ''' nim = nib.load(fim) hdr = nim.header rcnlst = hdr['descrip'].item().split(';') rcndic = {} if rcnlst[0]=='': # print 'w> no description in the NIfTI header' return rcndic ...
Write a Python 3 function that can extract the custom description header field to dictionary
You are a Python code analyst, evaluating scripts for potential improvements.
def array2nii(im, A, fnii, descrip='', trnsp=(), flip=(), storage_as=[]): '''Store the numpy array 'im' to a NIfTI file 'fnii'. ---- Arguments: 'im': image to be stored in NIfTI 'A': affine transformation 'fnii': output NIfTI file name. 'descrip': the descri...
How would you implement a function in Python 3 that stores the numpy array im to a NIfTI file fnii.
As a python code expert, you are capable of creating scripts from specifications.
def orientnii(imfile): '''Get the orientation from NIfTI sform. Not fully functional yet.''' strorient = ['L-R', 'S-I', 'A-P'] niiorient = [] niixyz = np.zeros(3,dtype=np.int8) if os.path.isfile(imfile): nim = nib.load(imfile) pct = nim.get_data() A = nim.get_sform() ...
How would you implement a function in Python 3 that gets the orientation from NIfTI sform. Not fully functional yet.
As a Python code analyst, you investigate and solve complex coding mysteries
Compress the NII - IML file and store it in a file
Can you generate the documentation for the following Python 3 function def nii_gzip(imfile, outpath=''): '''Compress *.gz file''' import gzip with open(imfile, 'rb') as f: d = f.read() # Now store the compressed data if outpath=='': fout = imfile+'.gz' else: fout = os.pat...
As a python code expert, you are capable of creating scripts from specifications.
Pick the MR T1w from the dictionary for MR - > PET registration.
Can you generate the documentation for the following Python 3 function def pick_t1w(mri): ''' Pick the MR T1w from the dictionary for MR->PET registration. ''' if isinstance(mri, dict): # check if NIfTI file is given if 'T1N4' in mri and os.path.isfile(mri['T1N4']): ft1w = mri['...
You are a Python code analyst, evaluating scripts for potential improvements.
Get basic info about the DICOM file.
How would you explain what the following Python 3 function does def dcminfo(dcmvar, verbose=True): ''' Get basic info about the DICOM file/header. ''' if isinstance(dcmvar, basestring): if verbose: print 'i> provided DICOM file:', dcmvar dhdr = dcm.dcmread(dcmvar) elif isins...
As a Python code analyst, you investigate and solve complex coding mysteries
def list_dcm_datain(datain): ''' List all DICOM file paths in the datain dictionary of input data. ''' if not isinstance(datain, dict): raise ValueError('The input is not a dictionary!') dcmlst = [] # list of mu-map DICOM files if 'mumapDCM' in datain: dcmump = os.listdir(datai...
Create a Python 3 function to list all DICOM files in the datain dictionary of input data.
You are a Python code architect, reviewing and designing scalable and efficient code
Anonymise DICOM file(s) Arguments: > dcmpth: it can be passed as a single DICOM file, or a folder containing DICOM files, or a list of DICOM file paths. > patient: the name of the patient. > physician:the name of the referring physician. > dob: patient...
Can you generate a brief explanation for the following Python 3 code def dcmanonym( dcmpth, displayonly=False, patient='anonymised', physician='anonymised', dob='19800101', verbose=True): ''' Anonymise DICOM file(s) Arguments: > dcmpth: it can be pa...
As a python code expert, you are capable of creating scripts from specifications.
Sort out the DICOM files in the folder according to the recorded series.
How would you explain what the following Python 3 function does def dcmsort(folder, copy_series=False, verbose=False): ''' Sort out the DICOM files in the folder according to the recorded series. ''' # list files in the input folder files = os.listdir(folder) srs = {} for f in files: i...
You are a Python code analyst, evaluating scripts for potential improvements.
Sort all input NIfTI images and check their shape.
How would you explain what the following Python 3 function does def niisort( fims, memlim=True ): ''' Sort all input NIfTI images and check their shape. Output dictionary of image files and their properties. Options: memlim -- when processing large numbers of frames ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert the DICOM files in the specified folder using DCM2NIIX.
Given the following Python 3 function, write the documentation def dcm2nii( dcmpth, fimout = '', fprefix = 'converted-from-DICOM_', fcomment = '', outpath = '', timestamp = True, executable = '', force = False, ): ''' Convert DICOM files in folder ...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the DICOM files from fpth into an image with the affine transformation.
Explain what the following Python 3 code does def dcm2im(fpth): ''' Get the DICOM files from 'fpth' into an image with the affine transformation. fpth can be a list of DICOM files or a path (string) to the folder with DICOM files. ''' # possible DICOM file extensions ext = ('dcm', 'DCM', 'ima',...
As a Python code composer, you craft elegant and concise scripts.
def path_niftypet_local(): '''Get the path to the local (home) folder for NiftyPET resources.''' # if using conda put the resources in the folder with the environment name if 'CONDA_DEFAULT_ENV' in os.environ: env = os.environ['CONDA_DEFAULT_ENV'] print 'i> conda environment found:', env ...
How would you implement a function in Python 3 that gets the path to the local folder for NiftyPET resources.
As a Python code composer, you craft elegant and concise scripts.
def find_cuda(): '''Locate the CUDA environment on the system.''' # search the PATH for NVCC for fldr in os.environ['PATH'].split(os.pathsep): cuda_path = join(fldr, 'nvcc') if os.path.exists(cuda_path): cuda_path = os.path.dirname(os.path.dirname(cuda_path)) break ...
Implement a Python 3 function for locating the CUDA environment on the system.
As a Python code analyst, you investigate and solve complex coding mysteries
def dev_setup(): '''figure out what GPU devices are available and choose the supported ones.''' # check first if NiftyPET was already installed and use the choice of GPU path_resources = path_niftypet_local() # if so, import the resources and get the constants if os.path.isfile(os.path.join(path_re...
Create a Python 3 function for figuring out what GPU devices are available and choose the supported ones.
As a Python code analyst, you investigate and solve complex coding mysteries
This function checks CUDA devices installs resources. py and installs it into the local NiftyPET folder.
Can you tell what is the following Python 3 function doing def resources_setup(): ''' This function checks CUDA devices, selects some and installs resources.py ''' print 'i> installing file <resources.py> into home directory if it does not exist.' path_current = os.path.dirname( os.path.realpath(__f...
You are a Python code analyst, evaluating scripts for potential improvements.
A function decorator that returns a generator that returns the value of the next item in the sequence.
Can you generate the documentation for the following Python 3 function def no_coroutine(f): @functools.wraps(f) def _no_coroutine(*args, **kwargs): generator = f(*args, **kwargs) # Special case for a function that returns immediately if not isinstance(generator, types.GeneratorType): ...
You are a Python code generator, capable of creating scripts from specifications.
A function decorator that returns a generator that yields only Promises or whatever.
Can you tell what is the following Python 3 function doing def maybe_coroutine(decide): def _maybe_coroutine(f): @functools.wraps(f) def __maybe_coroutine(*args, **kwargs): if decide(*args, **kwargs): return coroutine(f)(*args, **kwargs) else: ...
You are a Python code generator, capable of creating scripts from specifications.
Create a Promise that resolves with the result of a function that reports its result using a callback and returns a Promise that resolves with the result.
Can you generate a brief explanation for the following Python 3 code def makeCallbackPromise(function, *args, **kwargs): def _resolver(resolve, reject): function( lambda success, result: resolve(result) if success else reject(result), *args, **kwargs ) retur...
You are a Python code generator, capable of creating scripts from specifications.
Calculates the monoisotopic mass of a chemical element.
Can you generate a brief explanation for the following Python 3 code def calculate_mass(composition, mass_data=None): mass = 0.0 if mass_data is None: mass_data = nist_mass for element in composition: try: mass += (composition[element] * mass_data[element][0][0]) except K...
As a Python code analyst, you investigate and solve complex coding mysteries
Parse a chemical formula and construct a : class:`PyComposition` object containing the chemical formula.
Can you generate a brief explanation for the following Python 3 code def parse_formula(formula): if not formula_pattern.match(formula): raise ValueError("%r does not look like a formula" % (formula,)) composition = PyComposition() for elem, isotope, number in atom_pattern.findall(formula): c...
You are a Python code generator, capable of creating scripts from specifications.
Get all devices from Abode.
Can you generate a brief explanation for the following Python 3 code def get_devices(self, refresh=False): if refresh or self._devices is None: if self._devices is None: self._devices = {} _LOGGER.info("Updating all devices...") response = self.send_request("...
As a Python code composer, you craft elegant and concise scripts.
def send_request(self, method, url, headers=None, json_data=None, retry=True): """Send requests to Skybell.""" if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL: self.login() if not headers: headers = {} if self.cache(CONST.AC...
How would you implement a function in Python 3 that sends a request to Skybell.
As a Python code composer, you craft elegant and concise scripts.
Update a cached value.
Can you generate a brief explanation for the following Python 3 code def update_cache(self, data): UTILS.update(self._cache, data) self._save_cache()
As a Python code composer, you craft elegant and concise scripts.
def dev_cache(self, device, key=None): """Get a cached value for a device.""" device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id) if device_cache and key: return device_cache.get(key) return device_cache
Implement a function in Python 3 to get a cached value for a device.
As a Python code composer, you craft elegant and concise scripts.
Update cached values for a device.
Here you have a function in Python 3, explain what it does def update_dev_cache(self, device, data): self.update_cache( { CONST.DEVICES: { device.device_id: data } })
As a Python code analyst, you investigate and solve complex coding mysteries
Load existing cache and merge for updating if required.
How would you explain what the following Python 3 function does def _load_cache(self): if not self._disable_cache: if os.path.exists(self._cache_path): _LOGGER.debug("Cache found at: %s", self._cache_path) if os.path.getsize(self._cache_path) > 0: ...
You are a Python code analyst, evaluating scripts for potential improvements.
This method is used to encrypt a message for a given set of bare jids.
Make a summary of the following Python 3 code def __encryptKeyTransportMessage( self, bare_jids, encryption_callback, bundles = None, expect_problems = None, ignore_trust = False ): """ bare_jids: iterable<string> encryption_callback: A functio...
You are a Python code architect, reviewing and designing scalable and efficient code
Delete inactive devices by setting a quota.
Can you generate a brief explanation for the following Python 3 code def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0): if per_jid_max < 1 and global_max < 1: return if per_jid_max < 1: per_jid_max = None if global_max < 1: global_max...
As a python code expert, you are capable of creating scripts from specifications.
Delete all inactive devices from the device list storage and cache that are older than age_days days.
Here you have a function in Python 3, explain what it does def deleteInactiveDevicesByAge(self, age_days): if age_days < 1: return now = time.time() bare_jids = yield self._storage.listJIDs() for bare_jid in bare_jids: devices = yield self.__loadInactiveDevice...
You are a Python code generator, capable of creating scripts from specifications.
def runInactiveDeviceCleanup(self): """ Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota methods with the configuration that was set when calling create. """ yield self.deleteInactiveDevicesByQuota( self.__inactive_per_jid_max, ...
Implement a Python 3 function for running both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota methods with the configuration that was set when calling create.
You are a Python code analyst, evaluating scripts for potential improvements.
Get all - in - one trust information for all devices of a bare jid.
Explain what the following Python 3 code does def getTrustForJID(self, bare_jid): result = { "active" : {}, "inactive" : {} } devices = yield self.__loadActiveDevices(bare_jid) for device in devices: result["active"][device] = yield self.getTrustF...
As a Python code analyst, you investigate and solve complex coding mysteries
def deleteJID(self, bare_jid): """ Delete all data associated with a JID. This includes the list of active/inactive devices, all sessions with that JID and all information about trusted keys. """ yield self.runInactiveDeviceCleanup() self.__sessions_cache.pop(bare_jid, ...
Create a Python 3 function for deleting all data associated with a JID.
As a python code expert, you are capable of creating scripts from specifications.
Return a dictionary of GPU mu - map hardware and third - party set - up.
Here you have a function in Python 3, explain what it does def get_setup(Cnt = {}): '''Return a dictionary of GPU, mu-map hardware and third party set-up.''' # the name of the folder for NiftyPET tools Cnt['DIRTOOLS'] = DIRTOOLS # additional paramteres for compiling tools with cmake Cnt['CMAKE...
You are a Python code architect, reviewing and designing scalable and efficient code
def get_mmr_constants(): ''' Put all the constants together in a dictionary ''' Cnt = { 'ISOTOPE':'F18', 'DCYCRR':DCYCRR, 'ALPHA':ALPHA, 'NRNG':NRNG, 'NSRNG':NSRNG, 'NCRS':NCRS, 'NCRSR':NCRSR, 'NBCKT':224, 'NSANGLES':A, 'NS...
Write a Python 3 script for getting all the constants together in a dictionary
As a Python code composer, you craft elegant and concise scripts.
Check version and existence of all third - party software and input data.
Can you generate the documentation for the following Python 3 function def check_version(Cnt, chcklst=['RESPATH','REGPATH','DCM2NIIX','HMUDIR']): ''' Check version and existence of all third-party software and input data. Output a dictionary with bool type of the requested bits in 'chcklst' ''' # a...
As a Python code translator, you convert algorithms and pseudocode into Python.
def install_tool(app, Cnt): ''' Install the requested software from the git 'repo' and check out the version given by 'sha1'. ''' # get the current working directory cwd = os.getcwd() # pick the target installation folder for tools if 'PATHTOOLS' in Cnt and Cnt['PATHTOOLS']!='': ...
Can you write a function in Python 3 where it installs the requested software from the git repo and check out the version given by sha1.
You are a Python code analyst, evaluating scripts for potential improvements.
Update resources. py with the paths to the new installed apps.
Here you have a function in Python 3, explain what it does def update_resources(Cnt): '''Update resources.py with the paths to the new installed apps. ''' # list of path names which will be saved key_list = ['PATHTOOLS', 'RESPATH', 'REGPATH', 'DCM2NIIX', 'HMUDIR'] # get the local path to NiftyPET ...
As a Python code composer, you craft elegant and concise scripts.
def loadSessions(self, callback, bare_jid, device_ids): """ Return a dict containing the session for each device id. By default, this method calls loadSession for each device id. """ if self.is_async: self.__loadSessionsAsync(callback, bare_jid, device_ids, {}) ...
Write a Python 3 script for loading the session for each device id.
As a Python code translator, you convert algorithms and pseudocode into Python.
def loadTrusts(self, callback, bare_jid, device_ids): """ Return a dict containing the trust status for each device id. By default, this method calls loadTrust for each device id. """ if self.is_async: self.__loadTrustsAsync(callback, bare_jid, device_ids, {}) ...
Write a Python 3 script to load trust status for each device id.
You are a Python code architect, reviewing and designing scalable and efficient code
Create a new instance of the class from the data you ve retrieved from the PEP node.
How would you explain what the following Python 3 function does def parse(cls, backend, ik, spk, spk_signature, otpks): ik = backend.decodePublicKey(ik)[0] spk["key"] = backend.decodePublicKey(spk["key"])[0] otpks = list(map(lambda otpk: { "key" : backend.decodePublicKey(otpk["key...
You are a Python code generator, capable of creating scripts from specifications.
def serialize(self, backend): """ Use this method to prepare the data to be uploaded directly to some PEP node. This method applies an additional encoding step to the public keys in the bundle. The result is a dictionary with the keys ik, spk, spk_signature and otpks. The values ...
Write a Python 3 script for using this method to prepare the data to be uploaded directly to some PEP node. This method applies an additional encoding step to the public keys in the bundle. The result is a dictionary with the keys ik, spk, spk_signature and otpks. The values are structured the same way as the inputs of...
You are a Python code architect, reviewing and designing scalable and efficient code
fill the empty patches of image mask immsk
Can you generate a brief explanation for the following Python 3 code def imfill(immsk): '''fill the empty patches of image mask 'immsk' ''' for iz in range(immsk.shape[0]): for iy in range(immsk.shape[1]): ix0 = np.argmax(immsk[iz,iy,:]>0) ix1 = immsk.shape[2] - np.argmax(immsk[...
You are a Python code architect, reviewing and designing scalable and efficient code
def create_mask( fnii, fimout = '', outpath = '', fill = 1, dtype_fill = np.uint8, thrsh = 0., fwhm = 0.,): ''' create mask over the whole image or over the threshold area''' #> output path if outpath=='' and fimout!='': opth = ...
How would you code a function in Python 3 to create mask over the whole image or over the threshold area
As a python code expert, you are capable of creating scripts from specifications.
Calculate the Dice coefficient for the parcellation images im1 and im2 and ROI value val.
Given the following Python 3 function, write the documentation def dice_coeff(im1, im2, val=1): ''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>. Input images can be given as: 1. paths to NIfTI image files or as 2. Numpy arrays. The ROI val...
As a Python code composer, you craft elegant and concise scripts.
def dice_coeff_multiclass(im1, im2, roi2ind): ''' Calculate Dice score for parcellation images <im1> and <im2> and ROI value <val>. Input images can be given as: 1. paths to NIfTI image files or as 2. Numpy arrays. The ROI value must be given as a dictionary of lists of index...
Create a Python 3 function to calculate the Dice coefficient for parcellation images im1 and im2 and ROI value roi2ind.
As a Python code analyst, you investigate and solve complex coding mysteries
def gen_token(): """Generate a new Skybellpy token.""" return ''.join( random.choice( string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(32))
Can you write a function in Python 3 where it generates a new Skybellpy token.
As a Python code analyst, you investigate and solve complex coding mysteries
Validate the setting and value.
Explain what the following Python 3 code does def _validate_setting(setting, value): if setting not in CONST.ALL_SETTINGS: raise SkybellException(ERROR.INVALID_SETTING, setting) if setting == CONST.SETTINGS_DO_NOT_DISTURB: if value not in CONST.SETTINGS_DO_NOT_DISTURB_VALUES: raise ...
As a Python code analyst, you investigate and solve complex coding mysteries
Refresh the devices json object data.
Given the following Python 3 function, write the documentation def refresh(self): # Update core device data new_device_json = self._device_request() _LOGGER.debug("Device Refresh Response: %s", new_device_json) # Update avatar url new_avatar_json = self._avatar_request() ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the internal device json data.
Here you have a function in Python 3, explain what it does def update(self, device_json=None, info_json=None, settings_json=None, avatar_json=None): """Update the internal device json data.""" if device_json: UTILS.update(self._device_json, device_json) if avatar_json...
You are a Python code architect, reviewing and designing scalable and efficient code