コード例 #1
0
ファイル: Purchase.py プロジェクト: aliaafee/vikuraa
    def InitToolbar(self):
        toolbar = wx.ToolBar(self)#, style=wx.TB_NODIVIDER)

        tbBack = toolbar.AddLabelTool(
                wx.ID_ANY, 'Back', wx.Bitmap(Resource.GetFileName('arrow-left.png')))
        self.Bind(wx.EVT_TOOL, self.OnBack, tbBack)

        self.tcPurchaseBillId = wx.TextCtrl(toolbar,size=wx.Size(80,-1))
        self.tcPurchaseBillId.Bind(wx.EVT_KEY_UP, self.OnPurchaseBillId)

        toolbar.AddControl(self.tcPurchaseBillId)

        tbForward = toolbar.AddLabelTool(
                wx.ID_ANY, 'Forward', wx.Bitmap(Resource.GetFileName('arrow-right.png')))
        self.Bind(wx.EVT_TOOL, self.OnForward, tbForward)

        toolbar.AddSeparator()

        tbSave = toolbar.AddLabelTool(wx.ID_ANY, 'Save', wx.Bitmap(Resource.GetFileName('save.png')))
        self.Bind(wx.EVT_TOOL, self.OnSave, tbSave)
        tbAddRow = toolbar.AddLabelTool(wx.ID_ANY, 'Add Row', wx.Bitmap(Resource.GetFileName('add-row.png')))
        self.Bind(wx.EVT_TOOL, self.OnAddRow, tbAddRow)

        tbPrint = toolbar.AddLabelTool(
                wx.ID_ANY, 'Print', wx.Bitmap(Resource.GetFileName('print.png')))
        self.Bind(wx.EVT_TOOL, self.OnPrint, tbPrint)

        toolbar.Realize()

        self.toolbar = toolbar
コード例 #2
0
 def disconnect(self):
     try:
         if current_thread() is not self._thread:
             self._queue.push(exit)
             self._thread.join(3.0)
     finally:
         Resource.disconnect(self)
コード例 #3
0
def Start():

    # # make this plugin show up in the 'Video' section
    # # in Plex. The L() function pulls the string out of the strings
    # # file in the Contents/Strings/ folder in the bundle
    # # see also:
    # #  http://dev.plexapp.com/docs/mod_Plugin.html
    # #  http://dev.plexapp.com/docs/Bundle.html#the-strings-directory
    Plugin.AddPrefixHandler(VIDEO_PREFIX, MainMenu, NAME, ICON, ART)

    Plugin.AddViewGroup("InfoList", viewMode="InfoList", mediaType="items")
    Plugin.AddViewGroup("List", viewMode="List", mediaType="items")

    # # set some defaults so that you don't have to
    # # pass these parameters to these object types
    # # every single time
    # # see also:
    # #  http://dev.plexapp.com/docs/Objects.html
    MediaContainer.title1 = NAME
    MediaContainer.viewGroup = "List"
    MediaContainer.art = Resource.Load(ART)
    DirectoryItem.thumb = Resource.Load(ICON)
    VideoItem.thumb = Resource.Load(ICON)

    HTTP.CacheTime = CACHE_1HOUR
    check_login_token()
コード例 #4
0
 def exit(self):
     import sys
     import Resource
     self.graph.destroy()
     self.application.root.destroy()
     self.application.root.quit()
     Resource.clean()
     sys.exit()
コード例 #5
0
    def saveFile(self):

        tags = self.getTags()  #获取标签
        for path in self.paths:
            Resource.uploadSaveBaseData(path, self.username,
                                        tags)  #保存文件信息到数字资产库
            #保存上传信息到用户信息库
            self.saveFileInformationToUserdb(self.username, path)
コード例 #6
0
 def __init__(self, name, release):
     Resource.__init__(self, name)
     self._release = release
     self._ready, self._queue = Event(), InterlockedQueue()
     if __name__ == "__main__":
         self._timeout = Timeout(3.0)
     else:
         self._timeout = Timeout(60.0)
     self._count = 0
コード例 #7
0
ファイル: Main.py プロジェクト: xuweiliang/Codelibrary
def Main():
    f = None
    frame = None
    AdminShadow['admins'] = user.User()
    FirstUser['firstuser'] = user.User()
    threadddd['devicerequest'] = SendRequests.DeviceRequests()

    server = ServiceThread.Service()
    server.start()

    #add by wangderan start
    #thread = CheckHotplugDevice()
    #thread.start()
    #add by wangderan end
    #disaltl='xmodmap -e "keycode 64="'
    #disaltr='xmodmap -e "keycode 108="'
    os.system("service chronyd stop")
    os.system("chkconfig chronyd off")
    #os.system("%s"%disaltl)
    #os.system("%s"%disaltr)
    #Logger.info("Argbee Client start, version : %s", Version.string('python-hav-gclient', 3))
    #Logger.info("Get Video Device : %s", " ".join(get_device()))
    #sleep(2)
    #os.system("%s"%disaltl)
    #os.system("%s"%disaltr)

    app = wx.PySimpleApp()
    area = wx.Display().GetGeometry()
    width = area.GetWidth()
    height = area.GetHeight()
    Resource.load(width, height)

    frame = LoginFrame.LoginFrame(None)
    frame.ShowFullScreen(True)
    '''
    if autoLogin() :
        #f = MainFrame.MainFrame(frame, wx.ScreenDC().GetSize())
        f = MainFrame.MainFrame(frame, (width, height))
        f.Show(True)
    else :
    #frame.autoLogin()
        frame.ShowFullScreen(True)
    #Setting.save()
    #Logger.info( Setting.getIP()
        app.SetTopWindow(frame)
    '''

    devicethread = threadddd.get("devicerequest",
                                 SendRequests.DeviceRequests())
    devicethread.start()
    threadddd['devicerequest'] = devicethread

    app.MainLoop()

    Logger.info("Normal Exit")
コード例 #8
0
 def connect(self):
     Resource.connect(self)
     self._thread = LightThread(target=self._thread_proc,
                                name="{0:s}:?".format(self.name))
     self._thread.start()
     self._ready.wait(
         3.0)  # this may spend waiting slightly less, but it's ok
     if not self._ready.is_set():
         self._queue.push(
             exit)  # just in case the thread has in fact started
         raise Exception("new thread failed to start in 3.0 seconds")
コード例 #9
0
ファイル: Client.py プロジェクト: floort/mollie-api-python
 def __init__(self):
     self.api_endpoint = self.API_ENDPOINT
     self.api_version = self.API_VERSION
     self.api_key = ''
     self.payments = Resource.Payments(self)
     self.payment_refunds = Resource.Refunds(self)
     self.issuers = Resource.Issuers(self)
     self.methods = Resource.Methods(self)
     self.version_strings = []
     self.addVersionString('Mollie/' + self.CLIENT_VERSION)
     self.addVersionString('Python/' + sys.version.split(' ')[0])
     self.addVersionString('OpenSSL/' + ssl.OPENSSL_VERSION.split(' ')[1])
コード例 #10
0
 def __init__(self):
     self.r1 = Resource("Coal", 40, 50, 50, 1, 1, 0)
     self.r2 = Resource("Wind/Solar", 90, 0, 30, 0, 1, 0)
     self.r3 = Resource("Nuclear", 70, 25, 40, 2, 1, 0)
     self.rl = [self.r1, self.r2, self.r3]
     self.total_pollution = 0
     self.total_risk = 0
     self.catastrophes = 0
     self.gametime = 0
     self.countries = [Country(25000, 1100, 1000), Country(10000, 300, 200)]
     self.Taxman = Taxman()
     self.threshold = 100000
     self.global_collapse = False
     self.country_collapse = False
     self.currentResPrices = self.get_r_prices()
コード例 #11
0
ファイル: main.py プロジェクト: MElody9120/Repo-Hub
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
コード例 #12
0
  def __init__(self, prototype, fileName = None):
    """
    @param prototype:  The configuration protype mapping
    @param fileName:   The file that holds this configuration registry
    """
    self.prototype = prototype

    # read configuration
    self.config = MyConfigParser()

    if fileName:
      if not os.path.isfile(fileName):
        path = Resource.getWritableResourcePath()
        fileName = os.path.join(path, fileName)
      self.config.read(fileName)
  
    self.fileName  = fileName
  
    # fix the defaults and non-existing keys
    for section, options in prototype.items():
      if not self.config.has_section(section):
        self.config.add_section(section)
      for option in options.keys():
        type    = options[option].type
        default = options[option].default
        if not self.config.has_option(section, option):
          self.config.set(section, option, str(default))
コード例 #13
0
ファイル: Protocol.py プロジェクト: vanpf/htcache
    def __init__(self, request, prepcache=True):
        "Determine and open cache location, get descriptor backend. "
        super(CachingProtocol, self).__init__()

        self.request = request

        # Track server response
        self.__status, self.__message = None, None

        if not prepcache:
            return

        self.cache = Resource.get_cache(request.hostinfo, request.envelope[1])

        # Get descriptor storage reference
        self.descriptors = Resource.get_backend()
コード例 #14
0
 def nottest_func_get_size_for_dir_three_file(self):
     """
     Test get size for empty directories.
     """
     str_dir = os.path.join(self.str_test_directory,
                            "test_func_get_size_for_dir_three_file")
     str_file_1 = os.path.join(self.str_test_directory,
                               "test_func_get_size_for_dir_three_file",
                               "file_one.txt")
     str_file_2 = os.path.join(self.str_test_directory,
                               "test_func_get_size_for_dir_three_file",
                               "file_two.txt")
     str_file_3 = os.path.join(self.str_test_directory,
                               "test_func_get_size_for_dir_three_file",
                               "file_three.txt")
     str_answer = "316.0 B"
     self.func_make_dummy_dir(self.str_test_directory)
     self.func_make_dummy_dir(str_dir)
     self.func_make_dummy_file(str_file_1, "File_one.txt")
     self.func_make_dummy_file(str_file_2, "File_two.txt")
     self.func_make_dummy_file(str_file_3, "File_three.txt")
     str_size = Resource.Resource(str_path=str_dir,
                                  f_is_product=True).func_get_size()
     self.func_remove_files([str_file_1, str_file_2, str_file_3])
     self.func_remove_dirs([str_dir, self.str_test_directory])
     self.func_test_equals(str_answer, str_size)
コード例 #15
0
ファイル: Protocol.py プロジェクト: dotmpe/htcache
    def __init__(self, request, prepcache=True):
        "Determine and open cache location, get descriptor backend. "
        super(CachingProtocol, self).__init__()

        self.request = request

        # Track server response
        self.__status, self.__message = None, None

        if not prepcache:
            return

        self.cache = Resource.get_cache(request.hostinfo, request.envelope[1])

        # Get descriptor storage reference
        self.descriptors = Resource.get_backend()
コード例 #16
0
    def __init__(self, prototype, fileName=None):
        """
    @param prototype:  The configuration protype mapping
    @param fileName:   The file that holds this configuration registry
    """
        self.prototype = prototype

        # read configuration
        self.config = MyConfigParser()

        if fileName:
            if not os.path.isfile(fileName):
                path = Resource.getWritableResourcePath()
                fileName = os.path.join(path, fileName)
            self.config.read(fileName)

        self.fileName = fileName

        # fix the defaults and non-existing keys
        for section, options in prototype.items():
            if not self.config.has_section(section):
                self.config.add_section(section)
            for option in options.keys():
                type = options[option].type
                default = options[option].default
                if not self.config.has_option(section, option):
                    self.config.set(section, option, str(default))
コード例 #17
0
def __handleInternalRequest(pathNouns, _path, **kwargs):
    #
    # Handle a request internally
    #
    if len(pathNouns) > 1:
        if pathNouns[1] == "resources":
            if len(pathNouns) == 3:
                ext = pathNouns[2][pathNouns[2].rfind("."):]
                PMS.Log("(Framework) Getting resource named '%s'" %
                        pathNouns[2])
                resource = Resource.Load(pathNouns[2])
                return Objects.DataObject(resource,
                                          Resource.MimeTypeForExtension(ext))

        if pathNouns[1] == "sharedresources":
            if len(pathNouns) == 3:
                ext = pathNouns[2][pathNouns[2].rfind("."):]
                PMS.Log("(Framework) Getting shared resource named '%s'" %
                        pathNouns[2])
                resource = Resource.LoadShared(pathNouns[2])
                return Objects.DataObject(resource,
                                          Resource.MimeTypeForExtension(ext))

        elif pathNouns[1] == "function" and len(pathNouns) >= 3:
            name = pathNouns[2]
            pos = name.rfind(".")
            if pos > -1:
                name = name[:pos]
            PMS.Log(name)
            if name not in __reservedFunctionNames:
                if len(pathNouns) == 4:
                    kwargs['query'] = pathNouns[3]

                result = __callNamed(name, **kwargs)
                #PMS.Log(result)
                return result

        elif pathNouns[1] == "prefs":
            if len(pathNouns) == 2:
                return Prefs.__container()
            else:
                Prefs.__setAll(kwargs)
                result = __callNamed("ValidatePrefs", addToLog=False)
                if result:
                    return result
                else:
                    return ''
コード例 #18
0
ファイル: Plugin.py プロジェクト: torarnv/Framework.bundle
def __handleInternalRequest(pathNouns, path, **kwargs):
    #
    # Handle a request internally
    #
    if len(pathNouns) > 1:
        if pathNouns[1] == "resources":
            if len(pathNouns) == 3:
                if Resource.__publicResources.has_key(pathNouns[2]):
                    PMS.Log("(Framework) Getting resource named '%s'" %
                            pathNouns[2])
                    resource = Resource.Load(pathNouns[2])
                    return Objects.DataObject(
                        resource, Resource.__publicResources[pathNouns[2]])

        if pathNouns[1] == "sharedresources":
            if len(pathNouns) == 3:
                if Resource.__publicSharedResources.has_key(pathNouns[2]):
                    PMS.Log("(Framework) Getting shared resource named '%s'" %
                            pathNouns[2])
                    resource = Resource.LoadShared(pathNouns[2])
                    return Objects.DataObject(
                        resource,
                        Resource.__publicSharedResources[pathNouns[2]])

        elif pathNouns[1] == "function" and len(pathNouns) >= 4:
            name = pathNouns[2]
            if name not in __reservedFunctionNames:
                encodedArgs = pathNouns[3]
                pos = encodedArgs.rfind(".")
                if pos > -1:
                    encodedArgs = encodedArgs[:pos]
                fkwargs = pickle.loads(D(encodedArgs))
                # Override encoded kwargs with kwargs passed in the URL
                for key in kwargs:
                    fkwargs[key] = kwargs[key]
                if len(pathNouns) == 4:
                    return __callNamed(name, **fkwargs)
                elif len(pathNouns) == 5:
                    return __callNamed(name, query=pathNouns[4], **fkwargs)

        elif pathNouns[1] == "prefs":
            if len(pathNouns) == 2:
                return Prefs.__container()
            else:
                Prefs.__setAll(kwargs)
                return __callNamed("ValidatePrefs", addToLog=False)
コード例 #19
0
ファイル: Response.py プロジェクト: vanpf/htcache
    def serve_descriptor(self, status, protocol, request):
        q = urlparse.urlparse( request.url[3] )[4]
        url = urlparse.urlparse(urllib.unquote(q[4:]))

        if ':' in url[1]:
            hostinfo = url[1].split(':')
            hostinfo[1] = int(hostinfo[1])
        else:
            hostinfo = url[1], 80
        cache = Resource.get_cache(hostinfo, url[2][1:]) 
        descriptors = Resource.get_backend()
        if cache.path in descriptors:
            descr = descriptors[cache.path]
            self.prepare_response(status, 
                    Params.json_write(descr), 
                    mime='application/json')
        else:
            self.prepare_response("404 No Data", "No data for %s %s %s %s"%request.url)
コード例 #20
0
def init():
    pygame.init()  #pygame初始化
    pygame.mouse.set_visible(False)  #隐藏鼠标
    Et.game_state = GAMEINIT  #初始化游戏状态
    Et.R_if = Rs.RInterface("Resource/json/interface")  #加载界面资源
    Et.I_ctr = Ip.Control()  #初始化键盘控制
    Et.t_net = threading.Thread(target=host, args=())
    t = threading.Thread(target=music, args=())
    t.setDaemon(True)
    t.start()
コード例 #21
0
 def test_init_for_one_abs_path_product(self):
     """ Testing init for an absolute path. """
     str_path_one = os.path.join(os.getcwd(), "This", "is", "a", "path1")
     str_answer = " ".join([
         "PATH:", str_path_one + ",", "CLEAN:",
         str(Resource.CLEAN_DEFAULT) + ",", "Product",
         "PARENTS: [] CHILDREN: []"
     ])
     rsc_test = Resource.Resource(str_path=str_path_one, f_is_product=True)
     str_result = str(rsc_test)
     self.func_test_equals(str_answer, str_result)
コード例 #22
0
    def build_gui(self, container):
        self.root = container

        qtwidget = QtGui.QWidget()

        self.resource = Resource.ResourceDisplay(qtwidget, logger=self.logger)

        layout = QtGui.QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self.resource, stretch=1)
        container.setLayout(layout)
コード例 #23
0
 def test_func_is_dependency_clean_level_for_bad_case_none(self):
     """
     Testing for indicating if the dependency is a certain clean level.
     Level = None
     """
     str_path_one = os.path.join(os.path.sep, "This", "is", "a", "path1")
     rsc_test = Resource.Resource(str_path=str_path_one,
                                  f_is_product=True,
                                  i_clean=None)
     f_result = rsc_test.func_is_dependency_clean_level(None)
     f_answer = False
     self.func_test_equals(f_answer, f_result)
コード例 #24
0
 def test_init_for_one_relative_path_dependency(self):
     """ Testing init for updating relative path (dependency). """
     str_path_one = os.path.join("This", "is", "a", "path1")
     str_answer = " ".join([
         "PATH:",
         os.path.join(os.getcwd(), str_path_one) + ",", "CLEAN:",
         str(Resource.CLEAN_DEFAULT) + ",", "Dependency",
         "PARENTS: [] CHILDREN: []"
     ])
     rsc_test = Resource.Resource(str_path=str_path_one, f_is_product=False)
     str_result = str(rsc_test)
     self.func_test_equals(str_answer, str_result)
コード例 #25
0
ファイル: Command.py プロジェクト: trinityrnaseq/SciEDPipeR
    def __init__(self,
                 str_cur_command,
                 lstr_cur_dependencies,
                 lstr_cur_products,
                 str_name="unnamed"):
        """
        Initializer.
        All paths should be absolute paths.
        If given relative paths, the current working directory will be
        added on to the path to make the file path absolute.

        * str_cur_command : String
                            Command to execute

        * lstr_cur_dependencies : List of strings
                                  List of absolute paths paths for dependencies

        * lstr_cur_products : List of strings
                              List of absolute paths for products to be made
        """

        # Set there id for the parent vertex
        Graph.Vertex.__init__(self, str_cur_command)
        self.str_type = STR_TYPE
        self.str_status = STR_NOT_RUN
        self.str_name = str_name
        for str_dependency in lstr_cur_dependencies:
            rsc_dep = Resource.Resource(str_dependency, f_is_product=False)
            self.func_add_parent(rsc_dep)
            rsc_dep.func_add_child(self)
        for str_product in lstr_cur_products:
            rsc_prod = Resource.Resource(str_product, f_is_product=True)
            self.func_add_child(rsc_prod)
            rsc_prod.func_add_parent(self)

        # Controls updating the commandlines pas flags
        # This often needs to be true when adding a sciedpiper script with
        # an update command.
        self.f_stop_update_at_flags = False
コード例 #26
0
    def _InitToolBar(self):
        toolbar = wx.ToolBar(self, style=wx.TB_NODIVIDER)

        tbNewInvoice = toolbar.AddLabelTool(
            wx.ID_ANY, 'New Invoice',
            wx.Bitmap(Resource.GetFileName('invoice-new.png')))
        self.Bind(wx.EVT_TOOL, self.OnNewInvoice, tbNewInvoice)

        tbViewInvoice = toolbar.AddLabelTool(
            wx.ID_ANY, 'View Invoice',
            wx.Bitmap(Resource.GetFileName('invoice-view.png')))
        self.Bind(wx.EVT_TOOL, self.OnViewInvoice, tbViewInvoice)

        toolbar.AddSeparator()

        tbPurchase = toolbar.AddLabelTool(
            wx.ID_ANY, 'Purchase Bill',
            wx.Bitmap(Resource.GetFileName('purchase-bill.png')))
        self.Bind(wx.EVT_TOOL, self.OnPurchase, tbPurchase)

        toolbar.Realize()

        userbar = wx.ToolBar(self, style=wx.TB_NODIVIDER)

        tbLogOut = userbar.AddLabelTool(
            wx.ID_ANY, 'Quit', wx.Bitmap(Resource.GetFileName('exit.png')))
        self.Bind(wx.EVT_TOOL, self.OnLogOut, tbLogOut)

        userbar.Realize()

        self.stUserName = wx.StaticText(self, label="")

        maintoolbar = wx.BoxSizer(wx.HORIZONTAL)
        maintoolbar.Add(toolbar, 1, wx.ALIGN_LEFT, 5)
        maintoolbar.Add(self.stUserName, 0,
                        wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 5)
        maintoolbar.Add(userbar, 0, wx.ALIGN_RIGHT, 5)

        return maintoolbar
コード例 #27
0
 def nottest_func_get_size_for_empty_dir(self):
     """
     Test get size for empty directories.
     """
     str_dir = os.path.join(self.str_test_directory,
                            "test_func_get_size_for_empty_dir")
     str_answer = "68.0 B"
     self.func_make_dummy_dir(self.str_test_directory)
     self.func_make_dummy_dir(str_dir)
     str_size = Resource.Resource(str_path=str_dir,
                                  f_is_product=True).func_get_size()
     self.func_remove_dirs([str_dir, self.str_test_directory])
     self.func_test_equals(str_answer, str_size)
コード例 #28
0
ファイル: Main.py プロジェクト: AaronRiegel/Music
def match_templates(staff_img,
                    staff,
                    i,
                    note_imgs_,
                    note_lower_,
                    note_upper_,
                    note_thresh,
                    notation,
                    duration=0,
                    rest=False):
    _boxes = Resource.locate_templates(staff_img, note_imgs_, note_lower_,
                                       note_upper_, note_thresh)
    _boxes = Resource.merge([j for i in _boxes for j in i], 0.5)

    for box in _boxes:
        box.draw(staff_img, (0, 0, 255), 1)
        text = f"{notation}"
        font = cv2.FONT_HERSHEY_DUPLEX
        textsize = cv2.getTextSize(text, font, fontScale=0.255, thickness=1)[0]
        x = int(box.getCorner()[0] - (textsize[0] // 2))
        y = int(box.getCorner()[1] + box.getHeight() + 20)
        cv2.putText(staff_img,
                    text, (x, y),
                    font,
                    fontScale=0.25,
                    color=(0, 0, 255),
                    thickness=1)
        y_center = box.getCenter()
        # print(f'x_center {int(round(y_center[0]))} y_center {int(round(y_center[1]))}')
        pitch = staff.get_pitch(int(round((y_center)[1])))
        nimage = f'qnotes{i}.png'
        cv2.imwrite(nimage, staff_img)
        if (rest):
            obj = MusicObject(notation, 'rest', duration, box, pitch)
        else:
            obj = MusicObject(notation, 'note', duration, box, pitch)
        if (notation == 'sharp' or notation == 'flat'):
            return
        sequence.append(obj)
コード例 #29
0
 def test_init_for_clean_1(self):
     """ Testing init for cleaning level 1. """
     str_path_one = os.path.join(os.getcwd(), "This", "is", "a", "path1")
     str_answer = " ".join([
         "PATH:", str_path_one + ",", "CLEAN:",
         str(Resource.CLEAN_NEVER) + ",", "Product",
         "PARENTS: [] CHILDREN: []"
     ])
     rsc_test = Resource.Resource(str_path=str_path_one,
                                  f_is_product=True,
                                  i_clean=Resource.CLEAN_NEVER)
     str_result = str(rsc_test)
     self.func_test_equals(str_answer, str_result)
コード例 #30
0
ファイル: Main.py プロジェクト: AaronRiegel/Music
def find_cleff(staff_img, i, clef_imgs, clef_lower, clef_upper, clef_thresh):
    for clef in clef_imgs:
        # print("Matching {} clef template on staff".format(clef), i + 1)
        clef_boxes = Resource.locate_templates(staff_img, clef_imgs[clef],
                                               clef_lower, clef_upper,
                                               clef_thresh)
        clef_boxes = Resource.merge([j for i in clef_boxes for j in i], 0.5)

        if (len(clef_boxes) == 1):
            print("Clef Found: ", clef)
            staffs[i].setClef(clef)

            # print("[INFO] Displaying Matching Results on staff", i + 1)
            clef_boxes_img = staffs[i].getImage()
            clef_boxes_img = clef_boxes_img.copy()

            for boxes in clef_boxes:
                boxes.draw(staff_img, (0, 255, 0), 1)
                x = int(boxes.getCorner()[0] + (boxes.getWidth() // 2))
                y = int(boxes.getCorner()[1] + boxes.getHeight() + 10)
                cv2.putText(staff_img, "{} clef".format(clef), (x, y),
                            cv2.FONT_HERSHEY_DUPLEX, 0.9, (0, 255, 0))
コード例 #31
0
 def test_func_is_dependency_clean_level_for_good_case_temp(self):
     """
     Testing for indicating if the dependency is a certain clean level.
     Level = temp
     """
     str_path_one = os.path.join(os.path.sep, "This", "is", "a", "path1")
     rsc_test = Resource.Resource(str_path=str_path_one,
                                  f_is_product=True,
                                  i_clean=Resource.CLEAN_AS_TEMP)
     f_result = rsc_test.func_is_dependency_clean_level(
         Resource.CLEAN_AS_TEMP)
     f_answer = True
     self.func_test_equals(f_answer, f_result)
コード例 #32
0
def update(event):
    if Et.game_state == GAMEINIT:
        Et.R_if.screen.blit(Et.R_if.main_bk_pic, (0, 0))
        mouseResponseGameInit(event)
        buttonShow()
        cursorShow()
    elif Et.game_state == GAMESETTING:
        Et.R_if.screen.blit(Et.R_if.main_bk_pic, (0, 0))
        mouseResponseGameSetting(event)
        settingShow()
        cursorShow()
    elif Et.game_state == GAMEHELP:
        Et.R_if.screen.blit(Et.R_if.main_bk_pic, (0, 0))
        mouseResponseGameHelp(event)
        helpShow()
        cursorShow()
    elif Et.game_state == GAMEINIT1:
        cursorShow()
        Et.R_gc = Rs.RChoose(game_file[0])
        Et.game_state = GAMESINGLECHOOSE
    elif Et.game_state == GAMESINGLECHOOSE:
        Et.R_if.screen.blit(Et.R_gc.bottom_pic, (0, 0))
        mouseResponseGameSingleChoose(event)
        singleChooseShow()
        cursorShow()
    elif Et.game_state == GAMELOADSUB:
        Et.R_pl = Rs.RCharacter(Et.R_gc.character_file[Et.player_choice])
        Et.R_em = Rs.REnemy(enemy_file[Et.game_choice])
        Et.R_ob = Rs.RObstacle(obstacle_file[Et.game_choice])
        for i in range(0, 3):
            Et.R_sk[i] = Rs.RSkill(skill_file[Et.R_pl.skill[i]])
        Et.R_sg = Rs.RSingle(game_file[1][Et.game_choice])
        Et.game_state = GAMELOAD
    elif Et.game_state == GAMELOAD:
        Et.game_state = GAMESTART
    elif Et.game_state == GAMESTART:
        Et.I_ctr.update()
        gameBlit()
        #test_case.test()
    elif Et.game_state == GAMEONLINEINIT1:
        Et.R_pl = Rs.RCharacter(character_file[Et.player_choice])
        Et.R_sg = Rs.RSingle(game_file[1][Et.game_choice])
        Et.game_state = GAMEONLINEINIT2
    elif Et.game_state == GAMEONLINEINIT2:
        Et.game_state = GAMEONLINE
    elif Et.game_state == GAMEONLINE:
        Et.I_ctr.update()
        onlineBlit()
コード例 #33
0
ファイル: CommitController.py プロジェクト: ararog/iShareCode
	def updateStatus(self):
		self.files = []
		states = 'modified added removed deleted unknown ignored clean'.split()
		self.repository = hg.repository(ui.ui(), self.directory)
		status = self.repository.status('.', None, None, True, True, True)	
		self.changestates = zip(states, status)
		for _state, _files in self.changestates:
			for _file in _files:
				resource = Resource()
				resource.setPath(_file)
				resource.setState(NSLocalizedString(_state, None))
				resource.setSelected(False)
				self.files.append(resource)
コード例 #34
0
ファイル: Player.py プロジェクト: zelurker/fofix
Config.define("player", "leftymode",     int,  0, text = _("Lefty Mode"),    options = {0: _("Off"), 1: _("On")})
Config.define("player", "drumflip",      int,  0, text = _("Drum Flip"),     options = {0: _("Off"), 1: _("On")})
Config.define("player", "two_chord_max", int,  0, text = _("Two-Chord Max"), options = {0: _("Off"), 1: _("On")})
Config.define("player", "assist_mode",   int,  0, text = _("Assist Mode"),   options = {0: _("Off"), 1: _("Easy Assist"), 2: _("Medium Assist")})
Config.define("player", "auto_kick",     int,  0, text = _("Auto Kick"),     options = {0: _("Off"), 1: _("On")})
Config.define("player", "controller",    int,  0)

controlpath = os.path.join("data","users","controllers")
playerpath  = os.path.join("data","users","players")
if not hasattr(sys,"frozen"):
  controlpath = os.path.join("..",controlpath)
  playerpath  = os.path.join("..",playerpath)

#stump: permission fix for read-only system-wide installation
if not os.path.isfile(os.path.join(playerpath, 'FoFiX-players.cache')):
  baseuserpath = os.path.join(Resource.getWritableResourcePath(), 'users')
  newcontrolpath = os.path.join(baseuserpath, 'controllers')
  newplayerpath = os.path.join(baseuserpath, 'players')
  for old, new in [(controlpath, newcontrolpath), (playerpath, newplayerpath)]:
    if not os.path.isdir(new):
      os.makedirs(new)
    for f in os.listdir(old):
      shutil.copy(os.path.join(old, f), os.path.join(new, f))
  controlpath = newcontrolpath
  playerpath = newplayerpath

control0 = None
control1 = None
control2 = None
control3 = None
controlDict = {}
コード例 #35
0
ファイル: Debug.py プロジェクト: Gamer125/fofix
  def debugOut(self, engine):
    try:
      f = open("debug.log", "w+")
    except IOError:
      # fallback for unix (games dir read-only)
      import Resource
      # evilynux - Under MacOS X, put the logs in ~/Library/Logs
      if( os.uname()[0] == "Darwin" ):
        logFile = open(os.path.join(Resource.getWritableResourcePath(), 
                                    "..", "..", "Logs", Version.appName(),
                                    "debug.log"), "w+")
      else: # GNU/Linux et al.
        f = open(os.path.join(Resource.getWritableResourcePath(), 'debug.log'), "w+")
    version = Version.version()
    currentDir = os.getcwd()
    dataDir = Version.dataPath()
    translationDir = dataDir + "/translations"
    modsDir = dataDir + "/mods"

    f.write("Date = %s\n" % datetime.datetime.now())   
    f.write("\nVersion = %s\n" %  version)
    f.write("\nOS = %s\n" % os.name)

    f.write("\nCurrent Directory = %s\n" % currentDir)
    self.directoryList(f, currentDir)

    f.write("\nData Directory = %s\n" % dataDir)
    self.directoryList(f, dataDir)

    zip_path = os.path.join(dataDir, 'library.zip')
    # no library.zip on regular unix installation
    if os.path.exists(zip_path):
      f.write("\nLibrary.zip\n")
      zip = zipfile.ZipFile(zip_path, 'r')
      for info in zip.infolist():
        fileName = info.filename
        fileCSize = info.compress_size
        fileSize = info.file_size
        fileDate = datetime.datetime(*(info.date_time))
        f.write("%s, %s, %s, %s\n" % (fileName, fileCSize, fileSize, fileDate))
    
    f.write("\nTranslation Directory = %s\n" % translationDir)
    self.directoryList(f, translationDir)
    
    f.write("\nMods Directory = %s\n" % modsDir)
    self.directoryList(f, modsDir)

    mods = os.listdir(modsDir)

    for mod in mods:
      modDir = os.path.join(modsDir, mod)
      if os.path.isdir(modDir):
        f.write("\nMod Directory = %s\n" % modDir)
        self.directoryList(f, modDir)

    f.write("\nFretsonfire.ini\n")   
    engine.config.config.write(f)

    # No write() in Theme
    #f.write("\nTheme.ini\n")
    #Theme.write(f, engine.config)

    f.write("\nStage.ini\n")
    stage = Stage.Stage(self, self.engine.resource.fileName("stage.ini"))
    stage.config.write(f)
    f.close()
コード例 #36
0
ファイル: Log.py プロジェクト: Gamer125/fofix
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     #
# GNU General Public License for more details.                      #
#                                                                   #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software       #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,        #
# MA  02110-1301, USA.                                              #
#####################################################################

import sys
import os
import Resource

quiet = True
if os.name == "posix": # evilynux - logfile in ~/.fretsonfire/ for GNU/Linux and MacOS X
  logFile = open(os.path.join(Resource.getWritableResourcePath(), "fretsonfire.log"), "w")
else:
  logFile = open("fretsonfire.log", "w")  #MFH - local logfile!
  
encoding = "iso-8859-1"

if "-v" in sys.argv:
  quiet = False
  
if os.name == "posix":
  labels = {
    "warn":   "\033[1;33m(W)\033[0m",
    "debug":  "\033[1;34m(D)\033[0m",
    "notice": "\033[1;32m(N)\033[0m",
    "error":  "\033[1;31m(E)\033[0m",
  }
コード例 #37
0
def main():
  playing = None
  configFile = None
  fullscreen = None
  resolution = None
  theme = None
  #debug = False
  difficulty = None
  part = None
  mode = 0
  nbrplayers = 1
  for opt, arg in opts:
    if opt in ["--verbose", "-v"]:
      Log.quiet = False
    if opt in ["--config", "-c"]:
      configFile = arg
    if opt in ["--fullscreen", "-f"]:
      fullscreen = arg
    if opt in ["--resolution", "-r"]:
      resolution = arg
    if opt in ["--theme", "-t"]:
      theme = arg
    if opt in ["--song", "-s"]:
      playing = arg
    if opt in ["--part", "-p"]:
      part = arg
    if opt in ["--diff", "-d", "-l"]:
      difficulty = arg      
    #evilynux - Multiplayer and mode selection support
    if opt in ["--mode", "-m"]:
      mode = int(arg)
    if opt in ["--nbrplayers", "-n"]:
      nbrplayers = int(arg)

  # Load the configuration file.
  if configFile is not None:
    if configFile.lower() == "reset":
      fileName = os.path.join(Resource.getWritableResourcePath(), Version.PROGRAM_UNIXSTYLE_NAME + ".ini")
      os.remove(fileName)
      config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault = True)
    else:
      config = Config.load(configFile, setAsDefault = True)
  else:
    config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault = True)

  #Lysdestic - Allow support for manipulating fullscreen via CLI
  if fullscreen is not None:
    Config.set("video", "fullscreen", fullscreen)

  #Lysdestic - Change resolution from CLI
  if resolution is not None:
    Config.set("video", "resolution", resolution)

  #Lysdestic - Alter theme from CLI
  if theme is not None:
    Config.set("coffee", "themename", theme)

  engine = GameEngine(config)
  engine.cmdPlay = 0

  # Check for a valid invocation of one-shot mode.
  if playing is not None:
    Log.debug('Validating song directory for one-shot mode.')
    library = Config.get("game","base_library")
    basefolder = os.path.join(Version.dataPath(),library,"songs",playing)
    if not (os.path.exists(os.path.join(basefolder, "song.ini")) and (os.path.exists(os.path.join(basefolder, "notes.mid")) or os.path.exists(os.path.join(basefolder, "notes-unedited.mid"))) and (os.path.exists(os.path.join(basefolder, "song.ogg")) or os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
      Log.warn("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode." % playing)
      engine.startupMessages.append(_("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode.") % playing)
      playing = None

  # Set up one-shot mode if the invocation is valid for it.
  if playing is not None:
    Log.debug('Entering one-shot mode.')
    Config.set("game", "selected_library", "songs")
    Config.set("game", "selected_song", playing)
    engine.cmdPlay = 1
    if difficulty is not None:
      engine.cmdDiff = int(difficulty)
    if part is not None:
      engine.cmdPart = int(part)
    #evilynux - Multiplayer and mode selection support
    
    if nbrplayers == 1:
      engine.cmdMode = nbrplayers, mode, 0
    
    else:
      engine.cmdMode = nbrplayers, 0, mode

  encoding = Config.get("game", "encoding")
  if encoding is not None:
    #stump: XXX: Everything I have seen indicates that this is a
    # horrible, horrible hack.  Is there another way?  Do we even need this?
    reload(sys)
    sys.setdefaultencoding(encoding)

  # Play the intro video if it is present, we have the capability, and
  # we are not in one-shot mode.
  videoLayer = False
  if videoAvailable and not engine.cmdPlay:
    # TODO: Parameters to add to theme.ini:
    #  - intro_video_file
    #  - intro_video_start_time
    #  - intro_video_end_time
    themename = Config.get("coffee", "themename")
    vidSource = os.path.join(Version.dataPath(), 'themes', themename, \

                             'menu', 'intro.mp4')
    if os.path.isfile(vidSource):
      winWidth, winHeight = engine.view.geometry[2:4]
      songVideoStartTime = 0
      songVideoEndTime = None
      vidPlayer = VideoPlayer(-1, vidSource, (winWidth, winHeight),
                              startTime = songVideoStartTime,
                              endTime = songVideoEndTime)
      if vidPlayer.validFile:
        engine.view.pushLayer(vidPlayer)
        videoLayer = True
        try:
          engine.ticksAtStart = pygame.time.get_ticks()
          while not vidPlayer.finished:
            engine.run()
          engine.view.popLayer(vidPlayer)
          engine.view.pushLayer(MainMenu(engine))
        except KeyboardInterrupt:
          engine.view.popLayer(vidPlayer)
          engine.view.pushLayer(MainMenu(engine))
  if not videoLayer:
    engine.setStartupLayer(MainMenu(engine))

  #stump: make psyco optional
  if Config.get("performance", "use_psyco"):
    try:
      import psyco
      psyco.profile()
    except:
      Log.error("Unable to enable psyco as requested: ")

  # Run the main game loop.
  try:
    engine.ticksAtStart = pygame.time.get_ticks()
    while engine.run():
      pass
  except KeyboardInterrupt:
    Log.notice("Left mainloop due to KeyboardInterrupt.")
    # don't reraise

  # Restart the program if the engine is asking that we do so.
  if engine.restartRequested:
    Log.notice("Restarting.")
    engine.audio.close()
    try:
      # Extra arguments to insert between the executable we call and our
      # command line arguments.
      args = []
      # Figure out what executable to call.
      if hasattr(sys, "frozen"):
        if os.name == "nt":
          # When py2exe'd, sys.executable is the name of the EXE.
          exe = os.path.abspath(unicode(sys.executable, sys.getfilesystemencoding()))
        elif sys.frozen == "macosx_app":
          # When py2app'd, sys.executable is a Python interpreter copied
          # into the same dir where we live.
          exe = os.path.join(os.path.dirname(sys.executable), 'FoFiX')  # FIXME: don't hard-code "FoFiX" here
        else:
          raise RuntimeError, "Don't know how to restart when sys.frozen is %s" % repr(sys.frozen)
      else:
        # When running from source, sys.executable is the Python interpreter
        # being used to run the program.
        exe = sys.executable
        # Pass the optimization level on iif python version >= 2.6.0 as
        # sys.flags has been introduced in 2.6.0.
        if sys.version_info[:3] >= (2,6,0) and sys.flags.optimize > 0:
          args.append('-%s' % ('O' * sys.flags.optimize))
        args.append(sys.argv[0])
      os.execv(exe, [sys.executable] + args + sys.argv[1:])
    except:
      Log.error("Restart failed: ")
      raise

  # evilynux - MainMenu class already calls this - useless?
  engine.quit()
コード例 #38
0
ファイル: Incubator.py プロジェクト: tobiasterstad/Incubator
    def main(self):
        logging.info("Incubator started... " + self.start_time.strftime('%Y-%m-%d %H:%M:%S'))
        self.send_notification("Incubator started")

        self.ssr.set_point(self.config.get_temp())

        # Start roller
        self.roller.set_day(self.config.get_day())
        self.roller.start()

        web = Web.Web(self)
        web.start()
        lcd = Lcd()

        temp_sensor = Resource.create_temp_sensor()
        htu21d = Resource.create_humidity_sensor()

        # Start SSR service
        self.ssr.set_value(0)
        self.ssr.start()

        # Start buttons and relays
        # self.io_handler.start()

        i = 0
        state = State()
        state.set_day(self.get_days_from_start())

        http_sender = HttpSender.HttpSender()

        while self._running:
            state.update_ts()
            state.set_temp1(temp_sensor.read_temp())

            pid = self.ssr.update(state.get_temp1())
            state.set_pid(pid)

            #if state.temp1 > 38.5:
            #    self.send_notification("High temp alert, {} gr".format(state.temp1))

            if i % 10 == 0:
                # Read humidity and temp each 10 seconds
                try:
                    state.set_temp2(htu21d.read_temperature())
                    state.set_humidity(htu21d.read_humidity())
                except:
                    self.send_notification("Failed to read htu21d")

                self.ventilation.set_state(state)
                state.set_humidity_level(self.ventilation.get_output_level())

                http_sender.send("A123", state)

            if i >= 30:
                # Set new temp from config file
                self.config.reload()
                self.ssr.set_point(self.config.get_temp())
                self.ssr.set_k(self.config.get_k())
                self.ssr.set_i(self.config.get_i())

                self.ventilation.set_point(self.get_humidity())

                state.set_day(self.get_days_from_start())

                if self.config.get_day() != state.get_day():
                    self.config.set_day(state.get_day())
                    self.config.save()
                    self.roller.set_day(state.get_day())

                self.log_incubator_state(self.config, state)

                # update web page
                web.update(state, self.config)
                i = 0

            lcd.update(state, self.roller.get_minutes_from_last_roll())
            sys.stdout.flush()
            time.sleep(1)
            i += 1

        self.shutdown()
コード例 #39
0
ファイル: gamemaster.py プロジェクト: straemer/PowerGrid
    def main(self):

        # TODO Load the map blocked need map object

        # init turns
        # TODO
        self.initializePlayerTurns()
        for player in reversed(self.players):
            while len(player.get_PowerPlants()) == 0:
                auction = Auction.Auction(
                    self.Table.getDeck(), self.Table.getCardsForAuction() + self.Table.getFutureCardsForAuction()
                )
                # TODO Anandh add auction stuff

        while not self.gameover:
            print("buy resources")
            # PHASE 2 bid for resources
            for player in self.players:
                request = {}
                request[Resource.COAL] = player.getCoalRequest()
                request[Resource.OIL] = player.getOilRequest()
                request[Resource.GARBAGE] = player.getGarbageRequest()
                request[Resource.URANIUM] = player.getUraniumRequest()
                cost = Resource.buy_resource(request)
                if cost == 0:
                    player.warn(NOT_ENOUGH_RESOURCES)
                elif cost <= player.f_b_get_money():
                    player.pay(cost)
                    player.add_coal(request[Resource.COAL])
                    player.add_oil(request[Resource.OIL])
                    player.add_garbage(request[Resource.GARBAGE])
                    player.add_uranium(request[Resource.URANIUM])
                else:
                    # This case there is not enough money
                    player.warn(NOT_ENOUGH_MONEY)
            self.ResourceMarket.restore_resources()

            # PHASE 3 buy cities
            # TODO Blocked no map available

            # PHASE 4 power cities
            for player in self.players:
                player.powerCities()
                # TODO check game end

                # PHASE 5 pay the players
            for player in self.players:
                player.addMoney(payday.pay(player.get_cities_powered))

                # Check if advance to 2
            if self.currentPhase == 1:
                self.checkAdvancePhaseTwo()

            for player in self.players:
                if player.get_cities() >= self.GAMEEND[self.numPlayers]:
                    self.gameover = True
                    # PHASE 1 bid for power plants
            self.players = calculateTurns()
            availableCards = self.Table.getCardsForAuction()
            futureCards = self.Table.getFutureCardsForAuction()
            self.checkAdvancePhaseThree(availableCards)
            # Pass to players
            # TODO Auction
            print("Bid for power plants")
            auction = Auction.Auction(self.Table.getDeck(), availableCards + futureCards)
コード例 #40
0
ファイル: FoFiX.py プロジェクト: davwong/fofix
    if opt in ["--song", "-s"]:
      playing = arg
    if opt in ["--part", "-p"]:
      part = arg
    if opt in ["--diff", "-d", "-l"]:
      difficulty = arg      
    #evilynux - Multiplayer and mode selection support
    if opt in ["--mode", "-m"]:
      mode = int(arg)
    if opt in ["--nbrplayers", "-n"]:
      nbrplayers = int(arg)

  # Load the configuration file.
  if configFile is not None:
    if configFile.lower() == "reset":
      fileName = os.path.join(Resource.getWritableResourcePath(), Version.PROGRAM_UNIXSTYLE_NAME + ".ini")
      os.remove(fileName)
      config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault = True)
    else:
      config = Config.load(configFile, setAsDefault = True)
  else:
    config = Config.load(Version.PROGRAM_UNIXSTYLE_NAME + ".ini", setAsDefault = True)

  #Lysdestic - Allow support for manipulating fullscreen via CLI
  if fullscreen is not None:
    Config.set("video", "fullscreen", fullscreen)

  #Lysdestic - Change resolution from CLI
  if resolution is not None:
    Config.set("video", "resolution", resolution)
コード例 #41
0
ファイル: Log.py プロジェクト: Gamer125/fofix
import sys
import os
import Resource
import Version
import traceback
import time
import warnings

## Whether to output log entries to stdout in addition to the logfile.
quiet = True

## File object representing the logfile.
if os.name == "posix": # evilynux - logfile in ~/.fofix/ for GNU/Linux and MacOS X
  # evilynux - Under MacOS X, put the logs in ~/Library/Logs
  if os.uname()[0] == "Darwin":
    logFile = open(os.path.join(Resource.getWritableResourcePath(), 
                                "..", "..", "Logs",
                                Version.appName() + ".log"), "w")
  else: # GNU/Linux et al.
    logFile = open(os.path.join(Resource.getWritableResourcePath(), Version.appName() + ".log"), "w")
else:
  logFile = open(Version.appName() + ".log", "w")  #MFH - local logfile!

## Character encoding to use for logging.
encoding = "iso-8859-1"

if "-v" in sys.argv or "--verbose" in sys.argv:
  quiet = False

## Labels for different priorities, as output to the logfile.
labels = {
コード例 #42
0
ファイル: FretsOnFire.py プロジェクト: Gamer125/fofix
        if opt in ["--play", "-p"]:
            playing = arg
        if opt in ["--diff", "-D"]:
            difficulty = arg
        if opt in ["--part", "-P"]:
            part = arg
        # evilynux - Multiplayer and mode selection support
        if opt in ["--mode", "-m"]:
            mode = int(arg)
        if opt in ["--nbrplayers", "-N"]:
            nbrplayers = int(arg)

    while True:
        if configFile != None:
            if configFile.lower() == "reset":
                fileName = os.path.join(Resource.getWritableResourcePath(), Version.appName() + ".ini")
                os.remove(fileName)
                config = Config.load(Version.appName() + ".ini", setAsDefault=True)
            else:
                config = Config.load(configFile, setAsDefault=True)
        else:
            config = Config.load(Version.appName() + ".ini", setAsDefault=True)
        engine = GameEngine(config)
        engine.cmdPlay = 0

        if playing != None:
            Config.set("game", "selected_library", "songs")
            Config.set("game", "selected_song", playing)
            engine.cmdPlay = 1
            engine.cmdDiff = int(difficulty)
            engine.cmdPart = int(part)
コード例 #43
0
ファイル: JohnDoee_core.py プロジェクト: ccavxx/py-search
## core.py## Copyright (C) 2009 John Doee <*****@*****.**>## Basic plugin template created by:# Copyright (C) 2008 Martijn Voncken <*****@*****.**># Copyright (C) 2007-2009 Andrew Resch <*****@*****.**># Copyright (C) 2009 Damien Churchill <*****@*****.**>## Deluge is free software.## You may redistribute it and/or modify it under the terms of the# GNU General Public License, as published by the Free Software# Foundation; either version 3 of the License, or (at your option)# any later version.## deluge is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.# See the GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with deluge.    If not, write to:# 	The Free Software Foundation, Inc.,# 	51 Franklin Street, Fifth Floor# 	Boston, MA  02110-1301, USA.##    In addition, as a special exception, the copyright holders give#    permission to link the code of portions of this program with the OpenSSL#    library.#    You must obey the GNU General Public License in all respects for all of#    the code used other than OpenSSL. If you modify file(s) with this#    exception, you may extend this exception to your version of the file(s),#    but you are not obligated to do so. If you do not wish to do so, delete#    this exception statement from your version. If you delete this exception#    statement from all source files in the program, then also delete it here.#
import base64import jsonimport loggingimport osimport urllib
import deluge.configmanager
from collections import defaultdict
from deluge import componentfrom deluge._libtorrent import ltfrom deluge.core.rpcserver import exportfrom deluge.plugins.pluginbase import CorePluginBase
from twisted.internet import reactor, defer, taskfrom twisted.python import randbytesfrom twisted.web import server, resource, static, http, client
from .filelike import FilelikeObjectResourcefrom .resource import Resource
logger = logging.getLogger(__name__)
DEFAULT_PREFS = { 'ip': '127.0.0.1', 'port': 46123, 'allow_remote': False, 'reset_complete': True, 'use_stream_urls': True, 'auto_open_stream_urls': False, 'remote_username': '******', 'remote_password': '******',}

def sleep(seconds):    d = defer.Deferred()    reactor.callLater(seconds, d.callback, seconds) return d
class FileServeResource(resource.Resource):    isLeaf = True  def __init__(self): self.file_mapping = {}        resource.Resource.__init__(self)
 def generate_secure_token(self): return base64.urlsafe_b64encode(randbytes.RandomFactory().secureRandom(21, True))  def add_file(self, path):        token = self.generate_secure_token() self.file_mapping[token] = path  return token  def render_GET(self, request):        key = request.path.split('/')[2] if key not in self.file_mapping: return resource.NoResource().render(request)         f = self.file_mapping[key] if f.is_complete(): return static.File(f.full_path).render_GET(request) else:            tfr = f.open() return FilelikeObjectResource(tfr, f.size).render_GET(request)
class StreamResource(Resource):    isLeaf = True  def __init__(self, client, *args, **kwargs): self.client = client        Resource.__init__(self, *args, **kwargs)  @defer.inlineCallbacks def render_GET(self, request):        infohash = request.args.get('infohash', None)        path = request.args.get('path', None)  if infohash is None:            defer.returnValue(json.dumps({'status': 'error', 'message': 'missing infohash'}))  if path is None:            defer.returnValue(json.dumps({'status': 'error', 'message': 'missing path'}))         result = yield self.client.stream_torrent(infohash[0], path[0])        defer.returnValue(json.dumps(result))
class UnknownTorrentException(Exception): pass
class UnknownFileException(Exception): pass
class TorrentFileReader(object): def __init__(self, torrent_file): self.torrent_file = torrent_file self.size = torrent_file.size self.position = 0  self.waiting_for_piece = None self.current_piece = None self.current_piece_data = None  @defer.inlineCallbacks def read(self, size=1024):        required_piece, read_position = self.torrent_file.get_piece_info(self.position)  if self.current_piece != required_piece:            logger.debug('We are missing piece %i and it is required, requesting' % (required_piece, )) self.waiting_for_piece = required_piece self.current_piece_data = yield self.torrent_file.get_piece_data(required_piece) self.current_piece = required_piece self.waiting_for_piece = None         logger.debug('We can read from local piece from %s size %s from position %s' % (read_position, size, self.position))        data = self.current_piece_data[read_position:read_position+size] self.position += len(data)         defer.returnValue(data)  def tell(self): return self.position  def close(self): self.torrent_file.close(self)  def seek(self, offset, whence=os.SEEK_SET): self.position = offset
class TorrentFile(object): # can be read from, knows about itself def __init__(self, torrent, first_piece, last_piece, piece_size, offset, path, full_path, size, index): self.torrent = torrent self.first_piece = first_piece self.last_piece = last_piece self.piece_size = piece_size self.offset = offset self.path = path self.size = size self.full_path = full_path self.index = index  self.file_requested = False self.do_shutdown = False self.first_piece_end = self.piece_size * (self.first_piece + 1) - offset self.waiting_pieces = {} self.current_readers = [] self.registered_alert = False  self.alerts = component.get("AlertManager")   def open(self): """        Returns a filelike object """ if not self.registered_alert: self.alerts.register_handler("read_piece_alert", self.on_alert_got_piece_data) self.registered_alert = True        tfr = TorrentFileReader(self) self.current_readers.append(tfr) self.file_requested = False return tfr  def close(self, tfr): self.current_readers.remove(tfr) self.torrent.unprioritize_pieces(tfr)  def is_complete(self):        torrent_status = self.torrent.torrent.get_status(['file_progress', 'state'])        file_progress = torrent_status['file_progress'] return file_progress[self.index] == 1.0  def get_piece_info(self, tell): return divmod((self.offset + tell), self.piece_size)  def on_alert_got_piece_data(self, alert):        torrent_id = str(alert.handle.info_hash()) if torrent_id != self.torrent.infohash: return         logger.debug('Got piece data for piece %s' % alert.piece) if alert.piece not in self.waiting_pieces:            logger.debug('Got data for piece %i, but no data needed for this piece?' % alert.piece) return # TODO: check piece size is not zero  self.waiting_pieces[alert.piece].callback(alert.buffer)  @defer.inlineCallbacks def get_piece_data(self, piece):        logger.debug('Trying to get piece data for piece %s' % piece) for reader in self.current_readers: if reader.current_piece == piece:                defer.returnValue(reader.current_piece_data)  if piece not in self.waiting_pieces: self.waiting_pieces[piece] = defer.Deferred()         logger.debug('Waiting for %s' % piece) self.torrent.schedule_piece(self, piece, 0) while not self.torrent.torrent.handle.have_piece(piece): if self.do_shutdown: raise Exception()            logger.debug('Did not have piece %i, waiting' % piece) self.torrent.unrelease() yield sleep(1)  self.torrent.torrent.handle.read_piece(piece)         data = yield self.waiting_pieces[piece] if piece in self.waiting_pieces: del self.waiting_pieces[piece]        logger.debug('Done waiting for piece %i, returning data' % piece)        defer.returnValue(data)  def shutdown(self): self.do_shutdown = True
class Torrent(object): def __init__(self, torrent_handler, infohash): self.infohash = infohash self.torrent = component.get("TorrentManager").torrents.get(infohash, None) self.torrent_handler = torrent_handler  if not self.torrent: raise UnknownTorrentException('%s is not a known infohash' % infohash)  self.torrent_files = None self.priority_increased = defaultdict(set) self.do_shutdown = False self.torrent_released = True # set to True if all the files are set to download   self.populate_files() self.file_priorities = [0] * len(self.torrent_files)  self.last_piece = self.torrent_files[-1].last_piece self.torrent.handle.set_sequential_download(True)        reactor.callLater(0, self.update_piece_priority)        reactor.callLater(0, self.blackhole_all_pieces, 0, self.last_piece)  def populate_files(self): self.torrent_files = []         status = self.torrent.get_status(['piece_length', 'files', 'save_path'])        piece_length = status['piece_length']        files = status['files']        save_path = status['save_path']  for f in files:            first_piece = f['offset'] / piece_length            last_piece = (f['offset'] + f['size']) / piece_length            full_path = os.path.join(save_path, f['path'])  self.torrent_files.append(TorrentFile(self, first_piece, last_piece, piece_length, f['offset'],                                                  f['path'], full_path, f['size'], f['index']))  return files  def find_file(self, file_or_index=None, includes_name=False):        best_file = None        biggest_file_size = 0  for i, f in enumerate(self.torrent_files):            path = f.path if not includes_name and '/' in path:                path = '/'.join(path.split('/')[1:])             logger.debug('Testing file %r against %s / %r' % (file_or_index, i, path)) if file_or_index is not None: if i == file_or_index or path == file_or_index:                    best_file = f break else: if f.size > biggest_file_size:                    best_file = f                    biggest_file_size = f.size  return best_file  def get_file(self, file_or_index=None, includes_name=False):        f = self.find_file(file_or_index, includes_name) if f is None: raise UnknownFileException('Was unable to find %s' % file_or_index)  return f  def unprioritize_pieces(self, tfr):        logger.debug('Unprioritizing pieces for %s' % tfr)        currently_downloading = self.get_currently_downloading()  for piece, increased_by in self.priority_increased.items(): if tfr in increased_by:                increased_by.remove(tfr) if not increased_by and piece not in currently_downloading and not self.torrent.status.pieces[piece]:                    logger.debug('Unprioritizing piece %s' % piece) self.torrent.handle.piece_priority(piece, 0)  def get_currently_downloading(self):        currently_downloading = set() for peer in self.torrent.handle.get_peer_info(): if peer.downloading_piece_index != -1:                currently_downloading.add(peer.downloading_piece_index)  return currently_downloading  def blackhole_all_pieces(self, first_piece, last_piece):        currently_downloading = self.get_currently_downloading()         logger.debug('Blacklisting pieces from %i to %i skipping %r' % (first_piece, last_piece, currently_downloading)) for piece in range(first_piece, last_piece+1): if piece not in currently_downloading and not self.torrent.status.pieces[piece]: if piece in self.priority_increased: continue                logger.debug('Setting piece priority %s to blacklist' % piece) self.torrent.handle.piece_priority(piece, 0)  def unrelease(self): if self.torrent_released:            logger.debug('Unreleasing %s' % self.infohash) self.torrent_released = False self.torrent.set_file_priorities(self.file_priorities) self.blackhole_all_pieces(0, self.last_piece)  def get_torrent_file(self, file_or_index, includes_name):        f = self.get_file(file_or_index, includes_name)        f.file_requested = True  self.torrent.resume()         should_update_priorities = False if self.file_priorities[f.index] == 0: self.file_priorities[f.index] = 3            should_update_priorities = True  if self.torrent_released:            should_update_priorities = True  if should_update_priorities and not f.is_complete(): # Need to do this stuff on seek too self.unrelease()  return f  def shutdown(self):        logger.info('Shutting down torrent %s' % self.infohash) self.do_shutdown = True  for tf in self.torrent_files:            tf.shutdown()  def schedule_piece(self, torrent_file, piece, distance): if torrent_file not in self.priority_increased[piece]: if not self.priority_increased[piece]: self.priority_increased[piece].add(torrent_file)                 logger.debug('Scheduled piece %s at distance %s' % (piece, distance))  self.torrent.handle.piece_priority(piece, (7 if distance <= 4 else 6)) self.torrent.handle.set_piece_deadline(piece, 700*(distance+1))  self.priority_increased[piece].add(torrent_file)  def do_pieces_schedule(self, torrent_file, currently_downloading, from_piece):        logger.debug('Looking for stuff to do with pieces for file %s from piece %s' % (torrent_file, from_piece))         priority_increased = 0        chain_size = 0        download_chain_size = 0        end_of_chain = False         current_buffer_offset = 5 if self.torrent.status.pieces[torrent_file.last_piece]: if torrent_file.first_piece != torrent_file.last_piece and self.torrent.status.pieces[torrent_file.last_piece-1] \ or torrent_file.first_piece == torrent_file.last_piece:                current_buffer_offset = 20  for piece, status in enumerate(self.torrent.status.pieces[from_piece:torrent_file.last_piece+1], from_piece): if not end_of_chain: if status:                    chain_size += 1 elif piece in currently_downloading:                    download_chain_size += 1  if not status and piece not in currently_downloading: if not end_of_chain:                    status_increase = max(11, chain_size-current_buffer_offset)                end_of_chain = True                 priority_increased += 1 if priority_increased >= status_increase:                    logger.debug('Done increasing priority for %i pieces' % status_increase) break  self.schedule_piece(torrent_file, piece, piece-from_piece) else:            logger.info('We are done with the rest of this chain, we might be able to increase others') return True  return False  def update_piece_priority(self): # if all do_pieces_schedule returns true, allow all pices of file to be downloaded or whole torernt if self.do_shutdown: return         logger.debug('Updating piece priority for %s' % self.infohash)         currently_downloading = set() for peer in self.torrent.handle.get_peer_info(): if peer.downloading_piece_index != -1:                currently_downloading.add(peer.downloading_piece_index)         all_heads_done = True for f in self.torrent_files: if not f.file_requested and not f.current_readers: continue             logger.debug('Rescheduling file %s' % f.path)  if f.file_requested:                all_heads_done &= self.do_pieces_schedule(f, currently_downloading, f.first_piece) self.schedule_piece(f, f.last_piece, 0) if f.first_piece != f.last_piece: self.schedule_piece(f, f.last_piece-1, 1)  for tfr in f.current_readers: if tfr.waiting_for_piece is not None:                    logger.debug('Scheduling based on waiting for piece %s' % tfr.waiting_for_piece)                    all_heads_done &= self.do_pieces_schedule(f, currently_downloading, tfr.waiting_for_piece) elif tfr.current_piece is not None:                    logger.debug('Scheduling based on current piece %s' % tfr.current_piece)                    all_heads_done &= self.do_pieces_schedule(f, currently_downloading, tfr.current_piece)  if all(self.torrent.status.pieces):            logger.debug('All pieces complete, no need to loop') return  if all_heads_done and not self.torrent_released:            logger.debug('We are already done with all heads, figuring out what to do next')  if self.torrent_handler.config['reset_complete']: self.torrent_released = True                logger.debug('Resetting all disabled files')                file_priorities = [(1 if fp == 0 else fp) for fp in self.file_priorities] self.torrent.set_file_priorities(file_priorities)  if not all_heads_done and self.torrent_released:            logger.debug('Seems like the torrent was released too early') self.unrelease()         reactor.callLater(0.3, self.update_piece_priority)
class TorrentHandler(object): def __init__(self, config): self.torrents = {} self.config = config  self.alerts = component.get("AlertManager") self.alerts.register_handler("torrent_removed_alert", self.on_alert_torrent_removed)  def get_stream(self, infohash, file_or_index=None, includes_name=False):        logger.info('Trying to stream infohash %s and file %s include_name %s' % (infohash, file_or_index, includes_name)) if infohash not in self.torrents: self.torrents[infohash] = Torrent(self, infohash)  return self.torrents[infohash].get_torrent_file(file_or_index, includes_name)  def on_alert_torrent_removed(self, alert): try:            torrent_id = str(alert.handle.info_hash()) except (RuntimeError, KeyError):            logger.warning('Failed to handle on torrent remove alert') return  if torrent_id not in self.torrents: return  self.torrents[torrent_id].shutdown() del self.torrents[torrent_id]  def shutdown(self):        logger.debug('Shutting down TorrentHandler') self.alerts.deregister_handler(self.on_alert_torrent_removed) for torrent in self.torrents.values():            torrent.shutdown()
class Core(CorePluginBase): def enable(self): self.config = deluge.configmanager.ConfigManager("streaming.conf", DEFAULT_PREFS) self.fsr = FileServeResource()  self.resource = Resource() self.resource.putChild('file', self.fsr) if self.config['allow_remote']: self.resource.putChild('stream', StreamResource(username=self.config['remote_username'], password=self.config['remote_password'], client=self))  self.site = server.Site(self.resource)  try:            session = component.get("Core").session            settings = session.get_settings()            settings['prioritize_partial_pieces'] = True            session.set_settings(settings) except AttributeError:            logger.warning('Unable to exclude partial pieces')  self.torrent_handler = TorrentHandler(self.config)  try: self.listening = reactor.listenTCP(self.config['port'], self.site, interface=self.config['ip']) except: self.listening = reactor.listenTCP(self.config['port'], self.site, interface='0.0.0.0')
 @defer.inlineCallbacks def disable(self): self.site.stopFactory() self.torrent_handler.shutdown() yield self.listening.stopListening()
 def update(self): pass
 @export @defer.inlineCallbacks def set_config(self, config): """Sets the config dictionary""" for key in config.keys(): self.config[key] = config[key] self.config.save()  yield self.disable() self.enable()
 @export def get_config(self): """Returns the config dictionary""" return self.config.config  @export @defer.inlineCallbacks def stream_torrent(self, infohash=None, url=None, filedump=None, filepath_or_index=None, includes_name=False):        tor = component.get("TorrentManager").torrents.get(infohash, None)  if tor is None:            logger.info('Did not find torrent, must add it')  if not filedump and url:                filedump = yield client.getPage(url)  if not filedump:                defer.returnValue({'status': 'error', 'message': 'unable to find torrent, provide infohash, url or filedump'})             torrent_info = lt.torrent_info(lt.bdecode(filedump))            infohash = str(torrent_info.info_hash())             core = component.get("Core") try: yield core.add_torrent_file('file.torrent', filedump.encode('base64'), {'add_paused': True}) except:                defer.returnValue({'status': 'error', 'message': 'failed to add torrent'})  try:            tf = self.torrent_handler.get_stream(infohash, filepath_or_index, includes_name) except UnknownTorrentException:            defer.returnValue({'status': 'error', 'message': 'unable to find torrent, probably failed to add it'})         defer.returnValue({ 'status': 'success', 'use_stream_urls': self.config['use_stream_urls'], 'auto_open_stream_urls': self.config['auto_open_stream_urls'], 'url': 'http://%s:%s/file/%s/%s' % (self.config.config['ip'], self.config.config['port'], self.fsr.add_file(tf), urllib.quote_plus(os.path.basename(tf.path).encode('utf-8')))        })
コード例 #44
0
ファイル: FoFiX.py プロジェクト: zelurker/fofix
def main():
  playing = None
  configFile = None
  fullscreen = None
  resolution = None
  x = None
  y = None
  theme = None
  debug = False
  difficulty = None
  part = None
  mode = 0
  nbrplayers = 1
  for opt, arg in opts:
    if opt in ["--verbose", "-v"]:
      Log.quiet = False
    if opt in ["--debug", "-d"]:
      debug = True
    if opt in ["--config", "-c"]:
      configFile = arg
    if opt in ["--fullscreen", "-f"]:
      fullscreen = arg
    if opt in ["--resolution", "-r"]:
      resolution = arg
    if opt in ["--geometry", "-g"]:
      r = re.match('([0-9]+x\d+)\+?(\d+)?\+?(\d+)?',arg)
      print "geometry tested ",arg
      (resolution,x,y) = r.groups()
      print "found ",resolution," x ",x," y ",y
    if opt in ["--theme", "-t"]:
      theme = arg
    if opt in ["--song", "-s"]:
      playing = arg
    if opt in ["--diff", "-l"]:
      difficulty = arg
    if opt in ["--part", "-p"]:
      part = arg
    #evilynux - Multiplayer and mode selection support
    if opt in ["--mode", "-m"]:
      mode = int(arg)
    if opt in ["--nbrplayers", "-n"]:
      nbrplayers = int(arg)

  # Load the configuration file.
  if configFile is not None:
    if configFile.lower() == "reset":
      fileName = os.path.join(Resource.getWritableResourcePath(), Version.appName() + ".ini")
      os.remove(fileName)
      config = Config.load(Version.appName() + ".ini", setAsDefault = True)
    else:
      config = Config.load(configFile, setAsDefault = True)
  else:
    config = Config.load(Version.appName() + ".ini", setAsDefault = True)

  #Lysdestic - Allow support for manipulating fullscreen via CLI
  if fullscreen is not None:
    Config.set("video", "fullscreen", fullscreen)

  #Lysdestic - Change resolution from CLI
  if resolution is not None:
    Config.set("video", "resolution", resolution)
  if x is not None:
    Config.set("video", "x", x)
    Config.set("video","fullscreen",False)
  if y is not None:
    Config.set("video", "y", y)
    Config.set("video","fullscreen",False)

  #Lysdestic - Alter theme from CLI
  if theme is not None:
    Config.set("coffee", "themename", theme)

  engine = GameEngine(config)
  engine.cmdPlay = 0

  # Check for a valid invocation of one-shot mode.
  if playing is not None:
    Log.debug('Validating song directory for one-shot mode.')
    library = Config.get("game","base_library")
    basefolder = os.path.join(Version.dataPath(),library,"songs",playing)
    if not (os.path.exists(os.path.join(basefolder, "song.ini")) and (os.path.exists(os.path.join(basefolder, "notes.mid")) or os.path.exists(os.path.join(basefolder, "notes-unedited.mid"))) and (os.path.exists(os.path.join(basefolder, "song.ogg")) or os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
      Log.warn("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode." % playing)
      engine.startupMessages.append(_("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode.") % playing)
      playing = None

  # Set up one-shot mode if the invocation is valid for it.
  if playing is not None:
    Log.debug('Entering one-shot mode.')
    Config.set("game", "selected_library", "songs")
    Config.set("game", "selected_song", playing)
    engine.cmdPlay = 1
    if difficulty is not None:
      engine.cmdDiff = int(difficulty)
    if part is not None:
      engine.cmdPart = int(part)
    #evilynux - Multiplayer and mode selection support
    Config.set("game", "players", nbrplayers)
    if nbrplayers == 1:
      Config.set("game", "game_mode", mode)
    else:
      Config.set("game", "game_mode", 0)
      Config.set("game", "multiplayer_mode", mode)

  if debug:
    engine.setDebugModeEnabled(not engine.isDebugModeEnabled())
    engine.debugLayer.debugOut(engine)
    engine.quit()
    return

  encoding = Config.get("game", "encoding")
  if encoding is not None:
    #stump: XXX: Everything I have seen indicates that this is a
    # horrible, horrible hack.  Is there another way?  Do we even need this?
    reload(sys)
    sys.setdefaultencoding(encoding)

  engine.setStartupLayer(MainMenu(engine))

  #stump: make psyco optional
  if Config.get("performance", "use_psyco"):
    try:
      import psyco
      psyco.profile()
    except:
      Log.error("Unable to enable psyco as requested: ")

  # Run the main game loop.
  try:
    engine.ticksAtStart = pygame.time.get_ticks()
    while engine.run():
      pass
  except KeyboardInterrupt:
    Log.notice("Left mainloop due to KeyboardInterrupt.")
    # don't reraise

  # Restart the program if the engine is asking that we do so.
  if engine.restartRequested:
    Log.notice("Restarting.")
    engine.audio.close()
    try:
      # Extra arguments to insert between the executable we call and our
      # command line arguments.
      args = []
      # Figure out what executable to call.
      if hasattr(sys, "frozen"):
        if os.name == "nt":
          # When py2exe'd, sys.executable is the name of the EXE.
          exe = os.path.abspath(unicode(sys.executable, sys.getfilesystemencoding()))
        elif sys.frozen == "macosx_app":
          # When py2app'd, sys.executable is a Python interpreter copied
          # into the same dir where we live.
          exe = os.path.join(os.path.dirname(sys.executable), 'FoFiX')  # FIXME: don't hard-code "FoFiX" here
        else:
          raise RuntimeError, "Don't know how to restart when sys.frozen is %s" % repr(sys.frozen)
      else:
        # When running from source, sys.executable is the Python interpreter
        # being used to run the program.
        exe = sys.executable
        # Pass the optimization level on.
        if sys.flags.optimize > 0:
          args.append('-%s' % ('O' * sys.flags.optimize))
        args.append(__file__)
      os.execv(exe, [sys.executable] + args + sys.argv[1:])
    except:
      Log.error("Restart failed: ")
      raise

  # evilynux - MainMenu class already calls this - useless?
  engine.quit()
コード例 #45
0
ファイル: Log.py プロジェクト: Gamer125/fofix
import sys
import os
import Resource
import Version
import traceback
import time
import warnings

## Whether to output log entries to stdout in addition to the logfile.
quiet = True

## File object representing the logfile.
if os.name == "posix": # evilynux - logfile in ~/.fofix/ for GNU/Linux and MacOS X
  # evilynux - Under MacOS X, put the logs in ~/Library/Logs
  if os.uname()[0] == "Darwin":
    logFile = open(os.path.join(Resource.getWritableResourcePath(), 
                                "..", "..", "Logs",
                                Version.PROGRAM_UNIXSTYLE_NAME + ".log"), "w")
  else: # GNU/Linux et al.
    logFile = open(os.path.join(Resource.getWritableResourcePath(), Version.PROGRAM_UNIXSTYLE_NAME + ".log"), "w")
else:
  logFile = open(Version.PROGRAM_UNIXSTYLE_NAME + ".log", "w")  #MFH - local logfile!

## Character encoding to use for logging.
encoding = "iso-8859-1"

if "-v" in sys.argv or "--verbose" in sys.argv:
  quiet = False

## Labels for different priorities, as output to the logfile.
labels = {
コード例 #46
0
ファイル: FoFiX.py プロジェクト: Gamer125/fofix
def main():
  """Main thread"""

  try:
    opts, args = getopt.getopt(sys.argv[1:], "vdc:f:r:t:s:l:p:m:n:", ["verbose", "debug", "config=", "fullscreen=", "resolution=", "theme=", "song=", "diff=", "part=", "mode=", "nbrplayers="])
  except getopt.GetoptError:
    print usage
    sys.exit(1)
    
  playing = None
  configFile = None
  fullscreen = None
  resolution = None
  theme = None
  debug = False
  difficulty = None
  part = None
  mode = 0
  nbrplayers = 1
  for opt, arg in opts:
    if opt in ["--verbose", "-v"]:
      Log.quiet = False
    if opt in ["--debug", "-d"]:
      debug = True
    if opt in ["--config", "-c"]:
      configFile = arg
    if opt in ["--fullscreen", "-f"]:
      fullscreen = arg
    if opt in ["--resolution", "-r"]:
      resolution = arg
    if opt in ["--theme", "-t"]:
      theme = arg
    if opt in ["--song", "-s"]:
      playing = arg
    if opt in ["--diff", "-l"]:
      difficulty = arg      
    if opt in ["--part", "-p"]:
      part = arg
    #evilynux - Multiplayer and mode selection support
    if opt in ["--mode", "-m"]:
      mode = int(arg)
    if opt in ["--nbrplayers", "-n"]:
      nbrplayers = int(arg)
      
  while 1:
    if configFile != None:
      if configFile.lower() == "reset":
        fileName = os.path.join(Resource.getWritableResourcePath(), Version.appName() + ".ini")
        os.remove(fileName)
        config = Config.load(Version.appName() + ".ini", setAsDefault = True)
      else:
        config = Config.load(configFile, setAsDefault = True)
    else:
      config = Config.load(Version.appName() + ".ini", setAsDefault = True)

    #Lysdestic - Allow support for manipulating fullscreen via CLI
    if fullscreen != None:
      Config.set("video", "fullscreen", fullscreen)

    #Lysdestic - Change resolution from CLI
    if resolution != None:
      Config.set("video", "resolution", resolution)

    #Lysdestic - Alter theme from CLI
    if theme != None:
      Config.set("coffee", "themename", theme)
    
    if playing != None:
      library = Config.get("game","base_library")
      basefolder = os.path.join(Version.dataPath(),library,"songs",playing)
      if not (os.path.exists(os.path.join(basefolder, "song.ini")) and (os.path.exists(os.path.join(basefolder, "notes.mid")) or os.path.exists(os.path.join(basefolder, "notes-unedited.mid"))) and (os.path.exists(os.path.join(basefolder, "song.ogg")) or os.path.exists(os.path.join(basefolder, "guitar.ogg")))):
        Log.warn("Song directory provided ('%s') is not a valid song directory. Starting up FoFiX in standard mode." % playing)
        playing = None

    engine = GameEngine(config)
    engine.cmdPlay = 0
    
    if playing != None:
      Config.set("game", "selected_library", "songs")
      Config.set("game", "selected_song", playing)
      engine.cmdPlay = 1
      if difficulty is not None:
        engine.cmdDiff = int(difficulty)
      if part is not None:
        engine.cmdPart = int(part)
      #evilynux - Multiplayer and mode selection support
      Config.set("game", "players", nbrplayers)
      if nbrplayers == 1:
        Config.set("game", "game_mode", mode)
      else:
        Config.set("game", "game_mode", 0)
        Config.set("game", "multiplayer_mode", mode)

    if debug == True:
      engine.setDebugModeEnabled(not engine.isDebugModeEnabled())
      engine.debugLayer.debugOut(engine)
      engine.quit()
      break
      
    encoding = Config.get("game", "encoding")
    if encoding != None:
      reload(sys)
      sys.setdefaultencoding(encoding)
    engine.setStartupLayer(MainMenu(engine))

    #stump: make psyco optional
    if Config.get("performance", "use_psyco"):
      try:
        import psyco
        psyco.profile()
      except:
        Log.warn("Unable to enable psyco.")

    try:
      engine.ticksAtStart = pygame.time.get_ticks()
      while engine.run():
        pass
    except KeyboardInterrupt:
        pass
    if engine.restartRequested:
      Log.notice("Restarting.")
      engine.audio.close()
      try:
        # Determine whether were running from an exe or not
        if hasattr(sys, "frozen"):
          if os.name == "nt":
            os.execl("FoFiX.exe", "FoFiX.exe", *sys.argv[1:])
          elif sys.frozen == "macosx_app":
            import string
            import subprocess
            appname = string.join(string.split(sys.executable, '/')[:-1], '/')
            appname = appname+"/FoFiX"
            subprocess.Popen(`appname`, shell=True)
          else:
            os.execl("./FoFiX", "./FoFiX", *sys.argv[1:])
        else:
          # stump: sys.executable points to the active python interpreter
          os.execl(sys.executable, sys.executable, "FoFiX.py", *sys.argv[1:])
      except:
        Log.warn("Restart failed.")
        raise
      break
    else:
      break
  # evilynux - MainMenu class already calls this - useless?
  engine.quit()
コード例 #47
0
ファイル: FretsOnFire.py プロジェクト: Gamer125/fofix
def main():
  """Main thread"""

  try:
    opts, args = getopt.getopt(sys.argv[1:], "vdc:p:D:P:m:N:", ["verbose", "debug", "config=", "play=", "diff=", "part=", "mode=", "nbrplayers="])
  except getopt.GetoptError:
    print usage
    sys.exit(1)
    
  playing = None
  configFile = None
  debug = False
  difficulty = 0
  part = 0
  mode = 0
  nbrplayers = 1
  for opt, arg in opts:
    if opt in ["--verbose", "-v"]:
      Log.quiet = False
    if opt in ["--debug", "-d"]:
      debug = True
    if opt in ["--config", "-c"]:
      configFile = arg
    if opt in ["--play", "-p"]:
      playing = arg
    if opt in ["--diff", "-D"]:
      difficulty = arg      
    if opt in ["--part", "-P"]:
      part = arg
    #evilynux - Multiplayer and mode selection support
    if opt in ["--mode", "-m"]:
      mode = int(arg)
    if opt in ["--nbrplayers", "-N"]:
      nbrplayers = int(arg)
      
  while True:
    if configFile != None:
      if configFile.lower() == "reset":
        fileName = os.path.join(Resource.getWritableResourcePath(), Version.appName() + ".ini")
        os.remove(fileName)
        config = Config.load(Version.appName() + ".ini", setAsDefault = True)
      else:
        config = Config.load(configFile, setAsDefault = True)
    else:
      config = Config.load(Version.appName() + ".ini", setAsDefault = True)
    engine = GameEngine(config)
    engine.cmdPlay = 0
    
    if playing != None:
      Config.set("game", "selected_library", "songs")
      Config.set("game", "selected_song", playing)
      engine.cmdPlay = 1
      engine.cmdDiff = int(difficulty)
      engine.cmdPart = int(part)
      #evilynux - Multiplayer and mode selection support
      Config.set("game", "players", nbrplayers)
      Config.set("player0","mode_1p", mode)
      Config.set("player1","mode_2p", mode)

    if debug == True:
      engine.setDebugModeEnabled(not engine.isDebugModeEnabled())
      engine.debugLayer.debugOut(engine)
      engine.quit()
      break
      
    encoding = Config.get("game", "encoding")
    if encoding != None:
      reload(sys)
      sys.setdefaultencoding(encoding)
    engine.setStartupLayer(MainMenu(engine))

    try:
      import psyco
      psyco.profile()
    except:
      Log.warn("Unable to enable psyco.")

    try:
      while engine.run():
        pass
    except KeyboardInterrupt:
        pass
    if engine.restartRequested:
      Log.notice("Restarting.")
      engine.audio.close()
      try:
        # Determine whether were running from an exe or not
        if hasattr(sys, "frozen"):
          if os.name == "nt":
            os.execl("FretsOnFire.exe", "FretsOnFire.exe", *sys.argv[1:])
          elif sys.frozen == "macosx_app":
            import string
            import subprocess
            appname = string.join(string.split(sys.executable, '/')[:-1], '/')
            appname = appname+"/Frets on Fire"
            subprocess.Popen(`appname`, shell=True)
          else:
            os.execl("./FretsOnFire", "./FretsOnFire", *sys.argv[1:])
        else:
          if os.name == "nt":
            bin = "c:/python24/python"
          else:
            bin = "/usr/bin/python2.4"
          os.execl(bin, bin, "FretsOnFire.py", *sys.argv[1:])
      except:
        Log.warn("Restart failed.")
        raise
      break
    else:
      break
  engine.quit()