__author__ = 'romulo' from Spyder import * class classificadorManual: def classifica_manual(self, l_tweets): # funcao classifica manualmente os tweets lista_treino = [] lista_tweets = l_tweets for tweet in lista_tweets: classi = 'positivo' #raw_input("Classsifique como positivo ou negativo: ") #lista_treino.append("('"+tweet.strip('\n')+"','"+classi+"'),") lista_treino.append(tweet.strip('\n')+"','"+classi) #print(lista_treino) print("Tweet: "+tweet+" Classificacao: "+classi) for t in lista_treino: file = open('Tweets_classificados_positivo.txt','a') # abre arquivo file.write(t) # escreve no arquivo file.write('\n') # quebra linha file.close() #fecha arquivo #listatweets = ['#Dilma é é é é âo ââãã ç çç gastando os tubos em publicidade, mas a rejeição vai às alturas. Queimando dinheiro como sempre, a vaca - https://t.co/iPNKluOkr2,','RT @EuCobro:O governo de Dilma Rousseff esta de parabéns','Os números contra Dilma Rousseff'] sp = Spyder() listatweets = sp.pegatweets(':)') classifi_manual = classificadorManual() classifi_manual.classifica_manual(listatweets)
def convert_axis(axis): l = [] l.append(Spyder.Coordinate(0, 0, 0)) l.append(Spyder.Coordinate(1, 0, 0)) l.append(Spyder.Coordinate(0, 1, 0)) l.append(Spyder.Coordinate(0, 0, 1)) a = Spyder.AxisSystem() a.origin += (0.5, 0, 0) a.rotateY(-90) c = Spyder.Cylinder(0.2, 1, axis=a, material="red") l.append(c) a = Spyder.AxisSystem() a.origin += (0, 0.5, 0) a.rotateX(90) c = Spyder.Cylinder(0.2, 1, axis=a, material="green") l.append(c) a = Spyder.AxisSystem() a.origin += (0, 0, 0.5) c = Spyder.Cylinder(0.2, 1, axis=a, material="blue") l.append(c) og = Spyder.ObjectGroup3D(l, axis) return og
class myscene(myspyderframe): scene = bee.parameter("bee") canvas = bee.parameter("bee") mousearea = bee.parameter("bee") a = Spyder.AxisSystem() a *= 0.25 a.origin += (-8, 42, 0) env = Spyder.Model3D("models/environment", "egg", a) a = Spyder.AxisSystem() a *= 0.005 mypanda = Spyder.Actor3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, entityname="mypanda") a = Spyder.AxisSystem() a *= 0.005 pandaclass = Spyder.ActorClass3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, actorclassname="pandaclass") box = Spyder.Box2D(50, 470, 96, 96) icon = Spyder.Icon("pandaicon.png", "pandaicon", box, transparency=True) m1 = Spyder.NewMaterial("red", (255, 0, 0)) m2 = Spyder.NewMaterial("green", (0, 255, 0)) m3 = Spyder.NewMaterial("blue", (0, 0, 255)) m_ax = Spyder.AxisSystem(origin=(5, -3, 0)) m_ax2 = Spyder.AxisSystem(origin=(-5, -3, 3)) m_ax2.rotateZ(30) m_ax2.rotateX(-60) del a, box
def world_to_namespace(w): return Spyder.Namespace(w.materials, w.objects)
def convert_to_panda(c): a = Spyder.AxisSystem() a *= 0.001 a.origin = c p = Spyder.Model3D("models/panda-model", "egg", a) return p
#!/usr/bin/python # -*- coding: iso-8859-15 -*- from Spyder import * from Classificador import * import matplotlib.pyplot as pyplot sp = Spyder() listatweets = sp.pegatweets('Palmeiras') #listatweets = open('Tweets_classificados_teste.txt','r') negativo = 0 positivo = 0 for t in listatweets: classifica = Classificacao() processa = processamentoTexto() t = processa.processatweet(t) t = processa.removestopwords(t) t = processa.remover_acentos(t) tag = classifica.resultado_classificacao(t) if tag == 'pos': positivo = positivo + 1 else: negativo = negativo + 1 print ('TWEETs Positivos : %s \nTWEETs Negativos : %s' % (positivo,negativo))
class myscene(dragonfly.pandahive.spyderframe): a = Spyder.AxisSystem() a *= 0.25 a.origin += (-8, 42, 0) env = Spyder.Model3D("models/environment", "egg", a) a = Spyder.AxisSystem() a *= 0.005 pandaclass = Spyder.ActorClass3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, actorclassname="pandaclass") box = Spyder.Box2D(50, 470, 96, 96) icon = Spyder.Icon("pandaicon.png", "pandaicon", box, transparency=True) camcenter = Spyder.Entity3D("camcenter", ( Spyder.NewMaterial("white", color=(255, 255, 255)), Spyder.Block3D((1, 1, 1), material="white"), )) marker = Spyder.Entity3D( "marker", (Spyder.NewMaterial("blue", color=(0, 0, 255)), Spyder.Circle(2, origin=(0, 0, 0.1), material="blue"))) del a, box
import spyder import movingpanda_datamodel import Spyder pandadict = {} # First panda class a = Spyder.AxisSystem() a *= 0.005 data = "models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a box = Spyder.Box2D(50, 470, 96, 96) image = "pandaicon.png", True hivemap = "pandawalk.web" pandadict["pandaclass"] = ("actor", data, box, image, hivemap) #Second panda class a = Spyder.AxisSystem() a *= 0.002 data = "models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a box = Spyder.Box2D(200, 500, 48, 48) image = "pandaicon.png", True hivemap = "pandawalk2.web" pandadict["pandaclass2"] = ("actor", data, box, image, hivemap) #Third panda class a = Spyder.AxisSystem() a *= 0.3 data = "models/panda", "egg", [], a box = Spyder.Box2D(280, 480, 144, 112) image = "pandaicon2.png", True hivemap = "pandajump.web"
def _save(self, worker_ids): workermanager = self._workermanager spydernames = Spyder.StringArray() spyderobjectdata = Spyder.ObjectList() spyderparameters = Spyder.StringArray() wasps = Spyder.SpydermapWaspArray() coordinates = Spyder.Coordinate2DArray() paramcoordinates = Spyder.Coordinate2DArray() for workerid in sorted(worker_ids): node, mapping = self._wim.get_node(workerid) if node.empty: continue workertype, params, metaparams = workermanager.get_parameters( workerid) if params is None: params = {} if metaparams is None: metaparams = {} if workertype == "spyderbees.attribute": spydertype = metaparams.get("spydertype", None) if spydertype is None: print( "Warning: attribute '%s' has no spydertype, skipped!" % workerid) continue spydervalue = params.get("val", None) if spydervalue is None: print( "Warning: attribute '%s' (%s) has no value, skipped!" % (workerid, spydertype)) continue spydernames.append(workerid) spyderobjectdata.append(spydervalue) coordinates.append(Spyder.Coordinate2D(node.position)) elif workertype == "spyderbees.parameter": spyderparameters.append(workerid) paramcoordinates.append(Spyder.Coordinate2D(node.position)) elif workertype == "spyderbees.wasp": spydertype = metaparams.get("spydertype", None) if spydertype is None: print("Warning: wasp '%s' has no spydertype, skipped!" % workerid) continue spydervalue = params.get("val", None) if spydervalue is None: print("Warning: wasp '%s' (%s) has no value, skipped!" % (workerid, spydertype)) continue wasp = Spyder.SpydermapWasp( workerid, spydertype, str(spydervalue), params.get("target", ""), params.get("targetparam", ""), node.position, ) wasps.append(wasp) else: raise Exception(workertype) spydermap = Spyder.Spydermap.empty() spyderhive = self._spyderhive if spyderhive is None: spyderhive = "" spydermap.spyderhive = spyderhive spydermap.names = spydernames spydermap.objectdata = spyderobjectdata spydermap.parameters = spyderparameters spydermap.coordinates = coordinates spydermap.paramcoordinates = paramcoordinates spydermap.wasps = wasps return spydermap
def _set(self, value, _toplevelcall=True): need_update = False if isinstance(value, model): value = value._get() #print("model._set", self._path, str(value)[:30]) value, cancel = determine_value(self, value) if cancel: return self._status() if value == self._value: return _update_ok is_resource_file = False if self._is_resource: if isinstance(value, tuple) and len(value) == 2: is_resource_file = True if value[0] == None: value = None elif value[0] == "": value = None self.__exc = None try: if self._basic: #1: basic model, can be file or resource if value is not None: self._constructionstate = "failed" if self._is_file or is_resource_file: filename, fileclassname = value if self._is_file: fileclass = getattr(Spyder, fileclassname) v = Spyder.File(filename,fileclass,"r") elif self._is_resource: if is_resource_file: v = self._resourcetype(filename=filename) self._is_resource_file = True else: v = self._resourcetype(value) elif inspect.isclass(self._type) and issubclass(self._type, Spyder.Bool): v = True if value else False else: v = self._type(value) value = v self._constructionstate = "full" if value is not None else "empty" elif self._is_resource: #2: non-basic resource model self._is_resource_file = False if is_resource_file: filename,fileclassname = value fileclass = getattr(Spyder, fileclassname) fileobj = Spyder.File(filename,fileclass,"r") v0 = self._resourcetype(fileobj) self._is_resource_file = True self._constructionstate = "full" else: v0 = self._resourcetype(value) if v0.filename is not None: self._is_resource_file = True self._constructionstate = "full" if value is not None and value != {} else "empty" if self._is_resource_file: value = v0.file() self._constructionstate = "full" else: v = v0.data() self._constructionstate = "full" if not self._toplevel and value is None: self._constructionstate = "empty" value = v elif value is None and self._arraycount: value = self._type([]) self._constructionstate = "empty" elif self._type is None: if value is not None: assert isinstance(value, dict) for childname in self._children: if childname not in value: self._constructionstate = "partial" return self._value = {} for childname in self._children: child = self._children[childname] child._disable_passup() child._set(value[childname], _toplevelcall=False) child._enable_passup() self._value[childname] = child._value self._truevalue = self._value self.__dif = copy.copy(self._value) self.__ddif = copy.copy(self._value) self._constructionstate = "full" self._is_valued = True return _update_ok else: self.__dif = None self.__ddif = None self._constructionstate = "empty" if self._complete(): self._constructionstate = "full" self._is_valued = False else: #non-basic non-resource model value0 = value value = self._type(value) self._constructionstate = "full" if not self._toplevel and (value0 is None or value0 == {}): self._constructionstate = "empty" except: self.__exc = sys.exc_info() #return, unless we just cleared the value if value is None and self._value is not None: self._constructionstate = "empty" else: if not self._toplevel: self._parent._child_async(self._membername) if _toplevelcall: return self._status() return if not self._toplevel and not len(self._async_children): self._parent._child_sync(self._membername) if self._truevalue != value: need_update = True self._truevalue = value if not self._toplevel and not self._parent._arraycount: if self._parent._typedefaults[self._membername] == value: value = None self._value = value self._update_children() self.__dif = None self.__ddif = None c = self._constructionstate if self._truevalue is not None: if self._arraycount: for n in range(len(self._truevalue)): self.__update_dif(n, self._truevalue[n], self._truevalue[n].dict(), self._arraycount-1) self._constructionstate = c elif len(self._children) > 0 and not self._is_resource_file: for childname in self._children: mvalue = self._get_child_value(childname) child = self._get_child(childname) self.__update_dif(childname, mvalue, child._dif(), child._arraycount) self._constructionstate = c elif self._is_file or self._is_resource: self.__dif = self._value.dict() self.__ddif = self._value.dict() else: self.__dif = self._value self.__ddif = self._value #Are we valued or unvalued? if self.__exc is None: if self.__ddif is not None or self._toplevel: self._is_valued = True else: self._is_valued = False else: self._is_valued = False for listener in self._listeners: listener(self._truevalue) if self.__passup and not self._toplevel and need_update: self._parent._update_child(self._membername) return _update_ok
def find_workers(module, module_name, done_mods, found_workers, star=False, search_path=True, lister=None, opener=None): if module_name.endswith("__init__"): raise Exception if id(module) in done_mods: return {}, {} if lister is None: lister = os.listdir if opener is None: opener = functools.partial(open, mode="r") find_worker_state = FindWorkerState() done_mods.add(id(module)) for attribute_name in dir(module): if attribute_name in ("frame", "hive", "closedhive", "inithive", "raiser"): continue # If it is a module if isinstance(attribute_name, os.__class__): new_module_name = module_name + "." + attribute_name new_find_worker_state = find_workers(attribute_name, new_module_name, done_mods, found_workers, lister=lister, opener=opener) find_worker_state.update(new_find_worker_state) continue attribute = getattr(module, attribute_name) if id(attribute) in found_workers: continue worker_name = module_name + "." + attribute_name if hasattr(attribute, "__module__") and attribute.__module__ is not None: if not attribute.__module__.startswith(module_name): if hasattr(attribute, "guiparams") or hasattr(attribute, "metaguiparams"): if not attribute.__module__.startswith("bee.segments"): find_worker_state.suspect.append((worker_name, attribute_name, attribute)) continue add_worker(attribute, worker_name, find_worker_state, found_workers) module_path = module.__file__ motif = "" if module_path.startswith("//"): module_path = module_path[2:] motif = "//" search_path = motif + os.path.split(module_path)[0] new_modules = [] newstarmodules = [] if search_path: for filename in lister(search_path): file_path = search_path + os.sep + filename if (file_path.endswith(".web") or file_path.endswith(".hivemap") or file_path.endswith(".spydermap")): try: spydertype, spyderdata = spyder.core.parse(opener(file_path).read()) except: traceback.print_exc() continue if file_path.endswith(".web") or file_path.endswith(".hivemap") or file_path.endswith(".spydermap"): if spydertype == "Hivemap": try: hivemap = Spyder.Hivemap(spyderdata) except: print("Error in importing '%s':" % file_path) traceback.print_exc() continue newhivemapname = module_name + ":" + filename find_worker_state.hivemap_workers[newhivemapname] = hivemap elif spydertype == "Spydermap": try: # spydermap = Spyder.Spydermap(spyderdata) spydermap = Spyder.Spydermap.fromfile(file_path) except: print("Error in importing '%s':" % file_path) traceback.print_exc() continue newspydermapname = module_name + "#" + filename find_worker_state.spydermap_workers[newspydermapname] = spydermap elif star: if file_path.endswith(".py"): name = filename[:-len(".py")] newstarmodules.append((name, file_path)) elif file_path.endswith(".spy"): # importing like this is not a good idea... # n = f[:-len(".spy")] # newstarmodules.append((n,ff)) pass else: if os.path.isdir(file_path) and os.path.exists(file_path + os.sep + "__init__.py"): new_modules.append(filename) for name in new_modules: new_module_name = module_name + "." + name if new_module_name in find_worker_state.workers or new_module_name in find_worker_state.metaworkers: continue try: if new_module_name not in sys.modules: __import__(new_module_name) except Exception: print("Error in importing", new_module_name) traceback.print_exc() continue new_module = sys.modules[new_module_name] search_path = new_module.__file__.endswith("__init__.pyc") or module.__file__.endswith("__init__.py") new_find_worker_state = find_workers(new_module, new_module_name, done_mods, found_workers, search_path=search_path, lister=lister, opener=opener) find_worker_state.update(new_find_worker_state) for name, file_path in newstarmodules: if name == "__init__": continue new_module_name = module_name + "." + name if new_module_name in find_worker_state.workers or new_module_name in find_worker_state.metaworkers: continue try: if new_module_name not in sys.modules: if file_path.endswith(".spy"): #importing like this is not a good idea... # __import__(new_module_name) raise Exception elif opener is not None: __import__(new_module_name) sys.modules[new_module_name].__file__ = file_path else: fil = open(file_path, "r") imp.load_module(new_module_name, fil, file_path, ("py", "r", imp.PY_SOURCE)) except Exception: print("Error in importing", new_module_name) traceback.print_exc() continue new_module = sys.modules[new_module_name] search_path = new_module.__file__.endswith("__init__.pyc") or module.__file__.endswith("__init__.py") new_find_worker_state = find_workers(new_module, new_module_name, done_mods, found_workers, search_path=search_path, lister=lister, opener=opener) find_worker_state.update(new_find_worker_state) return find_worker_state
def loadspyder(self): """加载所有爬虫类""" self.zhihusearch = Spyder.ZhihuSearch("知乎热搜") self.zhihubank = Spyder.ZhihuBank("知乎热榜") self.weibosearch = Spyder.WeiboSearch("微博热搜") self.baidunews = Spyder.BaiduNews("百度新闻")
class myscene(dragonfly.pandahive.spyderframe): a = Spyder.AxisSystem() a *= 0.25 a.origin += (-8, 42, 0) env = Spyder.Model3D("models/environment", "egg", a) a = Spyder.AxisSystem() a *= 0.005 mypanda = Spyder.Actor3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, entityname="mypanda") ##First panda class a = Spyder.AxisSystem() a *= 0.005 pandaclass = Spyder.ActorClass3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, actorclassname="pandaclass") box = Spyder.Box2D(50, 470, 96, 96) icon = Spyder.Icon("pandaicon.png", "pandaicon", box, transparency=True) #Second panda class a = Spyder.AxisSystem() a *= 0.002 pandaclass2 = Spyder.ActorClass3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, actorclassname="pandaclass2") box = Spyder.Box2D(200, 500, 48, 48) icon2 = Spyder.Icon("pandaicon.png", "pandaicon2", box, transparency=True) del a, box
class python(object): """Snippet of custom Python code. Python assessors may have any number of pull inputs. When the assessor is evaluated (on demand), the values of the inputs is made available to the code, as variables of the same name. Once the code has executed, the value of the output is determined, based on the syntax mode. Parameters (Advanced) output pull type (bool by default) (Advanced) Syntax mode: "expression", "function" or "generator". "expression" (default) is a single Python expression, "function" uses return, "generator" uses yield. (Advanced) Advanced input mode: If enabled, inputs must be explicitly pulled using v(), where v is the name of the input. """ metaguiparams = { "inputs": "NodeIOArray", "output_type": "str", "syntaxmode": "str", "advanced": "bool", "autocreate": {"inputs": Spyder.NodeIOArray(), "output_type": "bool", "syntaxmode": "expression", "advanced": False}, "_memberorder": ["syntaxmode", "output_type", "advanced", "inputs"] } @classmethod def form(cls, f): f.syntaxmode.name = "Syntax mode" f.syntaxmode.type = "option" f.syntaxmode.options = "expression", "function", "generator" f.syntaxmode.optiontitles = "Expression", "Function", "Generator" f.syntaxmode.advanced = True f.output_type.name = "Output Type" f.output_type.type = "option" f.output_type.options = "bool", "int", "float", "(str,identifier)", "(str,action)", "(str,keycode)", "(str,message)", "(str,property)", "(str,process)", "str", "(object,matrix)", "(object,bge)", "object", "custom" f.output_type.optiontitles = "Bool", "Integer", "Float", "ID String", "Action String", "Key String", "Message String", "Property String", "Process ID String", "Generic String", "Matrix Object", "BGE Object", "Generic Object", "Custom" f.output_type.default = "bool" f.output_type.advanced = True f.advanced.name = "Advanced Mode" f.advanced.advanced = True f.inputs.name = "Inputs" f.inputs.length = 10 f.inputs.count_from_one = True f.inputs.form = "soft" f.inputs.arraymanager = "dynamic" def __new__(cls, syntaxmode, output_type, advanced, inputs): io_names = set() reserved = ("code", "code_parameter_", "outp", "v_outp", "con_outp", "form") output_type = stringtupleparser(output_type) cls_dict = { "code": variable("str"), "outp": output("pull", output_type), "v_outp": variable(output_type), "con_outp": connect("v_outp", "outp") } cls_dict["code_parameter_"] = parameter(cls_dict["code"], "") guiparams = {"outp": {"name": "Output"}} # Build set of IO names for input_ in inputs: if input_.io_name in reserved: raise ValueError("Reserved input name: %s" % input_.io_name) if input_.io_name in io_names: raise ValueError("Duplicate input name: %s" % input_.io_name) io_names.add(input_.io_name) # Create connections for input_ in inputs: buffer_name = input_.io_name antenna_name = buffer_name + "_" type_ = input_.type_ if type_ == "custom": type_ = input_.customtype if type_: type_ = stringtupleparser(type_) cls_dict[antenna_name] = antenna("pull", type_) cls_dict[buffer_name] = buffer("pull", type_) guiparams[antenna_name] = {"name": buffer_name} # Ensure we don't have a name clash with IO names connection_name = antenna_name + "connection" while connection_name in io_names: connection_name += "_" cls_dict[connection_name] = connect(antenna_name, buffer_name) cls_dict["guiparams"] = guiparams return type("python", (_python_base,), cls_dict)
import bee from bee.segments import * import libcontext from libcontext.socketclasses import * from libcontext.pluginclasses import * from .matrix import matrix import Spyder matrix0 = matrix(Spyder.AxisSystem(), "AxisSystem") class spawn_actor_or_entity(bee.worker): actorclassname = antenna("pull", "id") b_actorclassname = buffer("pull", "id") connect(actorclassname, b_actorclassname) v_actorname = variable("id") v_matrix = variable(("object", "matrix")) @modifier def do_spawn(self): try: self.actorspawnfunc(self.b_actorclassname, self.v_actorname) except KeyError: self.entspawnfunc(self.b_actorclassname, self.v_actorname) axis = self.v_matrix.get_copy("AxisSystem") ent = self.get_entity(self.v_actorname) ent.set_axissystem(axis) ent.commit()
a.origin = Spyder.Coordinate(15 * random() - 7.5, 15 * random() - 7.5, 0) yield dragonfly.scene.matrix(a, "AxisSystem") def id_generator(): n = 0 while 1: n += 1 yield "spawnedpanda" + str(n) pandadict = {} #global variable... #First panda class a = Spyder.AxisSystem() a *= 0.005 data = "models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a box = Spyder.Box2D(50, 470, 96, 96) image = "pandaicon.png", True hivemap = "pandawalk.web" pandadict["pandaclass"] = ("actor", data, box, image, hivemap) #Second panda class a = Spyder.AxisSystem() a *= 0.002 data = "models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a box = Spyder.Box2D(200, 500, 48, 48) image = "pandaicon.png", True hivemap = "pandawalk2.web" pandadict["pandaclass2"] = ("actor", data, box, image, hivemap)
def __new__(cls, config): # Create custom bindworker if isinstance(config, str): import Spyder config = Spyder.Launch(config) worker = config.make_launch() class launch(bee.frame): __doc__ = cls.__doc__ subprocess = bee.parameter("bool") bind_worker = launch_helper( subprocess=bee.get_parameter("subprocess")) hive_binder = worker() id_factory = id_suffix_worker() # To push identifier base in id factory id_transistor = std.transistor(("str", "identifier"))() bee.connect(id_transistor.outp, id_factory.identifier_base) # Create some hive IO pins trig = bee.antenna(id_transistor.trig) bee.connect(id_factory.trig_out, bind_worker.trig) # Secondary calls process_class = bee.antenna(id_transistor.inp) bee.connect(process_class, bind_worker.process_class) # Secondary calls process_identifier = bee.output(id_factory.new_identifier) bee.connect(process_identifier, bind_worker.process_identifier) # Weaver of these two w_bind_ids = std.weaver(("id", "id"))() process_id_duck = convert.pull.duck("str", "id")() bee.connect(id_factory.new_identifier, process_id_duck) bee.connect(process_id_duck, w_bind_ids.inp1) process_class_duck = convert.pull.duck("str", "id")() bee.connect(process_class, process_class_duck) bee.connect(process_class_duck, w_bind_ids.inp2) # Connect weaver to binder t_bind_ids = std.transistor(("id", "id"))() bee.connect(w_bind_ids, t_bind_ids) bee.connect(t_bind_ids, hive_binder.bind) # This only triggers if we're a subprocess bee.connect(bind_worker.trig_out, t_bind_ids.trig) guiparams = { "process_class": { "name": "Process class", "fold": True }, "trig": { "name": "Trigger" }, "process_identifier": { "name": "Process ID" }, "subprocess": { "name": "Subprocess" }, "memberorder": ["trig", "process_class", "process_identifier"], } return launch
def convert_to_sphere(c): a = Spyder.AxisSystem() a.origin = c s = Spyder.Sphere3D(0.25, 2, a, material="white") return s
def random_matrix_generator(): while 1: a = Spyder.AxisSystem() a.rotateZ(360 * random()) a.origin = Spyder.Coordinate(15 * random() - 7.5, 15 * random() - 7.5, 0) yield dragonfly.scene.matrix(a, "AxisSystem")
class myscene(myspyderframe): a = Spyder.AxisSystem() a *= 0.25 a.origin += (-8, 42, 0) env = Spyder.Model3D("models/environment", "egg", a) a = Spyder.AxisSystem() a *= 0.005 mypanda = Spyder.Actor3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, entityname="mypanda") a = Spyder.AxisSystem() a *= 0.005 pandaclass = Spyder.ActorClass3D("models/panda-model", "egg", [("walk", "models/panda-walk4", "egg")], a, actorclassname="pandaclass") box = Spyder.Box2D(50, 470, 96, 96) icon = Spyder.Icon("pandaicon.png", "pandaicon", box, transparency=True) m1 = Spyder.NewMaterial("red", (255, 0, 0)) m2 = Spyder.NewMaterial("green", (0, 255, 0)) m3 = Spyder.NewMaterial("blue", (0, 0, 255)) m4 = Spyder.NewMaterial("white", (255, 255, 255)) m_ax = Spyder.AxisSystem(origin=(5, -3, 0)) m_ax2 = Spyder.AxisSystem(origin=(-5, -3, 3)) m_ax2.rotateZ(30) m_ax2.rotateX(-60) m = Spyder.World3D(materials=[m1, m2, m3, m4], objects=[m_ax, m_ax2]) m.tofile("m.web") del m del a, box
def _save(self, worker_ids): workermanager = self._workermanager workers = Spyder.WorkerArray() connections = Spyder.WorkerConnectionArray() drones = Spyder.DroneArray() io = Spyder.HivemapIOArray() hparameters = Spyder.HivemapParameterArray() hattributes = Spyder.HivemapAttributeArray() hpyattributes = Spyder.HivemapPyAttributeArray() hparts = Spyder.HivemapPartBeeArray() hwasps = Spyder.HivemapWaspArray() bees = {} # storing workers for workerid in sorted(worker_ids): node, mapping = self._wim.get_node(workerid) if node.empty: continue workertype, params, metaparams = workermanager.get_parameters( workerid) if workertype.startswith("bees."): bees[workerid] = node, workertype, [], [] continue elif workertype.startswith("<drone>:"): droneid = workerid dronetype = workertype[len("<drone>:"):] parameters = None if params is not None: parameters = [] for index in range(5): parameter = params.get("arg%d" % (index + 1), "") parameters.append(parameter) if not any(parameters): parameters = None else: parameter_array = Spyder.StringArray() for index in range(5): parameter_string = Spyder.String( repr(parameters[index])) parameter_array.append(parameter_string) parameters = parameter_array drone = Spyder.Drone(droneid, dronetype, node.position) drone.parameters = parameters drones.append(drone) continue blockvalues = self._wim.get_blockvalues(workerid) if params is not None: params = params.items() if metaparams is not None: metaparams = metaparams.items() worker = Spyder.Worker(workerid, workertype, node.position, parameters=params, metaparameters=metaparams, blockvalues=blockvalues) workers.append(worker) #filtering connections for bees nconnections = [] for connection in self._wim.get_connections(): if connection.start_node in bees: node, workertype, wcon_in, wcon_out = bees[ connection.start_node] wcon_out.append( (connection.end_node, connection.end_attribute)) elif connection.end_node in bees: node, workertype, wcon_in, wcon_out = bees[connection.end_node] wcon_in.append( (connection.start_node, connection.start_attribute)) else: nconnections.append(connection) #saving bees for bee_id, bee in bees.items(): node, workertype, wcon_in, wcon_out = bee if workertype.startswith("bees.io"): if workertype in ("bees.io.push_antenna", "bees.io.pull_antenna"): assert not wcon_in #something wrong with the GUI if this happens if not wcon_out: print( "Warning: %s '%s' does not have any outgoing connections, bee is not saved!" % (workertype, bee_id)) continue elif len(wcon_out) > 1: print( "Warning: %s '%s' has multiple outgoing connections, selecting the first..." % (workertype, bee_id)) mio = "antenna" hook = "inhook" targetcon = wcon_out[0] mapattr = "_inmapr" elif workertype in ("bees.io.push_output", "bees.io.pull_output"): assert not wcon_out #something wrong with the GUI if this happens if not wcon_in: print( "Warning: %s '%s' does not have any incoming connections, bee is not saved!" % (workertype, bee_id)) continue elif len(wcon_in) > 1: print( "Warning: %s '%s' has multiple incoming connections, selecting the first..." % (workertype, bee_id)) mio = "output" hook = "outhook" targetcon = wcon_in[0] mapattr = "_outmapr" else: raise Exception(workertype) iomode = workertype[workertype.rindex(".") + 1:workertype.rindex("_")] iotype = None tnode, targetmapping = self._wim.get_node(targetcon[0]) for attribute in tnode.attributes: if attribute.name == targetcon[1]: iotype = getattr(attribute, hook).type break assert iotype is not None targetmap = getattr(targetmapping, mapattr) targetio = targetcon[1] try: targetio = targetmap[targetio] except KeyError: pass hivemap_io = Spyder.HivemapIO(bee_id, mio, targetcon[0], targetio, iomode, iotype, node.position) io.append(hivemap_io) elif workertype == "bees.attribute": params, metaparams = workermanager.get_parameters(bee_id)[1:3] if params is None: params = {} attribute = Spyder.HivemapAttribute(bee_id, metaparams.get( "spydertype", ""), params.get("val", ""), position=node.position) hattributes.append(attribute) elif workertype == "bees.pyattribute": params = workermanager.get_parameters(bee_id)[1] if params is None: params = {} code_variable = params.get("code_variable", "") if code_variable == "": code_variable = None py_attribute = Spyder.HivemapPyAttribute( bee_id, params.get("code", ""), code_variable, position=node.position) hpyattributes.append(py_attribute) elif workertype == "bees.parameter": params = workermanager.get_parameters(bee_id)[1] if params is None: params = {} hpar = Spyder.HivemapParameter(bee_id, params.get("internal_name", ""), params.get("typename", ""), position=node.position) gui_defaultvalue = params.get("gui_defaultvalue", "") if gui_defaultvalue != "": hpar.gui_defaultvalue = gui_defaultvalue hparameters.append(hpar) elif workertype == "bees.part": params = workermanager.get_parameters(bee_id)[1] if params is None: params = {} hpart = Spyder.HivemapPartBee(bee_id, params.get("beename", ""), params.get("part", ""), position=node.position) hparts.append(hpart) elif workertype == "bees.wasp": params = workermanager.get_parameters(bee_id)[1] if params is None: params = {} hwasp = Spyder.HivemapWasp(bee_id, params.get("injected", ""), params.get("target_name", ""), params.get("target_parameter", ""), params.get("sting", False), params.get("accumulate", False), position=node.position) hwasps.append(hwasp) else: raise Exception(workertype) for connection in nconnections: start_node, start_mapping = self._wim.get_node( connection.start_node) end_node, end_mapping = self._wim.get_node(connection.end_node) # Only save wanted connections if not (connection.start_node in worker_ids and connection.end_node in worker_ids): continue try: start_attribute = start_mapping._outmapr[ connection.start_attribute] except KeyError: start_attribute = connection.start_attribute try: end_attribute = end_mapping._inmapr[connection.end_attribute] except KeyError: end_attribute = connection.end_attribute connection = Spyder.WorkerConnection( (connection.start_node, start_attribute), (connection.end_node, end_attribute), connection.interpoints) connections.append(connection) if not io: io = None if not drones: drones = None if not hparameters: hparameters = None if not hpyattributes: hpyattributes = None if not hwasps: hwasps = None hivemap = Spyder.Hivemap.empty() hivemap.workers = workers hivemap.connections = connections hivemap.io = io hivemap.drones = drones hivemap.parameters = hparameters hivemap.attributes = hattributes hivemap.pyattributes = hpyattributes hivemap.docstring = "TEST" hivemap.partbees = hparts hivemap.wasps = hwasps #hivemap.tofile(hivemapfile) return hivemap
class advanced_python(object): """A snippet of advanced custom Python code. Activated by trigger. Can have any number of inputs and outputs, which can be push, pull or trigger. When the Python processor is activated, all push inputs are evaluated, and made available to the code as variables of the same name. Push inputs that have not been set since the previous invocation are set to None, unless the processor is persistent. Within the code, a pull input's value must be explicitly requested using v(), where v is the name of the pull input Within the code, a push output must be explicitly firedusing v(), where v is the name of the push output After the code has run, its locals() are inspected for pull output variables. All pull output variables must be set (unless persistent). Parameters: Persistent: if True, all push inputs and pull outputs have persistent values from one invocation to the next. Activate by push: if True, every change on a push input triggers the execution of the controller. Activate by pull: if True, every value request on a pull output (pre-)triggers the execution of the controller """ metaguiparams = { "inputs": "AdvancedNodeIOArray", "outputs": "AdvancedNodeIOArray", "autocreate": { "inputs": Spyder.AdvancedNodeIOArray(), "outputs": Spyder.AdvancedNodeIOArray() }, } @classmethod def form(cls, f): f.inputs.name = "Inputs" f.inputs.length = 10 f.inputs.count_from_one = True f.inputs.form = "soft" f.inputs.arraymanager = "dynamic" f.outputs.name = "Outputs" f.outputs.length = 10 f.outputs.count_from_one = True f.outputs.form = "soft" f.outputs.arraymanager = "dynamic" def __new__(cls, inputs, outputs): io_names = set() reserved = ("trig", "code", "code_parameter_", "persistent", "persistent_parameter_", "push_activates", "push_activates_parameter_", "pull_activates", "pull_activates_parameter_", "form") for inp in inputs: if inp.io_name in reserved: raise ValueError("Reserved input name: %s" % inp.io_name) if inp.io_name in io_names: raise ValueError("Duplicate input name: %s" % inp.io_name) io_names.add(inp.io_name) for outp in outputs: if outp.io_name in reserved: raise ValueError("Reserved output name: %s" % outp.io_name) if outp.io_name in io_names: raise ValueError("Duplicate input/output name: %s" % outp.io_name) io_names.add(outp.io_name) dic = { "trig": antenna("push", "trigger"), "code": variable("str"), "persistent": variable("bool"), "push_activates": variable("bool"), "pull_activates": variable("bool"), } dic["code_parameter_"] = parameter(dic["code"], "") dic["persistent_parameter_"] = parameter(dic["persistent"], False) dic["push_activates_parameter_"] = parameter(dic["push_activates"], False) dic["pull_activates_parameter_"] = parameter(dic["pull_activates"], False) guiparams = {} guiparams["trig"] = {"name": "Trigger"} guiparams["_memberorder"] = ["trig"] counter = 0 for inp in inputs: name = inp.io_name name2 = name + "_" typ = inp.type_ if typ == "custom": typ = inp.customtype if typ: typ = stringtupleparser(typ) dic[name2] = antenna("pull", typ) dic[name] = buffer("pull", typ) guiparams[name2] = {"name": name} while 1: counter += 1 conname = "con" + str(counter) if conname not in io_names: break dic[conname] = connect(name2, name) for outp in outputs: name = outp.io_name name2 = name + "_" typ = outp.type_ guiparams[name2] = {"name": name} if typ == "custom": typ = outp.customtype if typ: typ = stringtupleparser(typ) if outp.mode == "trigger": dic[name2] = output("push", "trigger") dic[name2 + "trig_"] = triggerfunc(dic[name2]) dic[name] = variable("bool") else: dic[name2] = output(outp.mode, typ) dic[name] = buffer(outp.mode, typ) while 1: counter += 1 conname = "con" + str(counter) if conname not in io_names: break dic[conname] = connect(name, name2) dic["guiparams"] = guiparams return type("advanced_python", (_advanced_python_base, ), dic)