Instruction:
Can you generate the documentation for the following Python 3 function
def show_cationpi(self):
        grp = self.getPseudoBondGroup("Cation-Pi-%i" % self.tid, associateWith=[self.model])
        grp.lineWidth = 3
        grp.lineType = self.chimera.Dash
        for i, cat in enumerate(self.plcomplex.pication):

            m = self.model
            r = m.newResidue("pseudoatoms", " ", 1, " ")
            chargecenter = m.newAtom("CHARGE", self.chimera.Element("CHARGE"))
            x, y, z = cat.charge_center
            chargecenter.setCoord(self.chimera.Coord(x, y, z))
            r.addAtom(chargecenter)

            centroid = m.newAtom("CENTROID", self.chimera.Element("CENTROID"))
            x, y, z = cat.ring_center
            centroid.setCoord(self.chimera.Coord(x, y, z))
            r.addAtom(centroid)

            b = grp.newPseudoBond(centroid, chargecenter)
            b.color = self.colorbyname('orange')

            if cat.protcharged:
                self.bs_res_ids += cat.charge_atoms
            else:
                self.bs_res_ids += cat.ring_atoms

Response: Visualizes cation - pi interactions.


Instruction:
Implement a Python 3 function for
cleaning up the visualization.

Response:
def cleanup(self):
        """Clean up the visualization."""

        if not len(self.water_ids) == 0:
            # Hide all non-interacting water molecules
            water_selection = []
            for wid in self.water_ids:
                water_selection.append('serialNumber=%i' % wid)
            self.rc("~display :HOH")
            self.rc("display :@/%s" % " or ".join(water_selection))

        # Show all interacting binding site residues
        self.rc("~display #%i & ~:/isHet" % self.model_dict[self.plipname])
        self.rc("display :%s" % ",".join([str(self.atoms[bsid].residue.id) for bsid in self.bs_res_ids]))
        self.rc("color lightblue :HOH")


Instruction:
Given the following Python 3 function, write the documentation
def zoom_to_ligand(self):
        self.rc("center #%i & :%s" % (self.model_dict[self.plipname], self.hetid))

Response: Centers the view on the ligand and its binding site residues.


Instruction:
Write a Python 3 function that can
detail for the visualization.

Response:
def refinements(self):
        """Details for the visualization."""
        self.rc("setattr a color gray @CENTROID")
        self.rc("setattr a radius 0.3 @CENTROID")
        self.rc("represent sphere @CENTROID")
        self.rc("setattr a color orange @CHARGE")
        self.rc("setattr a radius 0.4 @CHARGE")
        self.rc("represent sphere @CHARGE")
        self.rc("display :pseudoatoms")


Instruction:
Given the following Python 3 function, write the documentation
def forwards(self, orm):
        "Write your forwards methods here."
        if not db.dry_run:
            for pl in orm['core.Placement'].objects.all():
                pl.listing_set.update(publishable=pl.publishable)
                publishable = pl.publishable
                publishable.publish_from = pl.publish_from
                publishable.static = pl.static
                publishable.publish_to = pl.publish_to
                publishable.save(force_update=True)

Response: Write your forwards methods here.


Instruction:
Here you have a function in Python 3, explain what it does
def format(self):
        if hasattr(self.image, '_getexif'):
            self.rotate_exif()
        crop_box = self.crop_to_ratio()
        self.resize()
        return self.image, crop_box

Response: Return the image and crop_box used.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def set_format(self):
        f = self.fmt

        if f.flexible_height and f.flexible_max_height:
            flexw, flexh = self.fw, f.flexible_max_height
            flex_ratio = float(flexw) / flexh

            if abs(flex_ratio - self.image_ratio) < abs(self.format_ratio - self.image_ratio):
                self.fh = flexh
                self.format_ratio = flex_ratio

Response: Set the format of the image.


Instruction:
How would you implement a function in Python 3 that
gets coordinates of the rectangle defining the new image boundaries.

Response:
def get_crop_box(self):
        """
        Get coordinates of the rectangle defining the new image boundaries. It
        takes into acount any specific wishes from the model (explicitely
        passed in crop_box), the desired format and it's options
        (flexible_height, nocrop) and mainly it's ratio. After dimensions of
        the format were specified (see set_format), crop the image to the same
        ratio.
        """

        # check if the flexible height option is active and applies
        self.set_format()

        if self.fmt.nocrop:
            # cropping not allowed
            return

        if self.crop_box:
            # crop coordinates passed in explicitely
            return self.crop_box

        iw, ih = self.image.size

        if iw <= self.fw and ih <= self.fh:
            # image fits in the target format, no need to crop
            return

        if self.image_ratio < self.format_ratio:
            # image taller than format
            diff = ih - (iw * self.fh / self.fw)
            return (0, diff // 2 , iw, ih - diff // 2)

        elif self.image_ratio > self.format_ratio:
            # image wider than format
            diff = iw - (ih * self.fw / self.fh)
            return (diff // 2, 0, iw - diff // 2, ih)

        else:
            # same ratio as format
            return


Instruction:
Explain what the following Python 3 code does
def center_important_part(self, crop_box):
        if not self.important_box:
            return crop_box

        # shortcuts
        ib = self.important_box
        cl, ct, cr, cb = crop_box
        iw, ih = self.image.size

        # compute the move of crop center onto important center
        move_horiz = (ib[0] + ib[2]) // 2 - (cl + cr) // 2
        move_verti = (ib[1] + ib[3]) // 2 - (ct + cb) // 2

        # make sure we don't get out of the image
        # ... horizontaly
        if move_horiz > 0:
            move_horiz = min(iw - cr, move_horiz)
        else:
            move_horiz = max(-cl, move_horiz)

        # .. and verticaly
        if move_verti > 0:
            move_verti = min(ih - cb, move_verti)
        else:
            move_verti = max(-ct, move_verti)

        # move the crop_box
        return (cl + move_horiz, ct + move_verti, cr + move_horiz, cb + move_verti)

Response: Return the center of the important part of the image.


Instruction:
Create a Python 3 function for
getting crop coordinates and perform the crop if we get any.

Response:
def crop_to_ratio(self):
        " Get crop coordinates and perform the crop if we get any. "
        crop_box = self.get_crop_box()

        if not crop_box:
            return

        crop_box = self.center_important_part(crop_box)

        iw, ih = self.image.size
        # see if we want to crop something from outside of the image
        out_of_photo = min(crop_box[0], crop_box[1]) < 0 or crop_box[2] > iw or crop_box[3] > ih
        # check whether there's transparent information in the image
        transparent = self.image.mode in ('RGBA', 'LA')

        if photos_settings.DEFAULT_BG_COLOR != 'black' and out_of_photo and not transparent:
            # if we do, just crop the image to the portion that will be visible
            updated_crop_box = (
                max(0, crop_box[0]), max(0, crop_box[1]), min(iw, crop_box[2]), min(ih, crop_box[3]),
            )
            cropped = self.image.crop(updated_crop_box)

            # create new image of the proper size and color
            self.image = Image.new('RGB', (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), photos_settings.DEFAULT_BG_COLOR)
            # and paste the cropped part into it's proper position
            self.image.paste(cropped, (abs(min(crop_box[0], 0)), abs(min(crop_box[1], 0))))
        else:
            # crop normally if not the case
            self.image = self.image.crop(crop_box)
        return crop_box


Instruction:
Implement a function in Python 3 to
get target size for a cropped image and do the resizing if we got anything usable.

Response:
def resize(self):
        """
        Get target size for a cropped image and do the resizing if we got
        anything usable.
        """
        resized_size = self.get_resized_size()
        if not resized_size:
            return

        self.image = self.image.resize(resized_size, Image.ANTIALIAS)


Instruction:
Write a Python 3 script for
rotating image via exif information.

Response:
def rotate_exif(self):
        """
        Rotate image via exif information.
        Only 90, 180 and 270 rotations are supported.
        """
        exif = self.image._getexif() or {}
        rotation = exif.get(TAGS['Orientation'], 1)

        rotations = {
            6: -90,
            3: -180,
            8: -270,
        }
        if rotation not in rotations:
            return

        self.image = self.image.rotate(rotations[rotation])


Instruction:
Create a Python 3 function for
visualizing the protein - ligand pliprofiler at one site in PyMOL.

Response:
def visualize_in_pymol(plcomplex):
    """Visualizes the protein-ligand pliprofiler at one site in PyMOL."""

    vis = PyMOLVisualizer(plcomplex)

    #####################
    # Set everything up #
    #####################

    pdbid = plcomplex.pdbid
    lig_members = plcomplex.lig_members
    chain = plcomplex.chain
    if config.PEPTIDES != []:
        vis.ligname = 'PeptideChain%s' % plcomplex.chain
    if config.INTRA is not None:
        vis.ligname = 'Intra%s' % plcomplex.chain

    ligname = vis.ligname
    hetid = plcomplex.hetid

    metal_ids = plcomplex.metal_ids
    metal_ids_str = '+'.join([str(i) for i in metal_ids])

    ########################
    # Basic visualizations #
    ########################

    start_pymol(run=True, options='-pcq', quiet=not config.DEBUG)
    vis.set_initial_representations()

    cmd.load(plcomplex.sourcefile)
    current_name = cmd.get_object_list(selection='(all)')[0]
    write_message('Setting current_name to "%s" and pdbid to "%s\n"' % (current_name, pdbid), mtype='debug')
    cmd.set_name(current_name, pdbid)
    cmd.hide('everything', 'all')
    if config.PEPTIDES != []:
        cmd.select(ligname, 'chain %s and not resn HOH' % plcomplex.chain)
    else:
        cmd.select(ligname, 'resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position))
    write_message("Selecting ligand for PDBID %s and ligand name %s with: " % (pdbid, ligname), mtype='debug')
    write_message('resn %s and chain %s and resi %s*' % (hetid, chain, plcomplex.position), mtype='debug')

    # Visualize and color metal ions if there are any
    if not len(metal_ids) == 0:
        vis.select_by_ids(ligname, metal_ids, selection_exists=True)
        cmd.show('spheres', 'id %s and %s' % (metal_ids_str, pdbid))

    # Additionally, select all members of composite ligands
    if len(lig_members) > 1:
        for member in lig_members:
           resid, chain, resnr = member[0], member[1], str(member[2])
           cmd.select(ligname, '%s or (resn %s and chain %s and resi %s)' % (ligname, resid, chain, resnr))

    cmd.show('sticks', ligname)
    cmd.color('myblue')
    cmd.color('myorange', ligname)
    cmd.util.cnc('all')
    if not len(metal_ids) == 0:
        cmd.color('hotpink', 'id %s' % metal_ids_str)
        cmd.hide('sticks', 'id %s' % metal_ids_str)
        cmd.set('sphere_scale', 0.3, ligname)
    cmd.deselect()

    vis.make_initial_selections()

    vis.show_hydrophobic()  # Hydrophobic Contacts
    vis.show_hbonds()  # Hydrogen Bonds
    vis.show_halogen()  # Halogen Bonds
    vis.show_stacking()  # pi-Stacking Interactions
    vis.show_cationpi()  # pi-Cation Interactions
    vis.show_sbridges()  # Salt Bridges
    vis.show_wbridges()  # Water Bridges
    vis.show_metal()  # Metal Coordination

    vis.refinements()

    vis.zoom_to_ligand()

    vis.selections_cleanup()

    vis.selections_group()
    vis.additional_cleanup()
    if config.DNARECEPTOR:
        # Rename Cartoon selection to Line selection and change repr.
        cmd.set_name('%sCartoon' % plcomplex.pdbid, '%sLines' % plcomplex.pdbid)
        cmd.hide('cartoon', '%sLines' % plcomplex.pdbid)
        cmd.show('lines', '%sLines' % plcomplex.pdbid)

    if config.PEPTIDES != []:
        filename = "%s_PeptideChain%s" % (pdbid.upper(), plcomplex.chain)
        if config.PYMOL:
            vis.save_session(config.OUTPATH, override=filename)
    elif config.INTRA is not None:
        filename = "%s_IntraChain%s" % (pdbid.upper(), plcomplex.chain)
        if config.PYMOL:
            vis.save_session(config.OUTPATH, override=filename)
    else:
        filename = '%s_%s' % (pdbid.upper(), "_".join([hetid, plcomplex.chain, plcomplex.position]))
        if config.PYMOL:
            vis.save_session(config.OUTPATH)
    if config.PICS:
        vis.save_picture(config.OUTPATH, filename)


Instruction:
Write a Python 3 function that can
return a ContentType object based on its slugified verbose_name_plural.

Response:
def get_content_type(ct_name):
    """
    A helper function that returns ContentType object based on its slugified verbose_name_plural.

    Results of this function is cached to improve performance.

    :Parameters:
        - `ct_name`:  Slugified verbose_name_plural of the target model.

    :Exceptions:
        - `Http404`: if no matching ContentType is found
    """
    try:
        ct = CONTENT_TYPE_MAPPING[ct_name]
    except KeyError:
        for model in models.get_models():
            if ct_name == slugify(model._meta.verbose_name_plural):
                ct = ContentType.objects.get_for_model(model)
                CONTENT_TYPE_MAPPING[ct_name] = ct
                break
        else:
            raise Http404
    return ct


Instruction:
Write a Python 3 function for
returning a list of templates for a given content type and slug.

Response:
def get_templates(name, slug=None, category=None, app_label=None, model_label=None):
    """
    Returns templates in following format and order:

    * ``'page/category/%s/content_type/%s.%s/%s/%s' % (<CATEGORY_PART>, app_label, model_label, slug, name)``
    * ``'page/category/%s/content_type/%s.%s/%s' % (<CATEGORY_PART>, app_label, model_label, name)``
    * ``'page/category/%s/%s' % (<CATEGORY_PART>, name)``
    * ``'page/content_type/%s.%s/%s' % (app_label, model_label, name)``
    * ``'page/%s' % name``

    Where ``<CATEGORY_PART>`` is derived from ``path`` attribute by these rules:

    * When **no** parent exists (this is therfore root category) ``<CATEGORY_PART> = path``
    * When exactly **one** parent exists: ``<CATEGORY_PART> = path``
    * When multiple parent exist (category nestedN is deep in the tree)::

          <CATEGORY_PART> = (
              'nested1/nested2/../nestedN/',
              'nested1/nested2/../nestedN-1/',
              ...
              'nested1'
          )

    Examples. Three categories exist having slugs **ROOT**, **NESTED1**,
    **NESTED2** where **NESTED2**'s parent is **NESTED1**.::

        ROOT
           \
         NESTED1
             \
            NESTED2

    * For **ROOT**, ``<CATEGORY_PART>`` is only one - "ROOT".
    * For **NESTED1**, ``<CATEGORY_PART>`` is only one - "NESTED1".
    * For **NESTED2**, ``<CATEGORY_PART>`` has two elements: "NESTED1/NESTED2" and "NESTED1".
    """
    def category_templates(category, incomplete_template, params):
        paths = []
        parts = category.path.split('/')
        for i in reversed(range(1, len(parts) + 1)):
            params.update({'pth': '/'.join(parts[:i])})
            paths.append(incomplete_template % params)
        return paths

    FULL = 'page/category/%(pth)s/content_type/%(app_label)s.%(model_label)s/%(slug)s/%(name)s'
    FULL_NO_SLUG = 'page/category/%(pth)s/content_type/%(app_label)s.%(model_label)s/%(name)s'
    BY_CATEGORY = 'page/category/%(pth)s/%(name)s'
    BY_CONTENT_TYPE = 'page/content_type/%(app_label)s.%(model_label)s/%(name)s'

    templates = []
    params = {'name': name}

    if app_label and model_label:
        params.update({'app_label': app_label, 'model_label': model_label})

    if slug:
        params.update({'slug': slug})

    if category:
        if app_label and model_label:
            if slug:
                templates += category_templates(category, FULL, params)
            templates += category_templates(category, FULL_NO_SLUG, params)
        templates += category_templates(category, BY_CATEGORY, params)

    if app_label and model_label:
        templates.append(BY_CONTENT_TYPE % params)

    templates.append('page/%(name)s' % params)
    return templates


Instruction:
How would you explain what the following Python 3 function does
def get_templates_from_publishable(name, publishable):
    slug = publishable.slug
    category = publishable.category
    app_label = publishable.content_type.app_label
    model_label = publishable.content_type.model
    return get_templates(name, slug, category, app_label, model_label)

Response: Returns a list of templates from a Publishable instance.


Instruction:
Can you implement a function in Python 3 that
exports a list of objects in the tree.

Response:
def export(request, count, name='', content_type=None):
    """
    Export banners.

    :Parameters:
        - `count`: number of objects to pass into the template
        - `name`: name of the template ( page/export/banner.html is default )
        - `models`: list of Model classes to include
    """
    t_list = []
    if name:
        t_list.append('page/export/%s.html' % name)
    t_list.append('page/export/banner.html')

    try:
        cat = Category.objects.get_by_tree_path('')
    except Category.DoesNotExist:
        raise Http404()
    listing = Listing.objects.get_listing(count=count, category=cat)
    return render(
            request,
            t_list,
            { 'category' : cat, 'listing' : listing },
            content_type=content_type
        )


Instruction:
How would you explain what the following Python 3 function does
def get_templates(self, context, template_name=None):
        " Extract parameters for `get_templates` from the context. "
        if not template_name:
            template_name = self.template_name

        kw = {}
        if 'object' in context:
            o = context['object']
            kw['slug'] = o.slug

        if context.get('content_type', False):
            ct = context['content_type']
            kw['app_label'] = ct.app_label
            kw['model_label'] = ct.model

        return get_templates(template_name, category=context['category'], **kw)

Response: Extract parameters for get_templates from the context.


Instruction:
Implement a Python 3 function for
returning ARCHIVE_ENTRY_YEAR from settings ( if exists ) or year of the newest object in category

Response:
def _archive_entry_year(self, category):
        " Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category "
        year = getattr(settings, 'ARCHIVE_ENTRY_YEAR', None)
        if not year:
            n = now()
            try:
                year = Listing.objects.filter(
                        category__site__id=settings.SITE_ID,
                        category__tree_path__startswith=category.tree_path,
                        publish_from__lte=n
                    ).values('publish_from')[0]['publish_from'].year
            except:
                year = n.year
        return year


Instruction:
How would you code a function in Python 3 to
override models. Model. save.

Response:
def save(self, **kwargs):
        """Overrides models.Model.save.

        - Generates slug.
        - Saves image file.
        """
        if not self.width or not self.height:
            self.width, self.height = self.image.width, self.image.height

        # prefill the slug with the ID, it requires double save
        if not self.id:
            img = self.image

            # store dummy values first...
            w, h = self.width, self.height
            self.image = ''
            self.width, self.height = w, h
            self.slug = ''

            super(Photo, self).save(force_insert=True)

            # ... so that we can generate the slug
            self.slug = str(self.id) + '-' + slugify(self.title)
            # truncate slug in order to fit in an ImageField and/or paths in Redirects
            self.slug = self.slug[:64]
            # .. tha will be used in the image's upload_to function
            self.image = img
            # and the image will be saved properly
            super(Photo, self).save(force_update=True)
        else:
            try:
                old = Photo.objects.get(pk=self.pk)

                force_update = True
                # delete formatedphotos if new image was uploaded
                if old.image != self.image:
                    for f_photo in self.formatedphoto_set.all():
                        f_photo.delete()
            except Photo.DoesNotExist:
                # somebody is just trying to create new model with given PK
                force_update = False

            super(Photo, self).save(force_update=force_update)


Instruction:
Can you implement a function in Python 3 that
returns fake FormatedPhoto object to be used in templates when an error occurs in image generation.

Response:
def get_blank_img(self):
        """
        Return fake ``FormatedPhoto`` object to be used in templates when an error
        occurs in image generation.
        """
        if photos_settings.DEBUG:
            return self.get_placeholder_img()

        out = {
            'blank': True,
            'width': self.max_width,
            'height': self.max_height,
            'url': photos_settings.EMPTY_IMAGE_SITE_PREFIX + 'img/empty/%s.png' % (self.name),
        }
        return out


Instruction:
Create a Python 3 function to
return fake photo object grabbed from image placeholder generator service for the purpose of debugging when images are not available but we still want to see something.

Response:
def get_placeholder_img(self):
        """
        Returns fake ``FormatedPhoto`` object grabbed from image placeholder
        generator service for the purpose of debugging when images
        are not available but we still want to see something.
        """
        pars = {
            'width': self.max_width,
            'height': self.max_height
        }
        out = {
            'placeholder': True,
            'width': self.max_width,
            'height': self.max_height,
            'url': photos_settings.DEBUG_PLACEHOLDER_PROVIDER_TEMPLATE % pars
        }
        return out


Instruction:
Here you have a function in Python 3, explain what it does
def save(self, **kwargs):

        if self.id:
            for f_photo in self.formatedphoto_set.all():
                f_photo.delete()

        super(Format, self).save(**kwargs)

Response: Overrides models. Model. save. save.


Instruction:
Explain what the following Python 3 code does
def generate(self, save=True):
        stretched_photo, crop_box = self._generate_img()

        # set crop_box to (0,0,0,0) if photo not cropped
        if not crop_box:
            crop_box = 0, 0, 0, 0

        self.crop_left, self.crop_top, right, bottom = crop_box
        self.crop_width = right - self.crop_left
        self.crop_height = bottom - self.crop_top

        self.width, self.height = stretched_photo.size

        f = StringIO()
        imgf = (self.photo._get_image().format or
                Image.EXTENSION[path.splitext(self.photo.image.name)[1]])

        stretched_photo.save(f, format=imgf, quality=self.format.resample_quality)
        f.seek(0)

        self.image.save(self.file(), ContentFile(f.read()), save)

Response: Generates photo file in current format.


Instruction:
How would you implement a function in Python 3 that
overrides models. Model. save - Removes old file from the FS - Generates new file.

Response:
def save(self, **kwargs):
        """Overrides models.Model.save

        - Removes old file from the FS
        - Generates new file.
        """
        self.remove_file()
        if not self.image:
            self.generate(save=False)
        else:
            self.image.name = self.file()
        super(FormatedPhoto, self).save(**kwargs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def file(self):
        if photos_settings.FORMATED_PHOTO_FILENAME is not None:
            return photos_settings.FORMATED_PHOTO_FILENAME(self)
        source_file = path.split(self.photo.image.name)
        return path.join(source_file[0], str(self.format.id) + '-' + source_file[1])

Response: Method returns formated photo path derived from format. id and source photo filename


Instruction:
How would you explain what the following Python 3 function does
def _get_category_from_pars_var(template_var, context):
    '''
    get category from template variable or from tree_path
    '''
    cat = template_var.resolve(context)
    if isinstance(cat, basestring):
        cat = Category.objects.get_by_tree_path(cat)
    return cat

Response: get category from template variable or from tree_path


Instruction:
Explain what the following Python 3 code does
def position(parser, token):
    bits = token.split_contents()
    nodelist = parser.parse(('end' + bits[0],))
    parser.delete_first_token()
    return _parse_position_tag(bits, nodelist)

Response: Render a given position for category.


Instruction:
Here you have a function in Python 3, explain what it does
def ifposition(parser, token):
    bits = list(token.split_contents())
    end_tag = 'end' + bits[0]

    nofallback = False
    if bits[-1] == 'nofallback':
        nofallback = True
        bits.pop()

    if len(bits) >= 4 and bits[-2] == 'for':
        category = template.Variable(bits.pop())
        pos_names = bits[1:-1]
    else:
        raise TemplateSyntaxError('Invalid syntax: {% ifposition POSITION_NAME ... for CATEGORY [nofallback] %}')

    nodelist_true = parser.parse(('else', end_tag))
    token = parser.next_token()

    if token.contents == 'else':
        nodelist_false = parser.parse((end_tag,))
        parser.delete_first_token()
    else:
        nodelist_false = template.NodeList()

    return IfPositionNode(category, pos_names, nofallback, nodelist_true, nodelist_false)

Response: Returns a node for the if - position of the given tag.


Instruction:
Explain what the following Python 3 code does
def filter_contacts(pairings):
    if not config.INTRA:
        return pairings
    filtered1_pairings = [p for p in pairings if (p.resnr, p.reschain) != (p.resnr_l, p.reschain_l)]
    already_considered = []
    filtered2_pairings = []
    for contact in filtered1_pairings:
        try:
            dist = 'D{}'.format(round(contact.distance, 2))
        except AttributeError:
            try:
                dist = 'D{}'.format(round(contact.distance_ah, 2))
            except AttributeError:
                dist = 'D{}'.format(round(contact.distance_aw, 2))
        res1, res2 = ''.join([str(contact.resnr), contact.reschain]), ''.join(
            [str(contact.resnr_l), contact.reschain_l])
        data = {res1, res2, dist}
        if data not in already_considered:
            filtered2_pairings.append(contact)
            already_considered.append(data)
    return filtered2_pairings

Response: Filter interactions by two criteria.


Instruction:
Write a Python 3 function that can
return a list of hydrophobic interaction objects between two sets of atoms.

Response:
def hydrophobic_interactions(atom_set_a, atom_set_b):
    """Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand).
    Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX
    """
    data = namedtuple('hydroph_interaction', 'bsatom bsatom_orig_idx ligatom ligatom_orig_idx '
                                             'distance restype resnr reschain restype_l, resnr_l, reschain_l')
    pairings = []
    for a, b in itertools.product(atom_set_a, atom_set_b):
        if a.orig_idx == b.orig_idx:
            continue
        e = euclidean3d(a.atom.coords, b.atom.coords)
        if not config.MIN_DIST < e < config.HYDROPH_DIST_MAX:
            continue
        restype, resnr, reschain = whichrestype(a.atom), whichresnumber(a.atom), whichchain(a.atom)
        restype_l, resnr_l, reschain_l = whichrestype(b.orig_atom), whichresnumber(b.orig_atom), whichchain(b.orig_atom)
        contact = data(bsatom=a.atom, bsatom_orig_idx=a.orig_idx, ligatom=b.atom, ligatom_orig_idx=b.orig_idx,
                       distance=e, restype=restype, resnr=resnr,
                       reschain=reschain, restype_l=restype_l,
                       resnr_l=resnr_l, reschain_l=reschain_l)
        pairings.append(contact)
    return filter_contacts(pairings)


Instruction:
Write a Python 3 function that can
return a list of tuples containing the names of hydrogen bonds between acceptors and donor pairs.

Response:
def hbonds(acceptors, donor_pairs, protisdon, typ):
    """Detection of hydrogen bonds between sets of acceptors and donor pairs.
    Definition: All pairs of hydrogen bond acceptor and donors with
    donor hydrogens and acceptor showing a distance within HBOND DIST MIN and HBOND DIST MAX
    and donor angles above HBOND_DON_ANGLE_MIN
    """
    data = namedtuple('hbond', 'a a_orig_idx d d_orig_idx h distance_ah distance_ad angle type protisdon resnr '
                               'restype reschain resnr_l restype_l reschain_l sidechain atype dtype')
    pairings = []
    for acc, don in itertools.product(acceptors, donor_pairs):
        if not typ == 'strong':
            continue
        # Regular (strong) hydrogen bonds
        dist_ah = euclidean3d(acc.a.coords, don.h.coords)
        dist_ad = euclidean3d(acc.a.coords, don.d.coords)
        if not config.MIN_DIST < dist_ad < config.HBOND_DIST_MAX:
            continue
        vec1, vec2 = vector(don.h.coords, don.d.coords), vector(don.h.coords, acc.a.coords)
        v = vecangle(vec1, vec2)
        if not v > config.HBOND_DON_ANGLE_MIN:
            continue
        protatom = don.d.OBAtom if protisdon else acc.a.OBAtom
        ligatom = don.d.OBAtom if not protisdon else acc.a.OBAtom
        is_sidechain_hbond = protatom.GetResidue().GetAtomProperty(protatom, 8)  # Check if sidechain atom
        resnr = whichresnumber(don.d) if protisdon else whichresnumber(acc.a)
        resnr_l = whichresnumber(acc.a_orig_atom) if protisdon else whichresnumber(don.d_orig_atom)
        restype = whichrestype(don.d) if protisdon else whichrestype(acc.a)
        restype_l = whichrestype(acc.a_orig_atom) if protisdon else whichrestype(don.d_orig_atom)
        reschain = whichchain(don.d) if protisdon else whichchain(acc.a)
        rechain_l = whichchain(acc.a_orig_atom) if protisdon else whichchain(don.d_orig_atom)
        # Next line prevents H-Bonds within amino acids in intermolecular interactions
        if config.INTRA is not None and whichresnumber(don.d) == whichresnumber(acc.a):
            continue
        # Next line prevents backbone-backbone H-Bonds
        if config.INTRA is not None and protatom.GetResidue().GetAtomProperty(protatom, 8) and ligatom.GetResidue().GetAtomProperty(ligatom, 8):
            continue
        contact = data(a=acc.a, a_orig_idx=acc.a_orig_idx, d=don.d, d_orig_idx=don.d_orig_idx, h=don.h,
                       distance_ah=dist_ah, distance_ad=dist_ad, angle=v, type=typ, protisdon=protisdon,
                       resnr=resnr, restype=restype, reschain=reschain, resnr_l=resnr_l,
                       restype_l=restype_l, reschain_l=rechain_l, sidechain=is_sidechain_hbond,
                       atype=acc.a.type, dtype=don.d.type)
        pairings.append(contact)
    return filter_contacts(pairings)


Instruction:
Explain what the following Python 3 code does
def pistacking(rings_bs, rings_lig):
    data = namedtuple(
        'pistack', 'proteinring ligandring distance angle offset type restype resnr reschain restype_l resnr_l reschain_l')
    pairings = []
    for r, l in itertools.product(rings_bs, rings_lig):
        # DISTANCE AND RING ANGLE CALCULATION
        d = euclidean3d(r.center, l.center)
        b = vecangle(r.normal, l.normal)
        a = min(b, 180 - b if not 180 - b < 0 else b)  # Smallest of two angles, depending on direction of normal

        # RING CENTER OFFSET CALCULATION (project each ring center into the other ring)
        proj1 = projection(l.normal, l.center, r.center)
        proj2 = projection(r.normal, r.center, l.center)
        offset = min(euclidean3d(proj1, l.center), euclidean3d(proj2, r.center))

        # RECEPTOR DATA
        resnr, restype, reschain = whichresnumber(r.atoms[0]), whichrestype(r.atoms[0]), whichchain(r.atoms[0])
        resnr_l, restype_l, reschain_l = whichresnumber(l.orig_atoms[0]), whichrestype(
            l.orig_atoms[0]), whichchain(l.orig_atoms[0])

        # SELECTION BY DISTANCE, ANGLE AND OFFSET
        passed = False
        if not config.MIN_DIST < d < config.PISTACK_DIST_MAX:
            continue
        if 0 < a < config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX:
            ptype = 'P'
            passed = True
        if 90 - config.PISTACK_ANG_DEV < a < 90 + config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX:
            ptype = 'T'
            passed = True
        if passed:
            contact = data(proteinring=r, ligandring=l, distance=d, angle=a, offset=offset,
                           type=ptype, resnr=resnr, restype=restype, reschain=reschain,
                           resnr_l=resnr_l, restype_l=restype_l, reschain_l=reschain_l)
            pairings.append(contact)
    return filter_contacts(pairings)

Response: Return all pi - stackings between the given aromatic ring systems in receptor and ligand.


Instruction:
Explain what the following Python 3 code does
def pication(rings, pos_charged, protcharged):
    data = namedtuple(
        'pication', 'ring charge distance offset type restype resnr reschain restype_l resnr_l reschain_l protcharged')
    pairings = []
    if len(rings) == 0 or len(pos_charged) == 0:
        return pairings
    for ring in rings:
        c = ring.center
        for p in pos_charged:
            d = euclidean3d(c, p.center)
            # Project the center of charge into the ring and measure distance to ring center
            proj = projection(ring.normal, ring.center, p.center)
            offset = euclidean3d(proj, ring.center)
            if not config.MIN_DIST < d < config.PICATION_DIST_MAX or not offset < config.PISTACK_OFFSET_MAX:
                continue
            if type(p).__name__ == 'lcharge' and p.fgroup == 'tertamine':
                # Special case here if the ligand has a tertiary amine, check an additional angle
                # Otherwise, we might have have a pi-cation interaction 'through' the ligand
                n_atoms = [a_neighbor for a_neighbor in OBAtomAtomIter(p.atoms[0].OBAtom)]
                n_atoms_coords = [(a.x(), a.y(), a.z()) for a in n_atoms]
                amine_normal = np.cross(vector(n_atoms_coords[0], n_atoms_coords[1]),
                                        vector(n_atoms_coords[2], n_atoms_coords[0]))
                b = vecangle(ring.normal, amine_normal)
                # Smallest of two angles, depending on direction of normal
                a = min(b, 180 - b if not 180 - b < 0 else b)
                if not a > 30.0:
                    resnr, restype = whichresnumber(ring.atoms[0]), whichrestype(ring.atoms[0])
                    reschain = whichchain(ring.atoms[0])
                    resnr_l, restype_l = whichresnumber(p.orig_atoms[0]), whichrestype(p.orig_atoms[0])
                    reschain_l = whichchain(p.orig_atoms[0])
                    contact = data(ring=ring, charge=p, distance=d, offset=offset, type='regular',
                                   restype=restype, resnr=resnr, reschain=reschain,
                                   restype_l=restype_l, resnr_l=resnr_l, reschain_l=reschain_l,
                                   protcharged=protcharged)
                    pairings.append(contact)
                break
            resnr = whichresnumber(p.atoms[0]) if protcharged else whichresnumber(ring.atoms[0])
            resnr_l = whichresnumber(ring.orig_atoms[0]) if protcharged else whichresnumber(p.orig_atoms[0])
            restype = whichrestype(p.atoms[0]) if protcharged else whichrestype(ring.atoms[0])
            restype_l = whichrestype(ring.orig_atoms[0]) if protcharged else whichrestype(p.orig_atoms[0])
            reschain = whichchain(p.atoms[0]) if protcharged else whichchain(ring.atoms[0])
            reschain_l = whichchain(ring.orig_atoms[0]) if protcharged else whichchain(p.orig_atoms[0])
            contact = data(ring=ring, charge=p, distance=d, offset=offset, type='regular', restype=restype,
                           resnr=resnr, reschain=reschain, restype_l=restype_l, resnr_l=resnr_l,
                           reschain_l=reschain_l, protcharged=protcharged)
            pairings.append(contact)
    return filter_contacts(pairings)

Response: Return all pi - Cation interaction between aromatic rings and positively charged groups.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def saltbridge(poscenter, negcenter, protispos):
    data = namedtuple(
        'saltbridge', 'positive negative distance protispos resnr restype reschain resnr_l restype_l reschain_l')
    pairings = []
    for pc, nc in itertools.product(poscenter, negcenter):
        if not config.MIN_DIST < euclidean3d(pc.center, nc.center) < config.SALTBRIDGE_DIST_MAX:
            continue
        resnr = pc.resnr if protispos else nc.resnr
        resnr_l = whichresnumber(nc.orig_atoms[0]) if protispos else whichresnumber(pc.orig_atoms[0])
        restype = pc.restype if protispos else nc.restype
        restype_l = whichrestype(nc.orig_atoms[0]) if protispos else whichrestype(pc.orig_atoms[0])
        reschain = pc.reschain if protispos else nc.reschain
        reschain_l = whichchain(nc.orig_atoms[0]) if protispos else whichchain(pc.orig_atoms[0])
        contact = data(positive=pc, negative=nc, distance=euclidean3d(pc.center, nc.center), protispos=protispos,
                       resnr=resnr, restype=restype, reschain=reschain, resnr_l=resnr_l, restype_l=restype_l,
                       reschain_l=reschain_l)
        pairings.append(contact)
    return filter_contacts(pairings)

Response: Detect all salt bridges between centers of positive and negative charge


Instruction:
Write a Python 3 function that can
detect all halogen bonds of the type Y - O... X - C

Response:
def halogen(acceptor, donor):
    """Detect all halogen bonds of the type Y-O...X-C"""
    data = namedtuple('halogenbond', 'acc acc_orig_idx don don_orig_idx distance don_angle acc_angle restype '
                                     'resnr reschain restype_l resnr_l reschain_l donortype acctype sidechain')
    pairings = []
    for acc, don in itertools.product(acceptor, donor):
        dist = euclidean3d(acc.o.coords, don.x.coords)
        if not config.MIN_DIST < dist < config.HALOGEN_DIST_MAX:
            continue
        vec1, vec2 = vector(acc.o.coords, acc.y.coords), vector(acc.o.coords, don.x.coords)
        vec3, vec4 = vector(don.x.coords, acc.o.coords), vector(don.x.coords, don.c.coords)
        acc_angle, don_angle = vecangle(vec1, vec2), vecangle(vec3, vec4)
        is_sidechain_hal = acc.o.OBAtom.GetResidue().GetAtomProperty(acc.o.OBAtom, 8)  # Check if sidechain atom
        if not config.HALOGEN_ACC_ANGLE - config.HALOGEN_ANGLE_DEV < acc_angle \
                < config.HALOGEN_ACC_ANGLE + config.HALOGEN_ANGLE_DEV:
            continue
        if not config.HALOGEN_DON_ANGLE - config.HALOGEN_ANGLE_DEV < don_angle \
                < config.HALOGEN_DON_ANGLE + config.HALOGEN_ANGLE_DEV:
            continue
        restype, reschain, resnr = whichrestype(acc.o), whichchain(acc.o), whichresnumber(acc.o)
        restype_l, reschain_l, resnr_l = whichrestype(don.orig_x), whichchain(don.orig_x), whichresnumber(don.orig_x)
        contact = data(acc=acc, acc_orig_idx=acc.o_orig_idx, don=don, don_orig_idx=don.x_orig_idx,
                       distance=dist, don_angle=don_angle, acc_angle=acc_angle,
                       restype=restype, resnr=resnr,
                       reschain=reschain, restype_l=restype_l,
                       reschain_l=reschain_l, resnr_l=resnr_l, donortype=don.x.OBAtom.GetType(), acctype=acc.o.type,
                       sidechain=is_sidechain_hal)
        pairings.append(contact)
    return filter_contacts(pairings)


Instruction:
Write a Python 3 function for
finding all metal complexes between metals and appropriate groups in both protein and ligand as well as water

Response:
def metal_complexation(metals, metal_binding_lig, metal_binding_bs):
    """Find all metal complexes between metals and appropriate groups in both protein and ligand, as well as water"""
    data = namedtuple('metal_complex', 'metal metal_orig_idx metal_type target target_orig_idx target_type '
                                       'coordination_num distance resnr restype '
                                       'reschain  restype_l reschain_l resnr_l location rms, geometry num_partners complexnum')
    pairings_dict = {}
    pairings = []
    # #@todo Refactor
    metal_to_id = {}
    metal_to_orig_atom = {}
    for metal, target in itertools.product(metals, metal_binding_lig + metal_binding_bs):
        distance = euclidean3d(metal.m.coords, target.atom.coords)
        if not distance < config.METAL_DIST_MAX:
            continue
        if metal.m not in pairings_dict:
            pairings_dict[metal.m] = [(target, distance), ]
            metal_to_id[metal.m] = metal.m_orig_idx
            metal_to_orig_atom[metal.m] = metal.orig_m
        else:
            pairings_dict[metal.m].append((target, distance))
    for cnum, metal in enumerate(pairings_dict):
        rms = 0.0
        excluded = []
        # cnum +1 being the complex number
        contact_pairs = pairings_dict[metal]
        num_targets = len(contact_pairs)
        vectors_dict = defaultdict(list)
        for contact_pair in contact_pairs:
            target, distance = contact_pair
            vectors_dict[target.atom.idx].append(vector(metal.coords, target.atom.coords))

        # Listing of coordination numbers and their geometries
        configs = {2: ['linear', ],
                   3: ['trigonal.planar', 'trigonal.pyramidal'],
                   4: ['tetrahedral', 'square.planar'],
                   5: ['trigonal.bipyramidal', 'square.pyramidal'],
                   6: ['octahedral', ]}

        # Angle signatures for each geometry (as seen from each target atom)
        ideal_angles = {'linear': [[180.0]] * 2,
                        'trigonal.planar': [[120.0, 120.0]] * 3,
                        'trigonal.pyramidal': [[109.5, 109.5]] * 3,
                        'tetrahedral': [[109.5, 109.5, 109.5, 109.5]] * 4,
                        'square.planar': [[90.0, 90.0, 90.0, 90.0]] * 4,
                        'trigonal.bipyramidal': [[120.0, 120.0, 90.0, 90.0]] * 3 + [[90.0, 90.0, 90.0, 180.0]] * 2,
                        'square.pyramidal': [[90.0, 90.0, 90.0, 180.0]] * 4 + [[90.0, 90.0, 90.0, 90.0]],
                        'octahedral': [[90.0, 90.0, 90.0, 90.0, 180.0]] * 6}
        angles_dict = {}

        for target in vectors_dict:
            cur_vector = vectors_dict[target]
            other_vectors = []
            for t in vectors_dict:
                if not t == target:
                    [other_vectors.append(x) for x in vectors_dict[t]]
            angles = [vecangle(pair[0], pair[1]) for pair in itertools.product(cur_vector, other_vectors)]
            angles_dict[target] = angles

        all_total = []  # Record fit information for each geometry tested
        gdata = namedtuple('gdata', 'geometry rms coordination excluded diff_targets')  # Geometry Data
        # Can't specify geometry with only one target
        if num_targets == 1:
            final_geom = 'NA'
            final_coo = 1
            excluded = []
            rms = 0.0
        else:
            for coo in sorted(configs, reverse=True):  # Start with highest coordination number
                geometries = configs[coo]
                for geometry in geometries:
                    signature = ideal_angles[geometry]  # Set of ideal angles for geometry, from each perspective
                    geometry_total = 0
                    geometry_scores = []  # All scores for one geometry (from all subsignatures)
                    used_up_targets = []  # Use each target just once for a subsignature
                    not_used = []
                    coo_diff = num_targets - coo  # How many more observed targets are there?

                    # Find best match for each subsignature
                    for subsignature in signature:  # Ideal angles from one perspective
                        best_target = None  # There's one best-matching target for each subsignature
                        best_target_score = 999

                        for k, target in enumerate(angles_dict):
                            if target not in used_up_targets:
                                observed_angles = angles_dict[target]  # Observed angles from perspective of one target
                                single_target_scores = []
                                used_up_observed_angles = []
                                for i, ideal_angle in enumerate(subsignature):
                                    # For each angle in the signature, find the best-matching observed angle
                                    best_match = None
                                    best_match_diff = 999
                                    for j, observed_angle in enumerate(observed_angles):
                                        if j not in used_up_observed_angles:
                                            diff = abs(ideal_angle - observed_angle)
                                            if diff < best_match_diff:
                                                best_match_diff = diff
                                                best_match = j
                                    if best_match is not None:
                                        used_up_observed_angles.append(best_match)
                                        single_target_scores.append(best_match_diff)
                                # Calculate RMS for target angles
                                target_total = sum([x ** 2 for x in single_target_scores]) ** 0.5  # Tot. score targ/sig
                                if target_total < best_target_score:
                                    best_target_score = target_total
                                    best_target = target

                        used_up_targets.append(best_target)
                        geometry_scores.append(best_target_score)
                        # Total score is mean of RMS values
                        geometry_total = np.mean(geometry_scores)
                    # Record the targets not used for excluding them when deciding for a final geometry
                    [not_used.append(target) for target in angles_dict if target not in used_up_targets]
                    all_total.append(gdata(geometry=geometry, rms=geometry_total, coordination=coo,
                                           excluded=not_used, diff_targets=coo_diff))

        # Make a decision here. Starting with the geometry with lowest difference in ideal and observed partners ...
        # Check if the difference between the RMS to the next best solution is not larger than 0.5
        if not num_targets == 1:  # Can't decide for any geoemtry in that case
            all_total = sorted(all_total, key=lambda x: abs(x.diff_targets))
            for i, total in enumerate(all_total):
                next_total = all_total[i + 1]
                this_rms, next_rms = total.rms, next_total.rms
                diff_to_next = next_rms - this_rms
                if diff_to_next > 0.5:
                    final_geom, final_coo, rms, excluded = total.geometry, total.coordination, total.rms, total.excluded
                    break
                elif next_total.rms < 3.5:
                    final_geom, final_coo, = next_total.geometry, next_total.coordination
                    rms, excluded = next_total.rms, next_total.excluded
                    break
                elif i == len(all_total) - 2:
                    final_geom, final_coo, rms, excluded = "NA", "NA", float('nan'), []
                    break

        # Record all contact pairing, excluding those with targets superfluous for chosen geometry
        only_water = set([x[0].location for x in contact_pairs]) == {'water'}
        if not only_water:  # No complex if just with water as targets
            write_message("Metal ion %s complexed with %s geometry (coo. number %r/ %i observed).\n"
                          % (metal.type, final_geom, final_coo, num_targets), indent=True)
            for contact_pair in contact_pairs:
                target, distance = contact_pair
                if target.atom.idx not in excluded:
                    metal_orig_atom = metal_to_orig_atom[metal]
                    restype_l, reschain_l, resnr_l = whichrestype(metal_orig_atom), whichchain(
                        metal_orig_atom), whichresnumber(metal_orig_atom)
                    contact = data(metal=metal, metal_orig_idx=metal_to_id[metal], metal_type=metal.type,
                                   target=target, target_orig_idx=target.atom_orig_idx, target_type=target.type,
                                   coordination_num=final_coo, distance=distance, resnr=target.resnr,
                                   restype=target.restype, reschain=target.reschain, location=target.location,
                                   rms=rms, geometry=final_geom, num_partners=num_targets, complexnum=cnum + 1,
                                   resnr_l=resnr_l, restype_l=restype_l, reschain_l=reschain_l)
                    pairings.append(contact)
    return filter_contacts(pairings)


Instruction:
Explain what the following Python 3 code does
def getdata(self, tree, location, force_string=False):
        found = tree.xpath('%s/text()' % location)
        if not found:
            return None
        else:
            data = found[0]
        if force_string:
            return data
        if data == 'True':
            return True
        elif data == 'False':
            return False
        else:
            try:
                return int(data)
            except ValueError:
                try:
                    return float(data)
                except ValueError:
                    # It's a string
                    return data

Response: Gets XML data from a specific element and handles types.


Instruction:
How would you code a function in Python 3 to
get coordinates from a specific element in PLIP XML

Response:
def getcoordinates(self, tree, location):
        """Gets coordinates from a specific element in PLIP XML"""
        return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))


Instruction:
Can you generate the documentation for the following Python 3 function
def get_atom_mapping(self):
        # Atom mappings
        smiles_to_pdb_mapping = self.bindingsite.xpath('mappings/smiles_to_pdb/text()')
        if smiles_to_pdb_mapping == []:
            self.mappings = {'smiles_to_pdb': None, 'pdb_to_smiles': None}
        else:
            smiles_to_pdb_mapping = {int(y[0]): int(y[1]) for y in [x.split(':')
                                                                    for x in smiles_to_pdb_mapping[0].split(',')]}
            self.mappings = {'smiles_to_pdb': smiles_to_pdb_mapping}
            self.mappings['pdb_to_smiles'] = {v: k for k, v in self.mappings['smiles_to_pdb'].items()}

Response: Parses the ligand atom mapping.


Instruction:
Implement a Python 3 function for
counting the interaction types and backbone hydrogen bonding in a binding site

Response:
def get_counts(self):
        """counts the interaction types and backbone hydrogen bonding in a binding site"""

        hbondsback = len([hb for hb in self.hbonds if not hb.sidechain])
        counts = {'hydrophobics': len(self.hydrophobics), 'hbonds': len(self.hbonds),
                  'wbridges': len(self.wbridges), 'sbridges': len(self.sbridges), 'pistacks': len(self.pi_stacks),
                  'pications': len(self.pi_cations), 'halogens': len(self.halogens), 'metal': len(self.metal_complexes),
                  'hbond_back': hbondsback, 'hbond_nonback': (len(self.hbonds) - hbondsback)}
        counts['total'] = counts['hydrophobics'] + counts['hbonds'] + counts['wbridges'] + \
            counts['sbridges'] + counts['pistacks'] + counts['pications'] + counts['halogens'] + counts['metal']
        return counts


Instruction:
Write a Python 3 function that can
load and parses an XML resource and saves it as a tree if successful

Response:
def load_data(self, pdbid):
        """Loads and parses an XML resource and saves it as a tree if successful"""
        f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower())
        self.doc = etree.parse(f)


Instruction:
How would you code a function in Python 3 to
write your forwards methods here.

Response:
def forwards(self, orm):
        "Write your forwards methods here."
        for a in orm.Article.objects.all():
            if a.updated:
                a.last_updated = a.updated
                a.save(force_update=True)


Instruction:
Given the following Python 3 function, write the documentation
def check_pdb_status(pdbid):
    url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid
    xmlf = urlopen(url)
    xml = et.parse(xmlf)
    xmlf.close()
    status = None
    current_pdbid = pdbid
    for df in xml.xpath('//record'):
        status = df.attrib['status']  # Status of an entry can be either 'UNKWOWN', 'OBSOLETE', or 'CURRENT'
        if status == 'OBSOLETE':
            current_pdbid = df.attrib['replacedBy']  # Contains the up-to-date PDB ID for obsolete entries
    return [status, current_pdbid.lower()]

Response: Returns the status and up - to - date entry in the PDB for a given PDB ID


Instruction:
Can you write a function in Python 3 where it
gets the newest entry from the RCSB server for the given PDB ID. Exits with 1 if the given PDB ID is invalid.

Response:
def fetch_pdb(pdbid):
    """Get the newest entry from the RCSB server for the given PDB ID. Exits with '1' if PDB ID is invalid."""
    pdbid = pdbid.lower()
    write_message('\nChecking status of PDB ID %s ... ' % pdbid)
    state, current_entry = check_pdb_status(pdbid)  # Get state and current PDB ID

    if state == 'OBSOLETE':
        write_message('entry is obsolete, getting %s instead.\n' % current_entry)
    elif state == 'CURRENT':
        write_message('entry is up to date.\n')
    elif state == 'UNKNOWN':
        sysexit(3, 'Invalid PDB ID (Entry does not exist on PDB server)\n')
    write_message('Downloading file from PDB ... ')
    pdburl = 'http://www.rcsb.org/pdb/files/%s.pdb' % current_entry  # Get URL for current entry
    try:
        pdbfile = urlopen(pdburl).read().decode()
        # If no PDB file is available, a text is now shown with "We're sorry, but ..."
        # Could previously be distinguished by an HTTP error
        if 'sorry' in pdbfile:
            sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n")
    except HTTPError:
        sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n")
    return [pdbfile, current_entry]


Instruction:
Create a Python 3 function for
getting the active position for given position name.

Response:
def get_active_position(self, category, name, nofallback=False):
        """
        Get active position for given position name.

        params:
            category - Category model to look for
            name - name of the position
            nofallback - if True than do not fall back to parent
                        category if active position is not found for category
        """
        now = timezone.now()
        lookup = (Q(active_from__isnull=True) | Q(active_from__lte=now)) & \
                 (Q(active_till__isnull=True) | Q(active_till__gt=now))

        while True:
            try:
                return self.get(lookup, category=category, name=name,
                    disabled=False)
            except Position.DoesNotExist:
                # if nofallback was specified, do not look into parent categories
                if nofallback:
                    return False

                # traverse the category tree to the top otherwise
                category = category.tree_parent

                # we reached the top and still haven't found the position - return
                if category is None:
                    return False


Instruction:
Make a summary of the following Python 3 code
def set_initial_representations(self):
        self.standard_settings()
        cmd.set('dash_gap', 0)  # Show not dashes, but lines for the pliprofiler
        cmd.set('ray_shadow', 0)  # Turn on ray shadows for clearer ray-traced images
        cmd.set('cartoon_color', 'mylightblue')

        # Set clipping planes for full view
        cmd.clip('far', -1000)
        cmd.clip('near', 1000)

Response: Set initial representations for the current system


Instruction:
Explain what the following Python 3 code does
def standard_settings(self):
        cmd.set('bg_rgb', [1.0, 1.0, 1.0])  # White background
        cmd.set('depth_cue', 0)  # Turn off depth cueing (no fog)
        cmd.set('cartoon_side_chain_helper', 1)  # Improve combined visualization of sticks and cartoon
        cmd.set('cartoon_fancy_helices', 1)  # Nicer visualization of helices (using tapered ends)
        cmd.set('transparency_mode', 1)  # Turn on multilayer transparency
        cmd.set('dash_radius', 0.05)
        self.set_custom_colorset()

Response: Sets up standard settings for a nice visualization.


Instruction:
Implement a Python 3 function for
defining a colorset with matching colors. Provided by Joachim.

Response:
def set_custom_colorset(self):
        """Defines a colorset with matching colors. Provided by Joachim."""
        cmd.set_color('myorange', '[253, 174, 97]')
        cmd.set_color('mygreen', '[171, 221, 164]')
        cmd.set_color('myred', '[215, 25, 28]')
        cmd.set_color('myblue', '[43, 131, 186]')
        cmd.set_color('mylightblue', '[158, 202, 225]')
        cmd.set_color('mylightgreen', '[229, 245, 224]')


Instruction:
Write a Python 3 script to
visualize pi - stacking interactions.

Response:
def show_stacking(self):
        """Visualize pi-stacking interactions."""
        stacks = self.plcomplex.pistacking
        for i, stack in enumerate(stacks):
            pires_ids = '+'.join(map(str, stack.proteinring_atoms))
            pilig_ids = '+'.join(map(str, stack.ligandring_atoms))
            cmd.select('StackRings-P', 'StackRings-P or (id %s & %s)' % (pires_ids, self.protname))
            cmd.select('StackRings-L', 'StackRings-L or (id %s & %s)' % (pilig_ids, self.ligname))
            cmd.select('StackRings-P', 'byres StackRings-P')
            cmd.show('sticks', 'StackRings-P')

            cmd.pseudoatom('ps-pistack-1-%i' % i, pos=stack.proteinring_center)
            cmd.pseudoatom('ps-pistack-2-%i' % i, pos=stack.ligandring_center)
            cmd.pseudoatom('Centroids-P', pos=stack.proteinring_center)
            cmd.pseudoatom('Centroids-L', pos=stack.ligandring_center)

            if stack.type == 'P':
                cmd.distance('PiStackingP', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i)
            if stack.type == 'T':
                cmd.distance('PiStackingT', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i)
        if self.object_exists('PiStackingP'):
            cmd.set('dash_color', 'green', 'PiStackingP')
            cmd.set('dash_gap', 0.3, 'PiStackingP')
            cmd.set('dash_length', 0.6, 'PiStackingP')
        if self.object_exists('PiStackingT'):
            cmd.set('dash_color', 'smudge', 'PiStackingT')
            cmd.set('dash_gap', 0.3, 'PiStackingT')
            cmd.set('dash_length', 0.6, 'PiStackingT')


Instruction:
Write a Python 3 function that can
visualize cation - pi interactions.

Response:
def show_cationpi(self):
        """Visualize cation-pi interactions."""
        for i, p in enumerate(self.plcomplex.pication):
            cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center)
            cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center)
            if p.protcharged:
                cmd.pseudoatom('Chargecenter-P', pos=p.charge_center)
                cmd.pseudoatom('Centroids-L', pos=p.ring_center)
                pilig_ids = '+'.join(map(str, p.ring_atoms))
                cmd.select('PiCatRing-L', 'PiCatRing-L or (id %s & %s)' % (pilig_ids, self.ligname))
                for a in p.charge_atoms:
                    cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (a, self.protname))
            else:
                cmd.pseudoatom('Chargecenter-L', pos=p.charge_center)
                cmd.pseudoatom('Centroids-P', pos=p.ring_center)
                pires_ids = '+'.join(map(str, p.ring_atoms))
                cmd.select('PiCatRing-P', 'PiCatRing-P or (id %s & %s)' % (pires_ids, self.protname))
                for a in p.charge_atoms:
                    cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (a, self.ligname))
            cmd.distance('PiCation', 'ps-picat-1-%i' % i, 'ps-picat-2-%i' % i)
        if self.object_exists('PiCation'):
            cmd.set('dash_color', 'orange', 'PiCation')
            cmd.set('dash_gap', 0.3, 'PiCation')
            cmd.set('dash_length', 0.6, 'PiCation')


Instruction:
Make a summary of the following Python 3 code
def selections_cleanup(self):

        if not len(self.plcomplex.unpaired_hba_idx) == 0:
            self.select_by_ids('Unpaired-HBA', self.plcomplex.unpaired_hba_idx, selection_exists=True)
        if not len(self.plcomplex.unpaired_hbd_idx) == 0:
            self.select_by_ids('Unpaired-HBD', self.plcomplex.unpaired_hbd_idx, selection_exists=True)
        if not len(self.plcomplex.unpaired_hal_idx) == 0:
            self.select_by_ids('Unpaired-HAL', self.plcomplex.unpaired_hal_idx, selection_exists=True)

        selections = cmd.get_names("selections")
        for selection in selections:
            try:
                empty = len(cmd.get_model(selection).atom) == 0
            except:
                empty = True
            if empty:
                cmd.delete(selection)
        cmd.deselect()
        cmd.delete('tmp*')
        cmd.delete('ps-*')

Response: Cleans up non - used selections


Instruction:
Here you have a function in Python 3, explain what it does
def additional_cleanup(self):

        cmd.remove('not alt ""+A')  # Remove alternate conformations
        cmd.hide('labels', 'Interactions')  # Hide labels of lines
        cmd.disable('%sCartoon' % self.protname)
        cmd.hide('everything', 'hydrogens')

Response: Cleanup of various representations


Instruction:
Here you have a function in Python 3, explain what it does
def zoom_to_ligand(self):
        cmd.center(self.ligname)
        cmd.orient(self.ligname)
        cmd.turn('x', 110)  # If the ligand is aligned with the longest axis, aromatic rings are hidden
        if 'AllBSRes' in cmd.get_names("selections"):
            cmd.zoom('%s or AllBSRes' % self.ligname, 3)
        else:
            if self.object_exists(self.ligname):
                cmd.zoom(self.ligname, 3)
        cmd.origin(self.ligname)

Response: Zoom in too ligand and its interactions.


Instruction:
Write a Python 3 script for
saving a PyMOL session file.

Response:
def save_session(self, outfolder, override=None):
        """Saves a PyMOL session file."""
        filename = '%s_%s' % (self.protname.upper(), "_".join(
            [self.hetid, self.plcomplex.chain, self.plcomplex.position]))
        if override is not None:
            filename = override
        cmd.save("/".join([outfolder, "%s.pse" % filename]))


Instruction:
How would you explain what the following Python 3 function does
def save_picture(self, outfolder, filename):
        self.set_fancy_ray()
        self.png_workaround("/".join([outfolder, filename]))

Response: Saves a picture of the current object to the given folder.


Instruction:
Can you create a Python 3 function that
gives the molecules a flat modern look.

Response:
def set_fancy_ray(self):
        """Give the molecule a flat, modern look."""
        cmd.set('light_count', 6)
        cmd.set('spec_count', 1.5)
        cmd.set('shininess', 4)
        cmd.set('specular', 0.3)
        cmd.set('reflect', 1.6)
        cmd.set('ambient', 0)
        cmd.set('direct', 0)
        cmd.set('ray_shadow', 0)  # Gives the molecules a flat, modern look
        cmd.set('ambient_occlusion_mode', 1)
        cmd.set('ray_opaque_background', 0)


Instruction:
Write a Python 3 script to
adapt visualization for peptide ligands and interchain contacts

Response:
def adapt_for_peptides(self):
        """Adapt visualization for peptide ligands and interchain contacts"""
        cmd.hide('sticks', self.ligname)
        cmd.set('cartoon_color', 'lightorange', self.ligname)
        cmd.show('cartoon', self.ligname)
        cmd.show('sticks', "byres *-L")
        cmd.util.cnc(self.ligname)
        cmd.remove('%sCartoon and chain %s' % (self.protname, self.plcomplex.chain))
        cmd.set('cartoon_side_chain_helper', 0)


Instruction:
Write a Python 3 script for
showing refinements for the visualization

Response:
def refinements(self):
        """Refinements for the visualization"""

        # Show sticks for all residues interacing with the ligand
        cmd.select('AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or '
                               'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)')
        cmd.show('sticks', 'AllBSRes')
        # Show spheres for the ring centroids
        cmd.hide('everything', 'centroids*')
        cmd.show('nb_spheres', 'centroids*')
        # Show spheres for centers of charge
        if self.object_exists('Chargecenter-P') or self.object_exists('Chargecenter-L'):
            cmd.hide('nonbonded', 'chargecenter*')
            cmd.show('spheres', 'chargecenter*')
            cmd.set('sphere_scale', 0.4, 'chargecenter*')
            cmd.color('yellow', 'chargecenter*')

        cmd.set('valence', 1)  # Show bond valency (e.g. double bonds)
        # Optional cartoon representation of the protein
        cmd.copy('%sCartoon' % self.protname, self.protname)
        cmd.show('cartoon', '%sCartoon' % self.protname)
        cmd.show('sticks', '%sCartoon' % self.protname)
        cmd.set('stick_transparency', 1, '%sCartoon' % self.protname)

        # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein
        cmd.set('sphere_scale', 0.2, 'resn HOH or Water')  # Needs to be done here because of the copy made
        cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)')

        if 'Centroids*' in cmd.get_names("selections"):
            cmd.color('grey80', 'Centroids*')
        cmd.hide('spheres', '%sCartoon' % self.protname)
        cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname)  # Hide DNA/RNA Cartoon
        if self.ligname == 'SF4':  # Special case for iron-sulfur clusters, can't be visualized with sticks
            cmd.show('spheres', '%s' % self.ligname)

        cmd.hide('everything', 'resn HOH &!Water')  # Hide all non-interacting water molecules
        cmd.hide('sticks', '%s and !%s and !AllBSRes' %
                 (self.protname, self.ligname))  # Hide all non-interacting residues

        if self.ligandtype in ['PEPTIDE', 'INTRA']:
            self.adapt_for_peptides()

        if self.ligandtype == 'INTRA':
            self.adapt_for_intra()


Instruction:
Write a Python 3 script for
getting a cached object for the given model. If the object does not exist in the cache create it.

Response:
def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs):
    """
    Return a cached object. If the object does not exist in the cache, create it.

    Params:
        model - ContentType instance representing the model's class or the model class itself
        timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT
        **kwargs - lookup parameters for content_type.get_object_for_this_type and for key creation

    Throws:
        model.DoesNotExist is propagated from content_type.get_object_for_this_type
    """
    if not isinstance(model, ContentType):
        model_ct = ContentType.objects.get_for_model(model)
    else:
        model_ct = model

    key = _get_key(KEY_PREFIX, model_ct, **kwargs)

    obj = cache.get(key)
    if obj is None:
        # if we are looking for a publishable, fetch just the actual content
        # type and then fetch the actual object
        if model_ct.app_label == 'core' and model_ct.model == 'publishable':
            actual_ct_id = model_ct.model_class()._default_manager.values('content_type_id').get(**kwargs)['content_type_id']
            model_ct = ContentType.objects.get_for_id(actual_ct_id)

        # fetch the actual object we want
        obj = model_ct.model_class()._default_manager.get(**kwargs)

        # since 99% of lookups are done via PK make sure we set the cache for
        # that lookup even if we retrieved it using a different one.
        if 'pk' in kwargs:
            cache.set(key, obj, timeout)
        elif not isinstance(cache, DummyCache):
            cache.set_many({key: obj, _get_key(KEY_PREFIX, model_ct, pk=obj.pk): obj}, timeout=timeout)

    return obj


Instruction:
Write a Python 3 function that can
get a list of objects with given PKs using cache.

Response:
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE):
    """
    Return a list of objects with given PKs using cache.

    Params:
        pks - list of Primary Key values to look up or list of content_type_id, pk tuples
        model - ContentType instance representing the model's class or the model class itself
        timeout - TTL for the items in cache, defaults to CACHE_TIMEOUT

    Throws:
        model.DoesNotExist is propagated from content_type.get_object_for_this_type
    """
    if model is not None:
        if not isinstance(model, ContentType):
            model = ContentType.objects.get_for_model(model)
        pks = [(model, pk) for pk in pks]
    else:
        pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks]

    keys = [_get_key(KEY_PREFIX, model, pk=pk) for (model, pk) in pks]

    cached = cache.get_many(keys)

    # keys not in cache
    keys_to_set = set(keys) - set(cached.keys())
    if keys_to_set:
        # build lookup to get model and pks from the key
        lookup = dict(zip(keys, pks))

        to_get = {}
        # group lookups by CT so we can do in_bulk
        for k in keys_to_set:
            ct, pk = lookup[k]
            to_get.setdefault(ct, {})[int(pk)] = k

        # take out all the publishables
        publishable_ct = ContentType.objects.get_for_model(get_model('core', 'publishable'))
        if publishable_ct in to_get:
            publishable_keys = to_get.pop(publishable_ct)
            models = publishable_ct.model_class()._default_manager.values('content_type_id', 'id').filter(id__in=publishable_keys.keys())
            for m in models:
                ct = ContentType.objects.get_for_id(m['content_type_id'])
                pk = m['id']
                # and put them back as their native content_type
                to_get.setdefault(ct, {})[pk] = publishable_keys[pk]

        to_set = {}
        # retrieve all the models from DB
        for ct, vals in to_get.items():
            models = ct.model_class()._default_manager.in_bulk(vals.keys())
            for pk, m in models.items():
                k = vals[pk]
                cached[k] = to_set[k] = m

        if not isinstance(cache, DummyCache):
            # write them into cache
            cache.set_many(to_set, timeout=timeout)

    out = []
    for k in keys:
        try:
            out.append(cached[k])
        except KeyError:
            if missing == NONE:
                out.append(None)
            elif missing == SKIP:
                pass
            elif missing == RAISE:
                ct = ContentType.objects.get_for_id(int(k.split(':')[1]))
                raise ct.model_class().DoesNotExist(
                    '%s matching query does not exist.' % ct.model_class()._meta.object_name)
    return out


Instruction:
How would you implement a function in Python 3 that
gets the object from the cache or raise Http404

Response:
def get_cached_object_or_404(model, timeout=CACHE_TIMEOUT, **kwargs):
    """
    Shortcut that will raise Http404 if there is no object matching the query

    see get_cached_object for params description
    """
    try:
        return get_cached_object(model, timeout=timeout, **kwargs)
    except ObjectDoesNotExist, e:
        raise Http404('Reason: %s' % str(e))


Instruction:
Make a summary of the following Python 3 code
def tmpfile(prefix, direc):
    return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)

Response: Returns the path to a newly created temporary file.


Instruction:
Given the following Python 3 function, write the documentation
def extract_pdbid(string):
    p = re.compile("[0-9][0-9a-z]{3}")
    m = p.search(string.lower())
    try:
        return m.group()
    except AttributeError:
        return "UnknownProtein"

Response: Use regular expressions to get a PDB ID from a string


Instruction:
Can you generate the documentation for the following Python 3 function
def whichrestype(atom):
    atom = atom if not isinstance(atom, Atom) else atom.OBAtom  # Convert to OpenBabel Atom
    return atom.GetResidue().GetName() if atom.GetResidue() is not None else None

Response: Returns the residue name of an Pybel or OpenBabel atom.


Instruction:
Write a Python 3 script for
returning the residue number of an Pybel or OpenBabel atom.

Response:
def whichresnumber(atom):
    """Returns the residue number of an Pybel or OpenBabel atom (numbering as in original PDB file)."""
    atom = atom if not isinstance(atom, Atom) else atom.OBAtom  # Convert to OpenBabel Atom
    return atom.GetResidue().GetNum() if atom.GetResidue() is not None else None


Instruction:
How would you implement a function in Python 3 that
returns the residue number of an PyBel or OpenBabel atom.

Response:
def whichchain(atom):
    """Returns the residue number of an PyBel or OpenBabel atom."""
    atom = atom if not isinstance(atom, Atom) else atom.OBAtom  # Convert to OpenBabel Atom
    return atom.GetResidue().GetChain() if atom.GetResidue() is not None else None


Instruction:
Can you generate a brief explanation for the following Python 3 code
def euclidean3d(v1, v2):
    if not len(v1) == 3 and len(v2) == 3:
        print("Vectors are not in 3D space. Returning None.")
        return None
    return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)

Response: Faster implementation of euclidean distance for the 3D case.


Instruction:
Implement a function in Python 3 to
vector from p1 to p2.

Response:
def vector(p1, p2):
    """Vector from p1 to p2.
    :param p1: coordinates of point p1
    :param p2: coordinates of point p2
    :returns : numpy array with vector coordinates
    """
    return None if len(p1) != len(p2) else np.array([p2[i] - p1[i] for i in range(len(p1))])


Instruction:
Explain what the following Python 3 code does
def vecangle(v1, v2, deg=True):
    if np.array_equal(v1, v2):
        return 0.0
    dm = np.dot(v1, v2)
    cm = np.linalg.norm(v1) * np.linalg.norm(v2)
    angle = np.arccos(round(dm / cm, 10))  # Round here to prevent floating point errors
    return np.degrees([angle, ])[0] if deg else angle

Response: Calculate the angle between two vectors


Instruction:
Here you have a function in Python 3, explain what it does
def normalize_vector(v):
    norm = np.linalg.norm(v)
    return v/norm if not norm == 0 else v

Response: Take a vector and return the normalized vector


Instruction:
How would you explain what the following Python 3 function does
def centroid(coo):
    return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo]))))

Response: Calculates the centroid from a 3D point cloud and returns the coordinates


Instruction:
Write a Python 3 function for
giving a list of doubles this function returns a list of tuples that are clusters of the elements in the list if they share one element .

Response:
def cluster_doubles(double_list):
    """Given a list of doubles, they are clustered if they share one element
    :param double_list: list of doubles
    :returns : list of clusters (tuples)
    """
    location = {}  # hashtable of which cluster each element is in
    clusters = []
    # Go through each double
    for t in double_list:
        a, b = t[0], t[1]
        # If they both are already in different clusters, merge the clusters
        if a in location and b in location:
            if location[a] != location[b]:
                if location[a] < location[b]:
                    clusters[location[a]] = clusters[location[a]].union(clusters[location[b]])  # Merge clusters
                    clusters = clusters[:location[b]] + clusters[location[b]+1:]
                else:
                    clusters[location[b]] = clusters[location[b]].union(clusters[location[a]])  # Merge clusters
                    clusters = clusters[:location[a]] + clusters[location[a]+1:]
                # Rebuild index of locations for each element as they have changed now
                location = {}
                for i, cluster in enumerate(clusters):
                    for c in cluster:
                        location[c] = i
        else:
            # If a is already in a cluster, add b to that cluster
            if a in location:
                clusters[location[a]].add(b)
                location[b] = location[a]
            # If b is already in a cluster, add a to that cluster
            if b in location:
                clusters[location[b]].add(a)
                location[a] = location[b]
            # If neither a nor b is in any cluster, create a new one with a and b
            if not (b in location and a in location):
                clusters.append(set(t))
                location[a] = len(clusters) - 1
                location[b] = len(clusters) - 1
    return map(tuple, clusters)


Instruction:
Write a Python 3 script to
create a folder if it does not exists.

Response:
def create_folder_if_not_exists(folder_path):
    """Creates a folder if it does not exists."""
    folder_path = tilde_expansion(folder_path)
    folder_path = "".join([folder_path, '/']) if not folder_path[-1] == '/' else folder_path
    direc = os.path.dirname(folder_path)
    if not folder_exists(direc):
        os.makedirs(direc)


Instruction:
Create a Python 3 function for
initializing PyMOL with the given options.

Response:
def initialize_pymol(options):
    """Initializes PyMOL"""
    import pymol
    # Pass standard arguments of function to prevent PyMOL from printing out PDB headers (workaround)
    pymol.finish_launching(args=['pymol', options, '-K'])
    pymol.cmd.reinitialize()


Instruction:
Implement a function in Python 3 to
start up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.

Response:
def start_pymol(quiet=False, options='-p', run=False):
    """Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output.
    Command line options can be passed as the second argument."""
    import pymol
    pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:]
    if run:
        initialize_pymol(options)
    if quiet:
        pymol.cmd.feedback('disable', 'all', 'everything')


Instruction:
Can you write a function in Python 3 where it
supports for DNA and RNA ligands by finding missing covalent linkages to stitch DNA / RNA together.

Response:
def nucleotide_linkage(residues):
    """Support for DNA/RNA ligands by finding missing covalent linkages to stitch DNA/RNA together."""

    nuc_covalent = []
    #######################################
    # Basic support for RNA/DNA as ligand #
    #######################################
    nucleotides = ['A', 'C', 'T', 'G', 'U', 'DA', 'DC', 'DT', 'DG', 'DU']
    dna_rna = {}  # Dictionary of DNA/RNA residues by chain
    covlinkage = namedtuple("covlinkage", "id1 chain1 pos1 conf1 id2 chain2 pos2 conf2")
    # Create missing covlinkage entries for DNA/RNA
    for ligand in residues:
        resname, chain, pos = ligand
        if resname in nucleotides:
            if chain not in dna_rna:
                dna_rna[chain] = [(resname, pos), ]
            else:
                dna_rna[chain].append((resname, pos))
    for chain in dna_rna:
        nuc_list = dna_rna[chain]
        for i, nucleotide in enumerate(nuc_list):
            if not i == len(nuc_list) - 1:
                name, pos = nucleotide
                nextnucleotide = nuc_list[i + 1]
                nextname, nextpos = nextnucleotide
                newlink = covlinkage(id1=name, chain1=chain, pos1=pos, conf1='',
                                     id2=nextname, chain2=chain, pos2=nextpos, conf2='')
                nuc_covalent.append(newlink)

    return nuc_covalent


Instruction:
Write a Python 3 script for
checking if the ring is sufficiently planar

Response:
def ring_is_planar(ring, r_atoms):
    """Given a set of ring atoms, check if the ring is sufficiently planar
    to be considered aromatic"""
    normals = []
    for a in r_atoms:
        adj = pybel.ob.OBAtomAtomIter(a.OBAtom)
        # Check for neighboring atoms in the ring
        n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)]
        vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1])
        normals.append(np.cross(vec1, vec2))
    # Given all normals of ring atoms and their neighbors, the angle between any has to be 5.0 deg or less
    for n1, n2 in itertools.product(normals, repeat=2):
        arom_angle = vecangle(n1, n2)
        if all([arom_angle > config.AROMATIC_PLANARITY, arom_angle < 180.0 - config.AROMATIC_PLANARITY]):
            return False
    return True


Instruction:
Can you generate the documentation for the following Python 3 function
def classify_by_name(names):
    if len(names) > 3:  # Polymer
        if len(set(config.RNA).intersection(set(names))) != 0:
            ligtype = 'RNA'
        elif len(set(config.DNA).intersection(set(names))) != 0:
            ligtype = 'DNA'
        else:
            ligtype = "POLYMER"
    else:
        ligtype = 'SMALLMOLECULE'

    for name in names:
        if name in config.METAL_IONS:
            if len(names) == 1:
                ligtype = 'ION'
            else:
                if "ION" not in ligtype:
                    ligtype += '+ION'
    return ligtype

Response: Classify a composite ligand by the HETID s.


Instruction:
Make a summary of the following Python 3 code
def sort_members_by_importance(members):
    main = [x for x in members if x[0] not in config.METAL_IONS]
    ion = [x for x in members if x[0] in config.METAL_IONS]
    sorted_main = sorted(main, key=lambda x: (x[1], x[2]))
    sorted_main = sorted(main, key=lambda x: (x[1], x[2]))
    sorted_ion = sorted(ion, key=lambda x: (x[1], x[2]))
    return sorted_main + sorted_ion

Response: Sort the members of a composite ligand according to two criteria.


Instruction:
Explain what the following Python 3 code does
def get_isomorphisms(reference, lig):
    query = pybel.ob.CompileMoleculeQuery(reference.OBMol)
    mappr = pybel.ob.OBIsomorphismMapper.GetInstance(query)
    if all:
        isomorphs = pybel.ob.vvpairUIntUInt()
        mappr.MapAll(lig.OBMol, isomorphs)
    else:
        isomorphs = pybel.ob.vpairUIntUInt()
        mappr.MapFirst(lig.OBMol, isomorphs)
        isomorphs = [isomorphs]
    write_message("Number of isomorphisms: %i\n" % len(isomorphs), mtype='debug')
    # #@todo Check which isomorphism to take
    return isomorphs

Response: Get all isomorphisms of the ligand.


Instruction:
Make a summary of the following Python 3 code
def canonicalize(lig, preserve_bond_order=False):
    atomorder = None
    # Get canonical atom order

    lig = pybel.ob.OBMol(lig.OBMol)
    if not preserve_bond_order:
        for bond in pybel.ob.OBMolBondIter(lig):
            if bond.GetBondOrder() != 1:
                bond.SetBondOrder(1)
    lig.DeleteData(pybel.ob.StereoData)
    lig = pybel.Molecule(lig)
    testcan = lig.write(format='can')
    try:
        pybel.readstring('can', testcan)
        reference = pybel.readstring('can', testcan)
    except IOError:
        testcan, reference = '', ''
    if testcan != '':
        reference.removeh()
        isomorphs = get_isomorphisms(reference, lig)  # isomorphs now holds all isomorphisms within the molecule
        if not len(isomorphs) == 0:
            smi_dict = {}
            smi_to_can = isomorphs[0]
            for x in smi_to_can:
                smi_dict[int(x[1]) + 1] = int(x[0]) + 1
            atomorder = [smi_dict[x + 1] for x in range(len(lig.atoms))]
        else:
            atomorder = None
    return atomorder

Response: Get the canonical atom order for the ligand.


Instruction:
Can you write a function in Python 3 where it
checks if a suspicious number represented as a 32 bit integer returns the actual number.

Response:
def int32_to_negative(int32):
    """Checks if a suspicious number (e.g. ligand position) is in fact a negative number represented as a
    32 bit integer and returns the actual number.
    """
    dct = {}
    if int32 == 4294967295:  # Special case in some structures (note, this is just a workaround)
        return -1
    for i in range(-1000, -1):
        dct[np.uint32(i)] = i
    if int32 in dct:
        return dct[int32]
    else:
        return int32


Instruction:
Make a summary of the following Python 3 code
def read_pdb(pdbfname, as_string=False):
    pybel.ob.obErrorLog.StopLogging()  # Suppress all OpenBabel warnings
    if os.name != 'nt':  # Resource module not available for Windows
        maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1]
        resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize))
    sys.setrecursionlimit(10 ** 5)  # increase Python recoursion limit
    return readmol(pdbfname, as_string=as_string)

Response: Reads a given PDB file and returns a Pybel Molecule.


Instruction:
Can you implement a function in Python 3 that
returns a file handler and detects gzipped files.

Response:
def read(fil):
    """Returns a file handler and detects gzipped files."""
    if os.path.splitext(fil)[-1] == '.gz':
        return gzip.open(fil, 'rb')
    elif os.path.splitext(fil)[-1] == '.zip':
        zf = zipfile.ZipFile(fil, 'r')
        return zf.open(zf.infolist()[0].filename)
    else:
        return open(fil, 'r')


Instruction:
Can you write a function in Python 3 where it
reads the given file and returns the corresponding Pybel molecule as well as the input file type.

Response:
def readmol(path, as_string=False):
    """Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type.
    In contrast to the standard Pybel implementation, the file is closed properly."""
    supported_formats = ['pdb']
    # Fix for Windows-generated files: Remove carriage return characters
    if "\r" in path and as_string:
        path = path.replace('\r', '')

    for sformat in supported_formats:
        obc = pybel.ob.OBConversion()
        obc.SetInFormat(sformat)
        write_message("Detected {} as format. Trying to read file with OpenBabel...\n".format(sformat), mtype='debug')

        # Read molecules with single bond information
        if as_string:
            try:
                mymol = pybel.readstring(sformat, path)
            except IOError:
                sysexit(4, 'No valid file format provided.')
        else:
            read_file = pybel.readfile(format=sformat, filename=path, opt={"s": None})
            try:
                mymol = next(read_file)
            except StopIteration:
                sysexit(4, 'File contains no valid molecules.\n')

        write_message("Molecule successfully read.\n", mtype='debug')

        # Assign multiple bonds
        mymol.OBMol.PerceiveBondOrders()
        return mymol, sformat

    sysexit(4, 'No valid file format provided.')


Instruction:
Explain what the following Python 3 code does
def colorlog(msg, color, bold=False, blink=False):

    # ANSI Escape Codes
    PINK_COL = '\x1b[35m'
    GREEN_COL = '\x1b[32m'
    RED_COL = '\x1b[31m'
    YELLOW_COL = '\x1b[33m'
    BLINK = '\x1b[5m'
    RESET = '\x1b[0m'

    if platform.system() != 'Windows':
        if blink:
            msg = BLINK + msg + RESET
        if color == 'yellow':
            msg = YELLOW_COL + msg + RESET
        if color == 'red':
            msg = RED_COL + msg + RESET
        if color == 'green':
            msg = GREEN_COL + msg + RESET
        if color == 'pink':
            msg = PINK_COL + msg + RESET
    return msg

Response: Colors messages on non-Windows systems supporting ANSI escape.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write_message(msg, indent=False, mtype='standard', caption=False):
    if (mtype == 'debug' and config.DEBUG) or (mtype != 'debug' and config.VERBOSE) or mtype == 'error':
        message(msg, indent=indent, mtype=mtype, caption=caption)

Response: Writes a message to the log file if verbose mode is set.


Instruction:
Can you create a Python 3 function that
writes a message to the log

Response:
def message(msg, indent=False, mtype='standard', caption=False):
    """Writes messages in verbose mode"""
    if caption:
        msg = '\n' + msg + '\n' + '-'*len(msg) + '\n'
    if mtype == 'warning':
        msg = colorlog('Warning:  ' + msg, 'yellow')
    if mtype == 'error':
        msg = colorlog('Error:  ' + msg, 'red')
    if mtype == 'debug':
        msg = colorlog('Debug:  ' + msg, 'pink')
    if mtype == 'info':
        msg = colorlog('Info:  ' + msg, 'green')
    if indent:
        msg = '  ' + msg
    sys.stderr.write(msg)


Instruction:
Can you tell what is the following Python 3 function doing
def do_related(parser, token):
    bits = token.split_contents()
    obj_var, count, var_name, mods, finder = parse_related_tag(bits)
    return RelatedNode(obj_var, count, var_name, mods, finder)

Response: Parse related tag into a context variable optionally specifying related finder.


Instruction:
Implement a Python 3 function for
adding some content type info of self. target

Response:
def PublishableBox(publishable, box_type, nodelist, model=None):
    "add some content type info of self.target"
    if not model:
        model = publishable.content_type.model_class()
    box_class = model.box_class

    if box_class == PublishableBox:
        box_class = Box
    return box_class(publishable, box_type, nodelist, model=model)


Instruction:
Write a Python 3 function that can
delegate the boxing to the target s Box class.

Response:
def ListingBox(listing, *args, **kwargs):
    " Delegate the boxing to the target's Box class. "
    obj = listing.publishable
    return obj.box_class(obj, *args, **kwargs)


Instruction:
How would you explain what the following Python 3 function does
def get_absolute_url(self, domain=False):
        " Get object's URL. "
        category = self.category

        kwargs = {
            'slug': self.slug,
        }

        if self.static:
            kwargs['id'] = self.pk
            if category.tree_parent_id:
                kwargs['category'] = category.tree_path
                url = reverse('static_detail', kwargs=kwargs)
            else:
                url = reverse('home_static_detail', kwargs=kwargs)
        else:
            publish_from = localize(self.publish_from)
            kwargs.update({
                    'year': publish_from.year,
                    'month': publish_from.month,
                    'day': publish_from.day,
                })
            if category.tree_parent_id:
                kwargs['category'] = category.tree_path
                url = reverse('object_detail', kwargs=kwargs)
            else:
                url = reverse('home_object_detail', kwargs=kwargs)

        if category.site_id != settings.SITE_ID or domain:
            return 'http://' + category.site.domain + url
        return url

Response: Get object s URL.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def is_published(self):
        "Return True if the Publishable is currently active."
        cur_time = now()
        return self.published and cur_time > self.publish_from and \
            (self.publish_to is None or cur_time < self.publish_to)

Response: Return True if the Publishable is currently active.


Instruction:
Given the following Python 3 function, write the documentation
def resolve_params(self, text):
        " Parse the parameters into a dict. "
        params = MultiValueDict()
        for line in text.split('\n'):
            pair = line.split(':', 1)
            if len(pair) == 2:
                params.appendlist(pair[0].strip(), pair[1].strip())
        return params

Response: Parse the parameters into a dict.


Instruction:
Can you create a Python 3 function that
prepares the object for the next processing.

Response:
def prepare(self, context):
        """
        Do the pre-processing - render and parse the parameters and
        store them for further use in self.params.
        """
        self.params = {}

        # no params, not even a newline
        if not self.nodelist:
            return

        # just static text, no vars, assume one TextNode
        if not self.nodelist.contains_nontext:
            text = self.nodelist[0].s.strip()

        # vars in params, we have to render
        else:
            context.push()
            context['object'] = self.obj
            text = self.nodelist.render(context)
            context.pop()

        if text:
            self.params = self.resolve_params(text)

        # override the default template from the parameters
        if 'template_name' in self.params:
            self.template_name = self.params['template_name']


Instruction:
Can you write a function in Python 3 where it
gets context to render the template.

Response:
def get_context(self):
        " Get context to render the template. "
        return {
                'content_type_name' : str(self.name),
                'content_type_verbose_name' : self.verbose_name,
                'content_type_verbose_name_plural' : self.verbose_name_plural,
                'object' : self.obj,
                'box' : self,
        }


Instruction:
How would you explain what the following Python 3 function does
def render(self, context):
        self.prepare(context)
        " Cached wrapper around self._render(). "
        if getattr(settings, 'DOUBLE_RENDER', False) and self.can_double_render:
            if 'SECOND_RENDER' not in context:
                return self.double_render()
        key = self.get_cache_key()
        if key:
            rend = cache.get(key)
            if rend is None:
                rend = self._render(context)
                cache.set(key, rend, core_settings.CACHE_TIMEOUT)
        else:
            rend = self._render(context)
        return rend

Response: Cached wrapper around self. _render.


Instruction:
Can you tell what is the following Python 3 function doing
def _get_template_list(self):
        " Get the hierarchy of templates belonging to the object/box_type given. "
        t_list = []
        if hasattr(self.obj, 'category_id') and self.obj.category_id:
            cat = self.obj.category
            base_path = 'box/category/%s/content_type/%s/' % (cat.path, self.name)
            if hasattr(self.obj, 'slug'):
                t_list.append(base_path + '%s/%s.html' % (self.obj.slug, self.box_type,))
            t_list.append(base_path + '%s.html' % (self.box_type,))
            t_list.append(base_path + 'box.html')

        base_path = 'box/content_type/%s/' % self.name
        if hasattr(self.obj, 'slug'):
            t_list.append(base_path + '%s/%s.html' % (self.obj.slug, self.box_type,))
        t_list.append(base_path + '%s.html' % (self.box_type,))
        t_list.append(base_path + 'box.html')

        t_list.append('box/%s.html' % self.box_type)
        t_list.append('box/box.html')

        return t_list

Response: Get the hierarchy of templates belonging to the object / box_type given.


Instruction:
Explain what the following Python 3 code does
def get_cache_key(self):
        " Return a cache key constructed from the box's parameters. "
        if not self.is_model:
            return None

        pars = ''
        if self.params:
            pars = ','.join(':'.join((smart_str(key), smart_str(self.params[key]))) for key in sorted(self.params.keys()))

        return normalize_key('%s:box:%d:%s:%s' % (
                _get_key(KEY_PREFIX, self.ct, pk=self.obj.pk), settings.SITE_ID, str(self.box_type), pars
            ))

Response: Return a cache key constructed from the box s parameters.


Instruction:
Here you have a function in Python 3, explain what it does
def save(self, **kwargs):
        "Override save() to construct tree_path based on the category's parent."
        old_tree_path = self.tree_path
        if self.tree_parent:
            if self.tree_parent.tree_path:
                self.tree_path = '%s/%s' % (self.tree_parent.tree_path, self.slug)
            else:
                self.tree_path = self.slug
        else:
            self.tree_path = ''
        Category.objects.clear_cache()
        super(Category, self).save(**kwargs)
        if old_tree_path != self.tree_path:
            # the tree_path has changed, update children
            children = Category.objects.filter(tree_parent=self)
            for child in children:
                child.save(force_update=True)

Response: Override save () to construct tree_path based on the category s parent.


Instruction:
Make a summary of the following Python 3 code
def get_absolute_url(self):
        if not self.tree_parent_id:
            url = reverse('root_homepage')
        else:
            url = reverse('category_detail', kwargs={'category' : self.tree_path})
        if self.site_id != settings.SITE_ID:
            # prepend the domain if it doesn't match current Site
            return 'http://' + self.site.domain + url
        return url

Response: Returns the absolute URL for the category.