<commit_before>from xml.dom import minidom

BOOKMARK_COLOR_NONE = "-1"
BOOKMARK_COLOR_BLUE = "0"
BOOKMARK_COLOR_GREEN = "1"
BOOKMARK_COLOR_YELLOW = "2"
BOOKMARK_COLOR_ORANGE = "3"
BOOKMARK_COLOR_RED = "4"

LINK_STYLE_NORMAL = "0"
LINK_STYLE_DASHED = "1"
LINK_STYLE_DOTTED = "2"
LINK_STYLE_DASHDOT = "3"

UIM_FATAL = 'FatalError'
UIM_PARTIAL = 'PartialError'
UIM_INFORM = 'Inform'
UIM_DEBUG = 'Debug'

class MaltegoEntity(object):
    value = ""
    weight = 100
    displayInformation = []
    additionalFields = {}
    iconURL = ""
    entityType = "Phrase"

    def __init__(self, eT=None, v=None):
        if (eT is not None):
            self.entityType = eT
        if (v is not None):
            self.value = v
        self.additionalFields = {}
        self.weight = 100
        self.displayInformation = []
        self.iconURL = ""

    def setType(self, eT=None):
        if (eT is not None):
            self.entityType = eT

    def setValue(self, eV=None):
        if (eV is not None):
            self.value = eV

    def setWeight(self, w=None):
        if (w is not None):
            self.weight = w

    def addDisplayInformation(self, di=None, dl='Info'):
        if (di is not None):
            self.displayInformation.append([dl, di])

    def addProperty(self, fieldName=None, displayName=None, matchingRule=False, value=None):
        self.additionalFields[fieldName] = {}
        self.additionalFields[fieldName]['displayName'] = displayName
        self.additionalFields[fieldName]['matchingRule'] = matchingRule
        self.additionalFields[fieldName]['value'] = value

    def setIconURL(self, iU=None):
        if (iU is not None):
            self.iconURL = iU

    def setLinkColor(self, color):
        self.addProperty('link#maltego.link.color', 'LinkColor', '', color)

    def setLinkStyle(self, style):
        self.addProperty('link#maltego.link.style', 'LinkStyle', '', style)

    def setLinkThickness(self, thick):
        self.addProperty('link#maltego.link.thickness', 'Thickness', '', str(thick))

    def setLinkLabel(self, label):
        self.addProperty('link#maltego.link.label', 'Label', '', label)

    def setBookmark(self, bookmark):
        self.addProperty('bookmark#', 'Bookmark', '', bookmark)

    def setNote(self, note):
        self.addProperty('notes#', 'Notes', '', note)

    def returnEntity(self):
        # TODO: replace with programmatic XML generation
        r = ''
        r += "<Entity Type=\"" + str(self.entityType) + "\">"
        r += "<Value>" + str(self.value) + "</Value>"
        r += "<Weight>" + str(self.weight) + "</Weight>"
        if (len(self.displayInformation) > 0):
            r += "<DisplayInformation>"
            for i in range(len(self.displayInformation)):
                r += '<![CDATA[' + str(self.displayInformation[i][1]) + ']]>'
            r += '</DisplayInformation>'
        if (len(self.additionalFields) > 0):
            r += "<AdditionalFields>"
            for field in self.additionalFields:
                if (str(field['matchingRule']) != "strict"):
                    r += "<Field Name=\"" + str(field) + "\" DisplayName=\"" + str(field['displayName']) + "\">" + str(field['value']) + "</Field>"
                else:
                    r += "<Field MatchingRule=\"" + str(self.additionalFields[i][2]) + "\" Name=\"" + str(self.additionalFields[i][0]) + "\" DisplayName=\"" + str(self.additionalFields[i][1]) + "\">" + str(self.additionalFields[i][3]) + "</Field>"
            r += "</AdditionalFields>"
        if (len(self.iconURL) > 0):
            r += "<IconURL>" + self.iconURL + "</IconURL>"
        r += "</Entity>"
        return r

class MaltegoTransform(object):
    # TODO: replace with programmatic XML generation

    def __init__(self):
        self.entities = []
        self.exceptions = []
        self.UIMessages = []

    def addEntity(self, enType=None, enValue=None):
        me = MaltegoEntity(enType, enValue)
        self.entities.append(me)
        return me

    def addUIMessage(self, message, messageType="Inform"):
        self.UIMessages.append([messageType, message])

    def addException(self, exceptionString):
        self.exceptions.append(exceptionString)

    def throwExceptions(self):
        r = ''
        r += "<MaltegoMessage>"
        r += "<MaltegoTransformExceptionMessage>"
        r += "<Exceptions>"

        for i in range(len(self.exceptions)):
            r += "<Exception>" + self.exceptions[i] + "</Exceptions>"
        r += "</Exceptions>"
        r += "</MaltegoTransformExceptionMessage>"
        r += "</MaltegoMessage>"
        return r

    def returnOutput(self):
        r = ''
        r += "<MaltegoMessage>"
        r += "<MaltegoTransformResponseMessage>"

        r += "<Entities>"
        for i in range(len(self.entities)):
            r += self.entities[i].returnEntity()
        r += "</Entities>"

        r += "<UIMessages>"
        for i in range(len(self.UIMessages)):
            r += "<UIMessage MessageType=\"" + \
                self.UIMessages[i][0] + "\">" + self.UIMessages[i][1] + "</UIMessage>"
        r += "</UIMessages>"

        r += "</MaltegoTransformResponseMessage>"
        r += "</MaltegoMessage>"
        return r

class MaltegoMsg:

    def __init__(self, MaltegoXML=""):

        xmldoc = minidom.parseString(MaltegoXML)

        # read the easy stuff like value, limits etc
        self.Value = self.i_getNodeValue(xmldoc, "Value")
        self.Weight = self.i_getNodeValue(xmldoc, "Weight")
        self.Slider = int(
            self.i_getNodeAttributeValue(xmldoc, "Limits", "SoftLimit"))
        self.Type = self.i_getNodeAttributeValue(xmldoc, "Entity", "Type")

        # read additional fields
        Properties = {}
        try:
            AFNodes = xmldoc.getElementsByTagName("AdditionalFields")[0]
            Settings = AFNodes.getElementsByTagName("Field")
            for node in Settings:
                AFName = node.attributes["Name"].value
                AFValue = self.i_getText(node.childNodes)
                Properties[AFName] = AFValue
        except:
            # FIXME: What exceptions are we looking for?!
            pass

        # parse transform settings
        TransformSettings = {}
        try:
            TSNodes = xmldoc.getElementsByTagName("TransformFields")[0]
            Settings = TSNodes.getElementsByTagName("Field")
            for node in Settings:
                TSName = node.attributes["Name"].value
                TSValue = self.i_getText(node.childNodes)
                TransformSettings[TSName] = TSValue
        except:
            # FIXME: What exceptions are we looking for?!
            pass

        # load back into object
        self.Properties = Properties
        self.TransformSettings = TransformSettings

    def i_getText(self, nodelist):
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)

    def i_getNodeValue(self, node, Tag):
        return self.i_getText(node.getElementsByTagName(Tag)[0].childNodes)

    def i_getNodeAttributeValue(self, node, Tag, Attribute):
        return node.getElementsByTagName(Tag)[0].attributes[Attribute].value

    def getProperty(self, skey):
        if skey in self.Properties:
            return self.Properties[skey]
        else:
            return None

    def getTransformSetting(self, skey):
        if skey in self.TransformSettings:
            return self.TransformSettings[skey]
        else:
            return None
<commit_msg>Fix merge conflict again<commit_after>from xml.dom import minidom

BOOKMARK_COLOR_NONE = "-1"
BOOKMARK_COLOR_BLUE = "0"
BOOKMARK_COLOR_GREEN = "1"
BOOKMARK_COLOR_YELLOW = "2"
BOOKMARK_COLOR_ORANGE = "3"
BOOKMARK_COLOR_RED = "4"

LINK_STYLE_NORMAL = "0"
LINK_STYLE_DASHED = "1"
LINK_STYLE_DOTTED = "2"
LINK_STYLE_DASHDOT = "3"

UIM_FATAL = 'FatalError'
UIM_PARTIAL = 'PartialError'
UIM_INFORM = 'Inform'
UIM_DEBUG = 'Debug'

class MaltegoEntity(object):
    value = ""
    weight = 100
    displayInformation = []
    additionalFields = {}
    iconURL = ""
    entityType = "Phrase"

    def __init__(self, eT=None, v=None):
        if (eT is not None):
            self.entityType = eT
        if (v is not None):
            self.value = v
        self.additionalFields = {}
        self.weight = 100
        self.displayInformation = []
        self.iconURL = ""

    def setType(self, eT=None):
        if (eT is not None):
            self.entityType = eT

    def setValue(self, eV=None):
        if (eV is not None):
            self.value = eV

    def setWeight(self, w=None):
        if (w is not None):
            self.weight = w

    def addDisplayInformation(self, di=None, dl='Info'):
        if (di is not None):
            self.displayInformation.append([dl, di])

    def addProperty(self, fieldName=None, displayName=None, matchingRule=False, value=None):
        self.additionalFields[fieldName] = {}
        self.additionalFields[fieldName]['displayName'] = displayName
        self.additionalFields[fieldName]['matchingRule'] = matchingRule
        self.additionalFields[fieldName]['value'] = value

    def setIconURL(self, iU=None):
        if (iU is not None):
            self.iconURL = iU

    def setLinkColor(self, color):
        self.addProperty('link#maltego.link.color', 'LinkColor', '', color)

    def setLinkStyle(self, style):
        self.addProperty('link#maltego.link.style', 'LinkStyle', '', style)

    def setLinkThickness(self, thick):
        self.addProperty('link#maltego.link.thickness', 'Thickness', '', str(thick))

    def setLinkLabel(self, label):
        self.addProperty('link#maltego.link.label', 'Label', '', label)

    def setBookmark(self, bookmark):
        self.addProperty('bookmark#', 'Bookmark', '', bookmark)

    def setNote(self, note):
        self.addProperty('notes#', 'Notes', '', note)

    def returnEntity(self):
        # TODO: replace with programmatic XML generation
        r = ''
        r += "<Entity Type=\"" + str(self.entityType) + "\">"
        r += "<Value>" + unicode(self.value) + "</Value>"
        r += "<Weight>" + str(self.weight) + "</Weight>"
        if (len(self.displayInformation) > 0):
            r += "<DisplayInformation>"
            for i in range(len(self.displayInformation)):
                r += '<![CDATA[' + str(self.displayInformation[i][1]) + ']]>'
            r += '</DisplayInformation>'
        if (len(self.additionalFields) > 0):
            r += "<AdditionalFields>"
            for field in self.additionalFields:
                if (str(field['matchingRule']) != "strict"):
                    r += "<Field Name=\"" + str(field) + "\" DisplayName=\"" + str(field['displayName']) + "\">" + str(field['value']) + "</Field>"
                else:
                    r += "<Field MatchingRule=\"" + str(self.additionalFields[i][2]) + "\" Name=\"" + str(self.additionalFields[i][0]) + "\" DisplayName=\"" + str(self.additionalFields[i][1]) + "\">" + str(self.additionalFields[i][3]) + "</Field>"
            r += "</AdditionalFields>"
        if (len(self.iconURL) > 0):
            r += "<IconURL>" + self.iconURL + "</IconURL>"
        r += "</Entity>"
        return r

class MaltegoTransform(object):
    # TODO: replace with programmatic XML generation

    def __init__(self):
        self.entities = []
        self.exceptions = []
        self.UIMessages = []

    def addEntity(self, enType=None, enValue=None):
        me = MaltegoEntity(enType, enValue)
        self.entities.append(me)
        return me

    def addUIMessage(self, message, messageType="Inform"):
        self.UIMessages.append([messageType, message])

    def addException(self, exceptionString):
        self.exceptions.append(exceptionString)

    def throwExceptions(self):
        r = ''
        r += "<MaltegoMessage>"
        r += "<MaltegoTransformExceptionMessage>"
        r += "<Exceptions>"

        for i in range(len(self.exceptions)):
            r += "<Exception>" + self.exceptions[i] + "</Exceptions>"
        r += "</Exceptions>"
        r += "</MaltegoTransformExceptionMessage>"
        r += "</MaltegoMessage>"
        return r

    def returnOutput(self):
        r = ''
        r += "<MaltegoMessage>"
        r += "<MaltegoTransformResponseMessage>"

        r += "<Entities>"
        for i in range(len(self.entities)):
            r += self.entities[i].returnEntity()
        r += "</Entities>"

        r += "<UIMessages>"
        for i in range(len(self.UIMessages)):
            r += "<UIMessage MessageType=\"" + \
                self.UIMessages[i][0] + "\">" + self.UIMessages[i][1] + "</UIMessage>"
        r += "</UIMessages>"

        r += "</MaltegoTransformResponseMessage>"
        r += "</MaltegoMessage>"
        return r

class MaltegoMsg:

    def __init__(self, MaltegoXML=""):

        xmldoc = minidom.parseString(MaltegoXML)

        # read the easy stuff like value, limits etc
        self.Value = self.i_getNodeValue(xmldoc, "Value")
        self.Weight = self.i_getNodeValue(xmldoc, "Weight")
        self.Slider = int(
            self.i_getNodeAttributeValue(xmldoc, "Limits", "SoftLimit"))
        self.Type = self.i_getNodeAttributeValue(xmldoc, "Entity", "Type")

        # read additional fields
        Properties = {}
        try:
            AFNodes = xmldoc.getElementsByTagName("AdditionalFields")[0]
            Settings = AFNodes.getElementsByTagName("Field")
            for node in Settings:
                AFName = node.attributes["Name"].value
                AFValue = self.i_getText(node.childNodes)
                Properties[AFName] = AFValue
        except:
            # FIXME: What exceptions are we looking for?!
            pass

        # parse transform settings
        TransformSettings = {}
        try:
            TSNodes = xmldoc.getElementsByTagName("TransformFields")[0]
            Settings = TSNodes.getElementsByTagName("Field")
            for node in Settings:
                TSName = node.attributes["Name"].value
                TSValue = self.i_getText(node.childNodes)
                TransformSettings[TSName] = TSValue
        except:
            # FIXME: What exceptions are we looking for?!
            pass

        # load back into object
        self.Properties = Properties
        self.TransformSettings = TransformSettings

    def i_getText(self, nodelist):
        rc = []
        for node in nodelist:
            if node.nodeType == node.TEXT_NODE:
                rc.append(node.data)
        return ''.join(rc)

    def i_getNodeValue(self, node, Tag):
        return self.i_getText(node.getElementsByTagName(Tag)[0].childNodes)

    def i_getNodeAttributeValue(self, node, Tag, Attribute):
        return node.getElementsByTagName(Tag)[0].attributes[Attribute].value

    def getProperty(self, skey):
        if skey in self.Properties:
            return self.Properties[skey]
        else:
            return None

    def getTransformSetting(self, skey):
        if skey in self.TransformSettings:
            return self.TransformSettings[skey]
        else:
            return None
<|endoftext|>


<commit_before>#!/usr/bin/env python
""" A set of classes used for computing the dynamic properties of a Hoomd MD
simulation"""

from __future__ import print_function
import math
import numpy as np
import quaternion
from TransData import TransData, TransRotData
from CompDynamics import CompDynamics, CompRotDynamics

class TimeDep(object):
    """ Class to compute the time dependent characteristics of individual
    particles in a hoomd simulation.

    Args:
        system (system): Hoomd system object which is the initial configuration
            for the purposes of the dynamics calculations
    """
    def __init__(self, system):
        t_init = self._take_snapshot(system)
        self.pos_init = self._unwrap(t_init)
        self.timestep = system.get_metadata()['timestep']

    def _take_snapshot(self, system):
        """ Takes a snapshot of the current configuration of the system

        Args:
            system (system): Hoomd system objet in the configuration to be saved

        Returns:
            Snapshot: An immutable snapshot of the system at the current time
        """
        return system.take_snapshot()

    def get_time_diff(self, timestep):
        """ The difference in time between the currrent timestep and the
        timestep of the initial configuration.

        Args:
            timestep (int): The timestep the difference is to be calculated at

        Returns:
            int: Difference between initial and current timestep
        """
        return timestep - self.timestep

    def _unwrap(self, snapshot):
        """ Unwraps periodic positions to absolute positions

        Converts the periodic potition of each particle to it's *real* position
        by taking into account the *image* the particle exitsts on.

        Args:
            snapshot (snapshot): Hoomd snapshot of the system to unwrap

        Returns:
            :class:`numpy.array`: A numpy array of position arrays contianing
            the unwrapped positions
        """
        box_dim = np.array([snapshot.box.Lx,
                            snapshot.box.Ly,
                            snapshot.box.Lz
                           ])
        pos = np.array(snapshot.particles.position)
        image = np.array(snapshot.particles.image)
        return pos + image*box_dim

    def _displacement(self, snapshot):
        """ Calculate the squared displacement for all bodies in the system.

        This is the function that computes the per body displacements for all
        the dynamic quantities. This is where the most computation takes place
        and can be called once for a number of further calculations.

        Args:
            snapshot (snapshot): The configuration at which the difference is
                computed

        Returns:
            :class:`numpy.array`: An array containing per body displacements
        """
        curr = self._unwrap(snapshot)
        return np.sqrt(np.power(curr - self.pos_init, 2).sum(1))

    def get_data(self, system):
        """ Get translational and rotational data """

        return TransData().from_trans_array(
            self._displacement(self._take_snapshot(system)),
            self.get_time_diff(system.get_metadata['timestep']))

    def print_all(self, system, outfile):
        """Print all data to file"""
        data = self.get_data(system)
        CompDynamics(data).print_all(outfile)
        data.to_json(outfile+".json")

class TimeDep2dRigid(TimeDep):
    """ Class to compute the time dependent characteristics of 2D rigid bodies
    in a hoomd simulation.

    This class extends on from :class:TimeDep computing rotational properties of
    the 2D rigid bodies in the system. The distinction of two dimensional
    molecules makes for a simpler analysis of the rotational characteristics.

    Note:
        This class computes positional properties for each rigid body in the
        system. This means that for computations of rigid bodies it would be
        expected to get different translational quantities using the
        :class:TimeDep and the :class:TimeDep2dRigid classes.

    Warning:
        Hoomd doesn't store rotational data in a regular snapshot, even
        with the ``rigid_bodies=True`` option. My solution has been to
        modify the source code to add this functionality to taking
        snapshots.

    Todo:
        Have the capability to get the orientations from the system when taking
        the snapshot allowing for the computation of rotation on a default
        hoomd install.

    Args:
        system (system): Hoomd system object at the initial time for the
            dyanamics computations

    """
    def __init__(self, system):
        super(TimeDep2dRigid, self).__init__(system)
        t_init = self._take_snapshot(system)
        self.orient_init = np.array([scalar4_to_quaternion(i)
                                     for i in t_init.bodies.orientation])

    def _unwrap(self, snapshot):
        """ Unwraps the periodic positions to absolute positions

        Converts the periodic positions of each rigid body to absolute
        positions for computation of displacements.

        Note:
            This function overwrites the base class function due to differences
            in the way the rigid and non-rigid positions are stored in a
            snapshot

        Args:
            snapshot (snapshot): Hoomd snapshot of the configuration to unwrap

        Return:
            :class:`numpy.array`: A Numpy array of position arrays for each
            rigid body center of mass.
        """
        box_dim = np.array([snapshot.box.Lx,
                            snapshot.box.Ly,
                            snapshot.box.Lz
                           ])
        pos = np.array([scalar3_to_array(i) for i in snapshot.bodies.com])
        image = np.array([scalar3_to_array(i)
                          for i in snapshot.bodies.body_image])
        return pos + image*box_dim

    def _take_snapshot(self, system):
        """ Takes a snapshot of the system including rigid bodies

        Note:
            This overrides the :func:`_take_snapshot` of the base
            :class:`TimeDep` class to specify that that snapshot includes the
            rigid body data.

        Args:
            system (system): The hoomd system object

        Return:
            snapshot (snapshot): The snapshot of the system including the rigid
                body data
        """
        return system.take_snapshot(rigid_bodies=True)

    def _rotations(self, snapshot):
        R""" Calculate the rotation for every rigid body in the system

        This calculates the angle rotated between the initial configuration and
        the current configuration. It doesn't take into accout multiple
        rotations with values falling in the range :math:`[\-pi,\pi)`.

        Args:
            snapshot (snapshot): The final configuration

        Return:
            :class:`numpy.array`: Array of all the rotations
        """
        orient_final = np.array([scalar4_to_quaternion(i)
                                 for i in snapshot.bodies.orientation])
        rot_q = orient_final/self.orient_init
        rot = quaternion.as_rotation_vector(rot_q)[:, 0]
        for i, val in enumerate(rot):
            if val > math.pi:
                rot[i] -= 2*math.pi
            elif val < -math.pi:
                rot[i] += 2*math.pi
        return rot

    def get_data(self, system):
        """ Get translational and rotational data """
        snap = self._take_snapshot(system)

        return TransRotData().from_arrays(
            self._displacement(snap),
            self._rotations(snap),
            self.get_time_diff(system.get_metadata['timestep']))

    def print_all(self, system, outfile):
        """Print all data to file"""
        data = self.get_data(system)
        CompRotDynamics(data).print_all(outfile)
        data.to_json(outfile+".json")

def scalar3_to_array(scalar):
    """ Convert scalar3 representation to a numpy array

    Args:
        scalar (scalar3): Scalar3 position array

    Return:
        :class:`numpy.array`: Position array
    """
    return np.array([scalar.x, scalar.y, scalar.z])

def scalar4_to_array(scalar):
    """ Convert scalar4 representation to a numpy array

    Args:
        scalar (scalar4): Scalar4 position array

    Return:
        :class:`numpy.array`: numpy array
    """
    return np.array([scalar.x, scalar.y, scalar.z, scalar.w])

def scalar4_to_quaternion(scalar):
    R""" Convert scalar4 representation to a quaternion

    Conversion to quaternion where the *w* component of the scalar
    is the real part of the quaternion and the *x,y,z* values
    are the vector part.

    Args:
        scalar (scalar4): Scalar4 object representing a quaternion

    Return:
        :class:`quaternion.quaternion`: quaternion object
    """
    return quaternion.quaternion(scalar.w, scalar.x, scalar.y, scalar.z)
<commit_msg>Updating TimeDep module for hoomdv2<commit_after>#!/usr/bin/env python
""" A set of classes used for computing the dynamic properties of a Hoomd MD
simulation"""

from __future__ import print_function
import math
import numpy as np
import quaternion
from TransData import TransData, TransRotData
from CompDynamics import CompDynamics, CompRotDynamics

class TimeDep(object):
    """ Class to compute the time dependent characteristics of individual
    particles in a hoomd simulation.

    Args:
        system (system): Hoomd system object which is the initial configuration
            for the purposes of the dynamics calculations
    """
    def __init__(self, system):
        self.t_init = self._take_snapshot(system)
        self.pos_init = self._unwrap(self.t_init)
        self.timestep = system.get_metadata()['timestep']

    def _take_snapshot(self, system):
        """ Takes a snapshot of the current configuration of the system

        Args:
            system (system): Hoomd system objet in the configuration to be saved

        Returns:
            Snapshot: An immutable snapshot of the system at the current time
        """
        return system.take_snapshot()

    def get_time_diff(self, timestep):
        """ The difference in time between the currrent timestep and the
        timestep of the initial configuration.

        Args:
            timestep (int): The timestep the difference is to be calculated at

        Returns:
            int: Difference between initial and current timestep
        """
        return timestep - self.timestep

    def _unwrap(self, snapshot):
        """ Unwraps periodic positions to absolute positions

        Converts the periodic potition of each particle to it's *real* position
        by taking into account the *image* the particle exitsts on.

        Args:
            snapshot (snapshot): Hoomd snapshot of the system to unwrap

        Returns:
            :class:`numpy.array`: A numpy array of position arrays contianing
            the unwrapped positions
        """
        box_dim = np.array([snapshot.box.Lx,
                            snapshot.box.Ly,
                            snapshot.box.Lz
                           ])
        pos = snapshot.particles.position
        image = snapshot.particles.image
        return pos + image*box_dim

    def _displacement(self, snapshot):
        """ Calculate the squared displacement for all bodies in the system.

        This is the function that computes the per body displacements for all
        the dynamic quantities. This is where the most computation takes place
        and can be called once for a number of further calculations.

        Args:
            snapshot (snapshot): The configuration at which the difference is
                computed

        Returns:
            :class:`numpy.array`: An array containing per body displacements
        """
        curr = self._unwrap(snapshot)
        return np.sqrt(np.power(curr - self.pos_init, 2).sum(1))

    def get_data(self, system):
        """ Get translational and rotational data """
        data = TransData()
        data.from_trans_array(
            self._displacement(self._take_snapshot(system)),
            self.get_time_diff(system.get_metadata()['timestep']))
        return data

    def print_all(self, system, outfile):
        """Print all data to file"""
        data = self.get_data(system)
        CompDynamics(data).print_all(outfile)
        data.to_json(outfile+"-tr.dat")

class TimeDep2dRigid(TimeDep):
    """ Class to compute the time dependent characteristics of 2D rigid bodies
    in a hoomd simulation.

    This class extends on from :class:TimeDep computing rotational properties of
    the 2D rigid bodies in the system. The distinction of two dimensional
    molecules makes for a simpler analysis of the rotational characteristics.

    Note:
        This class computes positional properties for each rigid body in the
        system. This means that for computations of rigid bodies it would be
        expected to get different translational quantities using the
        :class:TimeDep and the :class:TimeDep2dRigid classes.

    Args:
        system (system): Hoomd system object at the initial time for the
            dyanamics computations

    """
    def __init__(self, system):
        super(TimeDep2dRigid, self).__init__(system)
        self.bodies = np.max(self.t_init.particles.body)+1
        self.pos_init = self.pos_init[:self.bodies]
        self.orient_init = quaternion.as_quat_array(np.array(
            self.t_init.particles.orientation[:self.bodies], dtype=float))

    def _rotations(self, snapshot):
        R""" Calculate the rotation for every rigid body in the system

        This calculates the angle rotated between the initial configuration and
        the current configuration. It doesn't take into accout multiple
        rotations with values falling in the range :math:`[\-pi,\pi)`.

        Args:
            snapshot (snapshot): The final configuration

        Return:
            :class:`numpy.array`: Array of all the rotations
        """
        orient_final = quaternion.as_quat_array(np.array(
            snapshot.particles.orientation[:self.bodies], dtype=float))
        rot_q = orient_final/self.orient_init
        rot = quaternion.as_rotation_vector(rot_q)[:, 0]
        for i, val in enumerate(rot):
            if val > math.pi:
                rot[i] -= 2*math.pi
            elif val < -math.pi:
                rot[i] += 2*math.pi
        return rot

    def _displacement(self, snapshot):
        """ Calculate the squared displacement for all bodies in the system.

        This is the function that computes the per body displacements for all
        the dynamic quantities. This is where the most computation takes place
        and can be called once for a number of further calculations.

        Args:
            snapshot (snapshot): The configuration at which the difference is
                computed

        Returns:
            :class:`numpy.array`: An array containing per body displacements
        """
        curr = self._unwrap(snapshot)[:self.bodies]
        return np.sqrt(np.power(curr - self.pos_init, 2).sum(1))

    def get_data(self, system):
        """ Get translational and rotational data """
        snap = self._take_snapshot(system)

        data = TransRotData()
        data.from_arrays(
            self._displacement(snap),
            self._rotations(snap),
            self.get_time_diff(system.get_metadata()['timestep']))
        assert (issubclass(type(data), TransRotData)), type(data)
        return data

    def print_all(self, system, outfile):
        """Print all data to file"""
        data = self.get_data(system)
        CompRotDynamics(data).print_all(outfile)
        data.to_json(outfile[:-8]+"-tr.dat")
<|endoftext|>


<commit_before>import tkinter

import tkinter as tk

manufacture = 0
research = 0
culture = 0

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        master.minsize(width=250, height=100)
        self.pack(side="top")
        self.create_Manufacture()
        self.create_Research()
        self.create_Culture()

    def create_Manufacture(self):
        global manufacture
        self.btn_manufacture = tk.Button(self)
        self.btn_manufacture["text"] = "{Manufacture = } 0"
        self.btn_manufacture["command"] = self.add_Manufacture
        self.btn_manufacture.pack(side="top")

    def create_Research(self):
        self.btn_research = tk.Button(self)
        self.btn_research["text"] = "{Research = } 0"
        self.btn_research["command"] = self.add_Research
        self.btn_research.pack(side="top")

    def create_Culture(self):
        self.btn_culture = tk.Button(self)
        self.btn_culture["text"] = "{Culture =} 0"
        self.btn_culture["command"] = self.add_Culture
        self.btn_culture.pack(side="top")

    def add_Manufacture(self):
        global manufacture
        manufacture += 1
        print("Manufacture = ", manufacture)
        manufacture_Button = 'Manufacture = ', manufacture
        self.btn_manufacture.configure(text=manufacture_Button)

    def add_Research(self):
        global research
        research += 1
        print("Research = ", research)
        research_Button = 'Research = ', research
        self.btn_research.configure(text=research_Button)

    def add_Culture(self):
        global culture
        culture += 1
        print("Culture = ", culture)
        culture_Button = 'Culture = ', culture
        self.btn_culture.configure(text=culture_Button)

root = tk.Tk()
app = Application(master=root)
app.mainloop()
<commit_msg>Added hash-bang for bash shell execution<commit_after>#!/usr/bin/python3

import tkinter as tk

manufacture = 0
research = 0
culture = 0

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        master.minsize(width=250, height=100)
        self.pack(side="top")
        self.create_Manufacture()
        self.create_Research()
        self.create_Culture()

    def create_Manufacture(self):
        global manufacture
        self.btn_manufacture = tk.Button(self)
        self.btn_manufacture["text"] = "{Manufacture = } 0"
        self.btn_manufacture["command"] = self.add_Manufacture
        self.btn_manufacture.pack(side="top")

    def create_Research(self):
        self.btn_research = tk.Button(self)
        self.btn_research["text"] = "{Research = } 0"
        self.btn_research["command"] = self.add_Research
        self.btn_research.pack(side="top")

    def create_Culture(self):
        self.btn_culture = tk.Button(self)
        self.btn_culture["text"] = "{Culture =} 0"
        self.btn_culture["command"] = self.add_Culture
        self.btn_culture.pack(side="top")

    def add_Manufacture(self):
        global manufacture
        manufacture += 1
        print("Manufacture = ", manufacture)
        manufacture_Button = 'Manufacture = ', manufacture
        self.btn_manufacture.configure(text=manufacture_Button)

    def add_Research(self):
        global research
        research += 1
        print("Research = ", research)
        research_Button = 'Research = ', research
        self.btn_research.configure(text=research_Button)

    def add_Culture(self):
        global culture
        culture += 1
        print("Culture = ", culture)
        culture_Button = 'Culture = ', culture
        self.btn_culture.configure(text=culture_Button)

root = tk.Tk()
app = Application(master=root)
app.mainloop()
<|endoftext|>


<commit_before>from UM.Signal import Signal, SignalEmitter
from UM.PluginObject import PluginObject
from UM.Event import Event
from UM.Scene.Selection import Selection

##  Abstract base class for tools that manipulate the scene.
#
class Tool(PluginObject, SignalEmitter):
    def __init__(self):
        super().__init__() # Call super to make multiple inheritence work.
        self._controller = None
        self._handle = None
        self._locked_axis = None
        self._drag_plane = None
        self._drag_start = None

    ##  Handle an event.
    #   \param event \type{Event} The event to handle.
    #   \sa Event
    def event(self, event):
        if event.type == Event.ToolActivateEvent:
            if Selection.hasSelection() and self._handle:
                self._handle.setParent(self.getController().getScene().getRoot())
                self._handle.setPosition(Selection.getAveragePosition())

        if event.type == Event.MouseMoveEvent and self._handle:
            if self._locked_axis:
                return

            id = self._renderer.getIdAtCoordinate(event.x, event.y)
            if not id:
                self._handle.setActiveAxis(None)

            if self._handle.isAxis(id):
                self._handle.setActiveAxis(id)

        if event.type == Event.ToolDeactivateEvent and self._handle:
            self._handle.setParent(None)

        return False

    def updateHandlePosition(self):
        if Selection.hasSelection():
            self._handle.setPosition(Selection.getAveragePosition())

    def getController(self):
        return self._controller

    def setController(self, controller):
        self._controller = controller

    def getHandle(self):
        return self._handle

    def setHandle(self, handle):
        self._handle = handle
<commit_msg>Add functionality for performing drags and axis locks to Tool<commit_after>from UM.Signal import Signal, SignalEmitter
from UM.PluginObject import PluginObject
from UM.Event import Event
from UM.Scene.Selection import Selection

##  Abstract base class for tools that manipulate the scene.
#
class Tool(PluginObject, SignalEmitter):
    def __init__(self):
        super().__init__() # Call super to make multiple inheritence work.
        self._controller = None
        self._handle = None
        self._locked_axis = None
        self._drag_plane = None
        self._drag_start = None

    ##  Handle an event.
    #   \param event \type{Event} The event to handle.
    #   \sa Event
    def event(self, event):
        if event.type == Event.ToolActivateEvent:
            if Selection.hasSelection() and self._handle:
                self._handle.setParent(self.getController().getScene().getRoot())
                self._handle.setPosition(Selection.getAveragePosition())

        if event.type == Event.MouseMoveEvent and self._handle:
            if self._locked_axis:
                return

            id = self._renderer.getIdAtCoordinate(event.x, event.y)
            if not id:
                self._handle.setActiveAxis(None)

            if self._handle.isAxis(id):
                self._handle.setActiveAxis(id)

        if event.type == Event.ToolDeactivateEvent and self._handle:
            self._handle.setParent(None)

        return False

    def updateHandlePosition(self):
        if Selection.hasSelection():
            self._handle.setPosition(Selection.getAveragePosition())

    def getController(self):
        return self._controller

    def setController(self, controller):
        self._controller = controller

    def getHandle(self):
        return self._handle

    def setHandle(self, handle):
        self._handle = handle

    def getLockedAxis(self):
        return self._locked_axis

    def setLockedAxis(self, axis):
        self._locked_axis = axis

        if self._handle:
            self._handle.setActiveAxis(axis)

    def getDragPlane(self):
        return self._drag_plane

    def setDragPlane(self, plane):
        self._drag_plane = plane

    def setDragStart(self, x, y):
        self._drag_start = self.getDragPosition(x, y)

    def getDragPosition(self, x, y):
        if not self._drag_plane:
            return None

        ray = self._controller.getScene().getActiveCamera().getRay(x, y)

        target = self._drag_plane.intersectsRay(ray)
        if target:
            return ray.getPointAlongRay(target)

        return None

    def getDragVector(self, x, y):
        if not self._drag_plane:
            return None

        if not self._drag_start:
            return None

        drag_end = self.getDragPosition(x, y)
        if drag_end:
            return drag_end - self._drag_start

        return None

<|endoftext|>


<commit_before>from UM.Resources import Resources
from UM.Preferences import Preferences

import gettext
import os

##  Wraps a gettext translation catalog for simplified use.
#
#   This class wraps a gettext translation catalog to simplify its use.
#   It will load the translation catalog from Resources' i18nLocation
#   and allows specifying which language to load.
#
#   To use this class, create an instance of it with the name of the catalog
#   to load. Then call `i18n` or `i18nc` on the instance to perform a look
#   up in the catalog.
class i18nCatalog:
    ##  Constructor.
    #
    #   \param name The name of the catalog to load.
    #   \param language The language to load. Valid values are language codes or
    #   'default'. When 'default' is specified, the language to load will be
    #   determined based on the system's language settings.
    #
    #   \note When `language` is `default`, the language to load can be overridden
    #   using the "LANGUAGE" environment variable.
    def __init__(self, name, language = 'default'):
        languages = []
        if language == 'default':
            preflang = Preferences.getInstance().getValue('general/language')

            if not preflang:
                envlang = os.getenv('LANGUAGE')
                if envlang:
                    languages.append(envlang)
            else:
                languages.append(preflang)
        else:
            languages.append(language)

        for path in Resources.getLocation(Resources.i18nLocation):
            if gettext.find(name, path, languages = languages):
                self.__translation = gettext.translation(name, path, languages=languages)
                break
        else:
            self.__translation = None

    ##  Mark a string as translatable
    #
    #   \param text The string to mark as translatable
    def i18n(self, text):
        if self.__translation:
            return self.__translation.gettext(text)

        return text

    ##  Mark a string as translatable, provide a context.
    #
    #   \param context The context of the string, i.e. something that explains the use of the text.
    #   \param text The text to mark translatable.
    #
    #   \return The translated text or the untranslated text if it was not found in this catalog.
    def i18nc(self, context, text):
        if self.__translation:
            message_with_context = "{0}\x04{1}".format(context, text)
            translated = self.__translation.gettext(message_with_context)
            if translated == message_with_context:
                return text
            else:
                return translated

        return text

    #TODO: Add support for plural formats
<commit_msg>Prefer environment language variable over preferences for easier testing<commit_after>from UM.Resources import Resources
from UM.Preferences import Preferences

import gettext
import os

##  Wraps a gettext translation catalog for simplified use.
#
#   This class wraps a gettext translation catalog to simplify its use.
#   It will load the translation catalog from Resources' i18nLocation
#   and allows specifying which language to load.
#
#   To use this class, create an instance of it with the name of the catalog
#   to load. Then call `i18n` or `i18nc` on the instance to perform a look
#   up in the catalog.
class i18nCatalog:
    ##  Constructor.
    #
    #   \param name The name of the catalog to load.
    #   \param language The language to load. Valid values are language codes or
    #   'default'. When 'default' is specified, the language to load will be
    #   determined based on the system's language settings.
    #
    #   \note When `language` is `default`, the language to load can be overridden
    #   using the "LANGUAGE" environment variable.
    def __init__(self, name, language = 'default'):
        languages = []
        if language == 'default':
            envlang = os.getenv('LANGUAGE')
            if envlang:
                languages.append(envlang)
            else:
                preflang = Preferences.getInstance().getValue('general/language')
                if preflang:
                    languages.append(preflang)
        else:
            languages.append(language)

        for path in Resources.getLocation(Resources.i18nLocation):
            if gettext.find(name, path, languages = languages):
                self.__translation = gettext.translation(name, path, languages=languages)
                break
        else:
            self.__translation = None

    ##  Mark a string as translatable
    #
    #   \param text The string to mark as translatable
    def i18n(self, text):
        if self.__translation:
            return self.__translation.gettext(text)

        return text

    ##  Mark a string as translatable, provide a context.
    #
    #   \param context The context of the string, i.e. something that explains the use of the text.
    #   \param text The text to mark translatable.
    #
    #   \return The translated text or the untranslated text if it was not found in this catalog.
    def i18nc(self, context, text):
        if self.__translation:
            message_with_context = "{0}\x04{1}".format(context, text)
            translated = self.__translation.gettext(message_with_context)
            if translated == message_with_context:
                return text
            else:
                return translated

        return text

    #TODO: Add support for plural formats
<|endoftext|>


<commit_before>__author__ = 'jon-bassi'

# Vignere Cipher encrypt and decrypt tools
# pdf contains methods<commit_msg>finalized Vignere cipher encrypt and decrypt<commit_after>__author__ = 'jon-bassi'

import sys

ALPHABET = 'abcdefghijklmnopqrstuvwxyz'

# Vignere Cipher encrypt and decrypt tools
# pdf contains methods

def encrypt(letter, alphabet):
    # alphabet is first letter in vignere alphabet
    # difference between letter and alphabet is the new letter
    shiftamt = ALPHABET.find(letter) + ALPHABET.find(alphabet)
    if shiftamt > 25:
        shiftamt -= 26
    return ALPHABET[shiftamt]

def decrypt(letter, alphabet):
    shiftamt = ALPHABET.find(letter) - ALPHABET.find(alphabet)
    if shiftamt < 0:
        shiftamt += 26
    return ALPHABET[shiftamt]

if len(sys.argv) < 2 or len(sys.argv) > 4:
    print 'error executing Vignere.py\nusage: python Vignere.py [text] [key] ["decrypt" (optional)]'
    sys.exit(0)
text = sys.argv[1]
key = sys.argv[2]

if len(sys.argv) < 4:
    encrypted = ''
    for idx in range(len(text)):
        encrypted += encrypt(text[idx], key[idx % len(key)])
    print encrypted
else:
    decrypted = ''
    for idx in range(len(text)):
        decrypted += decrypt(text[idx], key[idx % len(key)])
    print decrypted

<|endoftext|>


<commit_before>import socket
from collections import namedtuple
import VRTStream
import WSA4000SweepEntry

class WSA4000:

	def __init__(self):
		self.sock = namedtuple('socket', ['scpi', 'vrt'])

	## connects to a wsa
	#
	# @param host - the hostname or IP to connect to
	def connect(self, host):
		self.sock.scpi = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.scpi.connect((host, 37001))
		self.sock.scpi.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
		self.sock.vrt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.vrt.connect((host, 37000))
		self.vrt = VRTStream.VRTStream(self.sock.vrt);

	## send a scpi command
	#
	# @param cmd - the command to send
	def scpiset(self, cmd):
		self.sock.scpi.send("%s\n" % cmd)

	## get a scpi command
	#
	# @param cmd - the command to send
	# @return - the response back from the box if any
	def scpiget(self, cmd):
		self.sock.scpi.send("%s\n" % cmd)
		buf = self.sock.scpi.recv(1024)
		return buf

	## get the box identification string
	#
	# @return - the id string
	def id(self):
		return self.scpiget(":*idn?");

	## get/set current frequency
	#
	# @param freq - if this param is given, then the box is tuned to this freq. otherwise, the freq is queried
	# @return - the frequency of the box
	def freq(self, freq=None):
		if (freq == None):
			buf = self.scpiget("FREQ:CENTER?");
			freq = int(buf)
		else:
			self.scpiset(":FREQ:CENTER %d\n" % (freq))

		return freq

	## get/set frequency shift
	#
	# @param freq - if this param is given, then the frequency is shifted by this amount. otherwise, the freq shift is queried
	# @return - the amount of frequency shift
	def fshift(self, shift=None):
		if (shift == None):
			buf = self.scpiget("FREQ:SHIFT?");
			shift = float(buf)
		else:
			self.scpiset(":FREQ:SHIFT %d\n" % (shift))

		return shift

	## get/set decimation
	#
	# @param value - if this param is given, then the input signal is decimated by this amount. otherwise, the decimation is queried
	# @return - the amount of decimation
	def decimation(self, value=None):
		if (value == None):
			buf = self.scpiget("SENSE:DECIMATION?");
			value = int(buf)
		else:
			self.scpiset(":SENSE:DECIMATION %d\n" % (value))

		return value

	## get/set current gain
	#
	# @param gain - if this param is given, then the box is tuned to this freq. otherwise, the freq is queried
	# @return - the frequency of the box
	def gain(self, gain=None):
		if (gain == None):
			gain = self.scpiget("INPUT:GAIN:RF?");
		else:
			self.scpiset(":INPUT:GAIN:RF %s\n" % (gain))

		return gain

	## get/set current IF Gain
	#
	# @param gain - if this param is given, then the if of the box is set to this value. otherwise the gain is queried
	# @return - the ifgain in dB
	def ifgain(self, gain=None):
		if (gain == None):
			gain = self.scpiget(":INPUT:GAIN:IF?");
			gain = gain.partition(" ")
			gain = int(gain[0])
		else:
			self.scpiset(":INPUT:GAIN:IF %d\n" % (gain))

		return gain

	## flush any captures from the capture memory
	#
	def flush(self):
		self.scpiset(":sweep:flush\n")

	## get/set trigger settings
	#
	# @param gain - if this param is given, then the trigger settings are set as given.. if not, they are read
	# @return - the trigger settings set as an object
	def trigger(self, settings=None):
		if (settings == None):
			# find out what kind of trigger is set
			trigstr = self.scpiget(":TRIGGER:MODE?")
			if trigstr == "NONE":
				# build our return object
				settings = namedtuple("type")
				settings.type = "NONE"

			elif trigstr == "LEVEL":
				# build our return object
				settings = namedtuple("type", "fstart", "fstop", "amplitude")
				settings.type = "LEVEL"

				# read the settings from the box
				trigstr = self.scpiget(":TRIGGER:LEVEL?")
				(settings.fstart, settings.fstop, settings.amplitude) = trigstr.split(",")

			else:
				print "error: unsupported trigger type set: %s" % trigstr
				return None

		else:
			if settings.type == "NONE":
				self.scpiset(":TRIGGER:MODE NONE")

			elif settings.type == "LEVEL":
				self.scpiset(":TRIGGER:LEVEL %d, %d, %d" % (settings.fstart, settings.fstop, settings.amplitude))
				self.scpiset(":TRIGGER:MODE LEVEL")

		return settings

	## test for no more data
	## do a manual capture
	#
	# @param spp - the number of samples in a packet
	# @param ppb - the number of packets in a capture
	def capture(self, spp, ppb):
		self.scpiset(":TRACE:SPP %s\n" % (spp))
		self.scpiset(":TRACE:BLOCK:PACKETS %s\n" % (ppb))
		self.scpiset(":TRACE:BLOCK:DATA?\n")

	## test for no more data
	#
	# @return - 1 if no more data, 0 if more data
	def eof(self):
		return self.vrt.eof

	## has data
	#
	# @return - 1 if there is a packet to read.. 0 if not
	def has_data(self):
		return self.vrt.has_data()

	## read data
	#
	# @return - a packet object
	def read(self):
		return self.vrt.read_packet()

	## sweep add
	#
	# @param entry - the sweep entry to add
	def sweep_add(self, entry):
		self.scpiset(":sweep:entry:new")
		self.scpiset(":sweep:entry:freq:center %d, %d" % (entry.fstart, entry.fstop))
		self.scpiset(":sweep:entry:freq:step %d" % (entry.fstep))
		self.scpiset(":sweep:entry:freq:shift %d" % (entry.fshift))
		self.scpiset(":sweep:entry:decimation %d" % (entry.decimation))
		self.scpiset(":sweep:entry:antenna %d" % (entry.antenna))
		self.scpiset(":sweep:entry:gain:rf %s" % (entry.gain))
		self.scpiset(":sweep:entry:gain:if %d" % (entry.ifgain))
		self.scpiset(":sweep:entry:spp %d" % (entry.spp))
		self.scpiset(":sweep:entry:ppb %d" % (entry.ppb))
		self.scpiset(":sweep:entry:trigger:type %s" % (entry.trigtype))
		self.scpiset(":sweep:entry:trigger:level %d, %d, %d" % (entry.level_fstart, entry.level_fstop, entry.level_amplitude))
		self.scpiset(":sweep:entry:save")

	## sweep read
	#
	# @param index - the index of the entry to read
	# @return entry
	def sweep_read(self, index):
		ent = WSA4000SweepEntry.WSA4000SweepEntry()

		entrystr = self.scpiget(":sweep:entry:read? %d" % index)

		(value, sep, entrystr) = entrystr.partition(',')
		ent.fstart = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.fstop = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.fstep = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.fshift = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.decimation = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.antenna = int(value)
		(ent.gain, sep, entrystr) = entrystr.partition(',')
		(value, sep, entrystr) = entrystr.partition(',')
		ent.ifgain = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.spp = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.ppb = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.dwell_s = int(value)
		(value, sep, trigstr) = entrystr.partition(',')
		ent.dwell_us = int(value)

		if trigstr == "NONE":
			ent.trigtype = "NONE"
		else:
			(ent.trigtype, trigstr) = trigstr.split(',')
			if ent.trigtype == "LEVEL":
				(value, sep, trigstr) = trigstr.partition(',')
				ent.level_fstart = int(value)
				(value, sep, trigstr) = trigstr.partition(',')
				ent.level_fstop = int(value)
				(value, sep, trigstr) = trigstr.partition(',')
				ent.level_amplitude = int(value)

		return ent

	## flush the sweep list
	#
	def sweep_clear(self):
		self.scpiset(":sweep:entry:del all");

	## start the sweep engine
	#
	def sweep_start(self):
		self.scpiset(":sweep:list:start");

	## stop the sweep engine
	#
	def sweep_stop(self):
		self.scpiset(":sweep:list:stop");

<commit_msg>added the commands request_read_perm() and have_read_perm() for doing session handling<commit_after>import socket
from collections import namedtuple
import VRTStream
import WSA4000SweepEntry

class WSA4000:

	def __init__(self):
		self.sock = namedtuple('socket', ['scpi', 'vrt'])

	## connects to a wsa
	#
	# @param host - the hostname or IP to connect to
	def connect(self, host):
		self.sock.scpi = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.scpi.connect((host, 37001))
		self.sock.scpi.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True)
		self.sock.vrt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.vrt.connect((host, 37000))
		self.vrt = VRTStream.VRTStream(self.sock.vrt);

	## send a scpi command
	#
	# @param cmd - the command to send
	def scpiset(self, cmd):
		self.sock.scpi.send("%s\n" % cmd)

	## get a scpi command
	#
	# @param cmd - the command to send
	# @return - the response back from the box if any
	def scpiget(self, cmd):
		self.sock.scpi.send("%s\n" % cmd)
		buf = self.sock.scpi.recv(1024)
		return buf

	## get the box identification string
	#
	# @return - the id string
	def id(self):
		return self.scpiget(":*idn?");

	## get/set current frequency
	#
	# @param freq - if this param is given, then the box is tuned to this freq. otherwise, the freq is queried
	# @return - the frequency of the box
	def freq(self, freq=None):
		if (freq == None):
			buf = self.scpiget("FREQ:CENTER?");
			freq = int(buf)
		else:
			self.scpiset(":FREQ:CENTER %d\n" % (freq))

		return freq

	## get/set frequency shift
	#
	# @param freq - if this param is given, then the frequency is shifted by this amount. otherwise, the freq shift is queried
	# @return - the amount of frequency shift
	def fshift(self, shift=None):
		if (shift == None):
			buf = self.scpiget("FREQ:SHIFT?");
			shift = float(buf)
		else:
			self.scpiset(":FREQ:SHIFT %d\n" % (shift))

		return shift

	## get/set decimation
	#
	# @param value - if this param is given, then the input signal is decimated by this amount. otherwise, the decimation is queried
	# @return - the amount of decimation
	def decimation(self, value=None):
		if (value == None):
			buf = self.scpiget("SENSE:DECIMATION?");
			value = int(buf)
		else:
			self.scpiset(":SENSE:DECIMATION %d\n" % (value))

		return value

	## get/set current gain
	#
	# @param gain - if this param is given, then the box is tuned to this freq. otherwise, the freq is queried
	# @return - the frequency of the box
	def gain(self, gain=None):
		if (gain == None):
			gain = self.scpiget("INPUT:GAIN:RF?");
		else:
			self.scpiset(":INPUT:GAIN:RF %s\n" % (gain))

		return gain

	## get/set current IF Gain
	#
	# @param gain - if this param is given, then the if of the box is set to this value. otherwise the gain is queried
	# @return - the ifgain in dB
	def ifgain(self, gain=None):
		if (gain == None):
			gain = self.scpiget(":INPUT:GAIN:IF?");
			gain = gain.partition(" ")
			gain = int(gain[0])
		else:
			self.scpiset(":INPUT:GAIN:IF %d\n" % (gain))

		return gain

	## flush any captures from the capture memory
	#
	def flush(self):
		self.scpiset(":sweep:flush\n")

	## get/set trigger settings
	#
	# @param gain - if this param is given, then the trigger settings are set as given.. if not, they are read
	# @return - the trigger settings set as an object
	def trigger(self, settings=None):
		if (settings == None):
			# find out what kind of trigger is set
			trigstr = self.scpiget(":TRIGGER:MODE?")
			if trigstr == "NONE":
				# build our return object
				settings = namedtuple("type")
				settings.type = "NONE"

			elif trigstr == "LEVEL":
				# build our return object
				settings = namedtuple("type", "fstart", "fstop", "amplitude")
				settings.type = "LEVEL"

				# read the settings from the box
				trigstr = self.scpiget(":TRIGGER:LEVEL?")
				(settings.fstart, settings.fstop, settings.amplitude) = trigstr.split(",")

			else:
				print "error: unsupported trigger type set: %s" % trigstr
				return None

		else:
			if settings.type == "NONE":
				self.scpiset(":TRIGGER:MODE NONE")

			elif settings.type == "LEVEL":
				self.scpiset(":TRIGGER:LEVEL %d, %d, %d" % (settings.fstart, settings.fstop, settings.amplitude))
				self.scpiset(":TRIGGER:MODE LEVEL")

		return settings

	## test for no more data
	## do a manual capture
	#
	# @param spp - the number of samples in a packet
	# @param ppb - the number of packets in a capture
	def capture(self, spp, ppb):
		self.scpiset(":TRACE:SPP %s\n" % (spp))
		self.scpiset(":TRACE:BLOCK:PACKETS %s\n" % (ppb))
		self.scpiset(":TRACE:BLOCK:DATA?\n")

	## aquire a read permission for reading data
	#
	# @return - 1 if allowed to read, 0 if not
	def request_read_perm(self):
		lockstr = self.scpiget(":SYSTEM:LOCK:REQUEST? ACQ\n")
		if lockstr == "1":
			return 1
		else:
			return 0

	## query to see if you have read permissions
	#
	# @return - 1 if allowed to read, 0 if not
	def have_read_perm(self):
		lockstr = self.scpiget(":SYSTEM:LOCK:HAVE? ACQ\n")
		if lockstr == "1":
			return 1
		else:
			return 0

	## test for no more data
	#
	# @return - 1 if no more data, 0 if more data
	def eof(self):
		return self.vrt.eof

	## has data
	#
	# @return - 1 if there is a packet to read.. 0 if not
	def has_data(self):
		return self.vrt.has_data()

	## read data
	#
	# @return - a packet object
	def read(self):
		return self.vrt.read_packet()

	## sweep add
	#
	# @param entry - the sweep entry to add
	def sweep_add(self, entry):
		self.scpiset(":sweep:entry:new")
		self.scpiset(":sweep:entry:freq:center %d, %d" % (entry.fstart, entry.fstop))
		self.scpiset(":sweep:entry:freq:step %d" % (entry.fstep))
		self.scpiset(":sweep:entry:freq:shift %d" % (entry.fshift))
		self.scpiset(":sweep:entry:decimation %d" % (entry.decimation))
		self.scpiset(":sweep:entry:antenna %d" % (entry.antenna))
		self.scpiset(":sweep:entry:gain:rf %s" % (entry.gain))
		self.scpiset(":sweep:entry:gain:if %d" % (entry.ifgain))
		self.scpiset(":sweep:entry:spp %d" % (entry.spp))
		self.scpiset(":sweep:entry:ppb %d" % (entry.ppb))
		self.scpiset(":sweep:entry:trigger:type %s" % (entry.trigtype))
		self.scpiset(":sweep:entry:trigger:level %d, %d, %d" % (entry.level_fstart, entry.level_fstop, entry.level_amplitude))
		self.scpiset(":sweep:entry:save")

	## sweep read
	#
	# @param index - the index of the entry to read
	# @return entry
	def sweep_read(self, index):
		ent = WSA4000SweepEntry.WSA4000SweepEntry()

		entrystr = self.scpiget(":sweep:entry:read? %d" % index)

		(value, sep, entrystr) = entrystr.partition(',')
		ent.fstart = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.fstop = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.fstep = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.fshift = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.decimation = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.antenna = int(value)
		(ent.gain, sep, entrystr) = entrystr.partition(',')
		(value, sep, entrystr) = entrystr.partition(',')
		ent.ifgain = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.spp = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.ppb = int(value)
		(value, sep, entrystr) = entrystr.partition(',')
		ent.dwell_s = int(value)
		(value, sep, trigstr) = entrystr.partition(',')
		ent.dwell_us = int(value)

		if trigstr == "NONE":
			ent.trigtype = "NONE"
		else:
			(ent.trigtype, trigstr) = trigstr.split(',')
			if ent.trigtype == "LEVEL":
				(value, sep, trigstr) = trigstr.partition(',')
				ent.level_fstart = int(value)
				(value, sep, trigstr) = trigstr.partition(',')
				ent.level_fstop = int(value)
				(value, sep, trigstr) = trigstr.partition(',')
				ent.level_amplitude = int(value)

		return ent

	## flush the sweep list
	#
	def sweep_clear(self):
		self.scpiset(":sweep:entry:del all");

	## start the sweep engine
	#
	def sweep_start(self):
		self.scpiset(":sweep:list:start");

	## stop the sweep engine
	#
	def sweep_stop(self):
		self.scpiset(":sweep:list:stop");

<|endoftext|>


<commit_before>"""Generate a weather-report based on the user's location.

The script uses GeoIP to determine the user's location based on the IP and
retrieves the weather, which is then returned it in a english sentence.
"""

# Native libraries/modules
import json
import sys
import urllib2

# External libraries/modules
import user_loc

def weather_info(API_KEY):
    """Retrieve and parse Weather info from wunderground.com.

    :return: list
    """
    currloc = user_loc.loc()
    state = currloc['region_code']
    city = currloc['city']
    tz = currloc['time_zone']

    try:
        data = urllib2.urlopen(
            'http://api.wunderground.com/api/{}/geolookup/conditions'
            '/q/{}/{}.json'.format(api_key, state, city))
    except urllib2.URLError:
        print "Please check to your internet connection"
        exit()
    json_string = f.read()
    parsed_json = json.loads(json_string)
    f.close()

    try:
        location = parsed_json['location']['city']
    except KeyError:
        print "Invalid API key. please try again."
        exit()
    temp_f = parsed_json['current_observation']['temp_f']
    weather = parsed_json['current_observation']['weather']
    humidity = parsed_json['current_observation']['relative_humidity']
    windspeed = parsed_json['current_observation']['wind_mph']
    winddir = parsed_json['current_observation']['wind_dir']
    feelslike = parsed_json['current_observation']['feelslike_f']
    visibility = parsed_json['current_observation']['visibility_mi']
    if float(visibility) >= 10.0:
        visible_condition = "excellent"
    elif float(visibility) >= 5.0 < 10.0:
        visible_condition = "good"
    elif float(visibility) >= 2.0 < 5.0:
        visible_condition = "fair"
    elif float(visibility) > 0.5 < 2.0:
        visible_condition = "bad"
    else:
        visible_condition = "very bad"
    precip = parsed_json['current_observation']['precip_today_in']

    if float(precip) <= 0.0:
        precip = "It seems there is no rain in the forecast today."
    else:
        precip = "It is supposed to rain " + precip + " inches today."

    weather_data_lst = [weather, location, str(temp_f), humidity, winddir,
                        str(int(windspeed)), feelslike, visible_condition,
                        visibility, precip, tme_zone]

    return weather_data_lst

def full_summary(weather_lst):
    """Summarize the weather for the TTS (currently not implemented).

    The if statement deletes the feels like sentence if the 'temperature' and
    the 'feels_like' variables are the same.
    :param weather_lst
    :return: string
    """
    if weather_lst[2] == weather_lst[6]:
        report = ("It is {cnd} and {deg} degrees right now in {loc} with winds"
                  " of {wnd} miles per hour. Visibility is {vis} with the "
                  "range of {rng} miles. {pre}".format(
                      cnd=weather_lst[0], deg=weather_lst[2],
                      loc=weather_lst[1], wnd=weather_lst[5],
                      vis=weather_lst[7], rng=weather_lst[8],
                      pre=weather_lst[9]))
    else:
        report = ("It is {cnd} and {deg} degrees right now in {loc} with winds"
                  "of {wnd} miles per hour. So it feels like {flk} degrees "
                  "outside. Visibility is {vis} with the range of {rng} miles."
                  " {pre}".format(
                      cnd=weather_lst[0], deg=weather_lst[2],
                      loc=weather_lst[1], wnd=weather_lst[5],
                      flk=weather_lst[6], vis=weather_lst[7],
                      rng=weather_lst[8], pre=weather_lst[9]))
    return report

def short_summary(weather_lst):
    """Generate a short summary of the weather.

    :param weather_lst
    :return: string
    """
    if weather_lst[2] == weather_lst[6]:
        report = ("It is {cnd} and {deg} degrees right now in {loc} with winds"
                  " of {wnd} miles per hour.".format(
                      cnd=weather_lst[0], deg=weather_lst[2],
                      loc=weather_lst[1], wnd=weather_lst[5]))
    return report

def report(reqData, API_KEY):
    """Generate the weather report based on the parameter.

    :param report_length:
    :return: string
    """
    weather_data_lst = weather_info(API_KEY)
    if reqData == "fullReport":
        return full_summary(weather_data_lst)
    elif reqData == "shortReport":
        return short_summary(weather_data_lst)
    else:
        return "Invalid Argument"

if __name__ == '__main__':
    API_KEY = raw_input("Please enter your wunderground api key:")
    if len(sys.argv) != 2:
        print("{} of 2 Argument(s) found. Please enter 'fullReport' or "
              "'shortReport' as argument.".format(sys.argv))
    else:
        print report(sys.argv[1], API_KEY)
<commit_msg>Renamed Variables & Functions<commit_after>"""Generate a weather-report based on the user's location.

The script uses GeoIP to determine the user's location based on the IP and
retrieves the weather, which is then returned it in a english sentence.
"""

# Native libraries/modules
import json
import sys
import urllib2

# External libraries/modules
import user_loc

def weather_info(api_key):
    """Retrieve and parse Weather info from wunderground.com.

    :return: list
    """
    currloc = user_loc.loc()
    state = currloc['region_code']
    city = currloc['city']
    tme_zone = currloc['time_zone']

    try:
        data = urllib2.urlopen(
            'http://api.wunderground.com/api/{}/geolookup/conditions'
            '/q/{}/{}.json'.format(api_key, state, city))
    except urllib2.URLError:
        print "Please check to your internet connection"
        exit()
    json_string = data.read()
    parsed_json = json.loads(json_string)
    data.close()

    try:
        location = parsed_json['location']['city']
    except KeyError:
        print "Invalid API key. please try again."
        exit()
    temp_f = parsed_json['current_observation']['temp_f']
    weather = parsed_json['current_observation']['weather']
    humidity = parsed_json['current_observation']['relative_humidity']
    windspeed = parsed_json['current_observation']['wind_mph']
    winddir = parsed_json['current_observation']['wind_dir']
    feelslike = parsed_json['current_observation']['feelslike_f']
    visibility = parsed_json['current_observation']['visibility_mi']
    if float(visibility) >= 10.0:
        visible_condition = "excellent"
    elif float(visibility) >= 5.0 < 10.0:
        visible_condition = "good"
    elif float(visibility) >= 2.0 < 5.0:
        visible_condition = "fair"
    elif float(visibility) > 0.5 < 2.0:
        visible_condition = "bad"
    else:
        visible_condition = "very bad"
    precip = parsed_json['current_observation']['precip_today_in']

    if float(precip) <= 0.0:
        precip = "It seems there is no rain in the forecast today."
    else:
        precip = "It is supposed to rain " + precip + " inches today."

    weather_data_lst = [weather, location, str(temp_f), humidity, winddir,
                        str(int(windspeed)), feelslike, visible_condition,
                        visibility, precip, tme_zone]

    return weather_data_lst

def full_summary(weather_lst):
    """Summarize the weather for the TTS (currently not implemented).

    The if statement deletes the feels like sentence if the 'temperature' and
    the 'feels_like' variables are the same.
    :param weather_lst
    :return: string
    """
    if weather_lst[2] == weather_lst[6]:
        report = ("It is {cnd} and {deg} degrees right now in {loc} with winds"
                  " of {wnd} miles per hour. Visibility is {vis} with the "
                  "range of {rng} miles. {pre}".format(
                      cnd=weather_lst[0], deg=weather_lst[2],
                      loc=weather_lst[1], wnd=weather_lst[5],
                      vis=weather_lst[7], rng=weather_lst[8],
                      pre=weather_lst[9]))
    else:
        report = ("It is {cnd} and {deg} degrees right now in {loc} with winds"
                  "of {wnd} miles per hour. So it feels like {flk} degrees "
                  "outside. Visibility is {vis} with the range of {rng} miles."
                  " {pre}".format(
                      cnd=weather_lst[0], deg=weather_lst[2],
                      loc=weather_lst[1], wnd=weather_lst[5],
                      flk=weather_lst[6], vis=weather_lst[7],
                      rng=weather_lst[8], pre=weather_lst[9]))
    return report

def short_summary(weather_lst):
    """Generate a short summary of the weather.

    :param weather_lst
    :return: string
    """
    if weather_lst[2] == weather_lst[6]:
        report = ("It is {cnd} and {deg} degrees right now in {loc} with winds"
                  " of {wnd} miles per hour.".format(
                      cnd=weather_lst[0], deg=weather_lst[2],
                      loc=weather_lst[1], wnd=weather_lst[5]))
    return report

def generate_report(report_length, api_key):
    """Generate the weather report based on the parameter.

    :param report_length:
    :return: string
    """
    weather_data_lst = weather_info(api_key)
    if report_length == "fullReport":
        return full_summary(weather_data_lst)
    elif report_length == "shortReport":
        return short_summary(weather_data_lst)
    else:
        return "Invalid Argument"

if __name__ == '__main__':
    API_KEY = raw_input("Please enter your wunderground api key:")
    if len(sys.argv) != 2:
        print("{} of 2 Argument(s) found. Please enter 'fullReport' or "
              "'shortReport' as argument.".format(sys.argv))
    else:
        print generate_report(sys.argv[1], API_KEY)
<|endoftext|>