def app_init(): admin_role=Role("ADMIN") user_role=Role("USER") admin_role.add_resource("BACKEND_SERVER_CONFIG",["READ","WRITE","DELETE"]) admin_user=User("admin",[admin_role]) user=User("User1",[user_role])
def fromJson(self, data: dict, emojis: Tuple[Emoji], manual_load=False): self.name = data["name"] if not manual_load: self.isInline = data["isInline"] roles: List[str] = [] for roleEmoji, roleData in data["roles"].items(): try: roleEmoji = cfg.ADDITIONAL_ROLE_EMOJIS[int(roleEmoji)] except ValueError: for emoji in emojis: if emoji.name == roleEmoji: roleEmoji = emoji break if not manual_load: # Only create new roles if we're not loading data manually from # the command channel role = Role(roleData["name"], roleEmoji, self.get_corrected_name(roleData)) self.roles.append(role) else: try: role = next(x for x in self.roles if x.emoji == roleEmoji) except StopIteration: name = roleData.get("show_name") or roleData["name"] raise UnexpectedRole( "Cannot import unexpected role '{}'".format(name)) roles.append(roleEmoji) role.fromJson(roleData, manual_load=manual_load) if manual_load: # Remove roles that were not present in imported data self.roles = [x for x in self.roles if x.emoji in roles]
def test_find_role(self): r1 = Role("foo") r2 = Role("Bar") r3 = Role("Baz") roles = [r1, r2, r3] found_role = find_role(r2.name, roles) assert_that([role.name for role in roles]).contains(found_role.name)
def __init__(self, setting): #世界的生成,主角初始化 self.map = Map(setting) self.state = State(setting) self.me = Role(1, 1, '猪脚') self.me.setting_attr(1, 1000) self.me.check() self.map.add(self.me) self.should_add_time = 0
def __init__(self, level): super(HowlGame, self).__init__(255, 255, 255, 255, 4000, 2000) # init voice self.NUM_SAMPLES = 1000 # pyAudio内部缓存块大小 self.LEVEL = 1500 # 声音保存的阈值 self.sample_count = 0 # 取样次数 self.average_volume = 0 # 平均音量 # init floor self.floor = Floor(self, level) self.add(self.floor, 0) # init voiceBar self.voiceBar = Sprite('ground/black.png', color=(0, 0, 255)) # self.voiceBar.position = 100, 460 self.voiceBar.scale_y = 0.1 self.voiceBar.image_anchor = 0, 0 self.add(self.voiceBar, 1) # init role self.role = Role(self) self.role_run_to_right = False self.role_run_to_left = False self.add(self.role, 2) self.action = FadeOut(0.5) # init monster # self.monster_node = cocos.cocosnode.CocosNode() # for i in range(5): # self.monster_node.add(Monster(self)) # self.add(self.monster_node) # init flag # flag = cocos.sprite.Sprite('scene/flag.png') # flag.position = 3500, 120 # flag.scale = 0.5 # self.flag = flag # self.add(flag) # init stone self.stone = None self.boom = cocos.sprite.Sprite('scene/boom.png') # init gameoverlayer self.gameover = None # Open Audio Input pa = PyAudio() SAMPLING_RATE = int( pa.get_device_info_by_index(0)['defaultSampleRate']) self.stream = pa.open(format=paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=self.NUM_SAMPLES) self.schedule(self.update)
def test_req_num_emp_not_greater_than_minimum_task_req(self): generic = CommonTestFunctions() category = generic.category() location = generic.location() group = generic.group() duration1 = generic.duration(6, 7) duration2 = generic.duration(7, 8) duration3 = generic.duration(8, 9) task1 = generic.task(group, location, category, duration1, required_number_of_employees=2, id=1) task2 = generic.task(group, location, category, duration2, required_number_of_employees=4, id=2) task3 = generic.task(group, location, category, duration3, required_number_of_employees=3, id=3) tasks = [ task1, task2, task3, ] acceptable = [ 1, 2, ] unacceptable = [ 3, 4, 5, ] for a in acceptable: Role(1, 'Role', tasks, a) for u in unacceptable: try: Role(1, 'Role', tasks, u) except AssertionError: pass else: raise Exception( 'Creating a role with a bad req number of employees did not raise an exception. ' + str(u))
def add_role(self, role_json): """ Append Role object to list """ if not ("role" in role_json): print("Error: File format error. Missing 'role' in json array.") exit(100) if "inherits" in role_json: self.list.append(Role(role_json["role"], role_json["inherits"])) else: self.list.append(Role(role_json["role"]))
def add(self, ico_name, ico_token, ico_url, role_name): duplicate = self.__find_duplicate(ico_url) if duplicate is not None: self.__add_role_to_ico(duplicate, Role(role_name)) else: roles = [] roles.append(Role(role_name)) ico = Ico(ico_name, ico_token, ico_url) self.positions.append((ico, roles))
def select_and_print(role: Role, open: int) -> None: print('Selection for {}'.format(role)) for i, (score, person) in enumerate(role.get_top_applicants()): decision = "Deny" if i < open: decision = "Accept" role.accept(person) else: role.deny(person) print("{} {} {} for {}".format(decision, score, person, role)) print('\n')
def main(argv): ota = AWS_IoT_OTA() ota_bucket = S3Bucket(args.s3bucket, args.region) if (False == ota_bucket.exists()): if (True == ota_bucket.create()): print("Created bucket") else: sys.exit() ota_role = Role(args.role) if (False == ota_role.exists()): ota_role.init_role_policies(account_id=args.account, bucket_name=args.s3bucket) ota.DoUpdate()
def get_membership(self, user_id=None, role=Role('member'), group_id=None): """Search for user group membership, of a certain role. user_id -- if unspecified default to current_user_dn role -- Role group_id -- if specified search only for this group """ if not user_id: user_id = self.current_user_dn url = self.base_url + "/search?" params = {'ID': user_id, 'IDTYPE': 'x500', 'ROLE': role.get_name()} if group_id: params['GROUPID'] = group_id xml_string = self._download_xml(url, params=params) reader = GroupsReader() groups = reader.read(xml_string) self.logger.info('Retrieved groups ' + ', '.join([g.group_id for g in groups])) return groups
def repo_all_roles(account_number, commit=False): """ Repo all eligible roles in an account. Collect any errors and display them at the end. Args: account_number (string) commit (bool): actually make the changes Returns: None """ errors = [] role_ids_in_account = roledata.role_ids_for_account(account_number) roles = Roles([]) for role_id in role_ids_in_account: roles.append( Role(roledata.get_role_data(role_id), fields=['Active', 'RoleName'])) roles = roles.filter(active=True) for role in roles: errors.append(repo_role(account_number, role.role_name, commit=commit)) if errors: LOGGER.error('Error(s) during repo: \n{}'.format(errors)) else: LOGGER.info('Everything successful!')
def addDefaultRoles(self): for name, groupName in cfg.DEFAULT_ROLES[self.platoon_size].items(): # Only add role if the group exists if groupName in self.roleGroups.keys(): emoji = self.normalEmojis[name] newRole = Role(name, emoji, False) self.roleGroups[groupName].addRole(newRole)
def index(user): user_count = Profile.objects(user_id=user[0]).count() role = Role.objects(name="Citizen").first() channel = Channel.objects(slug=map_channel(user[4])).first() if user_count == 0: #channels = [] coordinates = str(user[11]) + "," + str(user[12]) profile = Profile(user_id=int(user[0]), full_name=user[1], sign_up_with="mobile_number", sign_up_ip_address=str(ipaddress.IPv4Address(user[2])), avatar=str(user[3]), roles=[role.id], channels=[{"id": channel.id, "slug": channel.slug, "mac_address": user[5], "sign_up": True, "device_token": user[6], "last_login_at": user[7], "settings": {"email_notifications_preferred": True, "sms_notifications_preferred": True, "push_notifications_preferred": True}}], locations=[{"app_name": channel.app_name, "location": {"name": user[8], "coordinates": coordinates, "ward_id": user[9], "city_id": user[10]}}]) profile.save() print('User: '******' indexed') else: print('User: '******' already exists') return True
def test_assign_role_with_bad_time(self): generic = CommonTestFunctions() category = generic.category() location = generic.location() group = generic.group() duration1 = generic.duration(6, 7) duration2 = generic.duration(7, 8) duration3 = generic.duration(8, 9) task1 = generic.task(group, location, category, duration1, required_number_of_employees=4, id=1) task2 = generic.task(group, location, category, duration2, required_number_of_employees=4, id=2) task3 = generic.task(group, location, category, duration3, required_number_of_employees=3, id=3) tasks = [ task1, task2, task3, ] role = Role(1, 'Role1', tasks, 3) availability = [generic.availability(6,8)] groups = [group] preferences = [generic.preference(category)] staff_member = generic.staff_member(availability=availability, preferences=preferences, groups=groups, id=1) self.assertRaises(BadRoleAssignmentException, staff_member.assign_role, role) self.assertFalse(staff_member.has_role(role)) self.assertFalse(staff_member.can_assign_role(role)) self.assertFalse(staff_member.has_role(role)) self.assertFalse(staff_member.try_assign_role(role)) self.assertFalse(staff_member.has_role(role))
class Slot: """class that defines slot side_ = string type: left, right center position_ = string type: winger, defence, ... player_ = Player type: role_ = Role type """ def __init__(self, side, position): self.position_ = position self.side_ = side self.player_ = None self.role_ = Role() def __str__(self): stringa = "" if self.player_ != None: stringa = self.side_[0] + self.side_[-1:] + " " stringa += self.position_[0] + self.position_[-1:] stringa += " (" + str(self.role_) + ")" stringa += ": " + str(self.player_) stringa += ";" return stringa def position(self): return self.position_ def side(self): return self.side_ def set_player(self, player): self.player_ = player; def has_player(self): return self.player_ != None def player(self): return self.player_ def set_role(self, role): self.role_.set_role(role); def role(self): return self.role_ def is_the_same(self, slot): return self.position_ == slot.position_ and self.side_ == slot.side_
def add_pair(self, member, role): try: self.stats[give_faction(role)] += 1 except KeyError: pass self.player_map[member] = Player(member, role) self.role_map[role] = Role(role, self.player_map[member]) self.player_map[member].role_class = self.role_map[role]
def create_base_tables(): """Cria as tabelas base e prenche os valores iniciais!""" import objs from base_models import Sequence model = Sequence() syncModel(model) #print('users') from users import Users model = Users() syncModel(model) #print('role') from role import Role model = Role() syncModel(model) result = Users().get() if len(result) == 0: import base64 password = base64.encodestring('noops!admin'.encode('utf-8')).decode('utf-8') new_user_id = get_identity(table='users', user=None) sql = "INSERT INTO users (nome, login, password, email, estado, id, user_create, date_create, active) VALUES ('admin', 'admin', '{var1}', 'admin@localhost', 'active','{var2}','{var3}','{var4}', True);".format(var1=password,var2= new_user_id, var3=new_user_id, var4=str(datetime.datetime.today())) #print(sql) with getcursor() as cursor: cursor.execute(sql) result = Role().get() if len(result) == 0: new_role_id = get_identity(table='role', user=new_user_id) sql = "INSERT INTO role (nome, id, user_create, date_create, active) VALUES ('Administrator', '{var1}','{var2}','{var3}', True);".format(var1=new_role_id, var2=new_role_id, var3=str(datetime.datetime.today())) #print(sql) with getcursor() as cursor: cursor.execute(sql) #sql = 'CREATE TABLE IF NOT EXISTS role_users (id VARCHAR(50) PRIMARY KEY, role INTEGER, user_id INTEGER);' #with getcursor() as cursor: # cursor.execute(sql) new_id = get_identity(table='role_users', user=new_user_id) sql = "INSERT INTO role_users (role, users, id) VALUES ('{var1}','{var2}','{var3}');".format(var1=new_role_id, var2=new_user_id, var3=new_id) #print(sql) with getcursor() as cursor: cursor.execute(sql)
def process_role(args): """ args: 0 -> operation create: 1 -> role_name delete, add-schema, remove-schema: 1 -> role_id add-schema, remove-schema: 2 -> schema_id """ operation = args[0] if operation == 'list': return Role.list_current() role = args[1] if role == '': return '>Missing parameters.' if operation == 'create': role_id = Role.create(role) return f'>Role created with ID: {role_id}' if not Role.exists(role): return '>Role does not exist.' if operation == 'delete': Role.delete(role) return f'>Role {role} deleted.' try: schema_id = args[2] except IndexError: return '>No scheme id specified.' if operation == 'add-schema': Role.add_schema(role, schema_id) return f'>Schema {schema_id} added to role {role}' elif operation == 'remove-schema': Role.remove_schema(role, schema_id) return f'>Schema {schema_id} removed from role {role}' return False
def index(user): user_count = Profile.objects(user_id=user[0]).count() role = Role.objects(name="Citizen").first() source_id = 1 if user[4] == 0 else user[4] channel = Channel.objects(slug=map_channel(source_id)).first() if user_count == 0: #channels = [] latitude = user[11] longitude = user[12] coordinates = [float(longitude), float(latitude) ] if latitude and longitude else None city_id = None if user[10] == 0 else user[10] full_name = (user[1].lower().title()) if user[1] else 'Citizen' profile = Profile(user_id=int(user[0]), full_name=full_name, sign_up_with="mobile_number", sign_up_ip_address=str(ipaddress.IPv4Address( user[2])), avatar=user[3], roles=[role.id], channels=[{ "id": channel.id, "slug": channel.slug, "mac_address": user[5], "sign_up": True, "device_token": user[6], "last_login_at": user[7], "settings": { "email_notifications_preferred": True, "sms_notifications_preferred": True, "push_notifications_preferred": True } }], locations=[{ "app_name": channel.app_name, "location": { "name": user[8], "coordinates": coordinates, "ward_id": user[9], "city_id": city_id } }]) profile.save() #role.update(push__profile_ids=str(profile.id)) #print('User: '******'==' + str(profile.id) + ' indexed') print('User: '******' indexed') else: print('User: '******' already exists') return True
def role(self, tasks, required_number_of_employees=1, name='Role', id=None): if id == None: id = self._get_next_role_id() r = Role(id, name, tasks, required_number_of_employees) self.created_roles.append(r) return r
def setup(meta): person = Person(email_address="*****@*****.**", activated=True, firstname="Admin", lastname="User") person.password = '******' person.activated = True role = Role.find_by_name('organiser') person.roles.append(role) meta.Session.add(person)
def __init__(self): self.iChat = ChatFeatures() self.iChat.process() self.linkFeatsDayUser = self.iChat.linkAnalysis() self.domainWordsDayUser = self.iChat.domainWordsPerDay() self.msgPerTurnDayUser = self.iChat.msgPerTurn() self.quranCitesDayUser = self.iChat.quranCites() self.iTopic = Topic() #generalRelevance[date] = score self.generalRelevanceDay = self.iTopic.relevantDayDetection() self.userRelevanceDay = {} for user in self.iChat.userSet: self.userRelevanceDay[user] = self.iTopic.relevantDayDetection( "./stats/distances" + user[0].upper() + user[1:] + ".tsv") self.iRole = Role() self.roleScoresDayUser = self.iRole.computeRolesPerDay() self.wordsPerDayUser = self.iChat.wordsPerDay()
def update(self, person_socials, ico_name, ico_token, ico_url, unclear_role): self.socials.update(person_socials) roles = Role.detect_roles(unclear_role) for role in roles: self.positions.add(ico_name, ico_token, ico_url, role) if len(roles) == 1 and "UNCERTAIN" in roles: self.uncertain_positions.add(ico_name, ico_token, ico_url, unclear_role)
def test_cannot_give_conflicting_tasks(self): generic = CommonTestFunctions() required_number_of_employees = 1 category = generic.category() location = generic.location() group = generic.group() duration1 = generic.duration(6, 7) duration2 = generic.duration(7, 8) duration3 = generic.duration(8, 9) duration4 = generic.duration(6, 8) task1 = generic.task( group, location, category, duration1, required_number_of_employees=required_number_of_employees, id=1) task2 = generic.task( group, location, category, duration2, required_number_of_employees=required_number_of_employees, id=2) task3 = generic.task( group, location, category, duration3, required_number_of_employees=required_number_of_employees, id=3) task4 = generic.task( group, location, category, duration4, required_number_of_employees=required_number_of_employees, id=4) tasks = [task1, task2, task3, task4] role = None try: role = Role(1, 'Role', tasks, required_number_of_employees) except AssertionError: pass else: raise Exception( 'Creating the role did not raise a conflicting task exception.' )
def delete_all_config(self): if 'C_CONFIG_LAMBDAPROXY' in self.vars: if self.config.has_section(self.vars['C_CONFIG_LAMBDAPROXY']): for lp in self.config.items(self.vars['C_CONFIG_LAMBDAPROXY']): self = Ltklambdaproxy(self, lp[0]).undeploy_lambda_proxy() if 'C_CONFIG_SQS_QUEUES' in self.vars and 'C_CONFIG_SQS' in self.vars: queues = Utils.get_list_config(self, self.vars['C_CONFIG_SQS'], self.vars['C_CONFIG_SQS_QUEUES']) for q in queues: self = Queue(self, q).delete_queue() self = Role(self, "bypassvalidator").unset_default_role()
def loginF(role): flag = True print('当前角色编码是%s' % role) while flag: exits = 0 user = input('用户:') password = input('密码:') f = open('../db/user.txt', 'r') data = f.readlines() print('用户数据:', data) for i in data: i = i.replace('\n', '').split(' ') #print('校验密码',i[0],i[1],i[2]) #print('校验密码', user, password, role) if i[0] == user and i[1] == password and i[2] == role: exits = 1 if exits == 1: print('用户校验成功!') r = Role(role, user) r.selectType() else: print('用户名或密码错误!')
def remove_role(email, role_id): logger.info({ 'status': 'remove', 'type': 'user', 'email': email, 'role_id': role_id }) User.table.update_item( Key={ 'email': email, 'type': 'user' }, UpdateExpression='DELETE role_list :role_id', ExpressionAttributeValues={':role_id': set([role_id])}) role_name = Role.get_role_name(role_id) schemas = Role.get_schemas(role_id) for schema in schemas: if schema == '0': continue User.change_role(email, schema, role_name, 'drop_group')
def setup(meta): person = Person( email_address="*****@*****.**", activated=True, firstname="Admin", lastname="User" ) person.password = '******' person.activated = True role = Role.find_by_name('organiser') person.roles.append(role) meta.Session.add(person)
def addAdditionalRole(self, name: str) -> str: # Find next emoji for additional role if self.countReactions() >= MAX_REACTIONS: raise RoleError("Too many roles, not adding role {}".format(name)) emoji = cfg.ADDITIONAL_ROLE_EMOJIS[self.additionalRoleCount] # Create role newRole = Role(name, emoji, True) # Add role to additional roles self.roleGroups["Additional"].addRole(newRole) self.additionalRoleCount += 1 return emoji
def create_role (self, role_type, player): """Creates a new role representing a role in this association. :param role_type: the role type :type role_type: `Topic` :param player: the role player :type player: `Topic` :rtype: `Role` """ if role_type is None: raise ModelConstraintException(self, 'The type may not be None') if player is None: raise ModelConstraintException(self, 'The player may not be None') if self.topic_map != role_type.topic_map: raise ModelConstraintException( self, 'The type is not from the same topic map') if self.topic_map != player.topic_map: raise ModelConstraintException( self, 'The player is not from the same topic map') role = Role(association=self, type=role_type, player=player, topic_map=self.topic_map) role.save() return role
def __init__(self, person_name, person_socials, ico_name, ico_token, ico_url, unclear_role): self.name = person_name self.socials = Social(person_socials) self.positions = Positions() self.uncertain_positions = Positions() roles = Role.detect_roles(unclear_role) for role in roles: self.positions.add(ico_name, ico_token, ico_url, role) if len(roles) == 1 and "UNCERTAIN" in roles: self.uncertain_positions.add(ico_name, ico_token, ico_url, unclear_role)
def parse(cls, id, data): token = Token() token.setId(id) data = data["token"] issued_at = None expires_at = None try: issued_at = datetime.strptime(data["issued_at"], "%Y-%m-%dT%H:%M:%S.%fZ") except Exception: issued_at = datetime.strptime(data["issued_at"], "%Y-%m-%dT%H:%M:%S.%f") try: expires_at = datetime.strptime(data["expires_at"], "%Y-%m-%dT%H:%M:%S.%fZ") except Exception: expires_at = datetime.strptime(data["expires_at"], "%Y-%m-%dT%H:%M:%S.%f") token.setCreation(issued_at) token.setExpiration(expires_at) project = Project() project.setId(data["project"]["id"]) project.setName(data["project"]["name"]) token.setProject(project) user = User() user.setId(data["user"]["id"]) user.setName(data["user"]["name"]) user.setProjectId(data["project"]["id"]) token.setUser(user) if "extras" in data: token.getExtras().update(data["extras"]) for info in data["roles"]: role = Role() role.setId(info["id"]) role.setName(info["name"]) token.getRoles().append(role) for service_info in data["catalog"]: service = Service() service.setId(service_info["id"]) service.setType(service_info["type"]) service.setName(service_info["name"]) for endpoint_info in service_info["endpoints"]: endpoint = Endpoint() endpoint.setId(endpoint_info["id"]) endpoint.setInterface(endpoint_info["interface"]) endpoint.setRegion(endpoint_info["region"]) endpoint.setRegionId(endpoint_info["region_id"]) endpoint.setURL(endpoint_info["url"]) service.getEndpoints().append(endpoint) token.getServices().append(service) return token
def buildRbac(self): self.prefixes = {} """for att in self.rbacdoc.attributes: a, p = att value = self.rbacdoc.getAttributeNS(XMLNS_NAMESPACE, str(p)) self.prefixes[str(p)] = value""" for child in self.rbacdoc.childNodes: if child.nodeType==Node.ELEMENT_NODE: if child.tagName == "prefixes": for node in child.childNodes: if node.nodeType==Node.ELEMENT_NODE: if node.tagName == "prefix": name = node.getAttributeNS(EMPTY_NAMESPACE,'name') value = node.getAttributeNS(EMPTY_NAMESPACE,'value') self.prefixes[name] = value if child.tagName == C.USERS: for node in child.childNodes: if node.nodeType==Node.ELEMENT_NODE: if node.tagName == C.USER: userId = node.getAttributeNS(EMPTY_NAMESPACE,'id') login = "" password = "" publickey = "" publickeytype = "" for nodeee in node.childNodes: if nodeee.nodeType==Node.ELEMENT_NODE: if nodeee.tagName == C.LOGIN: tmpval = nodeee.childNodes[0].nodeValue login = string.strip(str(tmpval)) if nodeee.tagName == C.PASSWORD: tmpval = nodeee.childNodes[0].nodeValue password = string.strip(str(tmpval)) if nodeee.tagName == C.PUBLIC_KEY: tmpval = nodeee.childNodes[0].nodeValue publickey = string.strip(str(tmpval)) tmpval = nodeee.getAttributeNS(EMPTY_NAMESPACE,'keytype') publickeytype = string.strip(str(tmpval)) user = User(userId, login, password, publickey, publickeytype) self.users.append(user) if child.tagName == C.ROLES: for node in child.childNodes: if node.nodeType==Node.ELEMENT_NODE: if node.tagName == C.ROLE: roleId="" roleName="" juniorRolesId=[] roleId = node.getAttributeNS(EMPTY_NAMESPACE,'id') for nodeee in node.childNodes: if nodeee.nodeType == Node.ELEMENT_NODE: if nodeee.tagName == C.NAME: tmpval = nodeee.childNodes[0].nodeValue name = string.strip(str(tmpval)) roleName = name if nodeee.tagName == C.JUNIOR_ROLES: juniorRoleIds = [] for n in nodeee.childNodes: if n.nodeType == Node.ELEMENT_NODE: if n.tagName == C.JUNIOR_ROLE: jrid = n.getAttributeNS(EMPTY_NAMESPACE,'roleRef') juniorRolesId.append(jrid) role = Role(roleId, roleName, juniorRolesId) self.roles.append(role) if child.tagName == C.PERMISSIONS: for node in child.childNodes: if node.nodeType==Node.ELEMENT_NODE: if node.tagName == C.PERMISSION: for nodeee in node.childNodes: if nodeee.nodeType==Node.ELEMENT_NODE: if nodeee.tagName == C.SCOPE: tmpval = nodeee.childNodes[0].nodeValue scope = string.strip(str(tmpval)) att_id = node.getAttributeNS(EMPTY_NAMESPACE,'id') att_op = node.getAttributeNS(EMPTY_NAMESPACE,'op') permission = Permission(att_id, att_op, scope) self.permissions.append(permission) if child.tagName == C.USER_ASSIGNEMENTS: for node in child.childNodes: if node.nodeType==Node.ELEMENT_NODE: if node.tagName == C.USER_ASSIGNEMENT: roleId = node.getAttributeNS(EMPTY_NAMESPACE,'roleRef') userId = node.getAttributeNS(EMPTY_NAMESPACE,'userRef') role = self.getRoleFromId(roleId) user = self.getUserFromId(userId) role.addUser(user) if child.tagName == C.PERMISSION_ASSIGNEMENTS: for node in child.childNodes: if node.nodeType==Node.ELEMENT_NODE: if node.tagName == C.PERMISSION_ASSIGNEMENT: roleId = node.getAttributeNS(EMPTY_NAMESPACE,'roleRef') permId = node.getAttributeNS(EMPTY_NAMESPACE,'permRef') role = self.getRoleFromId(roleId) perm = self.getPermFromId(permId) if role != None and perm != None: role.addPermission(perm) else: pass
import random from chessboard import Chessboard from role import Role import sys def sendMessage(message): sys.stdout.write(message + "\n") sys.stdout.flush() def receiveMessage(): message = sys.stdin.readline() sys.stdin.flush() return message[:len(message) - 1] rl = Role() # init the computer role while True: # receive command from judge program command = receiveMessage() command = command.split() if command[0].upper() == "QUIT" or command[0].upper() == "Q": # quit the game sendMessage("bye") exit() elif command[0].upper() == "START": # play a new game if command[1].upper() == "BLACK": # wait the opponent player to make a move sendMessage("ok") cb = Chessboard(-1) # black first always continue
def __init__(self, side, position): self.position_ = position self.side_ = side self.player_ = None self.role_ = Role()