class Config: # 行情 quote = Attribute({ 'client_id': CONST_QUOTE_CLIENT_ID, 'save_file_path': CONST_QUOTE_SAVE_FILE_PATH, 'ip': CONST_QUOTE_IP, 'port': CONST_QUOTE_PORT, 'user': CONST_QUOTE_USER, 'password': CONST_QUOTE_PASSWORD, 'sock_type': CONST_QUOTE_SOCK_TYPE, 'auto_login': CONST_QUOTE_AUTO_LOGIN }) # 交易 trade = Attribute({ 'client_id': CONST_TRADE_CLIENT_ID, 'save_file_path': CONST_TRADE_SAVE_FILE_PATH, 'ip': CONST_TRADE_IP, 'port': CONST_TRADE_PORT, 'user': CONST_TRADE_USER, 'password': CONST_TRADE_PASSWORD, 'sock_type': CONST_TRADE_SOCK_TYPE, 'auto_login': CONST_TRADE_AUTO_LOGIN, 'key': CONST_TRADE_KEY }) # -------------------------------------------------- def __init__(self): """Constructor""" raise NotImplementedError()
def test_001_withmaxsize(self): a = Attribute('stat3', history_max_size=5) self.assertEqual(a.name, 'stat3') for i in xrange(0, 8): a.value = i self.assertEqual(a.history, [2, 3, 4, 5, 6])
def main(): """Quick tests.""" a = Attribute('hour', ['0,...,23']) a2 = Attribute('minute', ['0,...,59']) r_ahead = Relation('R1(h1,m1,h2,m2) <=> h1 > h2 or (h1 = h2 and m1 > m2)', ['hour', 'minute', 'hour', 'minute'], 1) r_behind = Relation('R2(h1,m1,h2,m2) <=> h1 < h2 or (h1 = h2 and m1 < m2)', ['hour', 'minute', 'hour', 'minute'], 2) r_pm = Relation('R3(h1) <=> h1 > 12', ['hour'], 3) r_am = Relation('R4(h1) <=> h1 < 12', ['hour'], 4) attribute_structure = AttributeStructure(a, a2, r_ahead, r_behind, r_pm, r_am) ahead_rs = RelationSymbol('Ahead', 4) behind_rs = RelationSymbol('Behind', 4) pm_rs = RelationSymbol('PM', 1) vocabulary = Vocabulary(['C1', 'C2'], [ahead_rs, behind_rs, pm_rs], ['V1', 'V2']) profiles = [[ ahead_rs, ('hour', 1), ('minute', 1), ('hour', 2), ('minute', 2) ], [behind_rs, ('hour', 1), ('minute', 1), ('hour', 2), ('minute', 2)], [pm_rs, ('hour', 1)]] mapping = {ahead_rs: 1, behind_rs: 2, pm_rs: 3} ai = AttributeInterpretation(vocabulary, attribute_structure, mapping, profiles) print ai == ai
def setUp(self): """Set up the attribute for testing.""" self.attribute_name = 'Test Attribute' self.attribute = Attribute(self.attribute_name, weightage_function_mock, valuation_function_mock, production_function_mock)
def test_validations_run(self): def greater_than(n, t): return n > t def less_than(n, t): return n < t attribute = Attribute("field", validations=[(greater_than, [0]), (less_than, [2])]) result = attribute.validate(1) self.assertEqual(result, None) result = attribute.validate(0) self.assertEqual( result, "field: Validation failed for function greater_than with args: [0]" ) result = attribute.validate(2) self.assertEqual( result, "field: Validation failed for function less_than with args: [2]")
def setGlobal(name, data, description=""): global globals try: globals[name].data except KeyError: globals[name] = Attribute(data, description) globals[name].data = data
def new(self, machine_code, nickname): self.attrib = Attribute(self._table) yield self.attrib.new(machine_code=machine_code, nickname=nickname, max_weight=0, \ play_num=0, eat_num=0, be_eated_num=0) self.uid = self.attrib.attrib_id self.nickname = nickname self.machine_code = machine_code
def main(): """.""" color = Attribute("color", ['R', 'G', 'B']) size = Attribute("size", ['S', 'M', 'L']) a = AttributeStructure(color, size) o = ['s'] asys = AttributeSystem(a, o) s = State(asys) s1 = deepcopy(s) s1.set_ascription(('color', 's'), ['B', 'G']) s1.set_ascription(('size', 's'), ['S']) aes = s.get_alternate_extensions(s1) for ae in aes: print ae print s2 = deepcopy(s) s2.set_ascription(('color', 's'), ['R']) s2.set_ascription(('size', 's'), ['S', 'M', 'L']) s3 = deepcopy(s) s3.set_ascription(('color', 's'), ['R', 'B', 'G']) s3.set_ascription(('size', 's'), ['L', 'M'])
def test_fortitude_save_combines_constitution_and_class_bonus(self): constitution = Attribute(Attribute.CONSTITUTION, 17) rogue = Rogue(19) actor = Actor('Test Rogue With Rouge', [constitution], [rogue]) self.assertEqual( rogue.get_fortitude_save().value + constitution.get_attribute_modifier().value, actor.get_fortitude_save().value )
def test_reflex_save_combines_dexterity_and_class_bonus(self): dexterity = Attribute(Attribute.DEXTERITY, 13) rogue = Rogue(17) actor = Actor('Test Rogue With Rouge', [dexterity], [rogue]) self.assertEqual( rogue.get_reflex_save().value + dexterity.get_attribute_modifier().value, actor.get_reflex_save().value )
def test_will_save_combines_wisdom_and_class_bonus(self): wisdom = Attribute(Attribute.WISDOM, 21) rogue = Rogue(20) actor = Actor('Test Rogue With Rouge', [wisdom], [rogue]) self.assertEqual( rogue.get_will_save().value + wisdom.get_attribute_modifier().value, actor.get_will_save().value )
def main(): """Main method; quick testing.""" a, b, c = Attribute("a", []), Attribute("b", []), Attribute("c", []) r = Relation("R1(a,b) <=> ", ["a", "b"], 1) astr = AttributeStructure() print astr + a + b + r
def __init__(self, attrobj, name="resource", cur_val=0, min=None, max=None, recharge_interval=60, recharge_rate=1): self.name = name self._cur_val = cur_val self._min = Attribute(attrobj, **min) self._max = Attribute(attrobj, **max) self.recharge_rate = recharge_rate self.recharge_interval = recharge_interval self.will_recharge = False self.attrobj = attrobj
def test_eq(self): t1 = Attribute(self.__statement[0]) for statement in self.__statement: t = Attribute(statement) self.assertEqual(t, t1) self.assertFalse(t1 == 'name') t2 = Attribute('attribute name2;') for statement in self.__statement: t = Attribute(statement) self.assertTrue(t != t2)
def main(): """quick dev tests.""" from interval import Interval from relationSymbol import RelationSymbol from vocabulary import Vocabulary from attribute_interpretation import AttributeInterpretation from formula import Formula from assumption_base import AssumptionBase from attribute import Attribute from relation import Relation from attribute_structure import AttributeStructure from attribute_system import AttributeSystem from constant_assignment import ConstantAssignment from named_state import NamedState from context import Context from variable_assignment import VariableAssignment a = Attribute('hour', [Interval(0, 23)]) a2 = Attribute('minute', [Interval(0, 59)]) r_pm = Relation('R1(h1) <=> h1 > 11', ['hour'], 1) r_am = Relation('R2(h1) <=> h1 <= 11', ['hour'], 2) r_ahead = Relation('R3(h1,m1,h2,m2) <=> h1 > h2 or (h1 = h2 and m1 > m2)', ['hour', 'minute', 'hour', 'minute'], 3) r_behind = Relation('R4(h1,m1,h2,m2) <=> h1 < h2 or (h1 = h2 and m1 < m2)', ['hour', 'minute', 'hour', 'minute'], 4) attribute_structure = AttributeStructure(a, a2, r_ahead, r_behind, r_pm, r_am) pm_rs = RelationSymbol('PM', 1) am_rs = RelationSymbol('AM', 1) ahead_rs = RelationSymbol('Ahead', 4) behind_rs = RelationSymbol('Behind', 4) vocabulary = Vocabulary(['C1', 'C2'], [pm_rs, am_rs, ahead_rs, behind_rs], ['V1', 'V2']) objs = ['s1', 's2', 's3'] asys = AttributeSystem(attribute_structure, objs) const_mapping_2 = {'C1': 's1'} p2 = ConstantAssignment(vocabulary, asys, const_mapping_2) ascriptions_1 = { ("hour", "s1"): [13, 15, 17], ("minute", "s1"): [10], ("hour", "s2"): [1, 3, 5], ("minute", "s2"): [10], ("hour", "s3"): [1, 3, 5], ("minute", "s3"): [10] } named_state_4 = NamedState(asys, p2, ascriptions_1)
def get_attribute(self, title): if title == "sizes": if len(self.sizes) == 1: return Attribute("Sample Sizes", None, None, None, self.sizes, None, None) else: return [ Attribute("Sample Sizes", None, None, self.get_xx()[ii], self.sizes[ii], None, None) for ii in range(len(self.sizes)) ] raise title + " not available"
def __init__(self): self.gender = random.choice("male" "female") self.possessive_pronoun = 'her' self.pronoun = 'she' if self.gender == 'male': self.possessive_pronoun = 'his' self.pronoun = 'he' self.full_name = names.get(self.gender) self.first_name = self.full_name.split(' ')[0] if len(self.full_name.split(' ')[0]) > 1: self.last_name = self.full_name.split(' ')[1] else: self.last_name = "" self.qualities = [generate_quality()] self.history = [] self.attributes = { 'combat': Attribute('combat'), 'lore': Attribute('lore'), 'survival': Attribute('survival') } self.memories = {} for i in range(5): topic = random.choice([ 'traveling', 'camping', 'hunting', 'fishing' 'searching for food', 'fighting' ]) relation = random.choice([ 'father', 'mother', 'sister', 'brother', 'best friend', 'rival' ]) when = random.choice([ 'as a child', 'when ' + self.pronoun + ' was a teenager', 'after leaving ' + self.possessive_pronoun + ' home' ]) self.add_memory( topic, self.get_name() + ' remembered ' + topic + ' with ' + self.possessive_pronoun + ' ' + relation + ' ' + when + '.') self.weapon = Weapon() self.dead = False self.injuries = []
def addAttribute(self, name=None, type=None, value=None): # pylint: disable=W0622 """ Add a user-defined attribute to this network. >>> network.addAttribute('Preliminary', Attribute.BOOLEAN_TYPE, True) The type parameter should be one of the :class:`Attribute.*_TYPE <Network.Attribute.Attribute>` values. Returns the attribute object that is created. """ if name is None or type is None or value is None: raise ValueError, gettext( 'The name, type and value parameters must be specified when adding an attribute.' ) if not isinstance(name, str): raise TypeError, 'The name parameter passed to addAttribute() must be a string.' if type not in Attribute.TYPES: raise TypeError, 'The type parameter passed to addAttribute() must be one of the Attribute.*_TYPE values.' # TODO: validate value based on the type? attribute = Attribute(self, name, type, value) self._attributes.append(attribute) dispatcher.send(('set', 'attributes'), self) return attribute
def predictAllExamplesInFile(self, predictFile): """ predicts all the training examples in a file, and returns a list of tuples where the 0th index of the tuple is the predicted value using our tree, and the 1st index of the tuple is the actual value from the data point. """ if self.rootNode == None: print( "You must build a tree from training data before running predictions" ) sys.exit(1) values = [] with open(predictFile, "r") as fh: for exampleLine in fh: if exampleLine[0] == ';': continue #provides easy way to comment out data exampleLineParts = exampleLine.split("D:")[1].strip().split() targetValue = exampleLineParts[-1] exampleAttributes = [] for j in range(len(self.attributesAndValues)): attrName = self.attributesAndValues[j].attrName attrValues = [exampleLineParts[j]] attribute = Attribute(attrName, attrValues) exampleAttributes.append(attribute) te = TrainingExample(exampleAttributes, targetValue) predictVsActualTuple = self.predictExamplePoint(te) values.append(predictVsActualTuple) return values
def _fromXMLElement(cls, xmlElement): network = cls() network.setBulkLoading(True) # Load the classes in such an order that any referenced objects are guaranteed to have already been created. for moduleName, className in [('region', 'Region'), ('pathway', 'Pathway'), ('neuron', 'Neuron'), ('muscle', 'Muscle'), ('arborization', 'Arborization'), ('innervation', 'Innervation'), ('gap_junction', 'GapJunction'), ('synapse', 'Synapse'), ('stimulus', 'Stimulus')]: elementModule = getattr(sys.modules['network'], moduleName) elementClass = getattr(elementModule, className) for element in xmlElement.findall(className): networkObject = elementClass._fromXMLElement(network, element) if networkObject is not None: network.addObject(networkObject) weightingFunctionElement = xmlElement.find('WeightingFunction') if weightingFunctionElement is not None: funcType = weightingFunctionElement.get('type') funcName = weightingFunctionElement.get('name') if funcType == 'source': exec(weightingFunctionElement.text) network._weightingFunction = eval(funcName) elif funcType == 'marshal': code = marshal.loads(eval(weightingFunctionElement.text)) network._weightingFunction = types.FunctionType(code, globals(), funcName or 'weightingFunction') else: raise ValueError, gettext('Unknown weighting function type: %s') % (funcType) for element in xmlElement.findall('Attribute'): attribute = Attribute._fromXMLElement(network, element) if attribute is not None: network._attributes.append(attribute) network.setBulkLoading(False) return network
def test_attribute_above_eleven_returns_positive_modifier(self): attribute = Attribute(Attribute.STRENGTH, 12) self.assertEqual(attribute.get_attribute_modifier(), 1) attribute = Attribute(Attribute.STRENGTH, 13) self.assertEqual(attribute.get_attribute_modifier(), 1) attribute = Attribute(Attribute.STRENGTH, 14) self.assertEqual(attribute.get_attribute_modifier(), 2) attribute = Attribute(Attribute.STRENGTH, 45) self.assertEqual(attribute.get_attribute_modifier(), 17)
def test_attribute_below_ten_returns_negative_modifier(self): attribute = Attribute(Attribute.STRENGTH, 1) self.assertEqual(attribute.get_attribute_modifier(), -5) attribute = Attribute(Attribute.STRENGTH, 6) self.assertEqual(attribute.get_attribute_modifier(), -2) attribute = Attribute(Attribute.STRENGTH, 7) self.assertEqual(attribute.get_attribute_modifier(), -2) attribute = Attribute(Attribute.STRENGTH, 9) self.assertEqual(attribute.get_attribute_modifier(), -1)
def __init__(self, class_file: ClassFile, stream: Stream): self.access_flags = stream.read_u2() self.name_index = stream.read_u2() self.descriptor_index = stream.read_u2() self.attributes: List[Attribute] = [ Attribute.read(class_file, stream) for _ in range(stream.read_u2()) ] print(class_file.constants[self.name_index], self.attributes)
def generate_type(self, context, template): if self.has_attribute("type"): exist = self.get_attribute("type") attr = Attribute(self.name, "type", ConstValue(str(exist.value))) return attr attr = template.instantiate() attr.generate(context) _type = str(attr.value) if _type == "translate": self.value_class = svg.TransformTranslateValue elif _type == "scale": self.value_class = svg.TransformScaleValue elif _type == "rotate": self.value_class = svg.TransformRotateValue else: self.value_class = svg.TransformSkewXValue return attr
class TestAttribute(unittest.TestCase): """Unit test class to test the Attribute class functions.""" def setUp(self): """Set up the attribute for testing.""" self.attribute_name = 'Test Attribute' self.attribute = Attribute(self.attribute_name, weightage_function_mock, valuation_function_mock, production_function_mock) def test_init(self): """Test the constructor function.""" self.assertEqual(self.attribute.name, self.attribute_name, 'Attribute name not correct.') self.assertEqual(self.attribute._weightage_function.__name__, weightage_function_mock.__name__, 'Weightage function name not correct.') def test_repr(self): """Test the repr function.""" attribute_name = self.attribute.name attribute_repr = 'Attribute[name={}, value=0]'.format(attribute_name) self.assertEqual(attribute_repr, self.attribute.__repr__()) def test_production(self): """Test the production function.""" self.assertEqual(self.attribute.production(100, 0.5), 50, 'Production not correct.') def test_valuation(self): """Test the valuation function.""" self.assertEqual(self.attribute.valuation(100), 100, 'Valuation not correct.') def test_weightage(self): """Test the weightage function.""" self.assertEqual(self.attribute.weightage(5), 5 / 100, 'Weight not correct.')
def main(): """.""" from vocabulary import Vocabulary from attribute import Attribute from attribute_structure import AttributeStructure from attribute_system import AttributeSystem vocabulary = Vocabulary(['C'], [], ['V']) a = Attribute("a", []) b = Attribute("b", []) astr = AttributeStructure(a, b) objs = ['a', 'b', 'c'] attribute_system = AttributeSystem(astr, objs) C = ConstantAssignment(vocabulary, attribute_system, {'C': 'a'}) print C._vocabulary vocabulary.add_constant("C2") print C._vocabulary
def readFile(self, dataFilePath): """ @param dataFilePath: path to our dataSet Method reads in our data, and stores example points and attributes in approp fields """ targetNames = attributes = examples = None with open(dataFilePath, "r") as fh: nbrOfTargets = int(fh.readline().strip()) targetValues = fh.readline().strip().split("T:")[1].split() nbrOfAttributes = int(fh.readline().strip()) # build a list of attribute objects holding the attrName and attrValues attributes = [] for attrNum in range(nbrOfAttributes): attrLine = fh.readline().strip().split("A:")[1] attrLineParts = attrLine.split() attrName = attrLineParts[0] attrValues = [] for i in range(2, len(attrLineParts)): attrValues.append(attrLineParts[i]) attribute = Attribute(attrName, attrValues) attributes.append(attribute) # build a list of all the example data nbrOfExamples = int(fh.readline().strip()) examples = [] for i in range(nbrOfExamples): exampleLine = fh.readline().strip().split("D:")[1] exampleLineParts = exampleLine.split() targetValue = exampleLineParts[-1] exampleAttributes = [] for j in range(nbrOfAttributes): attrName = attributes[j].attrName attrValues = [exampleLineParts[j]] attribute = Attribute(attrName, attrValues) exampleAttributes.append(attribute) te = TrainingExample(exampleAttributes, targetValue) examples.append(te) self.targetNames = targetValues self.attributesAndValues = attributes self.trainingExamples = examples
class TestReceiveMessage(unittest.TestCase): def setUp(self): self.sender = Attribute() def test_send(self): self.sender.send() def test_receive(self): message = self.mock_receiver() self.assertEquals(message, 'Hi') def mock_receiver(self): connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() method_frame, header_frame, body = channel.basic_get('task_queue') if method_frame == None: raise Exception('Queue was empty') channel.basic_ack(delivery_tag=method_frame.delivery_tag) channel.close() connection.close() return body
def new(self, need_load=True, **dict_data):#Return { fn: value } if need_load: yield self.load(need_value=False) _attr = Attribute(self._table) _attrib_id = yield _attr.new(**dict_data) ''' try: _attrib_id = yield _attr.new(**dict_data) except Exception, e: raise AttribManagerException("[ %s ]new failed. table:%s, data: %s, error:%s." % ( self.__class__, self._table, dict_data, e)) ''' if self._multirow: if not isinstance(self.dict_attribs, dict): log.warn('[ %s.new ]property dict_attribs is not dict. %s' % ( self.__class__, self.dict_attribs )) self.dict_attribs = {} self.dict_attribs[_attrib_id] = _attr else: self.dict_attribs = _attr #returnValue( _attr.value ) returnValue( _attr.new_value() )
def generate_attribute_name(self, context, template): if self.parent is None: return None if self.has_attribute("attributeName"): exist = self.get_attribute("attributeName") attr = Attribute(self.name, "attributeName", ConstValue(str(exist.value))) return attr attr = template.instantiate() if self.name == "SVGAnimateTransformElement": template = get_svg_animatable_transform_attribute(self.parent.name) else: template = get_svg_animatable_attribute(self.parent.name) # setup value class if self.name == "SVGAnimateElement" or self.name == "SVGSetElement": self.value_class = template.value_class attr.value = ConstValue(template.attr) attr.generate(context) return attr
def argsInit(): global state, starts, snake, set, enermylist, score, shield, attr, normal, special, timeIndex shield = 0 score = 0 state = starts timeIndex = 30 set.setInit() attr = Attribute(screen) normal = [] special = [] snake = MySnake(screen, set) enermylist.clear() for i in range(5): enermylist.append(OtherSnake(screen))
def test(train_data_file_name, attribute_file_name, test_data_file_name, optimizer): data = read_data(train_data_file_name) attributes = Attribute.read_attribute(attribute_file_name, data) tmp_attributes = copy.deepcopy(attributes) root = tree_generate(data, tmp_attributes, attributes, optimizer) right = 0 # bfs(root) test_data = read_data(test_data_file_name) Attribute.change_types(attributes, test_data) for d in test_data: category, probability = tree_test(root, d, attributes) pmax = -1 index = -1 for i in range(len(probability)): # print(probability[i]) if probability[i] > pmax: pmax = probability[i] index = i # print(category[index], d.value[-1]) if category[index] == d.value[-1]: right += 1 print("correct percentage: %f" % (right / len(test_data)))
def load(self): if not self.attrib: if self._loading is False: self._loading = True self.attrib = yield Attribute.load(self._table, self._where, self._multirow) # no other data to load for _f in self._futures: _f.set_result(True) self._loading = False self._futures = list() else: _f = Future() self._futures.append(_f) yield _f
def __init__(self, sequence=5): self.scene = glob(PATH) self.scene.sort() self.sequence = sequence self.list = [] self.list_coordinate = [] self.all_data = [] for i, j in zip(self.scene, range(len(self.scene))): self.out = [] data_split = [] print i, "----------------------------" print j sub_path = os.path.join(i, "annotations_.txt") data = np.genfromtxt(sub_path, delimiter=' ') # Center coordinates from Bounding Box x_lim1, y_lim1 = data[:, 1], data[:, 2] x_lim2, y_lim2 = data[:, 3], data[:, 4] x = (x_lim1 + x_lim2) / 2 y = (y_lim1 + y_lim2) / 2 # Normalization x, y = test(x, y, j) data[:, 1], data[:, 2] = x, y # all target in the scene ID = np.unique(data[:, 0][-1]) for j in range(0, int(ID[0])): trajectory = data[data[:, 0] == j, :] # ID,x,y,frame,attribute trajectory = trajectory[:, [0, 1, 2, 5, 9]] # extract attribute trajectory = Attribute(trajectory) if len(trajectory) > 0: data_split.append(trajectory) for split in xrange(len(data_split)): data_split_coor = data_split[split] if data_split_coor.shape[0] > self.sequence + 1: self.out.append(data_split_coor[:, [1, 2, 4, 5, 6, 7, 8, 9]]) self.all_data.append( data_split_coor[:, [1, 2, 4, 5, 6, 7, 8, 9]]) self.list_coordinate.append(self.out) self.list.append(len(self.out))
def main(): # src = Path(getcwd(), 'default-values.txt') # dst = Path(getcwd(), 'AUTOGEN.md') writer = open('AUTOGEN.md', 'w') writer.write('# Default Values\n\n') with open('default-values.txt', 'r') as reader: for line in reader.readlines(): attribute = Attribute(line) description = Comment(line) entry = f'* `{attribute.name}` - {description.text}\n' writer.write(entry) writer.close() system('code AUTOGEN.md')
def test_002_withrate(self): a = Attribute('stat4', is_rate=True) self.assertEqual(a.name, 'stat4') a.value = 1 sleep(1) self.assertIsNone(a.value) a.value = 2 sleep(1) self.assertAlmostEqual(a.value, 1, places=2) a.value = 3 sleep(0.5) self.assertAlmostEqual(a.value, 1, places=2) a.value = 4 sleep(2) self.assertAlmostEqual(a.value, 2, places=2) a.value = 5 self.assertAlmostEqual(a.value, 0.5, places=2) self.assertAlmostEqual(a.history_mean(3), 6.0, places=1)
def __init__(self, stream: Stream): magic = stream.read_u4() if magic != 0xCAFEBABE: raise Exception('Wrong magic') self.minor_version = stream.read_u2() self.major_version = stream.read_u2() self.constants: List[Constant] = self.read_constants(stream) self.access_flags = stream.read_u2() self.this_class = stream.read_u2() self.super_class = stream.read_u2() self.interfaces = [stream.read_u2() for _ in range(stream.read_u2())] self.fields: List[FieldMethodInfo] = [ FieldMethodInfo(self, stream) for _ in range(stream.read_u2()) ] self.methods: List[FieldMethodInfo] = [ FieldMethodInfo(self, stream) for _ in range(stream.read_u2()) ] self.attributes: List[Attribute] = [ Attribute.read(self, stream) for _ in range(stream.read_u2()) ] print(self.attributes)
def load(self, force=False, where=None, need_value=True): ''' Warning! Do not use force-load in multi-line-mode!!! ''' if not force and self.dict_attribs: #returnValue( self.value ) if need_value: returnValue( self.new_value() ) else: returnValue( [] ) if not where: if hasattr(self, 'where'): where = self.where else: raise AttribManagerException("[ %s ]load failed. you can set where property at first." % self.__class__ ) if self._table not in TABLEs_NO_DELETED: where['deleted'] = 0 try: res = yield Attribute.load(self._table, self._fields, where ) except Exception, e: raise AttribManagerException("[ {0} ]load failed. table: {1}, where: {2}, error: {3}.".format( self.__class__, self._table, where, e))
def test_000_nominal(self): a = Attribute('stat') self.assertEqual(a.name, 'stat') a.name = 'stat2' self.assertEqual(a.name, 'stat2') self.assertIsNone(a.value) self.assertEqual(a.history, []) a.value = 1 self.assertEqual(a.value, 1) self.assertEqual(a.history, []) a.value = 2 self.assertEqual(a.value, 2) self.assertEqual(a.history, [1]) a.value = 3 self.assertEqual(a.value, 3) self.assertEqual(a.history, [1, 2]) self.assertEqual(a.history_mean(3), 1.0)
def __init__(self): self._value = 0x20 self.attr = Attribute()
class Cell(): """ >>> from attribute import Attribute >>> cell = Cell() >>> attr = Attribute() >>> cell.get() u' ' >>> cell.write(0x34, attr) >>> cell.get() u'4' >>> cell.clear(attr._attrvalue) >>> cell.get() u' ' >>> cell.write(0x3042, attr) >>> cell.get() u'\u3042' >>> cell.pad() >>> cell.get() >>> cell.write(0x09a4, attr) >>> cell.get() u'\u09a4' >>> cell.combine(0x20DE) >>> cell.get() u'\u09a4\u20de' >>> cell.combine(0x20DD) >>> cell.get() u'\u09a4\u20de\u20dd' >>> cell.combine(0x0308) >>> cell.get() u'\u09a4\u20de\u20dd\u0308' """ _value = None _combine = None def __init__(self): self._value = 0x20 self.attr = Attribute() def write(self, value, attr): self._value = value self.attr.copyfrom(attr) def pad(self): self._value = None def combine(self, value): if self._combine: self._combine += unichr(value) else: self._combine = unichr(value) def get(self): c = self._value if c is None: return None if c < 0x10000: result = unichr(c) else: # c > 0x10000 c -= 0x10000 c1 = (c >> 10) + 0xd800 c2 = (c & 0x3ff) + 0xdc00 result = unichr(c1) + unichr(c2) if self._combine is None: return result return result + self._combine def clear(self, attrvalue): self._value = 0x20 self._combine = None self.attr.setvalue(attrvalue)
num_users = 0 if len(value["user"]) > 0: num_users = len(value["user"]) selected_users = value["user"] else: num_users = float(self.attributes["user"]["domain"])*float(value["groupSupport"]) while len(selected_users) < num_users: selected = random.randrange(1, int(self.attributes["user"]["domain"])) selected_user = self.attributes["user"]["represent"] + str(selected) if selected_user not in selected_users: selected_users.append(selected_user) for user in selected_users: if user not in self.exp_sequences: self.exp_sequences[user] = {} self.exp_sequences[user][key] = expanded if __name__ == '__main__': attribute = Attribute() attribute.load_dist_json() attribute.load_attr_cvs() pattern = Pattern(attribute.sem_to_rep) pattern.load() expanded_seq = Sequencepat(attribute.distribution, pattern.patterns) expanded_seq.expand() #print expanded_seq.exp_sequences print json.dumps(expanded_seq.exp_sequences)
def __init__(self, generator, name, ui_name, min, max, default): Attribute.__init__(self, generator, name, ui_name) self.min = min self.max = max self.default = default
def test_attribute_above_nine_below_twelve_returns_zero_modifier(self): attribute = Attribute(Attribute.STRENGTH, 10) self.assertEqual(attribute.get_attribute_modifier(), 0) attribute = Attribute(Attribute.STRENGTH, 11) self.assertEqual(attribute.get_attribute_modifier(), 0)
def __init__(self, generator, name, ui_name, min, max): Attribute.__init__(self, generator, name, ui_name) self.min = min self.max = max
def test_will_save_includes_wisdom_bonus(self): wisdom = Attribute(Attribute.WISDOM, 24) actor = Actor('Test Actor Dude', [wisdom], []) self.assertEqual(wisdom.get_attribute_modifier().value, actor.get_will_save().value)
def get_ui_name(self): return '<b>' + Attribute.get_ui_name(self) + '</b>'
def test_attribute_above_forty_five_treated_as_forty_five(self): attribute = Attribute(Attribute.STRENGTH, 56) self.assertEqual(attribute.get_attribute_modifier(), 17)
def test_fortitude_save_includes_constitution_bonus(self): constitution = Attribute(Attribute.CONSTITUTION, 19) actor = Actor('Test Actor Dude', [constitution], []) self.assertEqual(constitution.get_attribute_modifier().value, actor.get_fortitude_save().value)
def __init__(self, generator, name, ui_name, choices): Attribute.__init__(self, generator, name, ui_name) self.choices = choices
import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages import numpy as np from attribute import Attribute import random # normal function, parameter mu and sigma is the fit parameter def normal(k, mu, sigma): return 1/(sigma * np.sqrt(2 * np.pi)) * np.exp( - (k - mu)**2 / (2 * sigma**2) ) attribute = Attribute() attribute.load_dist_json() for key, value in attribute.distribution.iteritems(): name = key type = value["type"] domain = int(value["domain"]) # only draw normal distribution if (type != "normal" and type != "random"): continue; mu = int(value["mu"]) sigma = int(value["sigma"]) #s = np.random.normal(mu, sigma, 1000) # 1000 random number following normal distribution s = [] eventfile = "output/events.txt" with open(eventfile, 'rb') as file:
def setUp(self): self.sender = Attribute()
def test_reflex_save_includes_dexterity_bonus(self): dexterity = Attribute(Attribute.DEXTERITY, 13) actor = Actor('Test Actor Dude', [dexterity], []) self.assertEqual(dexterity.get_attribute_modifier().value, actor.get_reflex_save().value)
def __init__(self, generator, ui_name): Attribute.__init__(self, generator, 'title', ui_name)