def LoadSounds():
    pGame = App.Game_GetCurrentGame()

    # Get the Bridge sound region and put these sounds in that region.
    pBridgeRegion = App.TGSoundRegion_GetRegion("bridge")

    # Make sure the region has no filters muting it..
    pBridgeRegion.SetFilter(App.TGSoundRegion.FT_NONE)

    for sFile, sSound, fVolume in (
        ("sfx/bridge2.loop.wav", "AmbBridge", 1.0),
        ("sfx/redalert.wav", "RedAlertSound", 1.0),
        ("sfx/yellowalert.wav", "YellowAlertSound", 1.0),
        ("sfx/greenalert.wav", "GreenAlertSound", 1.0),
        ("sfx/critical.wav", "CollisionAlertSound", 1.0),
        ("sfx/hail.wav", "ViewOn", 1.0),
        ("sfx/ViewscreenOff.WAV", "ViewOff", 1.0),
        ("sfx/Bridge/console_explo_01.wav", "ConsoleExplosion1", 0.5),
        ("sfx/Bridge/console_explo_02.wav", "ConsoleExplosion2", 0.5),
        ("sfx/Bridge/console_explo_03.wav", "ConsoleExplosion3", 0.5),
        ("sfx/Bridge/console_explo_04.wav", "ConsoleExplosion4", 0.5),
        ("sfx/Bridge/console_explo_05.wav", "ConsoleExplosion5", 0.5),
        ("sfx/Bridge/console_explo_06.wav", "ConsoleExplosion6", 0.5),
        ("sfx/Bridge/console_explo_07.wav", "ConsoleExplosion7", 0.5),
        ("sfx/Bridge/console_explo_08.wav", "ConsoleExplosion8", 0.5),
        ("sfx/Bridge/bridge_loop_warp.wav", "InSystemWarp", 1.0),
    ):

        pSound = pGame.LoadSoundInGroup(sFile, sSound, "BridgeGeneric")
        pBridgeRegion.AddSound(pSound)
        pSound.SetVolume(fVolume)
def get_serials_from_index_page(block_class):
    items = []

    content = App.http_request(URL)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        block = html.find(class_=block_class)
        if block is not None:
            for serial in block.find_all('li'):
                link = serial.find('a')
                img = link.find('img')

                url = link.get('href')
                cover = img.get('src')
                label = img.get('title')

                items.append({
                    'label':
                    label,
                    'thumb':
                    cover,
                    'art': {
                        'poster': cover
                    },
                    'url':
                    P.get_url(action='ns_serial_seasons', url=url)
                })
    return App.create_listing(items, content='tvshows')
Exemplo n.º 3
0
 def test_logout_attempt_assign_afterwards(self):
     # assume user logged in
     a = App()
     result = a.command('logout')
     self.assertEquals(result, 'Logout successful.')
     result = a.command('assign TA')
     self.assertEquals(result, 'Command unavailable. No user logged in.')
def co_index(params):
    # response = App.http_request(URL, response='headers')
    # if 'set-cookie' in response:
    #     for resp in response['set-cookie'].split(';'):
    #         keyvalue = resp.split('=')
    #         if (keyvalue[0] == 'PHPSESSID'):
    #             STORAGE['cookie'] = resp
    #             break

    return [{
        'label': '[ Поиск ]',
        'icon': App.get_media('find'),
        'url': P.get_url(action='co_search')
    }, {
        'label': App.format_bold('Новинки'),
        'url': P.get_url(action='co_movies', order_id='0')
    }, {
        'label': 'Популярное',
        'url': P.get_url(action='co_bestsellers')
    }, {
        'label': 'По жанрам',
        'url': P.get_url(action='co_genres')
    }, {
        'label': 'Лучшие по версии IMDB',
        'url': P.get_url(action='co_movies', order_id='2')
    }, {
        'label': 'Лучшие по версии КиноПоиск',
        'url': P.get_url(action='co_movies', order_id='9')
    }]
def co_bestsellers(params):
    items = []
    content = App.http_request(API, 'POST', {'action[0]': 'Video.getBestsellers'})
    if content:
        data = json.loads(content)['json'][0]['response']
        for category in data['bestsellers']:
            for movie in category['movies']:
                cover = get_bigger_cover(movie['cover'])

                items.append({
                    'label': App.replace_html_codes('[B]%s[/B] %s' % (movie['name'], category['name'])),
                    'thumb': cover,
                    'fanart': cover,
                    'art': {
                        'poster': cover
                    },
                    'info': {
                        'video': {
                            'year': movie['year'],
                        }
                    },
                    'url': P.get_url(action='co_movie', id=movie['movie_id'])
                })

    return App.create_listing(items, content='movies')
def get_serials_from_index_page(block_class):
    items = []

    content = App.http_request(URL)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        block = html.find(class_=block_class)
        if block is not None:
            for serial in block.find_all('li'):
                link = serial.find('a')
                img = link.find('img')

                url = link.get('href')
                cover = img.get('src')
                label = img.get('title')

                items.append({
                    'label': label,
                    'thumb': cover,
                    'art': {
                        'poster': cover
                    },
                    'url': P.get_url(action='ns_serial_seasons', url=url)
                })
    return App.create_listing(items, content='tvshows')
def co_bestsellers(params):
    items = []
    content = App.http_request(API, 'POST',
                               {'action[0]': 'Video.getBestsellers'})
    if content:
        data = json.loads(content)['json'][0]['response']
        for category in data['bestsellers']:
            for movie in category['movies']:
                cover = get_bigger_cover(movie['cover'])

                items.append({
                    'label':
                    App.replace_html_codes('[B]%s[/B] %s' %
                                           (movie['name'], category['name'])),
                    'thumb':
                    cover,
                    'fanart':
                    cover,
                    'art': {
                        'poster': cover
                    },
                    'info': {
                        'video': {
                            'year': movie['year'],
                        }
                    },
                    'url':
                    P.get_url(action='co_movie', id=movie['movie_id'])
                })

    return App.create_listing(items, content='movies')
Exemplo n.º 8
0
def plotly_data(interface):
    bottle.response.content_type = 'application/json; charset=UTF8'
    json_blob = json.loads(json_filtered(interface))

    App.vnstat_graph(json_blob)

    return json.dumps(json_blob)
Exemplo n.º 9
0
 def test_logout_login_again(self):
     # assume user logged in
     a = App()
     result = a.command('logout')
     self.assertEquals(result, 'Logout successful.')
     result = a.command('login username password')
     self.assertEquals(result, 'Login successful.')
Exemplo n.º 10
0
def nm_top(params):
    items = []

    content = App.http_request(URL + '/movie/')
    if content:
        html = BeautifulSoup(content, 'html.parser')
        block = html.find(class_='charts-block')
        if block is not None:
            for movie in block.find_all(class_='changed'):
                link = movie.find('a')
                img = link.find('img')

                id = link.get('href').split('=')[1]
                cover = img.get('src')
                label = img.get('title')

                items.append({
                    'label': label,
                    'thumb': cover,
                    'art': {
                        'poster': cover
                    },
                    'url': P.get_url(action='nm_movie', id=id)
                })
    return App.create_listing(items, content='movies')
Exemplo n.º 11
0
def ToggleSelection(pObject, pEvent):
	pMyShip = ftb.ShipHandlers.GetShip(App.Game_GetCurrentPlayer())
	pButton = App.STButton_Cast(pEvent.GetSource())
	if(pButton.IsChosen()):
		pMyShip.lSecondaryTargets.append(ftb.ShipHandlers.GetTargetByIdx(pEvent.GetInt()))
	else:
		pMyShip.lSecondaryTargets.remove(ftb.ShipHadnlers.GetTargetByIdx(pEvent.GetInt()))
def create_movie_item(episode_url, label, cover):
    item = {}

    content = App.http_request(URL + episode_url)
    if content:
        video_id = re.compile('<param value="config=.+?__(.+?)" name="flashvars">').findall(content)[0]
        content = App.http_request('%s/?%s' % (API, urllib.urlencode({
            'service': 'video',
            'action': 'video',
            'id': video_id
        })))
        if content:
            movie = json.loads(content)['video']

            item = {
                'label': label,
                'thumb': cover,
                'art': {
                    'poster': cover
                },
                'stream_info': {
                    'video': {
                        'duration': App.timestring2seconds(movie['duration'])
                    }
                },
                'info': {
                    'video': {
                        'plot': '' if App.get_skin_name() == 'skin.confluence' else movie['raw_description']
                    }
                },
                'url': movie['download']['flv'],
                'is_playable': True,
            }
    return item
 def test_assign_nonexistant_TA_as_supervisor(self):
     # Assume user logged in as supervisor
     a = App()
     result = a.command('assign TA')
     self.assertEquals(result, 'Name or username?: ')
     result = a.respond_to_prompt('Kurt Cobain')
     self.assertEquals(result, 'TA does not exist.')
Exemplo n.º 14
0
def ValidaPrecoMymoney():
    App.AbrirOrders()
    Principal.AcessarFormularioDeOrders()
    Order.EscolherProduto('MyMoney')
    Order.ValidarPreco('$100')
    Order.ClicarCancelar()
    App.FecharOrders()
def ns_serials_by_genre(params):
    items = []
    P.log_error(params.url)
    content = App.http_request(URL + params.url)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        block = html.find(class_='serials-list')
        for serial in block.find_all('li'):
            link = serial.find('a')
            img = link.find('img')

            url = link.get('href')
            cover = img.get('src')
            label = img.get('title').strip()

            items.append({
                'label': label,
                'thumb': cover,
                'art': {
                    'poster': cover
                },
                'url': P.get_url(action='ns_serial_seasons', url=url)
            })

    return App.create_listing(items, content='tvshows')
Exemplo n.º 16
0
def ts_index(params):
    items = []
    content = App.http_request(URL + '/show')
    if content:
        items.append({
            'label': '[ Поиск ]',
            'url': P.get_url(action='ts_search'),
            'icon': App.get_media('find')
        })
        items.append({
            'label': App.format_bold('Последние поступления'),
            'url': P.get_url(action='ts_last_added'),
        })

        html = BeautifulSoup(content, 'html.parser')
        categories = html.find(id='filter-category')

        for option in categories.find_all('option'):
            id = option.get('value')
            if id == '0':
                continue

            label = option.get_text()
            items.append({
                'label': label,
                'url': P.get_url(action='ts_category', id=id)
            })
    return App.create_listing(items)
def get_description(info):
    description = ''
    if 'description' in info:
        description = info['description']
    if 'long_description' in info:
        description = info['long_description']

    director = App.STR_NO_DATA
    if 'directors' in info:
        director = App.explode_info_string(info['directors'])

    # name_original = info['international_name']

    rating = get_movie_rating_value(info, 'rating_imdb_count',
                                    'rating_imdb_value')
    if rating == '':
        rating = get_movie_rating_value(info, 'rating_kinopoisk_count',
                                        'rating_kinopoisk_value')

    return App.format_description(
        country=App.explode_info_string(info['countries'])
        if 'countries' in info else '',
        genre='' if App.get_skin_name() != 'skin.estuary' else
        App.explode_info_string(info['genres']) if 'genres' in info else '',
        description=description.replace('<br>', '\n').encode('utf-8'),
        director=director,
        rating=rating)
Exemplo n.º 18
0
def WatchShipLeave(pAction, sSet, sObjectName, sCamera = "CutsceneCam"):
	pSet = App.g_kSetManager.GetSet(sSet)

	if not pSet:
		return 0

	pCamera = App.CameraObjectClass_GetObject(pSet, sCamera)

	if not pCamera:
		return 0

	pAction = App.TGScriptAction_Create("Actions.CameraScriptActions", 
							  "DropAndWatch", sSet, sObjectName)

	pAction.Play()

	pMode = pCamera.GetCurrentCameraMode()
	if not pMode:
		return 0

	pMode.SetAttrFloat("AwayDistance", -1.0)
	pMode.SetAttrFloat("ForwardOffset", -7.0)
	pMode.SetAttrFloat("SideOffset", -7.0)
	pMode.SetAttrFloat("RangeAngle1", 230.0)
	pMode.SetAttrFloat("RangeAngle2", 310.0)
	pMode.SetAttrFloat("RangeAngle3", -10.0)
	pMode.SetAttrFloat("RangeAngle4", 10.0)
	pMode.Update()
	pMode.SetAttrFloat("AwayDistance", 100000.0)

	return 0
Exemplo n.º 19
0
def SetCameraPositionAndFacing(pAction, sSetName, sCameraName,
							   fPosX, fPosY, fPosZ,
							   fFwdX, fFwdY, fFwdZ,
							   fUpX, fUpY, fUpZ):
	pSet = App.g_kSetManager.GetSet(sSetName)
	if (pSet == None):
		return 0

	pCamera = App.CameraObjectClass_GetObject(pSet, sCameraName)
	if (pCamera == None):
		return 0

	kPoint = App.TGPoint3()
	kPoint.SetXYZ(fPosX, fPosY, fPosZ)

	kFwd = App.TGPoint3()
	kFwd.SetXYZ(fFwdX, fFwdY, fFwdZ)

	kUp = App.TGPoint3()
	kUp.SetXYZ(fUpX, fUpY, fUpZ)

	pCamera.SetTranslate(kPoint)
	pCamera.AlignToVectors(kFwd, kUp)

	return 0
Exemplo n.º 20
0
 def test_editCourse(self):
     a = App()
     result = a.command('edit Course')
     # will fail:
     #           if TA/Instructors attempt to edit course
     #           if course doesnot exist
     self.assertEqual(result, 'course edited successfully')
Exemplo n.º 21
0
def SetViewscreenCamera(pAction, sSetName, sCameraName = None):
	pBridge = App.BridgeSet_Cast(App.g_kSetManager.GetSet("bridge"))
	pSet = App.g_kSetManager.GetSet(sSetName)

	if (pBridge == None) or (pSet == None):
		return 0

	pViewscreen = pBridge.GetViewScreen()
	if (sCameraName != None):
		pCamera = App.CameraObjectClass_GetObject(pSet, sCameraName)
	else:
		pCamera = pSet.GetActiveCamera()
		if (pCamera == None):
			# Try getting the player's camera from the game.
			pCamera = App.Game_GetPlayerCamera()

			if (pCamera == None):
				# Try getting "MainPlayerCamera".
				pCamera = App.CameraObjectClass_GetObject(pSet, "MainPlayerCamera")

	if (pViewscreen == None) or (pCamera == None):
		return 0

	pViewscreen.SetRemoteCam(pCamera)
	pViewscreen.SetIsOn(1)

	return 0
def ns_serials_by_genre(params):
    items = []
    P.log_error(params.url)
    content = App.http_request(URL + params.url)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        block = html.find(class_='serials-list')
        for serial in block.find_all('li'):
            link = serial.find('a')
            img = link.find('img')

            url = link.get('href')
            cover = img.get('src')
            label = img.get('title').strip()

            items.append({
                'label': label,
                'thumb': cover,
                'art': {
                    'poster': cover
                },
                'url': P.get_url(action='ns_serial_seasons', url=url)
            })

    return App.create_listing(items, content='tvshows')
def co_index(params):
    # response = App.http_request(URL, response='headers')
    # if 'set-cookie' in response:
    #     for resp in response['set-cookie'].split(';'):
    #         keyvalue = resp.split('=')
    #         if (keyvalue[0] == 'PHPSESSID'):
    #             STORAGE['cookie'] = resp
    #             break


    return [{
        'label': '[ Поиск ]',
        'icon': App.get_media('find'),
        'url': P.get_url(action='co_search')
    }, {
        'label': App.format_bold('Новинки'),
        'url': P.get_url(action='co_movies', order_id='0')
    }, {
        'label': 'Популярное',
        'url': P.get_url(action='co_bestsellers')
    }, {
        'label': 'По жанрам',
        'url': P.get_url(action='co_genres')
    }, {
        'label': 'Лучшие по версии IMDB',
        'url': P.get_url(action='co_movies', order_id='2')
    }, {
        'label': 'Лучшие по версии КиноПоиск',
        'url': P.get_url(action='co_movies', order_id='9')
    }]
Exemplo n.º 24
0
def CreateAndPopulateBridgeSet():
    #   kDebugObj.Print("Creating the generic bridge set")

    pBridgeSet = App.BridgeSet_Create()
    App.g_kSetManager.AddSet(pBridgeSet, "bridge")

    # Create ambient light source
    pBridgeSet.CreateAmbientLight(1.000000, 1.000000, 1.000000, 0.7000000,
                                  "ambientlight1")
    pLight = pBridgeSet.GetLight("ambientlight1")
    pLight.UnilluminateEntireSet()
    CreateCharacterMenus()

    # Load bridge characters
    Bridge.Characters.Felix.CreateCharacter(pBridgeSet)
    Bridge.Characters.Kiska.CreateCharacter(pBridgeSet)
    Bridge.Characters.Saffi.CreateCharacter(pBridgeSet)
    Bridge.Characters.Miguel.CreateCharacter(pBridgeSet)
    Bridge.Characters.Brex.CreateCharacter(pBridgeSet)

    # Load some random extras...
    import MissionLib
    for i in range(3):
        pcPath = None

        if (App.g_kSystemWrapper.GetRandomNumber(2) == 0):
            pcPath = "Bridge.Characters.FemaleExtra" + str(i + 1)
        else:
            pcPath = "Bridge.Characters.MaleExtra" + str(i + 1)

        pModule = __import__(pcPath)
        pModule.CreateCharacter(pBridgeSet)

    # Load up the generic bridge sounds
    LoadSounds()

    # Ambient looping bridge SFX
    pSound = App.g_kSoundManager.GetSound("AmbBridge")
    if (pSound != None):
        pSound.SetLooping(1)
        pSound.SetPriority(1.0)
        pSound.Play()

    # Setup the handler function, if it hasn't been setup already
    global ET_BRIDGE_BEEP, g_idBeepTimer
    if (ET_BRIDGE_BEEP == 0):
        ET_BRIDGE_BEEP = App.Game_GetNextEventType()
        pGame = App.Game_GetCurrentGame()
        pGame.AddPythonFuncHandlerForInstance(ET_BRIDGE_BEEP,
                                              "LoadBridge.BridgeBeep")
    g_idBeepTimer = App.NULL_ID

    # Start off the beeping immediately
    #NewBeep(0)

    # Preload any common animations common to multiple bridges
    PreloadCommonAnimations()

    #   kDebugObj.Print("End of creating the generic bridge set")
    return pBridgeSet
Exemplo n.º 25
0
def LaunchShip(pObject, pEvent):
    global pLaunchButton, launchTypeSave, launchTypeSaveNum, ShuttleLaunchShip, pShipMenu

    pLaunchShip = MissionLib.GetShip(ShuttleLaunchShip)
    pFTBCarrier = ftb.ShipManager.GetShip(pLaunchShip)
    if not pFTBCarrier:  # Our previous Ship maybe destroyed
        pShipMenu.SetName(App.TGString("None" + " " + "Selected"))
        return
    if pLaunchShip.IsCloaked():  # No we can't launch Ships while cloaked
        print("Sorry, can't launch while cloaked")
        return
    launcherIndex = pEvent.GetInt()
    if not hasattr(
            pFTBCarrier, "GetLaunchers"
    ):  # Our previous Ship maybe destroyed or is not configured to have Shuttles
        pShipMenu.SetName(App.TGString("None" + " " + "Selected"))
        return
    pFTBLauncher = pFTBCarrier.GetLaunchers()[launcherIndex]
    sShipName = pFTBLauncher.GetLaunchType()
    # test for the right selection here.
    if (launchTypeSaveNum != pFTBLauncher.GetNumLaunches(sShipName)
            or str(launchTypeSave) != str(sShipName)):
        ToggleLaunchType(None, None)
        return
    pFTBLauncher.LaunchShip(sShipName)
    if (pFTBLauncher.HasMoreLaunches(sShipName) == 0):
        pFTBLauncher.NextLaunchType()
    launchTypeSave = pFTBLauncher
    SetToggleLaunchButton()
    pLaunchButton[launcherIndex].SetDisabled()
Exemplo n.º 26
0
def SetToggleLaunchButton():
    global ButtonToggleLaunchType, launchTypeSave, launchTypeSaveNum, pLaunchButton, ShuttleLaunchShip

    pLaunchShip = MissionLib.GetShip(ShuttleLaunchShip)
    pFTBCarrier = ftb.ShipManager.GetShip(pLaunchShip)
    if not hasattr(
            pFTBCarrier, "GetLaunchers"
    ):  # Our previous Ship maybe destroyed or is not configured to have Shuttles
        pShipMenu.SetName(App.TGString("None" + " " + "Selected"))
        return
    pFTBLauncher = pFTBCarrier.GetLaunchers()
    numTypes = len(pFTBLauncher)
    launcherIndex = 0

    # cycle our whole Shuttle Type list
    for index in range(numTypes):
        launchType = pFTBLauncher[index].GetLaunchType()
        numLaunches = pFTBLauncher[index].GetNumLaunches(launchType)
        buttonLabel = launchType + ": " + str(numLaunches)
        ButtonToggleLaunchType.SetName(App.TGString(buttonLabel))
        launcherIndex = index

    # Test if the the Start Button is disabled but we still have Shuttles
    if (numLaunches > 0 and not pLaunchButton[launcherIndex].IsEnabled()):
        # Now lets make the launching Framework operational again.
        pLaunchButton[launcherIndex].SetEnabled()
        launcher = ftb.LauncherManager.GetLauncher(
            ReturnShuttles.GetFirstShuttleBayName(), pLaunchShip)
        launcher.SetClearToLaunch(1)

    # Saves the vars. We can use them for testing later.
    launchTypeSave = launchType
    launchTypeSaveNum = numLaunches
Exemplo n.º 27
0
def start():
    global skautis_token
    skautis_token = request.post['skautIS_Token']
    App.checker(skautis_token, App.cfg['unit'])
    logout_link = App.skautis.get_logout_url(skautis_token)
    response.body = logout_link
    skautis_token = None
    return response
def FixCollisions(pShip):
    pSet = pShip.GetContainingSet()
    pPlayer = App.ShipClass_GetObject(pSet, "Player")
    if pPlayer != None:
        pShip.EnableCollisionsWith(pPlayer, 1)
    else:
        pPlayer = App.ShipClass_GetObject(pSet, "player")
        pShip.EnableCollisionsWith(pPlayer, 1)
Exemplo n.º 29
0
def ToggleSecondaryTarget(pObject, pEvent):
    pPlayer = App.Game_GetCurrentPlayer()
    if pPlayer:
        pMyShip = GetShip(pPlayer)
        #pMyShip.ToggleSecondaryTarget( GetTargetByIdx( pEvent.GetInt()))
        if pPlayer.GetTarget():
            pMyShip.ToggleSecondaryTarget(
                App.ShipClass_Cast(pPlayer.GetTarget()))
Exemplo n.º 30
0
 def test_logout_login_as_other_user(self):
     # assume user logged in as Supervisor(username)
     # assume otherusername exists in the system and is a TA
     a = App()
     result = a.command('logout')
     self.assertEquals(result, 'Logout successful')
     result = a.command('login otherusername otherpassword')
     self.assertEquals(result, 'Login successful.')
     result = a.command('assign TA')
     self.assertEquals(result, 'Command unavailable.')
 def test_assign_TA_to_nonexistant_course_as_supervisor(self):
     # Assume user logged in as supervisor
     # Assume TA exists
     a = App()
     result = a.command('assign TA')
     self.assertEquals(result, 'Name or Username?: ')
     result = a.respond_to_prompt('Grant Wheeler')
     self.assertEquals(result, 'Course?: ')
     result = a.respond_to_prompt('CS575')
     self.assertEqual(result, 'Course does not exist.')
def GetFirstShuttleBayName(sFiringShipName=None):
    if not App.Game_GetCurrentPlayer().GetName():
        return
    if not sFiringShipName:
        sFiringShipName = App.Game_GetCurrentPlayer().GetName()

    ShuttleBayName = GetOEPs(sFiringShipName)  #calling Sim Rex's Function
    if not ShuttleBayName:
        return
    return ShuttleBayName[0]  # yes, thats the easy Version ;)
def co_movie(params):
    items = []

    request_data = sorted([
        ('action[0]', 'Video.getMovie'),
        ('movie_id[0]', params.id)
    ])
    content = App.http_request(API, 'POST', request_data)
    if content:
        movie = json.loads(content)['json'][0]['response']['movie']

        cover = '{0}/{1}'.format(URL, movie['covers'][0]['thumbnail'])

        for file in movie['files']:
            duration = ''
            url = P.get_url(action='co_movie_playlist', id=movie['movie_id'])

            if file['is_dir']:
                label = App.replace_html_codes(movie['name'] + '&emsp;Плейлист'.decode('utf-8'))
            else:
                label = file['name'] if len(movie['files']) > 1 else movie['name']
                url = file['path'].replace('/home/video/', 'http://p0.oc.kg:8080/')
                duration = file['metainfo']['playtime_seconds']

            items.append(
                {
                    'label': label,
                    'thumb': cover,
                    'art': {
                        'poster': cover
                    },
                    'stream_info': {
                        'video': {
                            'duration': duration
                        }
                    },
                    'info': {
                        'video': {
                            'plot': get_description(movie),
                            'year': movie['year'],
                            'mpaa': movie['mpaa'],
                            'title': movie['name'],
                            'originaltitle': movie['international_name'],
                        }
                    },
                    'url': url,
                    'is_playable': not(file['is_dir']),
                    'is_folder': not(file['is_dir']),
                }
            )

            if file['is_dir']:
                break

    return App.create_listing(items, content='movies')
def co_movie(params):
    items = []

    request_data = sorted([('action[0]', 'Video.getMovie'),
                           ('movie_id[0]', params.id)])
    content = App.http_request(API, 'POST', request_data)
    if content:
        movie = json.loads(content)['json'][0]['response']['movie']

        cover = '{0}/{1}'.format(URL, movie['covers'][0]['thumbnail'])

        for file in movie['files']:
            duration = ''
            url = P.get_url(action='co_movie_playlist', id=movie['movie_id'])

            if file['is_dir']:
                label = App.replace_html_codes(
                    movie['name'] + '&emsp;Плейлист'.decode('utf-8'))
            else:
                label = file['name'] if len(
                    movie['files']) > 1 else movie['name']
                url = file['path'].replace('/home/video/',
                                           'http://p0.oc.kg:8080/')
                duration = file['metainfo']['playtime_seconds']

            items.append({
                'label': label,
                'thumb': cover,
                'art': {
                    'poster': cover
                },
                'stream_info': {
                    'video': {
                        'duration': duration
                    }
                },
                'info': {
                    'video': {
                        'plot': get_description(movie),
                        'year': movie['year'],
                        'mpaa': movie['mpaa'],
                        'title': movie['name'],
                        'originaltitle': movie['international_name'],
                    }
                },
                'url': url,
                'is_playable': not (file['is_dir']),
                'is_folder': not (file['is_dir']),
            })

            if file['is_dir']:
                break

    return App.create_listing(items, content='movies')
Exemplo n.º 35
0
def CreateIntButton(name, eventType, eventDest, intVal, tglDatabase=None):
    button = None
    event = App.TGIntEvent_Create()
    event.SetEventType(eventType)
    event.SetInt(intVal)
    event.SetDestination(eventDest)
    if (tglDatabase == None):
        button = App.STButton_Create(name, event)
    else:
        button = App.STButton_CreateW(tglDatabase.GetString(name), event)
    return button
Exemplo n.º 36
0
 def test_assign_TA_not_assigned_to_course(self):
     # Assume user logged in as instructor
     # Assume TA exists
     # Assume TA NOT assigned to course by supervisor
     a = App()
     result = a.command('assign TA')
     self.assertEquals(result, 'Name or Username?: ')
     result = a.respond_to_prompt('wheelerg')
     self.assertEquals(result, 'Course?: ')
     result = a.respond_to_prompt('CS361')
     self.assertEqual(result, 'TA not assigned to this course.')
Exemplo n.º 37
0
def stop():
	response = App.status()
	if not response:
		print 'Service ' + __service__ + ' not running.'
		return

	status = App.shutdown()
	if status is None or status != 200:
		print 'E: unable to stop ' + __service__ + ' server (unknown error).'
		exit(1)

	print 'Service ' + __service__ + ' stopped.'
def co_movie_playlist(params):
    items = []
    xbmc.executebuiltin('ActivateWindow(busydialog)')

    request_data = sorted([
        ('action[0]', 'Video.getMovie'),
        ('movie_id[0]', params.id)
    ])
    content = App.http_request(API, 'POST', request_data)
    if content:
        movie = json.loads(content)['json'][0]['response']['movie']
        cover = '{0}/{1}'.format(URL, movie['covers'][0]['thumbnail'])
        for file in movie['files']:
            if file['is_dir']:
                continue

            url = file['path'].replace('/home/video/', 'http://p0.oc.kg:8080/')

            items.append(
                {
                    'label': file['name'],
                    'thumb': cover,
                    'art': {
                        'poster': cover
                    },
                    'stream_info': {
                        'video': {
                            'duration': file['metainfo']['playtime_seconds']
                        }
                    },
                    'info': {
                        'video': {
                            'plot': get_description(movie),
                            'year': movie['year'],
                            'mpaa': movie['mpaa'],
                            'title': '%s: %s' % (movie['name'], file['name']),
                            'originaltitle': movie['international_name'],
                        }
                    },
                    'url': url,
                    'is_playable': True
                }
            )

    xbmc.executebuiltin('Dialog.Close(busydialog)')

    if len(items) > 0:
        App.create_playlist(items)
        xbmc.executebuiltin('ActivateWindow(VideoPlaylist)')
    else:
        App.noty('playlist_empty')
def co_genres(params):
    items = []

    content = App.http_request(API, 'POST', {'action[0]': 'Video.getGenres'})
    if content:
        data = json.loads(content)['json'][0]['response']['genres']
        for genre in data:
            label = App.replace_html_codes(
                '[B]%s[/B]&emsp;%s' % (genre['name'], genre['count'])
            )
            items.append(
                {
                    'label': label,
                    'url': P.get_url(action='co_movies', order_id='0', genre_id=genre['id'])
                }
            )
    return App.create_listing(items)
def ns_serial_seasons(params):
    items = []

    content = App.http_request(URL + params.url)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        name = App.bs_get_text(html.find('h1')).strip()
        description = html.find(class_='serial-description')
        year = ''
        plot = App.STR_NO_DATA
        cover = ''
        if description is not None:
            cover = description.find('img').get('src')
            description_text = App.bs_get_text(description.find(class_='text')).encode('utf-8')

            year = re_compile_or_no_data('Год(.+?)\n', description_text)
            country = re_compile_or_no_data('Страна(.+?)\n', description_text)
            if country == App.STR_NO_DATA:
                country = re_compile_or_no_data('Производство(.+?)\n', description_text)
            genre = re_compile_or_no_data('Жанр(.+?)\n', description_text)
            director = re_compile_or_no_data('Режиссер(.+?)\n', description_text)
            plot = re_compile_or_no_data('\n(.+?)\n      \n', description_text)
            plot = App.format_description(description=plot, country=country, genre=genre, director=director)

        season_headers = html.find_all(class_='panel-title')

        items.append({
            'label': App.replace_html_codes('%s&emsp;Все сезоны'.decode('utf-8') % App.format_bold(name)),
            'thumb': cover,
            'art': {
                'poster': cover
            },
            'info': {
                'video': {
                    'plot': plot,
                    'year': year
                }
            },
            'url': P.get_url(action='ns_serial_season_episodes', url=params.url, season_number='-1')
        })

        for season_header in season_headers:
            label = App.bs_get_text(season_header.find('h2'))
            season_number = label.split(' ')[1]

            items.append({
                'label': label,
                'thumb': cover,
                'art': {
                    'poster': cover
                },
                'url': P.get_url(action='ns_serial_season_episodes', url=params.url, season_number=season_number)
            })

    return App.create_listing(items, content='tvshows')
def co_search(params):
    items = []
    query = App.keyboard(heading='Поиск')
    if query is None:
        pass
    elif query != '':
        content = App.http_request(URL + '/suggestion.php?' + urllib.urlencode({'q': query}))
        if content:
            movies = json.loads(content)['json'][0]['response']['movies']
            for movie in movies:
                cover = get_bigger_cover(movie['cover'])

                items.append({
                    'label': movie['name'],
                    'thumb': cover,
                    'art': {
                        'poster': cover
                    },
                    'info': {
                        'video': {
                            'year': movie['year'],
                        }
                    },
                    'url': P.get_url(action='co_movie', id=movie['movie_id'])
                })
            if len(items) == 0:
                App.noty('no_search_results')
    else:
        App.noty('no_search_results')

    return App.create_listing(items, content='movies')
def get_pagination(current, total, size, offset, params):
    items = []

    current = int(current)
    total = int(total)
    size = int(size)
    offset = int(offset)

    pages = {
        'total': total if (size == 0 and offset == 0) else int(math.ceil(total / size + 1)),
        'current': current if (current > 0) else 1
    }
    if pages['total'] < pages['current']:
        pages['current'] = pages['total']

    if pages['current'] > 1:
        items.append({
            'label': App.replace_html_codes('[B]<[/B]&emsp;Предыдущая страница'.decode('utf-8')),
            'icon': App.get_media('prev'),
            'url': P.get_url(
                action='co_movies',
                order_id=params.order_id,
                genre_id=params.genre_id,
                page=pages['current'] - 1 - offset
            )
        })
    if pages['current'] < pages['total']:
        items.append({
            'label': App.replace_html_codes('[B]>[/B]&emsp;Следующая страница'.decode('utf-8')),
            'icon': App.get_media('next'),
            'url': P.get_url(
                action='co_movies',
                order_id=params.order_id,
                genre_id=params.genre_id,
                page=pages['current'] + 1 - offset
            )
        })

    pages = {
        'total': int(math.ceil(total / size + 1)),
        'current': offset / size + 1
    }

    return items
Exemplo n.º 43
0
def status():
	response = App.status()
	if response is None:
		print 'Service ' + __service__ + ' stopped.'
		return

	if 'name' in response and response['name'] == __service__:
		print 'Service ' + __service__ + ' running on port ' + str(App.Http.PORT) + '.'
	else:
		print 'Another service running on port ' + str(App.Http.PORT) + '.'
def ns_search(params):
    items = []
    query = App.keyboard(heading='Поиск')
    if query is None:
        pass
    elif query != '':
        query = query.decode('utf-8').lower()
        serials = get_serials_list()
        for serial in serials:
            if serial['title'].lower().find(query) > -1:
                cover = serial['cover']

                items.append({
                    'label': serial['title'],
                    'thumb': cover,
                    'art': {
                        'poster': cover
                    },
                    'url': P.get_url(action='ns_serial_seasons', url=serial['url'])
                })
        if len(items) == 0:
            App.noty('no_search_results')
    else:
        App.noty('no_search_results')

    return App.create_listing(items, content='tvshows')
def ns_index(params):
    items = [{
        'label': '[ Поиск ]',
        'icon': App.get_media('find'),
        'url': P.get_url(action='ns_search')
    }, {
        'label': App.format_bold('Популярные'),
        'url': P.get_url(action='ns_top')
    }, {
        'label': App.format_bold('Новые серии'),
        'url': P.get_url(action='ns_new_episodes')
    }, {
        'label': App.format_bold('Новые сериалы'),
        'url': P.get_url(action='ns_new_serials')
    }]

    content = App.http_request(URL)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        block = html.find(class_='categories-menu')
        if block is not None:
            for genre in block.find_all('a'):
                label = App.bs_get_text(genre)
                url = genre.get('href').split('=')
                url[1] = urllib.quote(url[1].encode('utf-8'))
                url = '='.join(url)

                items.append({
                    'label': label,
                    'url': P.get_url(action='ns_serials_by_genre', url=url)
                })
    return items
def get_description(info):
    description = ''
    if 'description' in info:
        description = info['description']
    if 'long_description' in info:
        description = info['long_description']

    director = App.STR_NO_DATA
    if 'directors' in info:
        director = App.explode_info_string(info['directors'])

    # name_original = info['international_name']

    rating = get_movie_rating_value(info, 'rating_imdb_count', 'rating_imdb_value')
    if rating == '':
        rating = get_movie_rating_value(info, 'rating_kinopoisk_count', 'rating_kinopoisk_value')

    return App.format_description(
        country=App.explode_info_string(info['countries']) if 'countries' in info else '',
        genre='' if App.get_skin_name() != 'skin.estuary' else App.explode_info_string(info['genres']) if 'genres' in info else '',
        description=description.replace('<br>', '\n').encode('utf-8'),
        director=director,
        rating=rating
    )
def ns_serial_season_episodes(params):
    items = []

    xbmc.executebuiltin('ActivateWindow(busydialog)')

    content = App.http_request(URL + params.url)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        serial_name = App.bs_get_text(html.find('h1')).strip()
        season_headers = html.find_all(class_='panel-title')

        for season_header in season_headers:
            try:
                season_name = App.bs_get_text(season_header.find('h2'))
                season_number = season_name.split(' ')[1]
                if params.season_number == '-1' or params.season_number == season_number:
                    episodes_block = season_header.parent.find(class_='videos-pane')
                    for episode in episodes_block.find_all('li'):
                        try:
                            link = episode.find('a').get('href')
                            cover = episode.find('img').get('src')
                            episode_number = App.bs_get_text(episode.find(class_='grey')).split(' ')[0]
                            label = App.replace_html_codes('%s&emsp;%sx%s' % (serial_name, season_number, episode_number))

                            items.append(create_movie_item(link, label, cover))
                        except:
                            P.log_error(traceback.format_exc())
            except:
                P.log_error(traceback.format_exc())

    xbmc.executebuiltin('Dialog.Close(busydialog)')

    if len(items) > 0:
        App.create_playlist(items)
        xbmc.executebuiltin('ActivateWindow(VideoPlaylist)')
    else:
        App.noty('playlist_empty')
Exemplo n.º 48
0
def start():
	response = App.status()
	if response is None:
		pass
	elif response == False:
		print 'Unable to start service on ' + App.Http.ADDRESS + ':' + str(App.Http.PORT) + ' (address in use?).'
		return
	else:
		print 'Service ' + __service__ + ' already running.'
		return

	try:
		print 'Starting ' + __service__ + ' service (' + App.Http.NAME + ' on ' + str(App.Http.ADDRESS) + ':' + str(App.Http.PORT) + ')...'
		App.start()
		print 'Signal SHUTDOWN received, shutting down ' + __service__ + ' service.'
		App.stop()
	except KeyboardInterrupt, SystemExit:
		print 'Signal SIGINT received, shutting down ' + __service__ + ' service.'
		App.stop()
Exemplo n.º 49
0
 def __init__(self, ifile='-', ofile='-'):
    App.__init__(self)                                # call superclass init
    self.setInput(ifile or self.name + '.in')         # default i/o filenames
    self.setOutput(ofile or self.name + '.out')       # unless '-i', '-o' args
Exemplo n.º 50
0
import App as app

app.run()
Exemplo n.º 51
0
    def command(self, c):
        c = c.strip()

        if c == "help":
            print("""Welcome to the Key Server Admin!

** [Verb] [Type] [Optional Param] **
Verbs:
- List    = List out all the specified TYPE
            ex. list app

- Create  = Create a new TYPE
            ex. create user

- Update  = Update a TYPE, the item to modify is
            specified as an additional parameter
            ex. update app test

- Delete  = Delete a TYPE, the item to delete is
            specified as an additional parameter
            ex. delete param url

Types:
- app     = Applications - Act like folders for Parameters
- key     = API Key - used by clients to fetch params
- param   = Parameter, requires an app to be selected
- user    = Admin User


** select [App_Name] **
Select allows you to select an application to work with.
This is required when you want to modify parameters.

** exit **
If an app is currently selected, goes back to home.
If no app is currently selected, quits the admin CLI

** help **
Lists this help info""")

        elif c.lower().__contains__("select"):
            try:
                target_app = c.split(" ")[1]
            except IndexError:
                print("Invalid select condition - please specify which app you want to select")
                return

            if target_app in App.list_apps(self.username, self.password):
                CLI.current_app = target_app
            else:
                print("That is not a valid app name, type 'list apps' to see all the current apps.")

        elif c.lower().__contains__("list"):
            try:
                list_item = c.lower().split(" ")[1]
            except IndexError:
                print("Invalid list condition - please specify what you want to list")
                return

            if list_item.__contains__("-h") or list_item.__contains__("help"):
                print("""List allows you to list out different applications, keys, users, and parameters.

** list [type] **
type `help` to list out all the types and their roles

In order to list parameters, an application needs to be selected.""")

            elif list_item.__contains__("users"):
                for u in User.list_users(self.username, self.password):
                    print("\t%s (%s)" % (u['username'], u['email']))

            elif list_item.__contains__("apps"):
                for a in App.list_apps(self.username, self.password):
                    print("\t" + a)

            elif list_item.__contains__("key"):
                for k in Key.list_keys(self.username, self.password):
                    print ("\t%s (%s)\n"
                           "\t\t Permissions: %s" % (k["application_name"], k["application_key"], k["permissions"]))

            elif list_item.__contains__("param"):
                if CLI.current_app == "":
                    print("Cannot list params when no app is selected")
                else:
                    for p in Param.list_params(self.username, self.password, CLI.current_app):
                        print("\t%s = %s" % (p['name'], p['value']))

            else:
                print("Unknown List Command - type `list -h` or `list help` for help.")

        elif c.lower().__contains__("create"):
            try:
                create_item = c.lower().split(" ")[1]
            except IndexError:
                print("Invalid create condition - please specify what you want to create")
                return

            if create_item.__contains__("-h") or create_item.__contains__("help"):
                print("""Create allows you to create new applications, keys, users, and parameters

** create [type] **
type `help` to list out all the types and their roles

In order to create parameters, an application needs to be selected.""")

            elif create_item.__contains__("user"):
                while True:
                    username = raw_input("\tUsername: "******"\tPassword: "******"\tConfirm Password: "******"Passwords do not match. Try Again.")

                    email = raw_input("\tEmail: ").strip()

                    conf = raw_input("\n\tUsername: %s\n\tPassword: %s\n\tEmail: %s\n\tIs this correct [Y/n]" %
                                     (username, password, email)).strip()

                    if conf.lower() == "y" or conf == "":
                        user = User.create_new(self.username, self.password, username, password, email)
                        print("Created New User: %s" % user["username"])

                        break

            elif create_item.__contains__("app"):
                while True:
                    app_name = raw_input("\tApplication Name: ").strip()

                    conf = raw_input("\n\tApplication Name: %s\n\tIs this correct [Y/n]" % app_name).strip()
                    if conf.lower() == "y" or conf == "":
                        app = App.create_app(self.username, self.password, app_name)
                        print("Created New App: %s" % app["name"])

                        break

            elif create_item.__contains__("key"):
                while True:
                    application_name = raw_input("\tApplication Name: ").strip()
                    print("\tIn case you need a refresher... Application permissions are as follows:\n"
                          "\t\t* use +app_name to whitelist the key for that app\n"
                          "\t\t* use -app_name to blacklist the key for that app\n"
                          "\t\t* use NO to revoke the key\n"
                          "\t\t* or use ALL to grant the key access to all apps")
                    permissions = raw_input("\tApplication Permissions: ").strip()
                    if permissions == "":
                        permissions = "ALL"

                    conf = raw_input("\n\tName: %s\n\tPermissions: %s\n\tIs this correct [Y/n]" % (
                        application_name, permissions)).strip()

                    if conf.lower() == "y" or conf == "":
                        key = Key.create_key(self.username, self.password, application_name, permissions)
                        print("Created New Key: %s" % key["application_key"])

                        break

            elif create_item.__contains__("param"):
                if CLI.current_app == "":
                    print("Cannot create param when no app is selected")
                else:
                    while True:
                        param_name = raw_input("\tParameter Name: ").strip()
                        param_value = raw_input("\tParameter Value: ").strip()

                        conf = raw_input(
                            "\n\tParameter Name: %s\n\tParameter Value: %s\n\tIs this correct [Y/n]" % (param_name,
                                                                                                        param_value)) \
                            .strip()

                        if conf.lower() == "y" or conf == "":
                            param = Param.create_param(self.username, self.password, CLI.current_app, param_name,
                                                       param_value)
                            print("Created New Parameter: %s" % param["name"])

                            break

            else:
                print("Unknown Create Command - type `create -h` or `create help` for help.")

        elif c.lower().__contains__("update"):
            try:
                update_item = c.lower().split(" ")[1]
            except IndexError:
                print("Invalid update condition - please specify what you want to update")
                return

            try:
                update_item_name = c.split(" ")[2]
            except IndexError:
                print("Invalid update condition - please specify which %s you want to update." % update_item)
                return

            if update_item.__contains__("-h") or update_item.__contains__("help"):
                print("""Update allows you to update existing applications, keys, users, and parameters

** update [type] [username/applicationName/applicationKey/parameterName]**
type `help` to list out all the types and their roles

In order to create parameters, an application needs to be selected.""")

            elif update_item.__contains__("user"):
                user_info = User.list_users(self.username, self.password)
                for u in user_info:
                    if u['username'] == update_item_name:
                        user_info = u
                        break

                while True:
                    password = None
                    while True:
                        password = getpass.getpass("\tNew Password [Leave blank to keep]: ")
                        password_conf = getpass.getpass("\tConfirm New Password: "******"Passwords do not match. Try Again.")

                    email = raw_input("\tEmail [%s]: " % user_info['email']).strip()
                    email = email if email != "" else user_info['email']

                    conf = raw_input("\n\tUsername: %s\n\tPassword: %s\n\tEmail: %s\n\tIs this correct [Y/n]" %
                                     (update_item_name, password, email)).strip()

                    if conf.lower() == "y" or conf == "":
                        user = User.update_user(self.username, self.password, update_item_name, password=password,
                                                email=email)

                        # Updating the current user's password, so let's update the one we are using to login to the API
                        if update_item_name == self.username:
                            self.password = password

                        print("Updated User: %s" % user["username"])

                        break

            elif update_item.__contains__("key"):
                key_info = Key.list_keys(self.username, self.password)
                for k in key_info:
                    if k['application_key'] == update_item_name:
                        key_info = k
                        break

                while True:
                    application_name = raw_input("\tApplication Name [%s]: " % key_info['application_name'])
                    permissions = raw_input("\tPermissions [%s]: " % key_info['permissions'])

                    conf = raw_input("\n\tName: %s\n\tPermissions: %s\n\tIs this correct [Y/n]" % (
                        application_name, permissions)).strip()

                    if conf.lower() == "y" or conf == "":
                        key = Key.update_key(self.username, self.password, update_item_name,
                                             application_name=application_name,
                                             permissions=permissions)
                        print("Updated Key: %s" % key['application_key'])

                        break

            elif update_item.__contains__("param"):
                if CLI.current_app == "":
                    print("Cannot update param when no app is selected")
                else:
                    while True:
                        param_value = raw_input("\tNew Value Value: ").strip()

                        conf = raw_input("\n\tParameter Value: %s\n\tIs this correct [Y/n]" % param_value).strip()

                        if conf.lower() == "y" or conf == "":
                            param = Param.update_param(self.username, self.password, CLI.current_app, update_item_name,
                                                       param_value)
                            print("Updated Parameter: %s" % param["name"])

                            break
            else:
                print("Unknown Update Command - type `update -h` or `update help` for help.")

        elif c.lower().__contains__("delete"):
            try:
                delete_item = c.lower().split(" ")[1]
            except IndexError:
                print("Invalid delete condition - please specify what you want to delete")
                return

            try:
                delete_item_name = c.split(" ")[2]
            except IndexError:
                print("Invalid delete condition - please specify which %s you want to delete." % delete_item)
                return

            if delete_item.__contains__("-h") or delete_item.__contains__("help"):
                print("""Delete allows you to remove applications, users, and parameters.
Delete revokes keys, which is the only delete action that can be undone; to
reactivate a revoked key, update the permissions of the key.

** update [type] [username/applicationName/applicationKey/parameterName]**
type `help` to list out all the types and their roles

In order to create parameters, an application needs to be selected.""")

            elif delete_item.__contains__("user"):
                conf = raw_input("\n\tUsername to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip()

                if conf.lower() == "y" or conf == "":
                    status = User.delete_user(self.username, self.password, delete_item_name)
                    if status:
                        print("User was deleted Successfully")
                    else:
                        print("Problem deleting user, check server logs for details")

            elif delete_item.__contains__("app"):
                conf = raw_input("\n\tApplication to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip()

                if conf.lower() == "y" or conf == "":
                    status = App.delete_app(self.username, self.password, delete_item_name)
                    if status:
                        print("App was deleted Successfully")
                    else:
                        print("Problem deleting app, check server logs for details")

            elif delete_item.__contains__("key"):
                conf = raw_input("\n\tKey to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip()

                if conf.lower() == "y" or conf == "":
                    status = Key.delete_key(self.username, self.password, delete_item_name)
                    if status:
                        print("Key was Revoked Successfully - to reactivate the Key, update its permissions")
                    else:
                        print("Problem revoking key, check server logs for details")

            elif delete_item.__contains__("param"):
                if CLI.current_app == "":
                    print("Cannot delete param when no app is selected")
                else:
                    conf = raw_input("\n\tParam to remove: %s\n\tIs this correct [Y/n]" % delete_item_name).strip()

                    if conf.lower() == "y" or conf == "":
                        status = Param.delete_param(self.username, self.password, CLI.current_app, delete_item_name)
                        if status:
                            print("Param was deleted Successfully")
                        else:
                            print("Problem deleting param, check server logs for details")

            else:
                print("Unknown Delete Command - type `delete -h` or `delete help` for help.")

        elif c.lower().__contains__("exit"):
            if CLI.current_app == "":
                exit(0)
            else:
                CLI.current_app = ""

        else:
            print("Command not recognized")
Exemplo n.º 52
0
 def help(self):
    App.help(self):
    print '-i <input-file | "-">  (default: stdin  or per app)'
    print '-o <output-file| "-">  (default: stdout or per app)'
Exemplo n.º 53
0
import App

baselines = []
forests = []
neighbours = []
relations = []

iterations = 10

for i in range(0, iterations):
	baseline, forest, neighbour, relational = App.main()
	baselines.append(baseline)
	forests.append(forest)
	neighbours.append(neighbour)
	relations.append(relational)

forsets_means = []
neighbours_means = []
relations_means = []

for iteration in range(0, iterations):
	
	baseline_count = 0
	forest_mean = 0
	neighbour_mean = 0
	relation_mean = 0

	for key in baselines[iteration]:

		base = baselines[iteration][key]
def co_movies(params):
    if 'genre_id' not in params:
        params.genre_id = ''
    params.refresh = 'page' in params

    items = []
    size = 40
    try:
        if params.page == 'search':
            last_page = int(params.last_page) - 1
            page = int(App.keyboard(heading='Перейти на страницу', numeric=True)) - 1
            if page > last_page:
                page = last_page
            if page < 0:
                page = 0
            params.page = str(page)
        else:
            page = int(params.page)
    except:
        page = 0

    offset = page * size

    request_data = sorted([
        ('action[0]', 'Video.getCatalog'),
        ('offset[0]', offset),
        ('size[0]', size),
        ('order[0]', params.order_id),
        ('genre[0]', params.genre_id)
    ])
    content = App.http_request(API, 'POST', request_data)
    if content:
        data = json.loads(content)['json'][0]['response']

        for movie in data['movies']:
            plot = get_description(movie)
            id = movie['movie_id']

            cover = get_bigger_cover(movie['cover'])

            label = App.format_bold(movie['name'])

            items.append(
                {
                    'label': label,
                    'thumb': cover,
                    'fanart': cover,
                    'art': {
                        'poster': cover,
                    },
                    'info': {
                        'video': {
                            'plot': plot,
                            'year': movie['year'],
                            'genre': ' / '.join(movie['genres'][:2]) if 'genres' in movie else ''
                        }
                    },
                    'url': P.get_url(action='co_movie', id=id)
                }
            )

        movies_count = int(data['total'])
        add_pagination(
            items,
            get_pagination((offset / size + 1), movies_count, size, 1, params)
        )

        if movies_count > size:
            total_pages = int(math.ceil(movies_count / size + 1))
            items.insert(0, {
                'label': App.replace_html_codes('%s&emsp;%d / %d' % ('[ Перейти на страницу ]'.decode('utf-8'), page + 1, total_pages)),
                'url': P.get_url(action='co_movies', order_id=params.order_id, genre_id=params.genre_id, page='search', last_page=total_pages)
            })

    return App.create_listing(items, content='movies', update_listing=params.refresh)
Exemplo n.º 55
0
# coding: utf-8

import App
from tkinter import *

if __name__ == '__main__':
	root = Tk()
	root.title('Деревянный парсер')
	root.minsize(500, 200)
	App = App.Application(root)
	App.mainloop()
Exemplo n.º 56
0
sys.path.append('./scripts/libs')
import string
import Interface
import Event
import App
from chat import *             #Chat manager
from Interface import *
from Event import *
from App import *

import feedparser

###########################################################
######Global variables
I = Interface.get() #Interface manager
A = App.get()       #Application
E = Event.get()     #Event manager
##########################################################
#####Counter, returns new value every time
def counter():
 static_counter = 0
 while True:
  static_counter += 1
  yield static_counter
count = counter().next
#########################################################################
#####Function creates simple message box with specified title and name
#####Message box has one button - ok and is destroyed by interface manager
#####after pressing this button.
#####Every new popup window has unique id.
def createPopupWindow(title,text):
def get_serials_list():
    content = App.http_request(URL)
    if content:
        result = re.compile('var list_all_serial = (.+?)}];').findall(content)
        if len(result) > 0:
            return json.loads(result[0] + '}]')
Exemplo n.º 58
0
		return
	else:
		print 'Service ' + __service__ + ' already running.'
		return

	try:
		print 'Starting ' + __service__ + ' service (' + App.Http.NAME + ' on ' + str(App.Http.ADDRESS) + ':' + str(App.Http.PORT) + ')...'
		App.start()
		print 'Signal SHUTDOWN received, shutting down ' + __service__ + ' service.'
		App.stop()
	except KeyboardInterrupt, SystemExit:
		print 'Signal SIGINT received, shutting down ' + __service__ + ' service.'
		App.stop()
	except Exception, e:
		print 'E:', str(e)
		App.stop()
		exit(1)

def stop():
	response = App.status()
	if not response:
		print 'Service ' + __service__ + ' not running.'
		return

	status = App.shutdown()
	if status is None or status != 200:
		print 'E: unable to stop ' + __service__ + ' server (unknown error).'
		exit(1)

	print 'Service ' + __service__ + ' stopped.'
def wc_index(params):
    items = []

    
    # url_format = 'rtmp://212.42.105.251:1935/%s/?token=%s'
    # url_format = 'http://212.42.105.251:8080/record/mpegts?token=%s'
    # url_format = 'http://212.42.105.251:8080/%s/tracks-v1/mono.m3u8?token=%s'

    # content = App.http_request(URL % '/')
    # if content:
    #     html = BeautifulSoup(content, 'html.parser')
    #     container = html.find(class_='view-cameras')
    #     for link in container.find_all('a'):
    #         if link is not None:
    #             url = link.get('href')
    #             content = App.http_request(URL % url)
    #             if content:
    #                 html = BeautifulSoup(content, 'html.parser')
    #                 iframe = html.find('iframe')
    #                 if iframe is not None:
    #                     url = iframe.get('src')
    #                     parsed_url = urlparse(url)
    #                     url_splitted = url.split('/')
    #                     params = parse_qs(parsed_url.query)
    #                     if 'token' in params:
    #                         token = params['token'][0].strip()
    #                         items.append({
    #                             'label': link.get_text(),
    #                             'url': url_format % (url_splitted[3], token),
    #                             'is_playable': True
    #                         })

    url = 'http://live.saimanet.kg'
    content = App.http_request(url)
    if content:
        html = BeautifulSoup(content, 'html.parser')
        for camera in html.find_all(class_='onemaincam'):
            try:
                camera = camera.find(class_='title').find('a')
                label = App.bs_get_text(camera)
                href = camera.get('href')

                content = App.http_request(url + href)
                if content:
                    html1 = BeautifulSoup(content, 'html.parser')
                    source = html1.find('source')
                    items.append(
                        {
                            'label': label,
                            'url': source.get('src'),
                            'is_playable': True
                        }
                    )
            except:
                pass

    kt_cameras = [{
        'label': 'г. Бишкек (Чуй/Советская)',
        'url': 'rtmp://213.145.131.243:5010/camera1/mystream'
    },
    {
        'label': 'Иссык-Кульская область (с. Бостери)',
        'url': 'rtmp://213.145.131.243:5010/camera2/mystream'
    },
    {
        'label': 'г. Ош',
        'url': 'rtmp://213.145.131.243:5010/camera3/mystream'
    }]

    for camera in kt_cameras:
        items.append(
            {
                'label': camera['label'],
                'url': camera['url'],
                'is_playable': True
            }
        )

    return items