def run(self, arg):
        today_match = {"": ""}
        while(1):
            all_user_birth = DBHandler().select("SELECT Open_ID,Birth from UserInfo")
            for user_line in all_user_birth[1]:
                user_id = user_line[0]
                if user_line[1] is not None:
                    user_birth = user_line[1].strftime("%Y-%m-%d")
                    birth_MM_DD = user_birth.split("-", 1)[1]
                else:
                    birth_MM_DD = ""

                now_MM_DD = time.strftime('%m-%d', time.localtime(time.time()))

                if birth_MM_DD == now_MM_DD and today_match.get(user_id, "NoRecord") != birth_MM_DD:
                    today_match[user_id] = now_MM_DD
                    print("match")
                    ret = WeChatHandler().sendMsgViaCust(Resource.getMsg("Birth") + Resource.getMsg("ReplyHappy"),
                                                         "touser", user_id)
                    if int(ret) != 0:
                        print("BirthDayNotifier Cust Msg failed..Use preview")
                        sleep(300)
                        WeChatHandler().sendMsgToOneAsPreview(Resource.getMsg("Birth") + Resource.getMsg("ReplyHappy"),
                                                       "touser", user_id)

                    ActionsExecutor.add_manual_action(user_id, Action(self.check_reply, user_id, "NoHappy"))
                    threading.Timer(3600, self.get_action, args=(user_id,)).start()
            self.logger.debug("Sleep Birth")
            sleep(120)
Beispiel #2
0
    def unSub_Weahter(user, city, lang):
        UserHandler.logger.info(
            "User <%s> is un-subscribing the city <%s> weather" % (user, city))
        # QUERY
        user_sub_result = DBHandler().select(
            "SELECT Cities from WeatherSub WHERE Open_ID = '%s'" % user)
        content = ""
        if int(user_sub_result[0]) > 0:
            old_cities = user_sub_result[1][0][0].split()
            if city not in old_cities:
                content = "未订阅<%s>天气" % city
            else:
                old_cities.remove(city)
                if len(old_cities) > 0:
                    content = Resource.getMsg(
                        "UnSubWea", lang) % (city, " ".join(old_cities))
                    update_sql = "UPDATE WeatherSub SET Cities = '%s' WHERE Open_ID = '%s'" % (
                        " ".join(old_cities), user)
                    DBHandler().update(update_sql)
                else:
                    content = Resource.getMsg("UnSubAllWea", lang) % city
                    delete_sql = "DELETE from WeatherSub WHERE Open_ID = '%s'" % (
                        user)
                    DBHandler().delete(delete_sql)

        else:
            content = Resource.getMsg("NoSub", lang)
        return content
Beispiel #3
0
 def __init__(self,max_cores=1,name='Cores'):
     
     Resource.__init__(self)
     
     cores = self.manager.BoundedSemaphore(max_cores)
     
     in_service = InService(     \
         inbox = self.checkinbox ,
         cores = cores           ,
         name  = name+'_checkin' ,
     )        
     
     out_service = OutService(    \
         inbox = self.checkoutbox ,
         cores = cores            ,
         name  = name+'_checkout' ,
     )        
     
     self.name = name
     self.max_cores   = max_cores
     self.cores       = cores
     self.in_service  = in_service
     self.out_service = out_service
     
     self.start()
    def __init__(self, parentObject=None, resourceDescriptor = {}):
        Resource.__init__(self)
        # The resources dictionary is for subclasses of RESTfulResource, routable as http endpoints
        # The Properties dictionary is for serializable objects and strings, get/put but not routable
        self.Resources = RESTfulDictEndpoint(self.resources) #make resources endpoint from the dictionary
        # make properties resource and it's endpoint
        self._properties = {}
        self.Properties = RESTfulDictEndpoint(self._properties) #make Properties endpoint from its dict
        # make an entry in resources to point to properties
        self.Resources.update({'Properties': self.Properties}) # put Properties into the resource dict
        self.Resources.update({'thisObject': self}) #self-identity
        # initialize Properties by putting in the constructor properties
        
        self._resourceDescriptor = resourceDescriptor # for settings and properties update

        if parentObject == None : #no parent means this is a base object, fill in base settings
            self.Resources.update({'baseObject': self})
            self.Resources.update({'parentObject': self})
            self.Properties.update({'pathFromBase': ''})
            self.Properties.update({'resourceName': 'baseObject'})
            self.Properties.update({'resourceClass': 'SmartObject'})
        else : # fill in properties and identity of parent, base, and path to base
            self.Properties.update({'resourceName': resourceDescriptor['resourceName']}) 
            self.Properties.update({'resourceClass': resourceDescriptor['resourceClass']})
            self.Resources.update({'parentObject' : parentObject.Resources.get('thisObject')})
            self.Resources.update({'baseObject': parentObject.Resources.get('baseObject') })
            self.Properties.update({'pathFromBase': self.Resources.get('parentObject').Properties.get('pathFromBase') \
                                   + '/' + self.Properties.get('resourceName')})
            
        self._parseContentTypes = ['*/*'] 
        self._serializeContentTypes = ['*/*']
        self.defaultResources = None
        
        self.resources.update({'l': ResourceList(self)})
Beispiel #5
0
    def __init__(self, name):
        Resource.__init__(self, name)

        self._registry = {}
        self._resources = {}

        return
Beispiel #6
0
    def __init__(self, name):
        Resource.__init__(self, name)

        self._registry = {}
        self._resources = {}

        return
Beispiel #7
0
 def test_get_brief_summary_output(self):
     """ Test get_brief_summary method's output in Resource class"""
     
     # Create a Resource object
     resource = Resource(1, "White Noise", Name("Don", "", "DeLillo"), 
                         "Delillo's White Noise follows narrator Jack "\
                         "Gladney, a professor at a small Liberal Arts "\
                         "college and describes an academic year. Jack "\
                         "teaches at a school called the "\
                         "College-on-the-Hill, where he serves as the "\
                         "department chair of Hitler studies. He lives in "\
                         "Blacksmith, a quiet college town, with his wife, "\
                         "Babette, and four of their children from earlier "\
                         "marriages: Heinrich, Steffie, Denise, and "\
                         "Wilder. Throughout the novel, various "\
                         "half-siblings and ex-spouses drift in and out "\
                         "of the family’s home.",
                         "sci-fi", "English", 1985, "US", 326, "book",
                         ["culture", "survival", "life", "society"])
     
     # Assert expected results       
     self.assertEqual(resource.get_brief_summary(), "Delillo's White "\
                      "Noise follows narrator Jack Gladney, a professor "\
                      "at a \nsmall Liberal Arts college and describes an "\
                      "academic year. Jack teaches \nat ...")
 def __init__(self,max_cores=1,name='Cores'):
     
     Resource.__init__(self)
     
     cores = self.manager.BoundedSemaphore(max_cores)
     
     in_service = InService(     \
         inbox = self.checkinbox ,
         cores = cores           ,
         name  = name+'_checkin' ,
     )        
     
     out_service = OutService(    \
         inbox = self.checkoutbox ,
         cores = cores            ,
         name  = name+'_checkout' ,
     )        
     
     self.name = name
     self.max_cores   = max_cores
     self.cores       = cores
     self.in_service  = in_service
     self.out_service = out_service
     
     self.start()
Beispiel #9
0
def resourceSearchTests(pf):
    try:
        # try out isChild with a non-child resource
        p = Resource("eddie", "atype")
        c = Resource("franks|schild", "atype|btype")
        theVerdict = p.isChild(c)
    except PTexception, a:
        pf.failed(a.value)
def resourceSearchTests(pf):
    try:
       # try out isChild with a non-child resource
       p = Resource("eddie","atype")
       c = Resource("franks|schild","atype|btype")
       theVerdict = p.isChild(c)
    except PTexception, a:
        pf.failed(a.value)
Beispiel #11
0
 def __init__(self):
     Resource.__init__(self)
     self._parseContentTypes = []
     self._serializeContentTypes = []
     self.defaultClass = 'RESTfulResource'  # class name, override in derived classes
     self.wellKnownClasses = [
         'Description', 'Observers', 'PropertyOfInterest', 'SmartObject',
         'RESTfulResource', 'Agent'
     ]
Beispiel #12
0
    def testAsynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized=False)

        self.r.load(self, "result", lambda: loader())

        while not self.result:
            self.e.run()

        assert self.result == 0xdada
 def add_resource(self, resourceData: Dict):
     new_resource = Resource(self.__database_manager.get_next_resource_id(),
                             resourceData["title"],
                             resourceData["link"],
                             author=resourceData["author"],
                             subject=resourceData["subject"],
                             resource_type=Resource.Type(
                                 resourceData["type"]),
                             isbn=resourceData["isbn"])
     self.__resource_list.append(new_resource)
     self.__database_manager.add_resource(new_resource)
Beispiel #14
0
 def __notify(self, msg):
     if msg != "":
         for user in self.user_list:
             ret = WeChatHandler().sendMsgViaCust(
                 msg + Resource.getMsg("ReYes"), "touser", user)
             if int(ret) != 0:
                 print("HealthyNotifier Cust Msg failed..Use preview")
                 WeChatHandler().sendMsgToOneAsPreview(
                     msg + Resource.getMsg("ReYes"), "touser", user)
             self.user_wait_list.append(user)
             threading.Timer(300, self.clear_wait, (user, )).start()
Beispiel #15
0
    def testAsynchLoadSeries(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized=False)

        for i in range(10):
            self.r.load(self, "result%d" % i, loader)

        while not self.result9:
            self.e.run()

        assert self.result9 == 0xdada
Beispiel #16
0
def set_requests():
    """
    :return: request对象数组
    """
    requests = []
    for i in range(request_time):
        vcpu, disk, ram = get_random()
        resource = Resource(vcpu, disk, ram)
        resource.set_resource(vcpu, disk, ram)
        request = Request(None, resource)
        requests.append(request)
    return requests
Beispiel #17
0
 def __init__(self, appName="", AVs=None, executions=None):
    Resource.__init__(self,appName,"application")
    if AVs == None:
       self.attributes = []
    else:
       self.attributes = []
       self.addAttributes(AVs)
    if executions == None:
       self.executions = []
    else:
       self.executions = []
       self.addExecutions(executions)
Beispiel #18
0
def get_initial_run_info(resIdx, attrs, eInfo, ptds):
    """Parses the run data file and addes the information to the Execution
       object, exe."""

    runMachineArg = eInfo.machineName
    # expect only one execution resource in resIdx
    [exe] = resIdx.findResourcesByType("execution")
    (runMachine, runOS, exe, numberOfProcesses, threadsPerProcess) = getInitialAVs(
        resIdx, attrs, exe, runMachineArg, ptds
    )

    envNewName = ptds.getNewResourceName("env")
    env = Resource(envNewName, "environment")
    resIdx.addResource(env)
    if attrs.getCurrent()[0] != "RunDataEnd":
        (exe) = getSubmission(resIdx, attrs, exe, ptds)
    if attrs.getCurrent()[0] != "RunDataEnd":
        (exe) = getFilesystems(resIdx, attrs, exe, ptds)
    if attrs.getCurrent()[0] != "RunDataEnd":
        (env) = getLibraries(resIdx, attrs, env, exe)
        # env.dump(recurse=True)
    if attrs.getCurrent()[0] != "RunDataEnd":
        (exe) = getInputDecks(resIdx, attrs, exe, ptds)

    # expect only one build resource in resIdx
    [build] = resIdx.findResourcesByType("build")

    # check to see if we figured out how many processes there were
    if numberOfProcesses != -1:
        # yes, so create resource entries for all processes and threads
        i = 0
        while i < int(numberOfProcesses):
            process = Resource(
                exe.name + Resource.resDelim + "Process-" + str(i), "execution" + Resource.resDelim + "process"
            )
            resIdx.addResource(process)
            process.addAttribute("environment", env.name, "resource")
            process.addAttribute("build", build.name, "resource")
            process.addAttribute("OS name", runOS.name, "resource")
            if runMachine:
                process.addAttribute("machine name", runMachine.name, "resource")
            j = 0
            while j < int(threadsPerProcess):
                thread = Resource(
                    process.name + Resource.resDelim + "Thread-" + str(j),
                    "execution" + Resource.resDelim + "process" + Resource.resDelim + "thread",
                )
                resIdx.addResource(thread)
                j += 1
            i += 1
    # couldn't figure out number of processes, so link up resources with
    # the execution resource
    else:
        exe.addAttribute("environment", env.name, "resource")
        exe.addAttribute("build", build.name, "resource")
        exe.addAttribute("OS name", runOS.name, "resource")
        if runMachine:
            exe.addAttribute("machine name", runMachine.name, "resource")
Beispiel #19
0
    def dump(self, indent=0, recurse=False):
        """Dump routine for debugging."""
        i = indent
        ind_str = ""
        while i > 0:
            ind_str += "  "
            i -= 1

        Resource.dump(self, indent, recurse)
        print ind_str + self.name + "'s performanceResults: " \
              + str(len(self.performanceResults))
        for p in self.performanceResults:
            p.dump(indent + 1, recurse)
Beispiel #20
0
   def dump(self, indent=0, recurse=False):
       """Dump routine for debugging."""
       i = indent
       ind_str = ""
       while i > 0:
          ind_str += "  "
          i -= 1

       Resource.dump(self, indent, recurse)
       print ind_str + self.name + "'s performanceResults: " \
             + str(len(self.performanceResults)) 
       for p in self.performanceResults:
          p.dump(indent+1, recurse)
Beispiel #21
0
    def __init__(self, name, settings):
        Resource.__init__(self, 'PBXProject', name)

        self.organization = 'Pygling'
        self.archiveVersion = 1
        self.objectVersion = 46
        self.objects = Objects(self)
        self.targets = ObjectList()
        self.configurationList = self.objects.createConfigurationList(
            self, settings, 'Debug')
        self.mainGroup = self.objects.createGroup()
        self.sourcesGroup = self.addGroup('Sources')
        self.frameworksGroup = self.addGroup('Frameworks')
        self.productsGroup = self.addGroup('Products')
    def onUnSub(user_open_ID):
        WeChatName = DBHandler().select(
            "SELECT WechatName from UserInfo WHERE Open_ID = '%s'" %
            user_open_ID)[1][0][0]
        if len(WeChatName) > 0:
            msg = Resource.getMsg("UnSub") % WeChatName
        else:
            msg = Resource.getMsg("UnSub") % user_open_ID

        ret = WeChatHandler().sendMsgViaCust(msg)
        if int(ret) != 0:
            print("onUnSub Cust Msg failed..Use preview")
            WeChatHandler().sendMsgToOneAsPreview(msg)
        return "No Action"
Beispiel #23
0
 def clear_wait(self, user_open_id):
     if user_open_id in self.user_wait_list:
         self.user_wait_list.remove(user_open_id)
         ret = WeChatHandler().sendMsgViaCust(Resource.getMsg("FiveMins"),
                                              "touser", user_open_id)
         if int(ret) != 0:
             print("HealthyNotifier Cust Msg failed..Use preview")
             WeChatHandler().sendMsgToOneAsPreview(
                 Resource.getMsg("FiveMins"), "touser", user_open_id)
         DBHandler().insert(
             "INSERT into HealthyRecord VALUES (null, '%s', 'N', null)" %
             user_open_id)
     else:
         #has record into DB when user reply the correct message
         pass
Beispiel #24
0
    def testCallback(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized=False)

        self.quux = None

        def loaded(r):
            self.quux = r

        self.r.load(self, "fuuba", loader, onLoad=loaded).join()

        while not self.fuuba:
            self.e.run()

        assert self.fuuba == self.quux
Beispiel #25
0
    def __init__(self, objects, group, type, name, path, configurations,
                 defaultConfiguration):
        Resource.__init__(self, 'PBXNativeTarget', name)

        self.objects = objects
        self.group = group
        self.generated = None
        self.product = self.objects.createFileReference(
            type, path, 'BUILT_PRODUCTS_DIR')
        self.configurationList = self.objects.createConfigurationList(
            self, configurations, defaultConfiguration)
        self.sourcePhase = self.objects.createSourceBuildPhase(self)
        self.frameworkPhase = self.objects.createFrameworkPhase(self)
        self.copyFilesPhase = self.objects.createCopyFilesPhase(self)
        self.dependencies = ObjectList('PBXTargetDependency')
        self.phases = ObjectList('PBXBuildPhases')
    def onSub(user_open_ID):
        user_dict = WeChatHandler().getUserInfo(user_open_ID)
        user_priority = UserHandler.verify_user(user_open_ID)
        if user_priority == -1:
            user_insert_sql = "INSERT into UserInfo VALUES ('%s', 'N', '%s', null, '%s', null, null, null, '%s', null, " \
                              "null, null, null)" % (
                              user_open_ID, user_dict['nickname'], TypeDef.sex_dict[user_dict['sex']],
                              (user_dict['city'] + ',' + user_dict['province'] + ',' + user_dict[
                                  'country']).replace("\'", "\\\'"))
            DBHandler().insert(user_insert_sql)
        else:
            update_sql = "UPDATE UserInfo SET WechatName = '%s',Sex='%s',Address='%s' WHERE Open_ID = '%s'"\
                         %  (user_dict['nickname'], TypeDef.sex_dict[user_dict['sex']],
                         (user_dict['city'] + ',' + user_dict['province'] + ',' + user_dict['country']).replace("\'", "\\\'"),
                            user_open_ID)
            DBHandler().update(update_sql)

        return_msg = Resource.getMsg("WlcMsg", user_dict['language'])
        '''
        if user_dict['language'] == "zh_CN":
            sql_query = "Select IDX,Media_ID,Title from HistoryArticle"
        else:
            sql_query = "Select IDX,Media_ID,Title from HistoryArticle WHERE Language = 'en'"
        results = DBHandler().select(sql_query)

        for line in results[1]:
            return_msg = return_msg + str(line[0]) + "..." + line[2] + "\n"

        threading.Timer(3, WeChatHandler().sendMsgViaCust,
                        (Resource.getMsg("Menu", user_dict['language']), "touser", user_open_ID)
                        ).start()
       '''
        return return_msg
Beispiel #27
0
def script_main(argv):
    if (len(argv) != 15):
        exit(-1)
    currency = bool(int(argv[1]))
    trade = bool(int(argv[2]))
    #Should be -1 if no converging value should be used
    converging_value = float(argv[3])

    amountOfActors = int(argv[4])
    amountOfResources = int(argv[5])
    min_init_resources = float(argv[6])
    max_init_resources = float(argv[7])
    min_init_production = float(argv[8])
    max_init_production = float(argv[9])

    min_init_amountToSell = float(argv[10])
    max_init_amountToSell = float(argv[11])
    min_inti_priceDivergence = float(argv[12])
    max_inti_priceDivergence = float(argv[13])
    days = int(argv[14])

    resource = Resource(min_init_resources, max_init_resources,
                        min_init_production, max_init_production,
                        amountOfResources, amountOfActors, currency)
    society = Society(currency, amountOfActors, resource,
                      min_init_amountToSell, max_init_amountToSell,
                      min_inti_priceDivergence, max_inti_priceDivergence,
                      trade, converging_value)
    society.Update(days)
Beispiel #28
0
def resourceBasicTests(pf):
    print "ResourceBasicTests"
    try:
        # try giving Resource name=None
        app = Resource(None)
    except PTexception, a:
        pf.passed(a.value)
Beispiel #29
0
 def test_str(self):
     """ 
     Test that str method returns a string representation of the object.
     """
     
     # Create a Resource object
     resource = Resource(1, "White Noise", Name("Don", "", "DeLillo"), 
                         "Delillo's White Noise follows narrator Jack "\
                         "Gladney, a professor at a small Liberal Arts "\
                         "college and describes an academic year. Jack "\
                         "teaches at a school called the "\
                         "College-on-the-Hill, where he serves as the "\
                         "department chair of Hitler studies. He lives in "\
                         "Blacksmith, a quiet college town, with his wife, "\
                         "Babette, and four of their children from earlier "\
                         "marriages: Heinrich, Steffie, Denise, and "\
                         "Wilder. Throughout the novel, various "\
                         "half-siblings and ex-spouses drift in and out "\
                         "of the family’s home.",
                         "sci-fi", "English", 1985, "US", 326, "book",
                         ["culture", "survival", "life", "society"])
     
     # Assert expected result of the str function
     self.assertEqual(str(resource), ("ID: 1 \nTitle: White Noise "\
         "\nCreator: Don DeLillo \nSummary: Delillo's White Noise follows "\
         "narrator Jack Gladney, a professor at a \nsmall Liberal Arts "\
         "college and describes an academic year. Jack teaches \nat ... "\
         "\nGenre: sci-fi \nLanguage: English \nYear: 1985 "\
         "\nCountry: US \nLength: 326p \nType: book "\
         "\nKeywords: culture, life, society, survival"))
Beispiel #30
0
    def check_reply(self, user, msg, isTimer='N'):
        reply_msg = ""

        if msg != Resource.getMsg("IHappy"):
            reply_msg = Resource.getMsg("MustHappy") + Resource.get_random_birth_msg()
            ActionsExecutor.add_manual_action(user, Action(self.check_reply, user, "NoHappy"))
        else:
            reply_msg = Resource.getMsg("AlwaysHappy")

        if isTimer == "Y":
            ret = WeChatHandler().sendMsgViaCust(reply_msg, "touser", user)
            if int(ret) != 0:
                print("BirthDayNotifier.get_action  timer")
                WeChatHandler().sendMsgToOneAsPreview(reply_msg, "touser", user)
        self.logger.info("check_reply return %s" % reply_msg)
        return reply_msg
def system_init():
    processor_temp = Processor()
    resource_temp = Resource()
    processor_temp.create_process('init', 0)
    for x in processor_temp.get_running_list():
        print(x + " ", end='')
    return processor_temp, resource_temp
Beispiel #32
0
def main():
    currency = False
    trade = False
    #Should be -1 if no converging value should be used
    converging_value = 10**5

    amountOfActors = 10000
    amountOfResources = 20
    min_init_resources = 0
    max_init_resources = 50
    min_init_production = -0.2
    max_init_production = 0.2
    resource = Resource(min_init_resources, max_init_resources,
                        min_init_production, max_init_production,
                        amountOfResources, amountOfActors, currency)

    min_init_amountToSell = 0
    max_init_amountToSell = 1
    min_inti_priceDivergence = -0.2
    max_inti_priceDivergence = 0.2
    society = Society(currency, amountOfActors, resource,
                      min_init_amountToSell, max_init_amountToSell,
                      min_inti_priceDivergence, max_inti_priceDivergence,
                      trade, converging_value)
    society.Update(30)
Beispiel #33
0
    def sub_user_for_weather(user, new_city, lang):
        UserHandler.logger.info(
            "User <%s> is subscribing the city <%s> weather" %
            (user, new_city))
        #QUERY
        user_sub_result = DBHandler().select(
            "SELECT Cities from WeatherSub WHERE Open_ID = '%s'" % user)
        content = ""

        if len(new_city.split()) == 0 and int(user_sub_result[0]) > 0:
            content = Resource.getMsg(
                "WeatherHead", lang) + user_sub_result[1][0][
                    0]  #only one cell here, use [0][0] to visit
        elif int(user_sub_result[0]) == 0 and len(new_city.split()) == 0:
            content = Resource.getMsg("NoSubCity", lang)
        #INSERT
        elif int(user_sub_result[0]) == 0 and len(new_city.split()) != 0:
            weather = WeatherHandler()
            ret = weather.getWeather(new_city, lang)
            if ret != "Failed":
                content = Resource.getMsg("FirstSub", lang) % new_city + ret
                # write sub info into db
                insert_sql = "INSERT into WeatherSub VALUES ('%s', '%s', NULL)" % (
                    user, new_city)
                DBHandler().insert(insert_sql)
            else:
                content = Resource.getMsg("WrongCity", lang)
        #UPDATE
        elif int(user_sub_result[0]) > 0 and len(new_city.split()) != 0:
            old_cities = user_sub_result[1][0][0].split()
            if len(old_cities) > 5:
                content = Resource.getMsg("MAXCityLimit", lang)
            elif new_city in old_cities:
                content = Resource.getMsg("Subbed", lang) % new_city
            else:
                weather = WeatherHandler()
                ret = weather.getWeather(
                    new_city,
                    WeChatHandler().getUserInfo(user)['language'])
                if ret != "Failed":
                    old_cities.append(new_city)
                    content = Resource.getMsg(
                        "SubbedMore", lang) % " ".join(old_cities) + ret
                    update_sql = "UPDATE WeatherSub SET Cities = '%s' WHERE Open_ID = '%s'" % (
                        " ".join(old_cities), user)
                    DBHandler().update(update_sql)
                else:
                    content = Resource.getMsg("WrongCity", lang)
        else:
            content = Resource.getMsg("UnKnownIssue", lang)
        return content
Beispiel #34
0
def add_resource_with_access_map(resource_name, actions):
    ''' Add a resource with a dictionary of role names and supported actions '''
    if are_valid_roles(actions.keys()) and not is_valid_resource(resource_name) \
    and are_valid_actions(itertools.chain.from_iterable(actions.values())):
        resources[resource_name] = Resource(resource_name, actions)
        return True
    else:
        return False
Beispiel #35
0
def TEST_resource_trading_multiple_trades_with_one():
    number_of_resources = 2
    number_of_actors = 3
    resource = Resource(0, 0, 0, 0, number_of_resources, number_of_actors)
    actor1 = 0
    actor2 = 1
    actor3 = 2
    resource1 = 0
    resource2 = 1
    resource1_amount = 20
    resource2_amount = 20
    resource23_amount = 10
    resource.resourceArray[actor1][0][resource2] = resource1_amount
    resource.resourceArray[actor2][0][resource1] = resource2_amount
    resource.resourceArray[actor3][0][resource2] = resource23_amount

    resource_before = resource.GetTotalResources()

    bartermark = Market.NiceMarket(number_of_resources, resource)
    bartermark.PostResource(resource1, resource2, 10, 20, actor1)
    bartermark.PostResource(resource2, resource1, 40, 20, actor2)
    bartermark.PostResource(resource1, resource2, 5, 10, actor3)
    bartermark.MatchTrades()
    if resource_before == resource.GetTotalResources() and resource.resourceArray[actor2][0][resource2] == 30 and resource.resourceArray[actor2][0][resource1] == 5 and resource.resourceArray[actor1][0][resource2] == 0 and resource.resourceArray[actor1][0][resource1] == 10 and resource.resourceArray[actor3][0][resource2] == 0 and resource.resourceArray[actor3][0][resource1] == 5:
        print("TEST_resource_trading_multiple_trades_with_one successful")
    else:
        print("TEST_resource_trading_multiple_trades_with_one failed")
Beispiel #36
0
    def testAsynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        self.r.load(self, "result", lambda: loader())

        while not self.result:
            self.e.run()

        assert self.result == 0xdada
Beispiel #37
0
 def user_check_weather(user, city, lang):
     UserHandler.logger.info("User <%s> is checking the city <%s> weather" %
                             (user, city))
     content = ""
     ret = WeatherHandler().getWeather(city, lang)
     if ret != "Failed":
         content = ret
     else:
         content = Resource.getMsg("WrongCity", lang)
     return content
Beispiel #38
0
    def testAsynchLoadSeries(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        for i in range(10):
            self.r.load(self, "result%d" % i, loader)

        while not self.result9:
            self.e.run()

        assert self.result9 == 0xdada
Beispiel #39
0
class ResourceTest(unittest.TestCase):
    def testAsynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        self.r.load(self, "result", lambda: loader())

        while not self.result:
            self.e.run()

        assert self.result == 0xdada

    def testSynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        assert self.r.load(self, "result2", loader, synch = True) == 0xdada
        assert self.result2 == 0xdada

    def testAsynchLoadSeries(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        for i in range(10):
            self.r.load(self, "result%d" % i, loader)

        while not self.result9:
            self.e.run()

        assert self.result9 == 0xdada

    def testCallback(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        self.quux = None
        def loaded(r):
            self.quux = r

        self.r.load(self, "fuuba", loader, onLoad = loaded).join()

        while not self.fuuba:
            self.e.run()

        assert self.fuuba == self.quux

    def setUp(self):
        Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault = True)
        # Resource expects game_priority to be an integer,
        # Config won't know unless we define it as such.
        Config.define("performance", "game_priority", int, 2)
        self.e = GameEngine()

    def tearDown(self):
        self.e.quit()
Beispiel #40
0
    def testCallback(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        self.quux = None
        def loaded(r):
            self.quux = r

        self.r.load(self, "fuuba", loader, onLoad = loaded).join()

        while not self.fuuba:
            self.e.run()

        assert self.fuuba == self.quux
Beispiel #41
0
class ResourceTest(unittest.TestCase):
    def testAsynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        self.r.load(self, "result", lambda: loader())

        while not self.result:
            self.e.run()

        assert self.result == 0xdada

    def testSynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        assert self.r.load(self, "result2", loader, synch = True) == 0xdada
        assert self.result2 == 0xdada

    def testAsynchLoadSeries(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        for i in range(10):
            self.r.load(self, "result%d" % i, loader)

        while not self.result9:
            self.e.run()

        assert self.result9 == 0xdada

    def testCallback(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        self.quux = None
        def loaded(r):
            self.quux = r

        self.r.load(self, "fuuba", loader, onLoad = loaded).join()

        while not self.fuuba:
            self.e.run()

        assert self.fuuba == self.quux

    def setUp(self):
        self.e = Engine()

    def tearDown(self):
        self.e.quit()
Beispiel #42
0
    def __str__(self):
        symbolstr = ", ".join(["%s" %  k for k in sorted(self.getSymbolCardLists().keys())])
        secondCollection = ["%s" % k for k, l in sorted(self.getSymbolCardLists().items()) if len(l) > 1]
        if secondCollection:
            symbolstr += " || " + ", ".join(secondCollection)  
        multistrs = []
        for symbol, cards in self.getMultiplierCardsBySymbol():
            factor = sum([c.getMultiplier() for c in cards])
            multistrs.append("%d x %s" % (factor, symbol.name))
        return """%s%s%s
People: %d, Foodtrack: %d, Food: %d, Tools: %s, One-time tools: %s
Resources: %s
Hutcount: %d
Symbolcards: %s (%d)
Multipliercards: %s (%d)   
score (cardscore): %d (%d)\n""" % (self.colorOS, self.color.name, self.colorOSnormal, \
                  self.getPersonCount(), self.getFoodTrack(), self.resources.count(Resource.food), self.toolbox, self.oneTimeTools,  
                  Resource.coloredOutput(sorted(self.getNonFood())), 
                  len(self.huts), \
                  symbolstr, self.symbolCardPoints(), \
                  ", ".join(multistrs), self.multiplierCardPoints(),\
                  self.getScore(), self.getCardScore())
       p = Resource("eddie","atype")
       c = Resource("franks|schild","atype|btype")
       theVerdict = p.isChild(c)
    except PTexception, a:
        pf.failed(a.value)
    except:
       pf.failed("non-PTexception when try isChild non-child resource")
    else:
       if theVerdict == True:
          pf.failed("isChild fail with non-child resource")
       else:
          pf.passed("isChild pass with non-child resource")

    try:
       # try out isChild
       p = Resource("eddie","atype")
       c = Resource("eddie","atype")
       theVerdict = p.isChild(c)
    except PTexception, a:
        pf.failed(a.value)
    except:
       pf.failed("non-PTexception when try isChild same name resource")
    else:
       if theVerdict == True:
          pf.failed("isChild fail same name resource")
       else:
          pf.passed("isChild pass same name resource")

    try:
       # try out isChild
       p = Resource("eddie","atype")
Beispiel #44
0
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")
Beispiel #45
0
class GameEngine(Engine):
    """The main game engine."""
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        fps          = self.config.get("video", "fps")
        tickrate     = self.config.get("engine", "tickrate")
        Engine.__init__(self, fps = fps, tickrate = tickrate)

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        Log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        Log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        # Enable the high priority timer if configured
        if self.config.get("engine", "highpriority"):
            Log.debug("Enabling high priority timer.")
            self.timer.highPriority = True

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.sessions  = []
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.addTask(self.audio, synchronized = False)
        self.addTask(self.input, synchronized = False)
        self.addTask(self.view)
        self.addTask(self.resource, synchronized = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        Log.debug("Ready.")

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
                # evilynux - With self.audio.close(), calling self.quit() results in
                #            a crash. Calling the parent directly as a workaround.
            Engine.quit(self)

    def quit(self):
        self.audio.close()
        Engine.quit(self)

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.img.setGeometry((0, 0, width, height))

    def isServerRunning(self):
        return bool(self.server)

    def startServer(self):
        """Start the game server."""
        if not self.server:
            Log.debug("Starting server.")
            self.server = Server(self)
            self.addTask(self.server, synchronized = False)

    def connect(self, host):
        """
        Connect to a game server.

        @param host:  Name of host to connect to
        @return:      L{Session} connected to remote server
        """
        Log.debug("Connecting to host %s." % host)
        session = ClientSession(self)
        session.connect(host)
        self.addTask(session, synchronized = False)
        self.sessions.append(session)
        return session

    def stopServer(self):
        """Stop the game server."""
        if self.server:
            Log.debug("Stopping server.")
            self.removeTask(self.server)
            self.server = None

    def disconnect(self, session):
        """
        Disconnect a L{Session}

        param session:    L{Session} to disconnect
        """
        if session in self.sessions:
            Log.debug("Disconnecting.")
            self.removeTask(session)
            self.sessions.remove(session)

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize  Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""
        done = Engine.run(self)
        self.clearScreen()

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()
        self.video.flip()
        return done

    def clearScreen(self):
        self.img.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        # Tune the scheduler priority so that transitions are as smooth as possible
        if self.view.isTransitionInProgress():
            self.boostBackgroundThreads(False)
        else:
            self.boostBackgroundThreads(True)

        done = Engine.run(self)
        self.clearScreen()
        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)
        self.video.flip()
        return done

    def run(self):
        try:
            return self.mainloop()
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            Log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
Beispiel #46
0
    def testSynchLoad(self):
        self.r = Resource()
        self.e.addTask(self.r, synchronized = False)

        assert self.r.load(self, "result2", loader, synch = True) == 0xdada
        assert self.result2 == 0xdada
Beispiel #47
0
    def run(self):
        try:
            if not os.path.exists(self.output_dir):
                os.makedirs(self.output_dir)

            if len(self.file_list) == 0:
                resources = Resource.find_all_in_paths(self.paths)
            else:
                resources = []
                for file_path in self.file_list:
                    resources.append(Resource(file_path))
            if resources is not None:
                for resource in resources:
                    if resource.requirements is not None:
                        directory, file_name = os.path.split(resource.path_to_file)

                        try:
                            chunks = resource.get_chunks_by_merging_requirements_from_paths(self.paths, previously_merged=[])
                        except RequirementNotSatisfiedException, rnse:
                            print "A requirement could not be satisfied for %s\n\n%s\n" % (resource.path_to_file, rnse)
                            return -1

                        for chunk in chunks:
                            analyzers = self.config.get_analyzers_for_resource(chunk.resource)
                            if analyzers:
                                for analyzer in analyzers:
                                    print 'Analysis:%s:%s' % (analyzer.__class__, chunk.resource.path_to_file)
                                    analysis = analyzer.analyze(chunk.resource)
                                    print analysis
                                    if not analysis.good:
                                        return -1

                        merged_content = ''.join([chunk.content for chunk in chunks])

                        output_file_name = os.path.join(self.output_dir, file_name)
                        f = open(output_file_name, 'w')
                        try:
                            f.write(merged_content)
                        finally:
                            f.flush()
                            f.close()

                        print "Created %s" % output_file_name

                        # TODO: Process chunks to prevent reminification
                        output_resource = Resource(output_file_name)
                        minifier = self.config.get_minifier_for_file_type(output_resource.file_type)
                        if minifier and not output_resource.minified:
                            minification = minifier.minify(output_resource)
                            if not minification.good:
                                print minification
                                return -1
                            minified_output_file_path = os.path.join(self.output_dir, output_resource.minified_file_name)
                            f = open(minified_output_file_path, 'w')
                            try:
                                f.write(minification.content)
                            finally:
                                f.flush()
                                f.close()

        except Exception:
            traceback.print_exc(file=sys.stderr)
            return -1

        return 0
Beispiel #48
0
class GameEngine(object):
    """The main game engine."""
    def __init__(self, config = None):
        """
        Constructor.

        @param config:  L{Config} instance for settings
        """

        if not config:
            config = Config.load()

        self.config  = config

        self.fps          = self.config.get("video", "fps")

        pygame.init()

        self.title             = _("Frets on Fire")
        self.restartRequested  = False
        self.handlingException = False
        self.video             = Video(self.title)
        self.audio             = Audio()

        log.debug("Initializing audio.")
        frequency    = self.config.get("audio", "frequency")
        bits         = self.config.get("audio", "bits")
        stereo       = self.config.get("audio", "stereo")
        bufferSize   = self.config.get("audio", "buffersize")

        self.audio.pre_open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)
        pygame.init()
        self.audio.open(frequency = frequency, bits = bits, stereo = stereo, bufferSize = bufferSize)

        log.debug("Initializing video.")
        width, height = [int(s) for s in self.config.get("video", "resolution").split("x")]
        fullscreen    = self.config.get("video", "fullscreen")
        multisamples  = self.config.get("video", "multisamples")
        self.video.setMode((width, height), fullscreen = fullscreen, multisamples = multisamples)

        viewport = glGetIntegerv(GL_VIEWPORT)
        h = viewport[3] - viewport[1]
        w = viewport[2] - viewport[0]
        geometry = (0, 0, w, h)
        self.img = ImgContext(geometry)
        glViewport(int(viewport[0]), int(viewport[1]), int(viewport[2]), int(viewport[3]))

        self.input     = Input()
        self.view      = View(self, geometry)
        self.resizeScreen(w, h)

        self.resource  = Resource(Version.dataPath())
        self.server    = None
        self.mainloop  = self.loading

        # Load game modifications
        Mod.init(self)
        theme = Config.load(self.resource.fileName("theme.ini"))
        Theme.open(theme)

        # Make sure we are using the new upload URL
        if self.config.get("game", "uploadurl").startswith("http://kempele.fi"):
            self.config.set("game", "uploadurl", "http://fretsonfire.sourceforge.net/play")

        self.running = True
        self.timer = FpsTimer()
        self.tickDelta = 0
        self.task = TaskEngine(self)

        self.task.addTask(self.input, synced = False)
        self.task.addTask(self.view)
        self.task.addTask(self.resource, synced = False)
        self.data = Data(self.resource, self.img)

        self.input.addKeyListener(FullScreenSwitcher(self), priority = True)
        self.input.addSystemEventListener(SystemEventHandler(self))

        self.debugLayer         = None
        self.startupLayer       = None
        self.loadingScreenShown = False

        log.debug("Ready.")

    def enableGarbageCollection(self, enabled):
        """
        Enable or disable garbage collection whenever a random garbage
        collection run would be undesirable. Disabling the garbage collector
        has the unfortunate side-effect that your memory usage will skyrocket.
        """
        if enabled:
            gc.enable()
        else:
            gc.disable()

    def collectGarbage(self):
        """
        Run a garbage collection run.
        """
        gc.collect()

    def setStartupLayer(self, startupLayer):
        """
        Set the L{Layer} that will be shown when the all
        the resources have been loaded. See L{Data}

        @param startupLayer:    Startup L{Layer}
        """
        self.startupLayer = startupLayer

    def isDebugModeEnabled(self):
        return bool(self.debugLayer)

    def setDebugModeEnabled(self, enabled):
        """
        Show or hide the debug layer.

        @type enabled: bool
        """
        if enabled:
            self.debugLayer = DebugLayer(self)
        else:
            self.debugLayer = None

    def toggleFullscreen(self):
        """
        Toggle between fullscreen and windowed mode.

        @return: True on success
        """
        if not self.video.toggleFullscreen():
            # on windows, the fullscreen toggle kills our textures, se we must restart the whole game
            self.input.broadcastSystemEvent("restartRequested")
            self.config.set("video", "fullscreen", not self.video.fullscreen)
            return True
        self.config.set("video", "fullscreen", self.video.fullscreen)
        return True

    def restart(self):
        """Restart the game."""
        if not self.restartRequested:
            self.restartRequested = True
            self.input.broadcastSystemEvent("restartRequested")
        else:
            self.quit()

    def quit(self):
        self.audio.close()
        self.task.exit()
        self.running = False

    def resizeScreen(self, width, height):
        """
        Resize the game screen.

        @param width:   New width in pixels
        @param height:  New height in pixels
        """
        self.view.setGeometry((0, 0, width, height))
        self.img.setGeometry((0, 0, width, height))

    def startWorld(self):
        self.world = World(self)

    def finishGame(self):
        self.world.finishGame()
        self.world = None
        self.view.pushLayer(MainMenu.MainMenu(self))

    def loadImgDrawing(self, target, name, fileName, textureSize = None):
        """
        Load an SVG drawing synchronously.

        @param target:      An object that will own the drawing
        @param name:        The name of the attribute the drawing will be assigned to
        @param fileName:    The name of the file in the data directory
        @param textureSize  Either None or (x, y), in which case the file will
                            be rendered to an x by y texture
        @return:            L{ImgDrawing} instance
        """
        return self.data.loadImgDrawing(target, name, fileName, textureSize)

    def loading(self):
        """Loading state loop."""

        if self.data.essentialResourcesLoaded():
            if not self.loadingScreenShown:
                self.loadingScreenShown = True
                Dialogs.showLoadingScreen(self, self.data.resourcesLoaded)
                if self.startupLayer:
                    self.view.pushLayer(self.startupLayer)
                self.mainloop = self.main
            self.view.render()

    def clearScreen(self):
        self.img.clear(*Theme.backgroundColor)

    def main(self):
        """Main state loop."""

        self.view.render()
        if self.debugLayer:
            self.debugLayer.render(1.0, True)

    def run(self):
        try:
            self.tickDelta = self.timer.tick()
            done = self.task.run()
            self.clearScreen()

            self.mainloop()

            self.video.flip()

            # Calculate FPS every 2 seconds
            if self.timer.fpsTime >= 2000:
                self.fpsEstimate = self.timer.get_fps()
                print ("%.2f fps" % self.fpsEstimate)

            self.timer.delay(self.fps)

            return done
        except KeyboardInterrupt:
            sys.exit(0)
        except SystemExit:
            sys.exit(0)
        except Exception, e:
            def clearMatrixStack(stack):
                try:
                    glMatrixMode(stack)
                    for i in range(16):
                        glPopMatrix()
                except:
                    pass

            if self.handlingException:
                # A recursive exception is fatal as we can't reliably reset the GL state
                sys.exit(1)

            self.handlingException = True
            log.error("%s: %s" % (e.__class__, e))
            import traceback
            traceback.print_exc()

            clearMatrixStack(GL_PROJECTION)
            clearMatrixStack(GL_MODELVIEW)

            Dialogs.showMessage(self, unicode(e))
            self.handlingException = False
            return True
Beispiel #49
0
def getInitialAVs(resIdx, attrs, exeName, ptds):
    """ Takes attrs, which is a list of name, value pairs, and builds
        a build Resource object and Execution object
    """

    executableAVs = []
    buildAVs = []
    buildOSAVs = []
    AppName = ""
    BuildMachType = ""
    BuildMachine = ""
    BuildOSName = ""
    BuildOSVersion = ""
    BuildOSType = ""

    # regular expressions for parsing

    for name, value, type in attrs:
        if name == "BuildDataBegin":
            pass
        elif name == "BuildDataEnd":
            break
        # Get executable specific data
        elif name == "ApplicationName":
            AppName = value
        elif name == "ApplicationExeTrialName" or name == "ApplicationExeUserComment":
            AppTrialName = value
        elif name.startswith("Application"):
            if name == "ApplicationLanguages":
                value = fixListFormat(value)
                executableAVs.append(("Languages", value, "string"))
            elif name == "ApplicationParadigms":
                value = fixListFormat(value)
                executableAVs.append(("Concurrency", value, "string"))
            elif name == "ApplicationExeName":
                executableAVs.append(("Executable Name", value, "string"))
            elif name == "ApplicationExeSize":
                executableAVs.append(("Executable Size", value, "string"))
            elif name == "ApplicationExePerms":
                executableAVs.append(("Executable Permissions", value, "string"))
            elif name == "ApplicationExeUID":
                executableAVs.append(("Executable UID", value, "string"))
            elif name == "ApplicationExeGID":
                executableAVs.append(("Executable GID", value, "string"))
            elif name == "ApplicationExeTimestamp":
                executableAVs.append(("Executable Timestamp", value, "string"))
            elif name == "ApplicationExeUsername":
                executableAVs.append(("Username", value, "string"))
        # get Build specific data
        elif name.startswith("Build") and not (name.find("BuildOS") >= 0):
            if name == "BuildEnv":
                BuildEnv = []  # a list of attr value pairs
                # where attr = "BuildEnv"+ (enviroment variable name)
                # and value is the environment variable's value
                # e.g.  for PATH=/usr/bin:/usr/local/bin
                # attr = BuildEnvPATH
                # value = /usr/bin:/usr/local/bin
                BuildEnv = StringToList("Env_", "@@@", value)
                for (n, v) in BuildEnv:
                    if v != "":
                        buildAVs.append((n, v, "string"))
            else:
                if name == "BuildNode" or name == "BuildMachine":
                    BuildMachine = value
                if name == "BuildNode":
                    BuildMachType = "node"
                    buildAVs.append(("Node Name", value, "string"))
                elif name == "BuildMachine":
                    BuildMachType = "machine"
                    buildAVs.append(("Machine Name", value, "string"))
                if name == "BuildDateTime":
                    buildAVs.append(("DateTime", value, "string"))
                # get Build operating system  specific data
        elif name.startswith("BuildOS"):
            if name == "BuildOSName":
                BuildOSName = value
            elif name == "BuildOSReleaseVersion":
                BuildOSVersion = value
            elif name == "BuildOSReleaseType":
                BuildOSType = value

    if exeName == "" or exeName == None:
        raise PTexception("missing execution name in Build.getInitialAVs")

    exeNewName = ptds.getNewResourceName(exeName)
    # ATTR CHANGE TODO
    # executableAVs should be attrs of build, not execution
    exe = Execution(exeNewName, executableAVs)
    resIdx.addResource(exe)

    newBuildName = ptds.getNewResourceName("build")
    build = Resource(newBuildName, "build", buildAVs)
    resIdx.addResource(build)

    if BuildMachine == "" or BuildMachine == None:
        raise PTexception("missing build machine name in build data file for " " execution:%s" % exeName)

    if BuildMachType == "node":
        fullname, type = getMachineName(ptds, BuildMachine, BuildMachType)
        # print fullname
        buildMachine = Resource(fullname, type)
    else:  # machine
        fullname, type = getMachineName(ptds, BuildMachine, BuildMachType)
        buildMachine = Resource(fullname, type)

    if BuildOSName == "" or BuildOSName == None:
        raise PTexception("missing build operating system name for execution" "execution:%s" % exeName)
    if BuildOSVersion == "" or BuildOSVersion == None or BuildOSType == "" or BuildOSType == None:
        raise PTexception("missing build operating system details for execution" "execution:%s" % exeName)
    buildOSNewName = ptds.getNewResourceName(BuildOSName + " " + BuildOSVersion + " " + BuildOSType)
    buildOS = Resource(buildOSNewName, "operatingSystem", buildOSAVs)
    resIdx.addResources([buildOS, buildMachine])
    build.addAttribute("Node Name", buildMachine.name, "resource")
    build.addAttribute("OS Name", buildOS.name, "resource")

    return (build, exe)
Beispiel #50
0
    def testPureResource(self):
        rs = Resource()

        rs.addPerson(1, "r")
        with self.assertRaisesRegex(AttributeError, "object has no attribute 'resourceValue'"):
            rs.reapResources(self.redPlayer)
Beispiel #51
0
# -*- coding: UTF-8 -*-
import simplejson
from Resource import Resource

datacloud = Resource('A6988846915732','391BB7B7-827D-1DE5-2F64-04339E801812','http://192.168.13.183/mcm/api')


#################user operation##############################
# print datacloud.createUser({"username":"******","password":"******","email":"*****@*****.**"})
r = datacloud.userLogin('zxh','123456')

datacloud.setSessionToken(r["id"])
# print datacloud.userLogout(r["id"])
# r = datacloud.verifyEmail({"username":"******","email":"*****@*****.**","language":"zh_CN"})
# print simplejson.dumps(r, ensure_ascii=False)
# print r['msg']
# print r['status']

# print datacloud.resetRequest({"username":"******","email":"*****@*****.**","language":"zh_CN"})
# print datacloud.getUserInfo('5576b9eec24a9b3c54f82203');
# print datacloud.updateUserInfo({'userId':'55796f23dfc407df41432f94','address':'dandong'})
# print datacloud.deleteUser('55796f23dfc407df41432f94');


#################object operation##############################
# print datacloud.createObject("company",{"address":"丹东1", "name":"aaa","icon":{"isFile":True,"path":"E:\\2007119124513598_2.jpg"},"icon2":{"isFile":True,"path":"E:\\2007119124513598_2.jpg"}})
# print datacloud.createObject("company",{"address":"germany", "name":"ccc","icon":{"url":"http://a82510f6efdff35a65fb.b0.upaiyun.com/apicloud/e96e53bb577560b2d5acb1e3ef7a492b.jpg","id":"5578114b85ff91bf364f0d6a","name":"2007119124513598_2.jpg"}})
# print datacloud.getObject('company','55828f4c291f49171a8dba9b')

# print datacloud.updateObject('company','5578125185ff91bf364f0d6c',{'address':'dandong',"icon":{"isFile":True,"path":"E:\\zhanqi.PNG"}})
Beispiel #52
0
    def chooseResourecestoPay(self, nonFoodResources, hut):
        promptString = "\nchoose resources (format='wcsgj...') to pay the hut: %s\n available resources: %s " % (str(hut), 
                                                                                                                 Resource.coloredOutput(nonFoodResources))

        finished = False
        while not finished:
            chosenResources = fetchConvertedInput(promptString,
                                                 lambda v: printfString("the input '%s' does not consist of only numbers!", v),
                                                 mapToResources,
                                                 self.printPlayersFunc)
            if not chosenResources:
                chosenResources = nonFoodResources
            finished = all([self.chosenItemsAvailable(nonFoodResources, chosenResources),
                            self.validPaymentIfAnyHut(hut, chosenResources),
                            self.validPaymentIfCountHut(hut, chosenResources)])
        return chosenResources
Beispiel #53
0
 def filterOutPayableHuts(self, player, huts):
     notPayable, payable = [hut for hut in huts if not player.isPayable(hut)], [hut for hut in huts if player.isPayable(hut)]
     if notPayable:
         printError("with available resources: %s\nyou can't afford the following hut%s: " % (Resource.coloredOutput(player.getNonFood()) , suffix(notPayable)), " ".join([str(hut) for hut in notPayable]))
     return payable
Beispiel #54
0
 def wantsToBuy(self, outstring, nonFoodResources, hutOrCard):
     return fetchConvertedInput("with available resources: %s\ndo you want to buy this %s (y|n): %s ? (y) " % (Resource.coloredOutput(nonFoodResources),outstring, str(hutOrCard)),
                                lambda v: printfString("please answer y(es) or n(o) - not: '%s'", v),
                                yesNo,
                                self.printPlayersFunc) 
Program begins.
"""
# Total visited links
visited = []
# Total working links found
urls = []

resources = []


# Create excel file
# wb = Workbook()
# filename = input("Enter a title for the excel file: ")
url = input("Enter url to crawl: ")

resource = Resource(url)
resource.get_resource_data()
resource_values = {
    "title": resource.title,
    "url": resource.link,
    "link status": resource.status,
    "resource types": resource.resource_type,
    "disciplines": resource.themes,
    "organization": resource.get_org(),
    "organization validated in VIAF": resource.org.validated,
    "VIAF uri": resource.org.uri,
    "contact organization": resource.resource_contact_org,
    "contact name": resource.resource_contact_person_name,
    "contact email": resource.resource_contact_email,
    "contact phone": resource.resource_contact_phone,
}
Beispiel #56
0
 def printResourceStatus(self, player):
     nonFood = player.getNonFood()
     print("available Resource%s: %s " % (suffix(nonFood), Resource.coloredOutput(nonFood)))
Beispiel #57
0
 def fetchPlacePersonsInput(self, people, foodtrack, food, resources, personsLeft):
     return fetchConvertedInput(self.prompt % (people, foodtrack, food, suffix(resources), Resource.coloredOutput(resources), personsLeft, suffix(personsLeft), suffix(personsLeft)),
                                lambda v: printfString("'%s' does not seem to be of format <Resource><number>!", v),
                                stringAndNumber,
                                self.printPlayersFunc)
Beispiel #58
0
Program begins.
"""
# Total visited links
visited = []
# Total working links found
urls = []

resources = []


# Create excel file
# wb = Workbook()
# filename = input("Enter a title for the excel file: ")
url = input("Enter url to crawl: ")

resource = Resource(url)
resource.get_resource_data()
resource_values = {'title': resource.title, 'url': resource.link, 'link status': resource.status,
                   #'resource types': resource.resource_type, 'disciplines': resource.themes,
                   'organization': resource.get_org(), 'organization validated in VIAF': resource.org.validated,
                   'VIAF uri': resource.org.uri, 'contact organization': resource.resource_contact_org,
                   'contact name': resource.resource_contact_person_name,
                   'contact email': resource.resource_contact_email, 'contact phone': resource.resource_contact_phone}

fieldnames = ['title', 'url', 'link status', 'resource types', 'disciplines', 'organization',
              'organization validated in VIAF', 'VIAF uri', 'contact organization', 'contact name', 'contact email',
              'contact phone']

with open('{}.csv'.format(resource.title.replace("|", "").strip().replace(" ", "_")), 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
Beispiel #59
0
 def doBuyCards(self, player, cards, boughtCards, players, cardPile):
     for card in cards:
         if len(player.getNonFood()) < card[1]: 
             print("with available resources: %s you can't afford the following card:\nprice %d%s\n " % (Resource.coloredOutput(player.getNonFood()), card[1], str(card[0])))
         elif self.wantsToBuy("card", player.getNonFood(), card[0]):
             player.buyCard(card[0], players, cardPile, player.getNonFood()[:card[1]])
             boughtCards.append(card[0])
     return boughtCards