def __init__(self): # Initilized Pygame Library if pg.get_sdl_version()[0] == 2: pg.mixer.pre_init(44100, 32, 2, 1024) pg.init() if pg.mixer and not pg.mixer.get_init(): print("Warning, no sound") pg.mixer = None # Sets up Window/Screen Display self.winstyle = FULLSCREEN self.bestdepth = pg.display.mode_ok(SCREENRECT.size, self.winstyle, 32) self.screen = pg.display.set_mode(SCREENRECT.size, self.winstyle, self.bestdepth) pg.display.set_caption("Depth") # Stateful variables about mouse movement & IO events self.mouse_rel = pg.mouse.get_rel() self.events = [] self.resources = ResourceManager() # Initialize Containers/Components/UI self.main_menu = Component(SCREENRECT.x, SCREENRECT.y, SCREENRECT.w, SCREENRECT.h) mm = self.main_menu mm.image = self.resources.get_image("mm_back.png") mm.set_font("broadway") mm.text = "Depth" mm_exit_btn = Component(0, 0, 0, 0, parent=mm) mm_exit_btn.resize_width_ratio(1 / 6) mm_exit_btn.resize_height_ratio(1 / 10) mm_exit_btn.center_x_percent(1 / 3) mm_exit_btn.center_y_percent(3 / 4) mm_exit_btn.set_font("calibri") mm_exit_btn.text = "Quit" mm_exit_btn.register_event(Actions.on_left_click, lambda c, gctxt: self.close()) mm_start_btn = Component(0, 0, 0, 0, parent=mm) mm_start_btn.resize_width_ratio(1 / 6) mm_start_btn.resize_height_ratio(1 / 10) mm_start_btn.center_x_percent(2 / 3) mm_start_btn.center_y_percent(3 / 4) mm_start_btn.set_font("calibri") mm_start_btn.text = "Play" mm_start_btn.register_event( Actions.on_left_click, lambda c, gctxt: print("Call code to go to next menu")) self.current_component = self.main_menu
def __init__(self): self.ot = Others() self.ot.logDebug(" Application Started !!!!") self.st = StyleSheet() self.ff = FIFO() self.twdl = TWDL() self.comp = Component() self.ot.app = QtGui.QApplication([self.ot.app_name]) self.ot.desktop_width = 1280 self.ot.desktop_height = 640 print 'desktop resolution -- ', self.ot.app.desktop().geometry().width( ), self.ot.app.desktop().geometry().height() ret = GUI(self.ot, self.ff, self.st, self.comp) t1 = mainPage(self.ot, self.st, self.comp) #listener on socket self.initListener() if self.ff.udpconn.fileno() != 0: self.ot.logDebug(" Socket Connection Established !!!") self.ot.notifyStatus(" Socket Connection Established !!!", 1) else: self.ot.logWarning(" Socket Connection Failed !!!") self.ot.notifyStatus("Socket Connection Failed", 2) sys.exit(self.ot.app.exec_())
def gen_component(self, parent=None, parent_name=None): stop = False if parent is not None: if (parent.depth >= self.max_depth - 1) or (random.uniform(0, 1) < self.stop_prob): stop = True depth = parent.depth + 1 else: stop = False depth = 1 if stop: op_name = random.choice([0, 1]) op_func = None op_inputs = 0 else: op_name, (op_func, op_inputs) = random.choice(list(self.op_dict.items())) component = Component(op_name, parent, depth, op_func, op_inputs, self.encode(op_name)) # if stop: ### WEIRD BUG # self.leaves.append(component) return component
def first_component(self): comp_ref = icalfileset_get_first_component(self._ref) if comp_ref == None: return None return Component(ref=comp_ref)
def __getattr__(self, name): if name not in self._compDict: if name not in self.componentNames: raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name)) path = os.path.join(self.path, name) self._compDict[name] = Component(path) return self._compDict[name]
def _parse(self, xmlmodel): name = xmlmodel.get('name') if not name: logging.warn("Ignoring component definition with no name") else: attributes = xmlmodel.attrib categories = [category.get('name') for category in xmlmodel.findall("category")] self._components[name] = Component(categories, name, attributes)
def __init__(self, mapSize=20): self.mapSize = mapSize self.map = [["None" for _ in range(mapSize)] for _ in range(mapSize)] for i in range(self.mapSize): for j in range(self.mapSize): self.map[i][j] = Component( (['@'] + ['.'] * (self.mapSize**2 - 1))[i * self.mapSize + j], (i, j), self.mapSize, self)
def main(): backend = SimpleBackend() component = Component(jid="test@gic", password="******", server="147.102.6.34", port=5222, backend=backend) component.start() httpFrontend = HTTPFrontend(8081, backend) httpFrontend.start()
def test_that_resolving_does_not_warn_if_category_missing_backend_but_component_includes_it(self): backend = 'db' category = MockCategory() example_component = Component(categories = [category.catid]) component_name = 'example' root = _build_tree_with_valid_component_include(backend, component_name) op = UsesParser() op.parse(root) op.resolve([category], {component_name:example_component}, {backend:MockBackend()}) assert_that(self.l.__str__(), is_("No logging captured"))
def check_starers(self): input_types = {} for cmp in self.start_components: input_types.add(Component(component_node(cmp).comp).input_type) if len(input_types) > 1: tmp = input_types for type in tmp: for a in self.CONVERSION_MAP[type]: input_types.remove(a) if len(input_types) > 1: return "ERROR Starting components cannon be fead by single source" return 0
def FullAdder(): """ Retorna un component amb el funcionament d'un full-adder (suma A, B i Cin). :return: Un component amb el comportament d'un full-adder """ e1 = Entrada("A") e2 = Entrada("B") e3 = Entrada("Cin") s = Sortida('S') s1 = Sortida('Cout') componentFullAdder = Component( { e1.getName(): e1, e2.getName(): e2, e3.getName(): e3 }, { s.getName(): s, s1.getName(): s1 }, "Full Adder") #calcul s n1 = Node("N1") x = XOR(e1, e2, n1) x2 = XOR(e3, n1, s) #Cout n2 = Node("N2") a1 = And(e3, n1, n2) n3 = Node("N3") a2 = And(e1, e2, n3) o = Or(n2, n3, s1) sup = Supervisor() sup.addNode(n1) sup.addNode(n2) sup.addNode(n3) sup.addNode(s) sup.addNode(s1) sup.addTickable(x) sup.addTickable(x2) sup.addTickable(a1) sup.addTickable(a2) sup.addTickable(o) componentFullAdder.AddArchitecture([n1, n2, n3, a1, a2, o, x, x2], sup) return componentFullAdder
def __init__(self, brick): self.brick = brick self.queue = Queue() self.components = {} self.sensors = {} self.active = Component(self) self.InitializeHardware() self.InitializeComponents() self.InitializeSensors() self.active.Start() self.queue_thread = Thread(target=self.QueueWorker) self.queue_thread.start()
def getComponent( node_component, prefix): processor_name = PipelineXMLParser.getAttribute( node_component, PipelineXMLParser.COMPONENT_PROCESSOR_ATT) if processor_name != None and len( processor_name) > 0: PipelineXMLParser.RANK += 1 component = Component( processor_name, str(PipelineXMLParser.RANK), prefix) if component != None: for node in node_component: if node.tag.lower() == PipelineXMLParser.PARAM_TAG: PipelineXMLParser.getParam( node, component) return component else: raise ParsingException( "PipelineXMLParser.getComponent : Unable to create Component '" + processor_name) else: raise ParsingException( "PipelineXMLParser.getComponent : Malformed component - unable to retrieve processor name")
def test_that_component_level_exclude_overrides_include_all(self): category = MockCategory() example_component = Component(categories = [category.catid]) component_name = 'example' root = ET.Element('config') uses = ET.SubElement(root, 'uses') backend = 'db' use = ET.SubElement(uses, 'use', {'backend':backend}) ET.SubElement(use, 'includeall') exclude = ET.SubElement(use, 'exclude') ET.SubElement(exclude, 'component', {'name':component_name}) op = UsesParser() op.parse(root) op.resolve([category], {component_name:example_component}) self.l.check(('root', 'WARNING', "Category '{0}' has no backend specified".format(category.catid)))
def CreateMainCircuit(): """ Crea un component que fa el que se'ns havia demanat a la pràctica (el circuit proposat) :return: Un component amb el comportament del circuit proposat a la pràctica. """ # definim 4 entrades e1 = Entrada("E1") e2 = Entrada("E2") e3 = Entrada("E3") e4 = Entrada('E4') # definim 1 sortida s = Sortida('S1') defaultC = Component( { e1.getName(): e1, e2.getName(): e2, e3.getName(): e3, e4.getName(): e4 }, {s.getName(): s}, "Main Circuit") # definim el circuit n1 = Node('N1') a1 = And(e1, e2, n1) n2 = Node('N2') a2 = And(e3, e4, n2) a3 = And(n1, n2, s) # creem un supervisor i l'informem dels nodes i triports que ha de supervisar sup = Supervisor() sup.addNode(n1) sup.addNode(n2) sup.addNode(s) sup.addTickable(a1) sup.addTickable(a2) sup.addTickable(a3) defaultC.AddArchitecture([n1, a1, n2, a2, a3], sup) return defaultC
def start(self): """ Start load of all device controllers """ cp = CommPool(self.CONFIG, preferred_url=CommPool.URL_TICKETS) cp.logFromCore(Messages.system_controllers_connect.format(cp.URL_BASE), LogTypes.INFO, self.__class__.__name__) while True: #cp.logFromCore(Messages.controller_searching, LogTypes.DEBUG, self.__class__.__name__) controllersFolders = Misc.lsFolders("./Controllers") for cf in controllersFolders: if Misc.hasKey(self.controllers, cf, None) == None: comp = Component(cf, cp) self.controllers[cf] = comp for c in self.controllers: comp = self.controllers[c] comp.load() sleep(self.CHECKING_TIME) cp.logFromCore(Messages.controller_stop, LogTypes.INFO, self.__class__.__name__)
def loadChannel(self, config, cf: str): """ Load channel objects """ file_class = Misc.hasKey(config, 'FILE_CLASS', '') class_name = Misc.hasKey(config, 'CLASS_NAME', '') if file_class != '' and class_name != '': _cls = Misc.importModule(cf, file_class, class_name) obj = _cls() obj.ME_CONFIG = config obj.ME_PATH = cf obj.COMMPOOL = self.COMMPOOL obj.ENABLED = Misc.toBool( Misc.hasKey(obj.ME_CONFIG, 'ENABLED', 'False')) obj.ME_TYPE = SourceTypes.parse( Misc.hasKey(obj.ME_CONFIG, 'TYPE', None)) obj.ME_NAME = Misc.hasKey(obj.ME_CONFIG, 'NAME', class_name) obj.Check = hashlib.md5(str( obj.ME_CONFIG).encode('utf-8')).hexdigest() obj.preLoad() return obj else: comp = Component() comp.ENABLED = False return comp
def _grab_component(self): self.monitor.total_components += 1 self.monitor.sample_components_in_sys() component = Component(random.choice(self.types)) self.monitor.all_components_made.append(component) return component
from Component import Component sys = Component('sys') Game().start(players)
def check(self): """\ check() -> Interpretor, Design Checks the requirements of a design. """ if hasattr(self, '_check'): return self._check # Step 1, calculate the properties i, design = self.calculate() total_okay = True total_feedback = [] # Step 2, calculate the requirements for the properties ranks = self.rank() for rank in ranks.keys(): for property_id in ranks[rank]: property = Property(property_id) if property.requirements == '': print "Property with id (%i) doesn't have any requirements" % property_id continue print "Now checking the following requirement" print property.requirements result = i.eval( scheme.parse("""(%s design)""" % property.requirements)) print "Result was:", result okay, feedback = scheme.pair.car(result), scheme.pair.cdr( result) if okay != scheme.symbol.Symbol('#t'): total_okay = False if feedback != "": total_feedback.append(feedback) # Step 3, calculate the requirements for the components for component_id, amount in self.components: component = Component(component_id) if component.requirements == '': print "Component with id (%i) doesn't have any requirements" % component_id continue print "Now checking the following requirement" print component.requirements result = i.eval( scheme.parse("""(%s design)""" % component.requirements)) print "Result was:", result okay, feedback = scheme.pair.car(result), scheme.pair.cdr(result) if okay != scheme.symbol.Symbol('#t'): total_okay = False if feedback != "": total_feedback.append(feedback) self._check = (total_okay, "\n".join(total_feedback)) return total_okay, "\n".join(total_feedback)
#!/usr/bin/env python
### Fluid Properties ### ######################## ### Air ### Ti = 298.0 To = 293.0 Cp = 1012 m = 2.03576 Rho = 1.184 mu = 0.00001983 mu_w = 0.00001983 R_f = 0.0001 k = 0.026055 air = Component(Cp, m, Rho, Ti, To, mu, mu_w, R_f, k) ### Nitrogen ### Ti = 93.0 To = 288.0 Cp = 1932.8 m = 0.02687 Rho = 183.6 mu = 0.0000234342 mu_w = 0.000012352 R_f = 0.0001 k = 0.034983363 nitrogen = Component(Cp, m, Rho, Ti, To, mu, mu_w, R_f, k) nitrogen.add_data("nitrogen40bar")
def buildComponent(self): assert (self._ini_reader.has_option('Component', 'name')) ch = self.buildChannel() compName = self._ini_reader.get('Component', 'name').strip() retval = Component(compName, ch)
def build(objtId, p): if (p.__class__.__name__ == 'AttackerParameters'): return Attacker(objtId, p.name(), p.description(), p.image(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'PersonaParameters'): return Persona(objtId, p.name(), p.activities(), p.attitudes(), p.aptitudes(), p.motivations(), p.skills(), p.intrinsic(), p.contextual(), p.image(), p.assumption(), p.type(), p.tags(), p.environmentProperties(), p.codes()) if (p.__class__.__name__ == 'AssetParameters'): return Asset(objtId, p.name(), p.shortCode(), p.description(), p.significance(), p.type(), p.critical(), p.criticalRationale(), p.tags(), p.interfaces(), p.environmentProperties()) if (p.__class__.__name__ == 'TemplateAssetParameters'): return TemplateAsset(objtId, p.name(), p.shortCode(), p.description(), p.significance(), p.type(), p.surfaceType(), p.accessRight(), p.properties(), p.rationale(), p.tags(), p.interfaces()) if (p.__class__.__name__ == 'TemplateRequirementParameters'): return TemplateRequirement(objtId, p.name(), p.asset(), p.type(), p.description(), p.rationale(), p.fitCriterion()) if (p.__class__.__name__ == 'TemplateGoalParameters'): return TemplateGoal(objtId, p.name(), p.definition(), p.rationale(), p.concerns(), p.responsibilities()) if (p.__class__.__name__ == 'SecurityPatternParameters'): return SecurityPattern(objtId, p.name(), p.context(), p.problem(), p.solution(), p.requirements(), p.associations()) if (p.__class__.__name__ == 'ComponentParameters'): return Component(objtId, p.name(), p.description(), p.interfaces(), p.structure(), p.requirements(), p.goals(), p.associations()) if (p.__class__.__name__ == 'ComponentViewParameters'): return ComponentView(objtId, p.name(), p.synopsis(), p.components(), p.connectors(), p.attackSurfaceMetric()) if (p.__class__.__name__ == 'ValueTypeParameters'): return ValueType(objtId, p.name(), p.description(), p.type(), p.score(), p.rationale()) if (p.__class__.__name__ == 'ClassAssociationParameters'): return ClassAssociation(objtId, p.environment(), p.headAsset(), p.headDimension(), p.headNavigation(), p.headType(), p.headMultiplicity(), p.headRole(), p.tailRole(), p.tailMultiplicity(), p.tailType(), p.tailNavigation(), p.tailDimension(), p.tailAsset(), p.rationale()) if (p.__class__.__name__ == 'GoalAssociationParameters'): return GoalAssociation(objtId, p.environment(), p.goal(), p.goalDimension(), p.type(), p.subGoal(), p.subGoalDimension(), p.alternative(), p.rationale()) if (p.__class__.__name__ == 'DependencyParameters'): return Dependency(objtId, p.environment(), p.depender(), p.dependee(), p.dependencyType(), p.dependency(), p.rationale()) if (p.__class__.__name__ == 'GoalParameters'): return Goal(objtId, p.name(), p.originator(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'ObstacleParameters'): return Obstacle(objtId, p.name(), p.originator(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'DomainPropertyParameters'): return DomainProperty(objtId, p.name(), p.description(), p.type(), p.originator(), p.tags()) if (p.__class__.__name__ == 'ThreatParameters'): return Threat(objtId, p.name(), p.type(), p.method(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'VulnerabilityParameters'): return Vulnerability(objtId, p.name(), p.description(), p.type(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'RiskParameters'): return Risk(objtId, p.name(), p.threat(), p.vulnerability(), p.tags(), p.misuseCase()) if (p.__class__.__name__ == 'ResponseParameters'): return Response(objtId, p.name(), p.risk(), p.tags(), p.environmentProperties(), p.responseType()) if (p.__class__.__name__ == 'CountermeasureParameters'): return Countermeasure(objtId, p.name(), p.description(), p.type(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'TaskParameters'): return Task(objtId, p.name(), p.shortCode(), p.objective(), p.assumption(), p.author(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'UseCaseParameters'): return UseCase(objtId, p.name(), p.author(), p.code(), p.actors(), p.description(), p.tags(), p.environmentProperties()) if (p.__class__.__name__ == 'MisuseCaseParameters'): return MisuseCase(objtId, p.name(), p.environmentProperties(), p.risk()) if (p.__class__.__name__ == 'DotTraceParameters'): return DotTrace(p.fromObject(), p.fromName(), p.toObject(), p.toName()) if (p.__class__.__name__ == 'EnvironmentParameters'): return Environment(objtId, p.name(), p.shortCode(), p.description(), p.environments(), p.duplicateProperty(), p.overridingEnvironment(), p.tensions()) if (p.__class__.__name__ == 'RoleParameters'): return Role(objtId, p.name(), p.type(), p.shortCode(), p.description(), p.environmentProperties()) if (p.__class__.__name__ == 'ResponsibilityParameters'): return Responsibility(objtId, p.name()) if (p.__class__.__name__ == 'ExternalDocumentParameters'): return ExternalDocument(objtId, p.name(), p.version(), p.date(), p.authors(), p.description()) if (p.__class__.__name__ == 'InternalDocumentParameters'): return InternalDocument(objtId, p.name(), p.description(), p.content(), p.codes(), p.memos()) if (p.__class__.__name__ == 'CodeParameters'): return Code(objtId, p.name(), p.type(), p.description(), p.inclusionCriteria(), p.example()) if (p.__class__.__name__ == 'MemoParameters'): return Memo(objtId, p.name(), p.description()) if (p.__class__.__name__ == 'DocumentReferenceParameters'): return DocumentReference(objtId, p.name(), p.document(), p.contributor(), p.description()) if (p.__class__.__name__ == 'ConceptReferenceParameters'): return ConceptReference(objtId, p.name(), p.dimension(), p.objectName(), p.description()) if (p.__class__.__name__ == 'PersonaCharacteristicParameters'): return PersonaCharacteristic(objtId, p.persona(), p.qualifier(), p.behaviouralVariable(), p.characteristic(), p.grounds(), p.warrant(), p.backing(), p.rebuttal()) if (p.__class__.__name__ == 'TaskCharacteristicParameters'): return TaskCharacteristic(objtId, p.task(), p.qualifier(), p.characteristic(), p.grounds(), p.warrant(), p.backing(), p.rebuttal()) if (p.__class__.__name__ == 'ImpliedProcessParameters'): return ImpliedProcess(objtId, p.name(), p.description(), p.persona(), p.network(), p.specification(), p.channels()) if (p.__class__.__name__ == 'LocationsParameters'): return Locations(objtId, p.name(), p.diagram(), p.locations(), p.links()) else: raise UnknownParameterClass(str(objtId))
def ReadBlockData(self) -> List[Block]: # try: # First we open the BSG file and parse it. # Then we can use a xpath statement to find all the block tags self.cfile = ET.parse(self.cfile) all_blocks = self.cfile.findall(".//Blocks/*") returnList = [] total_blocks = 0 total_components = 0 skipped_blocks = 0 # We will also need to find the global rotation of the machine # This will not effect the normal blocks but will definetly affect # the rotation of the brace cubes and might effect the surface blocks... global_data = self.cfile.findall("./Global/*") global_rot_x = float(global_data[1].get('x')) global_rot_y = float(global_data[1].get('y')) global_rot_z = float(global_data[1].get('z')) global_rot_w = float(global_data[1].get('w')) surface_data_nodes = [] surface_data_edges = [] surface_data_surfaces = [] # We are going to loop over all the blocks in the BSG file... # Here we will organize the blocks, collect special attributes # for certain blocks. Because we have to collect special attributes # the method looks like a complete mess for block in all_blocks: block_id = block.get('id') # first we will check if its a surface data block... # and if it is, save them into an array so we can process them later... # We are checking it here because the surface block has only points and # doesn't need to be normalized... if block_id in ['71', '72', '73']: if block_id == '71': surface_data_nodes.append(block) continue if block_id == '72': surface_data_edges.append(block) continue if block_id == '73': surface_data_surfaces.append(block) continue # Check if the block is in the transform atlast... # if its not, print and increment the skipped block count # we can display it on the addon page... if not block_id in self.atlas.keys(): skipped_blocks += 1 print( "Warning: Cannot find block ID {} in transform data atlas..." .format(block_id)) continue total_blocks += 1 # Get the position of the block... trans_p_x = float(block.find("Transform/Position").get('x')) trans_p_y = float(block.find("Transform/Position").get('y')) trans_p_z = float(block.find("Transform/Position").get('z')) # Get the rotation of the block... trans_r_x = float(block.find("Transform/Rotation").get('x')) trans_r_y = float(block.find("Transform/Rotation").get('y')) trans_r_z = float(block.find("Transform/Rotation").get('z')) trans_r_w = float(block.find("Transform/Rotation").get('w')) # Get the scale of the block... trans_s_x = float(block.find("Transform/Scale").get('x')) trans_s_y = float(block.find("Transform/Scale").get('y')) trans_s_z = float(block.find("Transform/Scale").get('z')) # Create a new instance of the Block object and pass its # its information in... current_block = Block([trans_p_x, trans_p_y, trans_p_z], [trans_r_x, trans_r_y, trans_r_z, trans_r_w], [trans_s_x, trans_s_y, trans_s_z]) # Set the GUID and the other various data... current_block.guid = block.get('guid') current_block.block_id = block_id current_block.code_name = self.atlas[block_id]['code_name'] # Set the global rotation of the block... current_block.SetGlobalMachineRotation(global_rot_x, global_rot_y, global_rot_z, global_rot_w) # These are for propeller blocks... # Various blocks have the flipped property, these include, wheels, # steering blocks, steering hinges, wheels etc... But out of all these # blocks only the propeller blocks have their transform data altered... if (block_id in ['26', '55']): for key in list(block.find("Data")): if key.get('key').__eq__('flipped'): current_block.flipped = key.text # These are for the "Line type blocks". These blocks have two sets of co-ordinates. The start and # end position as well as rotation. if (block_id in ['7', '9', '45']): sp, ep, sr, er = ('0', '0', '0'), ('0', '0', '0'), ('0', '0', '0'), ('0', '0', '0') for key in list(block.find("Data")): if key.get('key').__eq__('start-position'): sp = [ key.find('X').text, key.find('Y').text, key.find('Z').text ] if key.get('key').__eq__('end-position'): ep = [ key.find('X').text, key.find('Y').text, key.find('Z').text ] if key.get('key').__eq__('start-rotation'): sr = [ key.find('X').text, key.find('Y').text, key.find('Z').text ] if key.get('key').__eq__('end-rotation'): er = [ key.find('X').text, key.find('Y').text, key.find('Z').text ] current_block.SetLineTypeGeometry(sp, ep, sr, er) # Each block will have multiple components. The main mesh itself and other little details that do not come # with the mesh. For example, stuff like the needle and switches. This segment will allow us to import that stuff # as well for component in self.atlas[block_id]['components']: print("Adding component ID {}...".format( component['base_source'])) total_components += 1 o_p_x, o_p_y, o_p_z = component['offset']['position'].values() o_r_x, o_r_y, o_r_z = component['offset']['rotation'].values() o_s_x = component['offset']['scale']['x'] o_s_y = component['offset']['scale']['z'] o_s_z = component['offset']['scale']['y'] current_comp_inst = Component([o_p_x, o_p_y, o_p_z], [o_r_x, o_r_y, o_r_z], [o_s_x, o_s_y, o_s_z]) try: current_comp_inst.skin_id = block.find( 'Settings/Skin').get('id') current_comp_inst.skin_name = block.find( 'Settings/Skin').get('name') except: current_comp_inst.skin_id = 'Template' current_comp_inst.skin_name = 'Template' if (current_comp_inst.skin_name == 'default'): current_comp_inst.skin_id = 'Template' current_comp_inst.skin_name = 'Template' current_comp_inst.base_source = component['base_source'] current_comp_inst.group = component['group'] current_comp_inst.line_type_block = component[ 'line_type_blocks'] if current_comp_inst.line_type_block: current_comp_inst.line_type_start = component[ 'line_type_components']['start'] current_comp_inst.line_type_end = component[ 'line_type_components']['end'] current_comp_inst.line_type_middle = component[ 'line_type_components']['middle'] current_block.components.append(deepcopy(current_comp_inst)) returnList.append(current_block) # now that the normal blocks have been processed and all the surface data blocks have been loaded, # we can easily process them as well... # First define a storage for the edges and surfaces. We'll process the edges first for surface in surface_data_surfaces: try: surface_guid = surface.get('guid') # Split the string to get a list of the edge GUIDs surface_edge_guids = surface.find( "Data/String[@key='edges']").text.split("|") c_surface = BuildSurface(surface_guid) if len(surface_edge_guids) == 3: # If we dont have enough edges, we can take a GUID # from the list and add it to the end of the list surface_edge_guids.append(surface_edge_guids[0]) c_surface.IsQuad = False raw_edges = [] # Ok so in the last version what went wrong was that the we needed the edges in the same order # that they were defined in the surface tag. But I simply used a for loop iterating through the # edge tags and checking if their guids were in the list of GUIDs from the surface block tag... # Should've seen that coming because ProNou did warn me... I really need to start reading the # instructions before starting to code... for edge_guid in surface_edge_guids: for edge in surface_data_edges: guid = edge.get('guid') if guid != edge_guid: continue c_edge = BuildSurfaceEdge(guid) start_guid = edge.find( "Data/String[@key='start']").text end_guid = edge.find("Data/String[@key='end']").text start_point_found = False end_point_found = False # Find the pointss that define the start and end point of the edge. for point in surface_data_nodes: if start_point_found and end_point_found: break if point.get('guid') == start_guid: start_point_found = True c_edge.SetStartPoint([ float( point.find("Transform/Position").get( 'x')), float( point.find("Transform/Position").get( 'z')), float( point.find("Transform/Position").get( 'y')) ]) if point.get('guid') == end_guid: end_point_found = True c_edge.SetEndPoint([ float( point.find("Transform/Position").get( 'x')), float( point.find("Transform/Position").get( 'z')), float( point.find("Transform/Position").get( 'y')) ]) # Then set the mid point for the edge... c_edge.SetMidPoint([ float(edge.find('Transform/Position').get('x')), float(edge.find('Transform/Position').get('z')), float(edge.find('Transform/Position').get('y')) ]) # Add it to the list of raw edges raw_edges.append(c_edge) # Now that we have all the raw data edge data, # We can use that data to create the U edges and save it... # First we'll calculate the center edge. Because that's more complicated # than the other two... # First we'll need to get the center point... center_edge_mid_point = [0, 0, 0] # Calculate the total location of the points and edges... # Initilze the variables for the location point_total_location_x = 0 point_total_location_y = 0 point_total_location_z = 0 # Initilize the variable for the edges edge_total_location_x = 0 edge_total_location_y = 0 edge_total_location_z = 0 # This code segment makes sure that no curtain effects are produced. # curtain effect is when the addon fails to align the points in the 3 # edges needed to generate the surface mesh # The curtain effect works differently for Quad surfaces from surfaces with # 3 sides if not c_surface.IsQuad: if raw_edges[0].GetStartPoint() != raw_edges[ 3].GetEndPoint() and raw_edges[2].GetEndPoint( ) != raw_edges[3].GetStartPoint(): raw_edges[3].InvertPointLocations() if raw_edges[0].GetEndPoint() != raw_edges[ 1].GetStartPoint() and raw_edges[1].GetEndPoint( ) != raw_edges[2].GetStartPoint(): raw_edges[1].InvertPointLocations() raw_edges[3].InvertPointLocations() if raw_edges[1].GetStartPoint( ) != raw_edges[3].GetStartPoint(): if raw_edges[1].GetEndPoint( ) != raw_edges[0].GetEndPoint(): raw_edges[3].InvertPointLocations() else: raw_edges[1].InvertPointLocations() else: if raw_edges[1].GetEndPoint( ) != raw_edges[0].GetStartPoint(): raw_edges[1].InvertPointLocations() if raw_edges[2].GetEndPoint( ) != raw_edges[1].GetStartPoint(): raw_edges[2].InvertPointLocations() if raw_edges[3].GetEndPoint( ) != raw_edges[2].GetStartPoint(): raw_edges[3].InvertPointLocations() if raw_edges[0].GetStartPoint() != raw_edges[ 3].GetEndPoint() and raw_edges[2].GetEndPoint( ) != raw_edges[3].GetStartPoint(): raw_edges[3].InvertPointLocations() if raw_edges[0].GetEndPoint() != raw_edges[ 1].GetStartPoint() and raw_edges[1].GetEndPoint( ) != raw_edges[2].GetStartPoint(): raw_edges[1].InvertPointLocations() raw_edges[3].InvertPointLocations() if not c_surface.IsQuad: raw_edges[3].IsFalseEdge = True # Add up all the surfaces edge location as well as # the point locations. If the surface is not a Quad, # then skip the edge position and the point positions for edge in raw_edges: if not edge.IsFalseEdge: point_total_location_x += edge.GetEndPoint()[0] point_total_location_y += edge.GetEndPoint()[1] point_total_location_z += edge.GetEndPoint()[2] point_total_location_x += edge.GetStartPoint()[0] point_total_location_y += edge.GetStartPoint()[1] point_total_location_z += edge.GetStartPoint()[2] edge_total_location_x += edge.GetMidPoint()[0] edge_total_location_y += edge.GetMidPoint()[1] edge_total_location_z += edge.GetMidPoint()[2] # Then do some mathematical magic... # Note that this formula is different for Quads. # because the number of points that needs to split apart # are differnet if c_surface.IsQuad: center_edge_mid_point[0] = 2 * ( edge_total_location_x / 4) - (point_total_location_x / 8) center_edge_mid_point[1] = 2 * ( edge_total_location_y / 4) - (point_total_location_y / 8) center_edge_mid_point[2] = 2 * ( edge_total_location_z / 4) - (point_total_location_z / 8) else: center_edge_mid_point[0] = 2 * ( edge_total_location_x / 3) - (point_total_location_x / 6) center_edge_mid_point[1] = 2 * ( edge_total_location_y / 3) - (point_total_location_y / 6) center_edge_mid_point[2] = 2 * ( edge_total_location_z / 3) - (point_total_location_z / 6) # And now we can finally create a new BuildSurfaceEdge object and feed it the points center_edge = BuildSurfaceEdge("NULL") center_edge.SetStartPoint(raw_edges[0].GetMidPoint()) center_edge.SetEndPoint(raw_edges[2].GetMidPoint()) center_edge.SetMidPoint(center_edge_mid_point) # if the surface is not a quad, then check if the edge_a and edge_b's start and end points # align. if they do not align, use the Start point of the center edge. Otherwise use the end # point. This will result with all the points converging to a single point... if not c_surface.IsQuad: # if raw_edges[0].GetStartPoint() != center_edge.GetEndPoint(): center_edge.InvertPointLocations() if raw_edges[1].GetStartPoint( ) != raw_edges[0].GetEndPoint(): center_edge.SetStartPoint(raw_edges[0].GetStartPoint()) else: center_edge.SetStartPoint(raw_edges[0].GetEndPoint()) # As for the other two edges we already have the data for those two... # So we can feed it to the surface object... c_surface.edge_a = raw_edges[1] c_surface.edge_b = center_edge c_surface.edge_c = raw_edges[3] c_surface.RawEdgeList = raw_edges # define the color data for the surface blocks... c_surface.thickness = float( surface.find("Data/Single[@key='bmt-thickness']").text) c_surface.saturation = float( surface.find("Data/Single[@key='bmt-sat']").text) c_surface.luminosity = float( surface.find("Data/Single[@key='bmt-lum']").text) c_surface.col_rgb = [ float(surface.find("Data/Color/R").text), float(surface.find("Data/Color/G").text), float(surface.find("Data/Color/B").text) ] c_surface.UsePaint = surface.find( "Data/Boolean[@key='bmt-painted']").text == "True" c_surface.MaterialType = int( surface.find("Data/Integer[@key='bmt-surfMat']").text) # define the skin data try: c_surface.skin_id = surface.find('Settings/Skin').get('id') c_surface.skin_name = surface.find('Settings/Skin').get( 'name') except: c_surface.skin_id = 'Template' c_surface.skin_name = 'Template' if (c_surface.skin_name == 'default'): c_surface.skin_id = 'Template' c_surface.skin_name = 'Template' # Add it to the list and increment the number of blocks imported returnList.append(c_surface) total_blocks += 1 # try: # skin_name = surface.find("Settings/Skin").get("name") # skin_id = surface.find("Settings/Skin").get("id") # except: # skin_name = "Template" # skin_id = "Template" # c_surface.skin = skin_name # c_surface.skin_id = skin_id # returnList.append(c_surface) except: skipped_blocks += 1 print( "{} blocks imported...\n{} components imported...\n{} blocks skipped" .format(total_blocks, total_components, skipped_blocks)) return { 'RETURN_LIST': returnList, 'TOTAL_BLOCKS': total_blocks, 'TOTAL_COMPONENTS': total_components, 'SKIPPED_BLOCKS': skipped_blocks, 'FAILED': False }
#GeochemConst.py #Contains definitions of the different components from Component import Component from GarnetComponent import GarnetComponent from ComponentMol import ComponentMol #Making the components: Input values are name, molar weight, oxide ratio, cation number, Cation name Si = Component("Si", 28.086, 2, 1, "SiO2") Al = Component("Al", 26.982, 3/2, 2, "Al2O3") Fe = Component("Fe", 55.933, 1, 1,"FeO") Fe3 = Component("Fe3", 55.933, 3/2, 2,"Fe2O3") Mn = Component("Mn", 54.938, 1, 1, "MnO") Mg = Component("Mg", 24.305, 1, 1, "MgO") Ca = Component("Ca", 40.078, 1, 1, "CaO") Na = Component("Na", 22.990, 1/2, 2, "Na2O") K = Component("K", 39.098, 1/2, 2, "K2O") Ti = Component("Ti", 47.88, 2, 1, "TiO2") P = Component("P", 30.974, 5/2, 2, "P2O5") H = Component("H", 1.008, 1/2, 2, "H2O") C = Component("C",12.011, 2, 1, "CO2") O = Component("O",15.999,1,1, "O2") #Oxide is O2 1:1 ratio COMPONENTS = [Si, Al, Fe,Fe3, Mn, Mg, Ca, Na, K, Ti, H, C, O, P] #No P2O5 because unreliable data, add if desired GRT_DENSITY = 4.19 #Density in g/cm^3 SPSS = GarnetComponent("Mn","spss",[ComponentMol(Mn,3),ComponentMol(Al,2),ComponentMol(Si,3),ComponentMol(O,12)]) PY = GarnetComponent("Mg","py",[ComponentMol(Mg,3),ComponentMol(Al,2),ComponentMol(Si,3),ComponentMol(O,12)]) GR = GarnetComponent("Ca","gr",[ComponentMol(Ca,3),ComponentMol(Al,2),ComponentMol(Si,3),ComponentMol(O,12)]) ALM = GarnetComponent("Fe","alm",[ComponentMol(Fe,3),ComponentMol(Al,2),ComponentMol(Si,3),ComponentMol(O,12)])
from Component import Component from Application import Application from Box import Box from Button import Button from ColorPicker import ColorPicker sys = Component('system') app = sys.attach(Component('app')) app.attach(Application('main')) app.attach(Box('box1')) app.attach(Box('box2')) app.attach(Button('button')) app.attach(ColorPicker('color picker')) app.start() app.stop()
print("tip chord: ", wing.tipChord) print() empennage = Empennage() empennage.calcHTGeometry(wing.wingArea, wing.MAC) empennage.calcVTGeometry(wing.wingArea, wing.wingSpan) print("ht area: ", empennage.ht.wingArea) print("ht span: ", empennage.ht.wingSpan) print("ht root chord: ", empennage.ht.rootChord) print("ht tip chord: ", empennage.ht.tipChord) print() print("vt area: ", empennage.vt.wingArea) print("vt span: ", empennage.vt.wingSpan) print("vt root chord: ", empennage.vt.rootChord) print("vt tip chord : ", empennage.vt.tipChord) battery = Component(1.1 * 9.81, 180) edf = Component(0.5 * 9.81, 350) payload = Component(1 * 9.81, 100) components = [battery, edf, payload] plane = Plane(fuselage, wing, empennage, components) print() print(plane.calcCG()) cg = plane.calcCG() X_Right_wing, Y_Right_wing, X_Left_wing, Y_Left_wing = plane.wingTopViewPoints( ) X_ht, Y_ht = plane.empennageTopViewPoints() X_fuse, Y_fuse = fuselage.topViewPoints()
from Component import Component from Arrow import Arrow # https://www.tutorialspoint.com/python_data_structure/python_graphs.htm bat = Component("Battery") res1 = Component("Resistor1") res2 = Component("Resistor2") res3 = Component("Resistor3") res4 = Component("Resistor4") graph = { bat: [res1, res2, res3], # 0 res1: [res4], # 1 res2: [res4], # 1 res3: [bat], # 1 res4: [bat] # 2 } def find_shortest_path(graph, start, goal): explored = [] # Queue for traversing the # graph in the BFS queue = [[start]] # If the desired node is # reached if start == goal: print("Same Node")
def create_component(my_type): return Component(my_type)