Beispiel #1
0
  def initUI(self):

    for i in range(0, self._size_barette):
      if i == 0 :
        self.element_tab.append(Element.Element(master = self.master, canvas = self._canvas, angle = self._angle, x_antecedent = self.antecedent_x, y_antecedent = self.antecedent_y))
      else :
        self.element_tab.append(Element.Element(master = self.master, canvas = self._canvas, angle = self._angle, x_antecedent = self.element_tab[i-1].getXYEndincart()[0], y_antecedent = self.element_tab[i-1].getXYEndincart()[1]))
    self.isStripInit = True
Beispiel #2
0
    def init(self):
        print("initialising basic game")

        #create enemy1spawner at middle leftmost block
        elementSpawner1Pos = (0, int(self.board.y / 2))
        elementspawner1 = Element.Element(ElementState.element1Spawner,
                                          elementSpawner1Pos, Direction.right)
        #
        #		##create enemy2spawner at middle rightmost block
        elementSpawner2Pos = (int(self.board.x - 1), int(self.board.y / 2))
        elementspawner2 = Element.Element(ElementState.element2Spawner,
                                          elementSpawner2Pos, Direction.left)

        #print(id(elementspawner1))
        self.board[elementSpawner1Pos] += elementspawner1
        self.board[elementSpawner2Pos] += elementspawner2
Beispiel #3
0
    def getElement(self, elename):
        """Create an element instance from the connectivity information
        (the Element class holds a list of nodes)
        |elem| is the name (i.e. the number) of the element
        (This used to be ElementFactory)
        """
        # test whether the element already exists, shortcut if exists
        try:
            return self.elementCache[elename]
        except:
            pass
        conn = self.Conn[elename]
        nodes = conn[1]
        try:
            sh = self.shapeCache[conn[0]]
        except:
            sh = ShapeFunctions.shapeFunctions[conn[0]]()
            self.shapeCache[conn[0]] = sh

        # collect the nodal coordinates
        nodcoord = N.array([self.Coord[n] for n in nodes])

        # invoke an instance of the element
        e = Element.Element(nodes, sh, nodcoord, elename)
        self.elementCache[elename] = e
        return e
Beispiel #4
0
    def _parse_opening_tag_match(self, opening_tag_match, text):
        tag_closed_count = 1
        end_pos = opening_tag_match.end()
        tag_dict = opening_tag_match.groupdict()
        tag, attributes = tag_dict["tag"], tag_dict["attributes"]

        opening_tag_p = Regex.OPENING_TAG_P_FORMAT.format(tag=tag)
        closing_tag_p = Regex.CLOSING_TAG_P_FORMAT.format(tag=tag)

        while tag_closed_count != 0:
            opening_tag = re.compile(opening_tag_p).search(text, end_pos)
            closing_tag = re.compile(closing_tag_p).search(text, end_pos)

            nearest_match_tag = Regex.nearest_match(opening_tag, closing_tag)
            if nearest_match_tag is None:
                raise Exceptions.NoMatchingClosingTagError(
                    tag_dict["opening_tag"])
            elif nearest_match_tag == opening_tag:
                tag_closed_count += 1
            elif nearest_match_tag == closing_tag:
                tag_closed_count -= 1

            end_pos = nearest_match_tag.end()

        content = self._create_content(
            text[opening_tag_match.end():closing_tag.start()])
        element = Element.Element(tag, content, attributes)
        return element, end_pos
Beispiel #5
0
def makeElements(EI, F, w0, l, N):
    elts = []
    for i in range(N):
        elts.append(Element(EI, F, w0, l, N))
    print(elts)
    #K1 = elt.makeKbCblist()
    return elts
Beispiel #6
0
def writeHeader(identifier, number, text):
    if number < 1 or number > 6:
        raise ValueError('Invalid header number: ' + str(number) + '\n')

    f.write('\t<h' + str(number) + ' id="' + identifier + '">' + text + '</h' +
            str(number) + '>\n')
    elements.append(Element(identifier, 'heading' + str(number), text))
    return
Beispiel #7
0
def writeHyperlink(identifier, link, text):
    if identifier is None:
        f.write('\t<a href="' + link + '";>' + text + '</a>\n')
    else:
        f.write('\t<a id="' + identifier + '" href="' + link + '";>' + text +
                '</a>\n')
    elements.append(Element(identifier, 'hyperlink', text))
    return
Beispiel #8
0
 def __init__(self,Z=42):
     self.element = Element(Z)
     self.path0 = '../data/XRayAttenuation/'
     self.fileName = str(Z)+'XRayAttenuation.txt'
     self.data = genfromtxt(self.Path0+self.fileName,skiprows=11)
     self.energy = self.data[:,0]*1e6
     self.mu = self.data[:,1] # cm^2/g
     self.muEnergy = self.data[:,2] # cm^2/g
     self.label= self.element.Symbol #'Z = '+ str(Z)
Beispiel #9
0
 def addToHeap(self, key, item):
     if APQ.length(self) == 0: # if the length of the heap is zero
         index = 0 # initialise i to be zero
     else: # otherwise if the length is greater than 0
         index = APQ.length(self) # i is initialised to length of heap
     element = Element(key, item, index) # create the element
     self._binaryheap.append(element) # add this to the binary heap - append as it is a list
     if APQ.length(self) > 1: # if the size of the binary heap is greater than 1, run the bubble up heap sort
         self.bubbleUpHeap(element)
     return element
Beispiel #10
0
def writeImage(identifier, source, height, width, link):
    if link is None:
        f.write('\t<img id="' + identifier + '" src="' + source +
                '" height = "' + height + '" width = "' + width + '"/>\n')
        elements.append(Element(identifier, 'image', None))
    else:
        writeHyperlink(
            identifier, link, '<img id="' + identifier + '" src="' + source +
            '" height = "' + height + '" width = "' + width + '"/>')
    return
Beispiel #11
0
def insertModule():
    if len(connectEntry.get()) > 0:
        connectValue = connectEntry.get()
        ser = serial.Serial(connectValue, 19200)
        time.sleep(2)
        unit = ControlUnit(ser, protocol)
        s = 1
        number = str(len(elementen) + 1)
        name = '#%s' % number
        element = Element(rootframe, name, unit, s)
        elementen.append(element)
Beispiel #12
0
def minusExponent(lastResult, dividendElements, divisorElements):
    # lastResult times divisor elements
    divisorElementsPosition = 1
    while divisorElementsPosition <= len(divisorElements) - 1:
        # init value for tempResult
        if lastResult.sign == divisorElements[divisorElementsPosition].sign:
            tempResultSign = '+'
        else:
            tempResultSign = '-'
        tempResultBase = lastResult.base * divisorElements[
            divisorElementsPosition].base
        if lastResult.unknow != '':
            tempResultUnknow = lastResult.unknow
        else:
            tempResultUnknow = divisorElements[divisorElementsPosition].unknow
        tempResultExponent = lastResult.exponent + divisorElements[
            divisorElementsPosition].exponent

        # create class for tempResult
        tempResult = Element.Element()
        tempResult.inputElement(sign=tempResultSign,
                                base=tempResultBase,
                                unknow=tempResultUnknow,
                                exponent=tempResultExponent)
        # print(f'Create minus exponent: {output(tempResult)}')

        # minus to dividend
        elementExist = False
        for eachDividendElement in dividendElements:
            if eachDividendElement.unknow == tempResult.unknow and eachDividendElement.exponent == tempResult.exponent:
                # print(f'Minus: {output(eachDividendElement)} and {output(tempResult)}')
                elementExist = True
                eachDividendElement.base = eachDividendElement.base - tempResult.base
                if eachDividendElement.base < 0:
                    eachDividendElement.sign = '-'
                else:
                    eachDividendElement.sign = '+'
        # if element not exist
        if not elementExist:
            tempResult.base *= -1
            if tempResult.base < 0:
                tempResult.sign = '-'
            else:
                tempResult.sign = '+'
            # add tempResult to dividendElements
            dividendElements.append(tempResult)
            # print(f'Add minus: {output(tempResult)}')
            # sort dividendElements
            dividendElements = Element.sortElement(dividendElements)

        divisorElementsPosition += 1

    return dividendElements
Beispiel #13
0
def _find_k_neighbors(input, samples, errors, k):
    result = []
    heapq.heapify(result)
    for i in range(0, len(samples)):
        current_element = Element.Element(
            _calculate_distance(input, samples[i]) * -1, errors[i][0])
        if len(result) < k:
            result.append(current_element)
        else:
            max = heapq.heappop(result)
            if max < current_element:
                heapq.heappush(result, current_element)
            else:
                heapq.heappush(result, max)

    return result
Beispiel #14
0
    def addElement(self, infoList):
        id, a, b, c, d, e, f, g, h = infoList
        id = int(id.split(",")[0].strip())

        a = self.getNodeByID(int(a.split(",")[0].strip()))
        b = self.getNodeByID(int(b.split(",")[0].strip()))
        c = self.getNodeByID(int(c.split(",")[0].strip()))
        d = self.getNodeByID(int(d.split(",")[0].strip()))
        e = self.getNodeByID(int(e.split(",")[0].strip()))
        f = self.getNodeByID(int(f.split(",")[0].strip()))
        g = self.getNodeByID(int(g.split(",")[0].strip()))
        h = self.getNodeByID(int(h.split(",")[0].strip()))

        newElement = Element(id, a, b, c, d, e, f, g, h)
        self.elementMap[id] = newElement
        self.elements += 1
        self.insertSurfaces(newElement)
Beispiel #15
0
    def createMaze(self, matrix):
        self.maze = matrix
        self.mazeRow = matrix.row
        self.mazeCol = matrix.col

        for i in range(self.mazeRow):
            elementLine = []
            for j in range(self.mazeCol):
                if ([i, j]) in matrix.getAvailable():
                    available = True
                else:
                    available = False
                elementLine.append(el.Element(i, j, available))
            self.element.append(elementLine)

        self.mazeStart = self.getElement(*matrix.getStart())
        self.mazeEnd = self.getElement(*matrix.getEnd())
Beispiel #16
0
    def fixml_sell_eod(self, ticker, quantity,limit):
        """ Generates FIXML for a sell order"""

        fixml=Element("FIXML")
        fixml.set("xmlns",FIXML_NAMESPACE)
        order=SubElement(fixml,"Order")
        order.set("TmInForce","7") #Market on close
        order.set("Typ","2") #Limit
        order.set("Side","2") #Sell
        order.set("Px","%.2f"%limit) #Limit price
        order.set("Acct",TRADEKING_ACCOUNT_NUMBER)
        instrmt=SubElement(order,"Instrmt")
        instrmt.set("SecTyp","CS") #Common stock
        instrmt.set("Sym",ticker)
        ord_qty=SubElement(order,"OrdQty")
        ord_qty.set("Qty",str(quantity))

        return self.xml_tostring(fixml)
Beispiel #17
0
    def load_elements(self, filename):
        data = np.loadtxt(filename, delimiter="\t", dtype=np.str)

        data = np.char.strip(data)

        property_names = data[0, :]
        data = data[1:, :]

        name_col_index = np.where(property_names == "Name")[0][0]

        self.__e_list = []
        for i in range(len(data)):
            row = data[i]

            name = row[name_col_index]
            properties = {}

            for j in range(0, len(row)):
                if j != name_col_index:
                    properties[property_names[j]] = row[j]

            self.__e_list.append(Element.Element(name, properties))
Beispiel #18
0
def divideHandling(dividendElements, divisorElements):
    # result element list
    resultElements = []

    # keep working if the synthesis division is not finish
    while checkExponent(dividendElements, divisorElements):

        firstDividendElement = dividendElements[0]
        firstDivisorElement = divisorElements[0]

        # create the result when 1st dividend element divide to 1st divisor element
        result = Element.Element()
        if firstDividendElement.sign == firstDivisorElement.sign:
            resultSign = '+'
        else:
            resultSign = '-'
        resultBase = firstDividendElement.base / firstDivisorElement.base
        resultUnknow = firstDividendElement.unknow
        resultExponent = firstDividendElement.exponent - firstDivisorElement.exponent
        if resultExponent == 0: resultUnknow = ''
        # input variable to class
        result.inputElement(sign=resultSign,
                            base=resultBase,
                            unknow=resultUnknow,
                            exponent=resultExponent)
        # add current result to result element list
        resultElements.append(result)
        # print(f'Add result: {output(result)}')

        # erase first element in dividend
        # print(f'Delete element: {output(dividendElements[0])}')
        dividendElements.pop(0)

        dividendElements = minusExponent(result, dividendElements,
                                         divisorElements)

    return resultElements, dividendElements
Beispiel #19
0
    def dragEnterEvent(self, event):
        _spatium = self.score().spatium()
        self.dragElement = 0

        data = event.mimeData()

        if data.hasFormat(mimeSymbolListFormat) or data.hasFormat(mimeStaffListFormat):
            event.acceptProposedAction()
            return

        if data.hasFormat(mimeSymbolFormat):
            event.acceptProposedAction()

            a = data.data(mimeSymbolFormat)

            doc = QDomDocument()
            line = 0
            column = 0
            err = QString()
            (ok, err, line, column) = doc.setContent(a)
            if not ok:
                print "error reading drag data at %d/%d: %s\n<%s>\n" %(line, column, err.toLatin1().data(), a.data())
                return
            docName = "--"
            e = doc.documentElement()

            dragOffset = QPoint()

            type = Element().readType(e, dragOffset, self.duration)

            el = Element(None)
            if type == ElementType.IMAGE:
                path = QString()
                ee = e.firstChildElement()
                while not ee.isNull():
                    tag = QString(ee.tagName())
                    if tag == "path":
                        path = ee.text()
                        break
                    ee = ee.nextSiblingElement()
                image = Image(None)
                lp = QString(path.toLower())

                if lp.endsWith(".svg"):
                    image = SvgImage(self.score())
                elif lp.endsWith(".jpg") or lp.endsWith(".png") or lp.endsWith(".gif") or lp.endsWith(".xpm"):
                    image = RasterImage(self.score())
                else:
                    print "unknown image format <%s>\n" %path.toLatin1().data()
                el = image
            elif type == ElementType.SLUR or\
                  type == ElementType.VOLTA or\
                  type == ElementType.OTTAVA or \
                  type == ElementType.TRILL or \
                  type == ElementType.PEDAL or \
                  type == ElementType.HAIRPIN or \
                  type == ElementType.TEXTLINE or \
                  type == ElementType.KEYSIG or \
                  type == ElementType.CLEF or \
                  type == ElementType.TIMESIG or \
                  type == ElementType.BREATH or \
                  type == ElementType.GLISSANDO or \
                  type == ElementType.ARTICULATION or \
                  type == ElementType.ACCIDENTAL or \
                  type == ElementType.DYNAMIC or \
                  type == ElementType.TEXT or \
                  type == ElementType.TEMPO_TEXT or \
                  type == ElementType.STAFF_TEXT or \
                  type == ElementType.NOTEHEAD or \
                  type == ElementType.TREMOLO or \
                  type == ElementType.LAYOUT_BREAK or \
                  type == ElementType.MARKER or \
                  type == ElementType.JUMP or \
                  type == ElementType.REPEAT_MEASURE or \
                  type == ElementType.ICON or \
                  type == ElementType.NOTE or \
                  type == ElementType.SYMBOL or \
                  type == ElementType.CHORD or \
                  type == ElementType.SPACER or \
                  type == ElementType.ACCIDENTAL_BRACKET:
                el = Element().create(type, self.score())
            elif type == ElementType.BAR_LINE or type == ElementType.ARPEGGIO or type == ElementType.BRACKET:
                el = Element().create(type, self.score())
                el.setHeight(_spatium * 5)
            else:
                print "dragEnter %s\n" %Element().name(type)

            if el:
                self.dragElement = el
                self.dragElement.setParent(None)
                self.dragElement.read(e)
                self.dragElement.layout()
            return

        if data.hasUrls():
            ul = data.urls()
            for u in ul:
                if u.scheme() == "file":
                    fi = QFileInfo(u.path())
                    suffix = QString(fi.suffix().toLower())
                    if suffix == "svg" or suffix == "jpg" or suffix == "png" or suffix == "gif" or suffix == "xpm":
                        event.acceptProposedAction()
            return
        s = QString(self.tr("unknown drop format: formats %1:\n").arg(data.hasFormat(mimeSymbolFormat)))

        for ss in data.formats():
            s = s +  (QString("   <%1>\n").arg(ss))
        QMessageBox.warning(0, "Drop:", s, QString.null, "Quit", QString.null, 0, 1)
Beispiel #20
0
def create_file(path, content=["<!DOCTYPE html>", Element.Element("html")]):
    return HTMLFile(path, content)
Beispiel #21
0
    def __init__(self, parent):
        GGrule.__init__(self, 1)  # this is the first rule to be executed
        # create the pattern...
        self.LHS = ASG_LinkedListMM()  # create LHS

        self.LHSnode1 = Top(parent)  # List head
        self.LHSnode1.graphObject_ = graph_Top(
            10, 10, self.LHSnode1)  # graphical representation...
        self.LHSnode1.setGGLabel(1)  # Set Graph Grammar Label...

        self.LHSnode2 = LLink(parent)  # Link to 1st. element
        self.LHSnode2.graphObject_ = graph_LLink(
            30, 60, self.LHSnode2)  # graphical representation...
        self.LHSnode2.setGGLabel(2)  # Set Graph Grammar Label...

        self.LHSnode3 = Element(parent)  # Any value
        self.LHSnode3.graphObject_ = graph_Element(
            10, 150, self.LHSnode3)  # graphical representation...
        self.LHSnode3.Label.setNone()
        self.LHSnode3.setGGLabel(3)  # Set Graph Grammar Label...

        self.LHSnode1.out_connections_.append(self.LHSnode2)  # n1 -> n2
        self.LHSnode2.in_connections_.append(self.LHSnode1)

        self.LHSnode2.out_connections_.append(self.LHSnode3)  # n2 -> n3
        self.LHSnode3.in_connections_.append(self.LHSnode2)

        self.LHS.addNode(self.LHSnode1)
        self.LHS.addNode(self.LHSnode2)
        self.LHS.addNode(self.LHSnode3)

        # create RHS...

        self.RHS = ASG_LinkedListMM()  # Also a Linked List...

        self.RHSnode1 = Top(parent)  # List head
        self.RHSnode1.graphObject_ = graph_Top(
            10, 10, self.RHSnode1)  # graphical representation...
        self.RHSnode1.setGGLabel(1)  # Set Graph Grammar Label...

        self.RHSnode2 = LLink(parent)  # Link to inserted element
        self.RHSnode2.graphObject_ = graph_LLink(
            30, 60, self.RHSnode2)  # graphical representation...
        self.RHSnode2.setGGLabel(2)  # Set Graph Grammar Label...

        self.RHSnode3 = Element(parent)  # NEW ELEMENT
        self.RHSnode3.Label.setValue('NEW ELEMENT')
        self.RHSnode3.graphObject_ = graph_Element(
            10, 150, self.RHSnode3)  # graphical representation...
        self.RHSnode3.setGGLabel(4)  # Set Graph Grammar Label (NEW LABEL)

        self.RHSnode4 = LLink(parent)  # Link to inserted element
        self.RHSnode4.graphObject_ = graph_LLink(
            30, 220, self.RHSnode4)  # graphical representation...
        self.RHSnode4.setGGLabel(5)  # Set Graph Grammar Label...

        self.RHSnode5 = Element(parent)  # Any value
        self.RHSnode5.Label.setNone()
        self.RHSnode5.graphObject_ = graph_Element(
            10, 280, self.RHSnode5)  # graphical representation...
        self.RHSnode5.setGGLabel(3)  # Set Graph Grammar Label...

        self.RHSnode1.out_connections_.append(self.RHSnode2)  # n1 -> n2
        self.RHSnode2.in_connections_.append(self.RHSnode1)

        self.RHSnode2.out_connections_.append(self.RHSnode3)  # n2 -> n3
        self.RHSnode3.in_connections_.append(self.RHSnode2)

        self.RHSnode3.out_connections_.append(self.RHSnode4)  # n3 -> n4
        self.RHSnode4.in_connections_.append(self.RHSnode3)

        self.RHSnode4.out_connections_.append(self.RHSnode5)  # n4 -> n5
        self.RHSnode5.in_connections_.append(self.RHSnode4)

        self.RHS.addNode(self.RHSnode1)
        self.RHS.addNode(self.RHSnode2)
        self.RHS.addNode(self.RHSnode3)
        self.RHS.addNode(self.RHSnode4)
        self.RHS.addNode(self.RHSnode5)
Beispiel #22
0
 def __init__(self):
      self.item =  Element()
from Element import *

periodicTable = {
    'Al': Element('Al', '26.97'),
    'Sb': Element('Sb', '121.76'),
    'Cu': Element('Cu', '63.57'),
    'Ag': Element('Ag', '107.88'),
    'Hg': Element('Hg', '200.61'),
    'Ba': Element('Ba', '137.36'),
    'Be': Element('Be', '9.02'),
    'Bi': Element('Bi', '209.00'),
    'Br': Element('Br', '79.91'),
    'Ca': Element('Ca', '40.08'),
    'C': Element('C', '12.01'),
    'Cl': Element('Cl', '35.457'),
    'Co': Element('Co', '58.94'),
    'Cu': Element('Cu', '63.57'),
    'Sn': Element('Sn', '118.70'),
    'Sr': Element('Sr', '87.63'),
    'Fe': Element('Fe', '55.84'),
    'F': Element('F', '19.00'),
    'P': Element('P', '31.02'),
    'H': Element('H', '1.0078'),
    'I': Element('I', '126.92'),
    'Li': Element('Li', '6.940'),
    'Mg': Element('Mg', '24.32'),
    'Mn': Element('Mn', '54.18'),
    'Hg': Element('Hg', '200.61'),
    'Mo': Element('Mo', '96.0'),
    'Ni': Element('Ni', '58.69'),
    'N': Element('N', '14.008'),
Beispiel #24
0
 def setUp(self):
     self.driver = Element()
Beispiel #25
0
 def addElement(self, e, a, n1, n2):
     self.Elements.append(Element(e, a, n1, n2))
     return self.Elements[-1]
Beispiel #26
0
def writeParagraph(identifier, text):
    f.write('\t<p id="' + identifier + '">' + text + '</p>\n')
    elements.append(Element(identifier, 'paragraph', text))
    return
Beispiel #27
0
from Node import *
from Element import *

eqn = 0
n1 = Node(0, 0, 0)
n2 = Node(1, 1, 0)
e1 = Element(1, 1, n1, n2)
c1 = Constraint(False, True, True)
print(c1.constraint_print())
n1.set_constraint(c1)
eqn = n1.enumerate_dofs(eqn)
eqn = n2.enumerate_dofs(eqn)
print(e1.get_e1())
print(e1.compute_stiffness_matrix())
print(eqn)
print(n1.get_dof_numbers())
print(n2.get_dof_numbers())
Beispiel #28
0
    def __init__(self, js):
        # Load the jason file and construct the virtual structure
        # Create Node objects and put them in nparray "nodes"
        # self.n_totalFreeDof = 0 #added by pubudu to extractDOF from deformation increment vector
        self.fix_Point_array = []

        self.n_nodes = js["no_of_nodes"]
        self.nodes = np.empty(self.n_nodes, dtype=Node)
        js_nodes = js["nodes"]
        for node in js_nodes:
            id = node["id"]
            p_x = node["x"]
            p_y = node["y"]
            p_z = node["z"]
            new_node = Node(id, p_x, p_y, p_z)
            self.nodes.put(id, new_node)

        # Create CrossSection objects and put them in nparray "cross_sections"
        self.no_of_crosssection_types = js["no_of_crosssection_types"]
        self.cross_sections = np.empty(self.no_of_crosssection_types, dtype=CrossSection)
        js_cross_sections = js["cross_sections"]
        for cross_section in js_cross_sections:
            id = cross_section["id"]
            shape = cross_section["shape"]
            dimensions = cross_section["dimensions"]
            new_cross_section = None
            if shape == "rectangle":
                width = dimensions["z"]
                height = dimensions["y"]
                new_cross_section = SquareCrossSection(id, width, height)

            elif shape == "circle":
                radius = dimensions["radius"]
                new_cross_section = CircularCrossSection(id, radius)

            self.cross_sections.put(id, new_cross_section)

        # Create Element objects and put them in nparray "elements"
        self.n_elements = js["no_of_elements"]
        self.elements = np.empty(self.n_elements, dtype=Element)
        js_elements = js["elements"]
        for element in js_elements:
            id = element["id"]
            start_node_id = element["start_node_id"]
            start_node = self.nodes[start_node_id]
            end_node_id = element["end_node_id"]
            end_node = self.nodes[end_node_id]
            cross_section = self.cross_sections[element["element_type"]]
            material_id = element["material_id"]
            local_x_dir = element["local_x_dir"]

            local_dirs = [local_x_dir, 0, 0]

            new_element = Element(id, start_node, end_node, cross_section, material_id, local_dirs)
            self.elements.put(id, new_element)

        # Take loads applied and assign them to Nodes
        self.no_of_loads = js["no_of_loads"]
        js_loads = js["loads"]
        for load in js_loads:
            # id = load["id"]
            node_id = load["point_id"]
            force = load["force"]
            f_x = force["x"]
            f_y = force["y"]
            f_z = force["z"]
            torque = load["torque"]
            m_x = torque["x"]
            m_y = torque["y"]
            m_z = torque["z"]

            node = self.nodes[node_id]
            [node.f_x, node.f_y, node.f_z, node.m_x, node.m_y, node.m_z] = [f_x, f_y, f_z, m_x, m_y, m_z]

        # Take fixed points and assign nodes as fixed
        self.no_of_fixed_points = js["no_of_fixed_points"]
        js_fixed_points = js["fixed_points"]
        for fixed_point in js_fixed_points:
            # id = fixed_point["id"]
            node_id = fixed_point["point_id"]
            translation = fixed_point["translation"]
            self.fix_Point_array += [node_id]
            t_x = translation["x"]
            t_y = translation["y"]
            t_z = translation["z"]

            rotation = fixed_point["rotation"]
            r_x = rotation["x"]
            r_y = rotation["y"]
            r_z = rotation["z"]

            node = self.nodes[node_id]
            [node.t_x, node.t_y, node.t_z, node.r_x, node.r_y, node.r_z] = [t_x, t_y, t_z, r_x, r_y, r_z]
Beispiel #29
0
    def parse(self, strInput):
        """ Detect les element et les insere dans une liste """

        strInput = strInput.replace(' ', '')
        strInput = strInput.replace('+-', '-')
        strInput = self.replacePowerI(strInput)
        i = 0
        list = []
        error = str()
        while i < len(strInput):
            if re.match('-i', strInput[i:]):
                find = re.search('-i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(real=0, img=-1))
            elif re.match('\d+?\*?i', strInput[i:]):
                find = re.search('\d+?\*?i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(find))
            elif re.match('\d+\.\d+\*?i', strInput[i:]):
                find = re.search('\d+\.\d+\*?i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(find))
            elif re.match('i', strInput[i:]):
                find = re.search('i', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Complex(find))
            elif re.match('\d+\.\d+', strInput[i:]):
                find = re.search('\d+\.\d+', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Number(find, 'float'))
            elif re.match('\d+', strInput[i:]):
                find = re.search('\d+', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Number(find, 'int'))
            elif re.match('[a-zA-Z]+\([a-zA-Z]+\)', strInput[i:]):
                find = re.search('[a-zA-Z]+\([a-zA-Z]+\)',
                                 strInput[i:]).group(0)
                i += len(find) - 1
                if 'i' in find:
                    error = "\033[31mA function cannot contain i\033[0m"
                list.append(Element(find, 'defFunction'))
            elif re.match('[a-zA-Z]+\(\-?\d+\)', strInput[i:]):
                find = re.search('[a-zA-Z]+\(\-?\d+\)', strInput[i:]).group(0)
                i += len(find) - 1
                if 'i' in find:
                    error = "\033[31mA function cannot contain i\033[0m"
                list.append(Element(find, 'callFunction'))
            elif re.match('[a-zA-Z]+', strInput[i:]):
                find = re.search('[a-zA-Z]+', strInput[i:]).group(0)
                i += len(find) - 1
                if 'i' in find:
                    error = "\033[31mA variable cannot contain i\033[0m"
                list.append(Element(find, 'var'))
            elif strInput[i] == '[':
                find = Matrice.getMatrice(strInput[i:])
                i += len(find) - 1
                matrice = Matrice(find)
                if not matrice.valid:
                    error = "\033[31mInvalid Matrice:\033[0m " + find
                list.append(matrice)
            elif re.match('\*\*', strInput[i:]):
                find = re.search('\*\*', strInput[i:]).group(0)
                i += len(find) - 1
                list.append(Element(find, 'operator'))
            elif strInput[i] in '+-*/%^=?()':
                list.append(Element(strInput[i], 'operator'))
            else:
                error = "\033[31mInvalid input:\033[0m " + strInput[i]
            i += 1
            if not error == "":
                break
        self.solveError(list)
        if error == "":
            error = self.checkError(strInput)
        return list, error
Beispiel #30
0
    def dropEvent(self, event):
        pos = QPointF(self.imatrix.map(QPointF(event.pos())))

        if self.dragElement:
            self._score.startCmd()
            self.dragElement.setScore(self._score)
            self._score.addRefresh(self.dragElement.abbox())
            if self.dragElement.type() == ElementType.VOLTA or\
               self.dragElement.type() == ElementType.OTTAVA or \
               self.dragElement.type() == ElementType.TRILL or\
               self.dragElement.type() == ElementType.PEDAL or\
               self.dragElement.type() == ElementType.DYNAMIC or\
               self.dragElement.type() == ElementType.HAIRPIN or\
               self.dragElement.type() == ElementType.TEXTLINE:
                self.dragElement.setScore(self.score())
                self.score().cmdAdd1(self.dragElement, pos, self.dragOffset)
                self.event.acceptProposedAction()
            elif self.dragElement.type() == ElementType.SYMBOL or\
                  self.dragElement.type() == ElementType.IMAGE:
                el = self.elementAt(pos)
                if el == 0:
                    staffIdx = -1
                    seg = Segment()
                    tick = 0
                    el = self._score.pos2measure(pos, tick, staffIdx, 0, seg, 0)
                    if el == 0:
                        print "cannot drop here\n"
                        del self.dragElement

                self._score.addRefresh(el.abbox())
                self._score.addRefresh(self.dragElement.abbox())
                dropElement = el.drop(self, pos, self.dragOffset, self.dragElement)
                self._score.addRefresh(el.abbox())
                if dropElement:
                    self._score.select(dropElement, SelectType.SELECT_SINGLE, 0)
                    self._score.addRefresh(dropElement.abbox())
                    event.acceptProposedAction()
            elif self.dragElement.type() == ElementType.KEYSIG or\
                  self.dragElement.type() == ElementType.CLEF or\
                  self.dragElement.type() == ElementType.TIMESIG or\
                  self.dragElement.type() == ElementType.BAR_LINE or\
                  self.dragElement.type() == ElementType.ARPEGGIO or\
                  self.dragElement.type() == ElementType.BREATH or\
                  self.dragElement.type() == ElementType.GLISSANDO or\
                  self.dragElement.type() == ElementType.BRACKET or\
                  self.dragElement.type() == ElementType.ARTICULATION or\
                  self.dragElement.type() == ElementType.ACCIDENTAL or\
                  self.dragElement.type() == ElementType.TEXT or\
                  self.dragElement.type() == ElementType.TEMPO_TEXT or\
                  self.dragElement.type() == ElementType.STAFF_TEXT or\
                  self.dragElement.type() == ElementType.NOTEHEAD or\
                  self.dragElement.type() == ElementType.TREMOLO or\
                  self.dragElement.type() == ElementType.LAYOUT_BREAK or\
                  self.dragElement.type() == ElementType.MARKER or\
                  self.dragElement.type() == ElementType.JUMP or\
                  self.dragElement.type() == ElementType.REPEAT_MEASURE or\
                  self.dragElement.type() == ElementType.ICON or\
                  self.dragElement.type() == ElementType.NOTE or\
                  self.dragElement.type() == ElementType.CHORD or\
                  self.dragElement.type() == ElementType.SPACER or\
                  self.dragElement.type() == ElementType.SLUR or\
                  self.dragElement.type() == ElementType.ACCIDENTAL_BRACKET:
                el = Element()
                for e in self.elementsAt(pos):
                    if e.acceptDrop(self, pos, self.dragElement.type(), self.dragElement.subtype()):
                        el = e
                        break
                if not el:
                    print "cannot drop here\n"
                    del self.dragElement
                self._score.addRefresh(el.abbox())
                self._score.addRefresh(self.dragElement.abbox())
                dropElement = el.drop(self, pos, self.dragOffset, self.dragElement)
                self._score.addRefresh(el.abbox())
                if dropElement:
                    if not self._score.noteEntryMode():
                        self._score.select(dropElement, SelectType.SELECT_SINGLE, 0)
                        self._score.addRefresh(dropElement.abbox())
                        event.acceptProposedAction()
            else:
                del self.dragElement

            self.dragElement = 0
            self.setDropTarget(0)
            self.score().endCmd()
            return

        if event.mimeData().hasUrls():
            ul = event.mimeData().urls()
            u = ul.front()
            if u.scheme() == "file":
                fi = QFileInfo(u.path())
                s = Image()
                suffix = fi.suffix().toLower()
                if suffix == "svg":
                    s = SvgImage(self.score())
                elif suffix == "jpg" or suffix == "png" or suffix == "gif" or suffix == "xpm":
                    s = RasterImage(self.score())
                else:
                    return
                self._score.startCmd()
                s.setPath(u.toLocalFile())

                el = self.elementAt(pos)
                if el and (el.type() == ElementType.NOTE or el.type() == ElementType.REST):
                    s.setTrack(el.track())
                    if el.type() == ElementType.NOTE:
                        note = el
                        s.setTick(note.chord().tick())
                        s.setParent(note.chord().segment().measure())
                    else:
                        rest = el
                        s.setTick(rest.tick())
                        s.setParent(rest.segment().measure())
                        self.score().undoAddElement(s)
                else:
                    self.score().cmdAddBSymbol(s, pos, self.dragOffset)

                event.acceptProposedAction()
                self.score().endCmd()
                self.setDropTarget(0)
                return
            return

        md = event.mimeData()
        data = QFileInfo()
        if md.hasFormat(mimeSymbolListFormat):
            etype = ElementType.ELEMENT_LIST
            data = md.data(mimeSymbolListFormat)
        elif md.hasFormat(mimeStaffListFormat):
            etype = ElementType.STAFF_LIST
            data = md.data(mimeStaffListFormat)
        else:
            print "cannot drop this object: unknown mime type\n"
            sl = md.formats()
            for s in sl:
                print "  %s\n" %s.toAscii().data()
            self._score.end()
            return


        doc = QDomDocument()

        (ok, err, line, column) = doc.setContent(data)
        if not ok:
            qWarning("error reading drag data at %d/%d: %s\n   %s\n" %(line, column, err.toAscii().data(), data.data()))
            return
        docName = "--"
        el = self.elementAt(pos)
        if el == 0 or el.type() != ElementType.MEASURE:
            self.setDropTarget(0)
            return
        measure = el

        if etype == ElementType.ELEMENT_LIST:
            print "drop element list\n"
        elif etype == ElementType.MEASURE_LIST or etype == ElementType.STAFF_LIST:
            self._score.startCmd()
            s = measure.system()
            idx   = s.y2staff(pos.y())
            if idx != -1:
                seg = measure.first()
                while seg.subtype() != SegmentType.SegChordRest:
                    seg = seg.next()
                self.score().pasteStaff(doc.documentElement(), seg.element(idx * VOICES))
            event.acceptProposedAction()
            self._score.setLayoutAll(True)
            self._score.endCmd()
        self.setDropTarget(0)