def set_api_instance(api_token): global api_instance configuration = swagger_client.Configuration() configuration.api_key['Authorization'] = api_token configuration.api_key_prefix['Authorization'] = 'Bearer' api_instance = swagger_client.DefaultApi( swagger_client.ApiClient(configuration))
def get_check(): check = None while True: try: driver.get( "https://bridges.torproject.org/bridges?transport=obfs4") time.sleep(2) # 购买的appcode appcode = 'ad616df07c494fefaa08f1ddffaed204' rescode, check = AliAPI( driver.find_element_by_tag_name("img").get_attribute("src") [23:], appcode) driver.save_screenshot("screen.jpg") api_instance = swagger_client.DefaultApi() # result = json.loads(result) # check = result['result']['showapi_res_body']['Result'] if (rescode != 0): print "验证码解析错误 code = ", rescode print "check is not right,reload the page..." continue else: break except WebDriverException: print "Script error :", WebDriverException continue print "will return check:", check return check
def onTestKipartbase( self, event ): try: base_url = self.edit_kipartbase.Value+'/api' client = swagger_client.ApiClient(base_url) api = swagger_client.DefaultApi(client) currencies = api.find_currencies() except Exception as e: print_stack() wx.MessageBox(format(e), 'Error', wx.OK | wx.ICON_ERROR)
def handle(self, *args, **options): api_client = ApiClient() api_client.configuration.host = "https://deims.org/api" api = swagger_client.DefaultApi(api_client=api_client) sites = api.sites_get() for s in sites: site = api.sites_resource_id_get(resource_id=s.id.suffix) if not (set(['Italy', 'Slovenia', 'Croatia']) & set(site.attributes.geographic.country)): continue print(site.id.prefix, site.id.suffix, site.title, site.attributes.geographic.country) domain_area = None if site.attributes.geographic.boundaries is not None: domain_area = GEOSGeometry(site.attributes.geographic.boundaries, srid=4326) if domain_area and (isinstance(domain_area, LineString) or (domain_area, MultiLineString)): domain_area = domain_area.buffer(0.0001) if domain_area and isinstance(domain_area, Polygon): domain_area = MultiPolygon(domain_area) obj, created = EcosSite.objects.get_or_create( suffix = site.id.suffix, defaults= {'location' : GEOSGeometry(site.attributes.geographic.coordinates, srid=4326)} ) obj.data = json.loads(api_client.last_response.data) obj.denomination = site.title obj.description = site.attributes.general.abstract obj.domain_area = domain_area obj.website= site.id.prefix+site.id.suffix obj.last_update = site.changed obj.img = imgimport(site.id.suffix) obj.location = GEOSGeometry(site.attributes.geographic.coordinates, srid=4326) obj.save() if site.attributes.focus_design_scale.parameters is not None: #print(site.attributes.focus_design_scale.parameters.__class__, site.attributes.focus_design_scale.parameters.__dict__) #print(site.attributes.focus_design_scale.parameters) #print(site.attributes.focus_design_scale.parameters[0].label) #print(site.attributes.focus_design_scale.parameters[0].uri) preferred_label_en = site.attributes.focus_design_scale.parameters[0].label obj, created = Parameter.objects.get_or_create( uri = site.attributes.focus_design_scale.parameters[0].uri, defaults={'preferred_label_en': preferred_label_en} ) preferred_label_en = preferred_label_en
def handle(self, *args, **options): api_client = ApiClient() api_client.configuration.host = "https://deims.org/api" api = swagger_client.DefaultApi(api_client=api_client) sites = api.sites_get() for s in EcosSite.objects.all(): s.delete()
def reload(): global unauthenticated_client global client global api global model unauthenticated_client = swagger_client.ApiClient() client = swagger_client.ApiClient() api = swagger_client.DefaultApi(client) model = swagger_client
def test_get_users_by_city(self): """Test case for get_users_by_city """ api_instance = swagger_client.DefaultApi(swagger_client.ApiClient()) try: users = api_instance.get_users_by_city("London") except ApiException as e: print("Exception when calling DefaultApi->get_users: %s\n" % e) print(json.dumps(users, indent=4)) pass
def __init__(self, name="greentranslator", config={}): Translator.__init__(self, name) self.config = config blaze_uri = None if 'blaze_uri' in config: blaze_uri = self.config ['blaze_uri'] if not blaze_uri: blaze_uri = 'http://stars-blazegraph.renci.org/bigdata/sparql' self.blazegraph = TripleStore (blaze_uri) #self.exposures_uri = self.config ['exposures_uri'] self.exposures = Exposures (swagger_client.DefaultApi ()) self.medbiochem = MedicalBioChemical (self.blazegraph)
def get_instance_transcription_api(): # configure API key authorization: subscription_key configuration = cris_client.Configuration() configuration.api_key["Ocp-Apim-Subscription-Key"] = SUBSCRIPTION_KEY configuration.host = f"https://{SERVICE_REGION}.api.cognitive.microsoft.com/speechtotext/v3.0" # create the client object and authenticate client = cris_client.ApiClient(configuration) # create an instance of the transcription api class api = cris_client.DefaultApi(api_client=client) return api
def _create_api_instance(self, ip: str, port: str): """ Creates an instance of the API class with the given ip address and port number Args: ip (str): ip address representing the PC port (str): port number representing the device on the PC Returns: api_instance: instance of the API class """ WISUN_UI = f"http://{ip}:{port}/Wi-SUN/TBU/1.0.0" configuration = swagger_client.Configuration(WISUN_UI) # Create an instance of the API class (Device) api_instance = swagger_client.DefaultApi( swagger_client.ApiClient(configuration)) print(f"Finish creating Device at {ip}:{port}") return api_instance
def __init__(self, graph, hostname="gfe.b12x.org"): ''' Constructor ''' self.graph = graph api_client = ApiClient(host=hostname) self.api = swagger_client.DefaultApi(api_client=api_client) structure_dir = os.path.dirname(__file__) struture_files = glob.glob(structure_dir + '/data/*.structure') self.structures = {} for inputfile in struture_files: file_path = inputfile.split("/") locus = file_path[len(file_path)-1].split(".")[0] inputdata = (l.strip() for l in open(inputfile, "r") if l.strip()) features = [] for line in inputdata: line.rstrip() line.strip('\n') [feature, rank] = line.split("\t") features.append("-".join([feature, rank])) self.structures.update({"HLA-" + locus: features})
def __init__(self): # create an instance of the API class self.api_instance = swagger_client.DefaultApi() self.apikey = 'eLVAr118T0kPOfYAoIy3RYjvYgH0Gygt' self.iso = loadIso()
def retrieve_transcript(identifier, language, speaker_type, service_config): blob_service_client = BlobServiceClient.from_connection_string( service_config['connection_string']) container_client = blob_service_client.get_container_client(identifier) blob_client = container_client.get_blob_client('audio.wav') sas_blob = generate_blob_sas(account_name=service_config['account_name'], container_name=identifier, blob_name='audio.wav', account_key=service_config['account_key'], permission=BlobSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=24)) uri = blob_client.url + '?' + sas_blob logging.info("Starting transcription client...") # configure API key authorization: subscription_key configuration = cris_client.Configuration() configuration.api_key["Ocp-Apim-Subscription-Key"] = service_config[ 'subscription_key'] configuration.host = f"https://{service_config['service_region']}.api.cognitive.microsoft.com/speechtotext/v3.0" # create the client object and authenticate client = cris_client.ApiClient(configuration) # create an instance of the transcription api class api = cris_client.DefaultApi(api_client=client) try: # Specify transcription properties by passing a dict to the properties parameter. See # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription#configuration-properties # for supported parameters. properties = { "punctuationMode": "Automatic", "profanityFilterMode": "None", "wordLevelTimestampsEnabled": True, "diarizationEnabled": (speaker_type == "both"), "timeToLive": "PT1H" } # Use base models for transcription. transcription_definition = cris_client.Transcription( display_name="Simple transcription", description="Simple transcription description", locale=language, content_urls=[uri], properties=properties) created_transcription, status, headers = api.create_transcription_with_http_info( transcription=transcription_definition) # get the transcription Id from the location URI transcription_id = headers["location"].split("/")[-1] # Log information about the created transcription. If you should ask for support, please # include this information. logging.info( f"Created new transcription with id '{transcription_id}' in region {service_config['service_region']}" ) logging.info("Checking status.") transcript = {} completed = False while not completed: # wait for 5 seconds before refreshing the transcription status time.sleep(5) transcription = api.get_transcription(transcription_id) logging.info(f"Transcriptions status: {transcription.status}") if transcription.status in ("Failed", "Succeeded"): completed = True if transcription.status == "Succeeded": pag_files = api.get_transcription_files(transcription_id) for file_data in _paginate(api, pag_files): if file_data.kind != "Transcription": continue results_url = file_data.links.content_url results = requests.get(results_url) transcript = json.loads(results.content) elif transcription.status == "Failed": raise Exception( f"Transcription failed: {transcription.properties.error.message}" ) finally: delete_all_transcriptions(api) return transcript
def buddleiaWrapper(sentence): ''' We use [email protected]'s platform to access the output from different OIEs and we return a dict for every OIE we need ''' reverbDict = {} ollieDict = {} clausieDict = {} stanfordDict = {} openie4Dict = {} propsDict = {} #we replace troublesome characters with a special name, we will change it back later sentence = charAnnotClean(sentence) #we launch the api api_instance = swagger_client.DefaultApi() src_text = sentence # str | The source text extractors = ['reverb', 'ollie', 'clausie', 'stanford', 'openie', 'props' ] # list[str] | The extractors used to extract triples. try: apiResponse = api_instance.oie_extract_triples_get( src_text, extractors) for dictApi in apiResponse: arg1 = charAnnotDirty(dictApi.arg1) rel = charAnnotDirty(dictApi.rel) arg2 = charAnnotDirty(dictApi.arg2) score = dictApi.score sentence = charAnnotDirty(sentence) #we catch the reverb content if dictApi.extractor == 'reverb': reverbDict[u'_'.join([toUtf8(arg1), rel, toUtf8(arg2) ])] = [arg1, rel, arg2, sentence, score] #we catch the ollie content elif dictApi.extractor == 'ollie': ollieDict[u'_'.join([toUtf8(arg1), rel, toUtf8(arg2) ])] = [arg1, rel, arg2, sentence, score] #we catch the clausie content except if there was a timeout elif dictApi.extractor == 'clausie' and dictApi.rel != u'timeout': clausieDict[u'_'.join( [toUtf8(arg1), rel, toUtf8(arg2)])] = [arg1, rel, arg2, sentence, score] #we catch the stanford content elif dictApi.extractor == 'stanford': stanfordDict[u'_'.join( [toUtf8(arg1), rel, toUtf8(arg2)])] = [arg1, rel, arg2, sentence, score] #we catch the openie-4 content elif dictApi.extractor == 'openie': openie4Dict[u'_'.join( [toUtf8(arg1), rel, toUtf8(arg2)])] = [arg1, rel, arg2, sentence, score] #we catch the props content elif dictApi.extractor == 'props': propsDict[u'_'.join([toUtf8(arg1), rel, toUtf8(arg2) ])] = [arg1, rel, arg2, sentence, score] #if there is a problem with the server except ApiException as e: raise Exception( "Exception when calling DefaultApi -> oie_extract_triples_get: {0}\n" .format(e)) return reverbDict, ollieDict, clausieDict, stanfordDict, openie4Dict, propsDict
# preliminaries import swagger_client base_url = 'http://localhost:8200/api' client_id = '' client_secret = '' # instantiate Auth API unauthenticated_client = swagger_client.ApiClient(base_url) #unauthenticated_authApi = api.ApiAuthApi(unauthenticated_client) # authenticate client #token = unauthenticated_authApi.login(client_id=client_id, client_secret=client_secret) #client = api.ApiClient(base_url, 'Authorization', 'token ' + token.access_token) client = swagger_client.ApiClient(base_url) # instantiate Look API api = swagger_client.DefaultApi(client) model = swagger_client
def set_api_instance_for_token(): global api_instance configuration = swagger_client.Configuration() api_instance = swagger_client.DefaultApi( swagger_client.ApiClient(configuration))
def main(): if display_players: # getting board information from the server # from __future__ import print_function import sys # for using print('function: {}'.format(sys._getframe().f_code.co_name)) import time import swagger_client from swagger_client.rest import ApiException from swagger_client import configuration from pprint import pprint import swagger_client from swagger_client.models import GetGame, Move, Player, StartGame, GetPlayer import tkinter.messagebox as messageBox import copy # global start_new_game # global play_with_another_player start_new_game = False play_with_another_player = False # play_as_spacific_player = False default_server = '10.44.37.98:9000' game_id = '' player = '' server = '' player1 = '' player2 = '' api_instance_1 = swagger_client.DefaultApi( swagger_client.ApiClient()) games = api_instance_1.games_get( ) # 'http://10.44.37.98:9000/games/') print('games=\n{}'.format(games)) if messageBox.askokcancel("BattleShips", "Start a new game?", icon="question"): # NOTE, the order of the params provide has to be in the same order as defined in # MyDialog_StartGameDlg.__init__ start_new_game = True game_def = None d = MyDialog_StartGameDlg("Start a new game", default_server, player1, player2, root) game_def = d.result if not game_def: messageBox.showerror( 'error', 'two player names are needed to start a new game', icon="error") else: while game_def['start_another_game']: d = MyDialog_StartGameDlg("Start a new game", default_server, player1, player2, root) game_def = d.result server = game_def['server'] player1 = game_def['player1'] player2 = game_def['player2'] print( 'starting a new game: server={}, player1={}, player2={}\n' .format(server, player1, player2)) # NOTE, api_instance_1.games_post returns a game_id object, then id method returns the string game_id = api_instance_1.games_post( body=StartGame(player1, player2)).id print('new game started, game_id={}'.format(game_id)) if messageBox.askokcancel("BattleShips", "Play with another player?", icon="question"): play_with_another_player = True # NOTE, the order of the params provide has to be in the same order as defined in # MyDialog_JoinGameDlg.__init__ if ((start_new_game and play_with_another_player) or not start_new_game): game_def = None # NOTE, if started a new game, game_id has a value, else, empty d = MyDialog_JoinGameDlg("Join a game", game_id, '', play_with_another_player, root) game_def = d.result # Rule I: # either game_id or player value must be provided, cannot be both empty # Rule II: # If play with another player, player name must be provided: # Rule III: # if player provided, it should be the self-player, and two scenarios entail: # 1. game_id provided, the player only plays with a specific game # 2. game_id not provided, the player plays multiple games that request the player's participation # Rules IV: # if player not provided, game_id must be provided, and the client plays both players if not game_def: errorMsg = 'current setting: play_with_another_player = {}, ' \ ' some information missing'.format(play_with_another_player) messageBox.showerror('error', errorMsg, icon="error") else: game_id = game_def['game_id'] player = game_def['player'] if (player == ''): player_str = 'play two players' else: player_str = player print('\njoined a game: game_id: {}, player: {}\n'.format( game_id, player_str)) # drawing graphics based on information from the server # NOTE, number range from 1 to 11, as last 11 is excluded, # chr value range from A to K, as last K is exlcluded # and top row and left col are for labelling int_list = list(range(1, 11)) chr_val_list = list(range(ord('A'), ord('K'))) print('int_list={}, chr_val_list={}'.format( int_list, chr_val_list)) while ( True ): # keep the client alive checking if anyone requires a game game_ids = list() if game_id == '': player_info = api_instance_1.players_name_get(player) game_ids = player_info.games else: game_ids.append(game_id) print('current player = {}, game_ids = {}'.format( player, game_ids)) for this_game_id in game_ids: print('this_game_id = {}, getting game information'.format( this_game_id)) game = api_instance_1.games_game_id_get(this_game_id) print('game=\n{}'.format(game)) player1_fleet_state = get_initial_fleet_state(game) player2_fleet_state = copy.deepcopy(player1_fleet_state) if ((game.winner == '') and (not play_with_another_player or (play_with_another_player and game.move == player))): if make_random_move: grid_ref = get_random_move_with_player_knowledge( int_list, chr_val_list, game) elif enforce_non_adjacent_ships: grid_ref, player1_fleet_state, player2_fleet_state = \ get_stratigic_move_with_player_knowledge_enforce_non_adjacent_ships( int_list, chr_val_list, game, player1_fleet_state, player2_fleet_state) else: grid_ref = get_stratigic_move_with_player_knowledge( int_list, chr_val_list, game) print('this_game_id={}, grid_ref={}. game.move={}'. format(this_game_id, grid_ref, game.move)) move_result = api_instance_1.games_game_id_grid_ref_put( this_game_id, grid_ref, body=Move(game.move)) print('game.move={}\ngrid_ref={}\nmove_result=\n{}'. format(game.move, grid_ref, move_result)) game = api_instance_1.games_game_id_get(this_game_id) print('this_game_id={}\ngame=\n{}'.format( this_game_id, game)) update_plot(number_of_cells, font_szie, w, global_total_rows_in_plot, fig, plotCanvas, grid_texts_default, grid_colours_default, game) elif display_graphic: test_realtime_display_graphics(number_of_cells, font_szie, w, global_total_rows_in_plot, fig, plotCanvas, grid_texts_default, grid_colours_default, sleep_param=0.5) else: test_title_img_pairs_list = generate_test_title_img_pairs_list() print('test_title_img_pairs_list = \n{}'.format( test_title_img_pairs_list)) test_realtime_display_group_of_images(global_total_rows_in_plot, test_title_img_pairs_list, fig, plotCanvas) root.mainloop()
def transcribe(): logging.info("Starting transcription client...") # configure API key authorization: subscription_key configuration = cris_client.Configuration() configuration.api_key["Ocp-Apim-Subscription-Key"] = SUBSCRIPTION_KEY configuration.host = f"https://{SERVICE_REGION}.api.cognitive.microsoft.com/speechtotext/v3.0" # create the client object and authenticate client = cris_client.ApiClient(configuration) # create an instance of the transcription api class api = cris_client.DefaultApi(api_client=client) # Specify transcription properties by passing a dict to the properties parameter. See # https://docs.microsoft.com/azure/cognitive-services/speech-service/batch-transcription#configuration-properties # for supported parameters. properties = { # "punctuationMode": "DictatedAndAutomatic", # "profanityFilterMode": "Masked", # "wordLevelTimestampsEnabled": True, # "diarizationEnabled": True, # "destinationContainerUrl": "<SAS Uri with at least write (w) permissions for an Azure Storage blob container that results should be written to>", # "timeToLive": "PT1H" } # Use base models for transcription. Comment this block if you are using a custom model. transcription_definition = transcribe_from_single_blob(RECORDINGS_BLOB_URI, properties) # Uncomment this block to use custom models for transcription. # transcription_definition = transcribe_with_custom_model(api, RECORDINGS_BLOB_URI, properties) # Uncomment this block to transcribe all files from a container. # transcription_definition = transcribe_from_container(RECORDINGS_CONTAINER_URI, properties) created_transcription, status, headers = api.create_transcription_with_http_info(transcription=transcription_definition) # get the transcription Id from the location URI transcription_id = headers["location"].split("/")[-1] # Log information about the created transcription. If you should ask for support, please # include this information. logging.info(f"Created new transcription with id '{transcription_id}' in region {SERVICE_REGION}") logging.info("Checking status.") completed = False while not completed: # wait for 5 seconds before refreshing the transcription status time.sleep(5) transcription = api.get_transcription(transcription_id) logging.info(f"Transcriptions status: {transcription.status}") if transcription.status in ("Failed", "Succeeded"): completed = True if transcription.status == "Succeeded": pag_files = api.get_transcription_files(transcription_id) for file_data in _paginate(api, pag_files): if file_data.kind != "Transcription": continue audiofilename = file_data.name results_url = file_data.links.content_url results = requests.get(results_url) logging.info(f"Results for {audiofilename}:\n{results.content.decode('utf-8')}") elif transcription.status == "Failed": logging.info(f"Transcription failed: {transcription.properties.error.message}")
def checkDegree(graph): degs = nx.degree(graph) availableNodes = [] for k, v in degs.items(): if v <= 3: availableNodes.append(k) return availableNodes def api_call(latitude=42.3656132, longitude=-71.00956020000001, category="Museum", number_of_results=15): <<<<<<< HEAD # create an instance of the API class api_instance = swagger_client.DefaultApi() # str | API Key provided for your account, to identify you for API access. Make sure to keep this API key secret. apikey = 'eLVAr118T0kPOfYAoIy3RYjvYgH0Gygt' # int | Radius around the center to look for points-of-interest around the given latitude and longitude in kilometers (km) (default to 42) radius = 42 # str | The preferred language of the content related to each point of interest. Content will be returned in this language if available (optional) (default to EN) lang = 'EN' # str | Filters the resulting points_of_interest to include only results which have a least one category containing the given provided word. Good examples are <em>museum</em>, <em>landmark</em> or <em>church</em> (optional) (default to Museum) category = 'Museum' # bool | Setting this to true includes only points of interest with a geonames ID (optional) (default to false) geonames = False # bool | Includes content that doesn't correspond to an active physical place, but which gives the user some background information, or <em>vibe</em> for the place they are visiting. An example of this may be information on an influential demolished building that used to exist at a certain location, or more information on a district of the city (optional) (default to false) vibes = True # bool | Enabling this includes images from Instagram in the output results. This is disabled by default, since these images are often just pictures of people or food, which often have little relevance to the actual location (optional) (default to false) social_media = False # str | The size of the images you'd like to see in the response (optional) (default to MEDIUM)
#endregion #region Test Swagger_Client Web API if run_swagger_client_api: # default get start code from nsw yaml # from __future__ import print_function import sys # for using print('function: {}'.format(sys._getframe().f_code.co_name)) import time import swagger_client from swagger_client.rest import ApiException from swagger_client import configuration from pprint import pprint # create an instance of the API class # api_instance = swagger_client.DefaultApi(swagger_client.ApiClient(configuration)) api_instance = swagger_client.DefaultApi(swagger_client.ApiClient()) game_id = 'game_id_example' # str | The ID of the game to return try: # Delete the given game api_instance.games_game_id_delete(game_id) except ApiException as e: print("Exception when calling DefaultApi->games_game_id_delete: %s\n" % e) #endregion #region Graphic Drawing if run_graphics: from generaltools import * from MyDialog import MyDialog_JoinGameDlg, MyDialog_StartGameDlg