Exemplo n.º 1
0
def get_information(url):
    """Get information for url using webscraping and API calls."""

    all_info = []

    scrape_info = get_all_recipe_info(url)

    response1 = unirest.get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/extract?forceExtraction=false&url=%s" % url,
        headers={
            "X-Mashape-Key": os.environ['MASHAPE_KEY']
        }
    )
    api_info = response1.body
    recipe_api_id = api_info['id']

    #instructions for recipe through api request
    response2 = unirest.get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/%s/analyzedInstructions?stepBreakdown=true" % recipe_api_id,
        headers={
            "X-Mashape-Key": os.environ['MASHAPE_KEY'],
            "Accept": "application/json"
        }
    )
    instruction_info = response2.body[0]['steps']

    all_info.append(scrape_info)
    all_info.append(api_info)
    all_info.append(instruction_info)

    return all_info
Exemplo n.º 2
0
 def __init__(self, url):
     self.tournaments_data, self.return_code = json.dumps(unirest.get(url, headers={"Accept":"application/json"}).body), \
     unirest.get(url).code
     checkCode(self.return_code)
     self.parsed_data = json.loads(self.tournaments_data)
     self.past = {}
     self.setTournamentsAttributes(self.parsed_data)
Exemplo n.º 3
0
def detail_view(request, recipe_id, ingredients):
    ingredients = ingredients.split('+') # list of ingredients owned

    response = unirest.get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/" + recipe_id + "/information",
      headers={
        "X-Mashape-Key": "QN5CLcAiQXmshOrib4vl7QifQAPjp1MjXoijsnsKdgztp93FnI"
      }
    )

    needed = []

    for ingredient in response.body["extendedIngredients"]:
        needed.append(ingredient["name"])

    missing = list(set(needed) - set(ingredients))

    print missing

    recipe = unirest.get("https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/extract?forceExtraction=false&url=http%3A%2F%2F" + response.body['sourceUrl'][7:].replace("/", "%2F") + "",
      headers={
        "X-Mashape-Key": "QN5CLcAiQXmshOrib4vl7QifQAPjp1MjXoijsnsKdgztp93FnI"
      }
    )
    context = {
        'recipe': response.body,
        'directions': recipe.body
    }

    return render(request, 'recipe_detail.html', context)
Exemplo n.º 4
0
def Client(x):
    if x == 1:
        data = unirest.get('http://localhost:4567/rest/estudiantes/',
                           headers={"Accept": "application/json"})
        print(data.body)
        return Menu()

    elif x == 2:
        y = input("Digite una matricula")
        data2 = unirest.get(
            'http://localhost:4567/rest/estudiantes/{}'.format(y),
            headers={"Accept": "application/json"})
        print(data2.body)
        return Menu()

    elif x == 3:
        nom = raw_input("Digite el nombre del nuevo estudiante")
        email = raw_input("Digite el correo del nuevo estudiante")
        carrera = raw_input("Digite la carrera del nuevo estudiante")
        data3 = unirest.post('http://localhost:4567/rest/estudiantes/',
                             headers={
                                 "Content-Type": "application/json",
                                 "Accept": "application/json"
                             },
                             params=json.dumps({
                                 "nombre": nom,
                                 "correo": email,
                                 "carrera": carrera
                             }))
        print(data3.body)
        return Menu()
    else:
        return 0
Exemplo n.º 5
0
def get_concepts(url):
    encoded_url = urllib.quote(url, '')

    response = unirest.get(
        "http://access.alchemyapi.com/calls/url/URLGetRankedConcepts",
        headers={"Accept": "text/plain"},
        params={
            'url': encoded_url,
            'apikey': creds['alchemy_key_3'],
            'maxRetrieve': 20,
            'outputMode': 'json'
        })

    concepts = []

    for c in response.body['concepts']:
        concepts.append(c['text'])

    response = unirest.get('http://interest-graph.getprismatic.com/url/topic',
                           headers={
                               "Accept": "text/plain",
                               'X-API-TOKEN': creds['prismatic_key']
                           },
                           params={
                               'url': encoded_url,
                           })

    try:
        for t in response.body['topics']:
            concepts.append(t['topic'])
    except TypeError:
        pass

    return set(concepts)
Exemplo n.º 6
0
   def _dispatch(self, urls):
      with self.lock:
         for link in urls:
            # Avoid exploring the same page twice.
            if link in self.seen:
               continue

            try:
               # TODO: Should be removed in final version.
               # If it's a local file, just go ahead and read the file.
               if link.startswith('/'):
                  class ResponseDummy:
                     def __init__(self, file):
                        self.body = open(file)
                  syncCB = partial(self._callback, self.router.match(link))
                  Thread(target=syncCB, args=(link, ResponseDummy(link))).start()
               # TODO: stop removing dummy code here.

               else:
                  # Request page contents asynchronously.
                  get(link, callback=partial(self._callback, self.router.match(link), link))

               self.seen.add(link)
               self.pending += 1

            except Router.NoMatchError as e:
               print 'Could not find handler endpoint for {0}.'.format(str(e))
Exemplo n.º 7
0
def handleGif(msg, chatID, bot):

    # Handle commands issued with no arguments
    try:
        tag = msg["text"].split(' ', 1)[1:]
    except:
        tag = ""

    formattedTag = ""
    for i in range(len(tag)):
        if tag[i] == ' ':
            formattedTag += '+'
        else:
            formattedTag += tag[i]

    # No arguments: Random trending Gif
    if formattedTag == "":
        response = unirest.get(
            "http://api.giphy.com/v1/gifs/trending?api_key=dc6zaTOxFJmzC&limit=1"
        ).body
        bot.sendMessage(chatID, response["data"][0]["url"])
    # Gif related to keyword
    else:
        response = unirest.get(
            "http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=" +
            formattedTag).body
        bot.sendMessage(chatID, response["data"]["image_url"])
Exemplo n.º 8
0
def get_class_collection(player_class):
    response = unirest.get(
        "https://omgvamp-hearthstone-v1.p.mashape.com/cards/classes/" + player_class + "?collectible=1",
        headers={"X-Mashape-Key": "HFXwiln4KJmshs6B1jOMfsA75kg3p1Jj1qOjsntjBvnGaWzx1v"},
    )

    classCards = json.dumps(response.body, indent=1, separators=(",", ": "))

    classCardsDict = json.loads(classCards)

    removeHeroes = list()

    for x in classCardsDict:
        if x["type"] != "Hero":
            removeHeroes.append(x)

    response2 = unirest.get(
        "https://omgvamp-hearthstone-v1.p.mashape.com/cards/types/Minion?collectible=1",
        headers={"X-Mashape-Key": "HFXwiln4KJmshs6B1jOMfsA75kg3p1Jj1qOjsntjBvnGaWzx1v"},
    )

    minionCards = json.dumps(response2.body, indent=1, separators=(",", ": "))

    minionCardsDict = json.loads(minionCards)

    neutralCardsDict = list()

    for y in minionCardsDict:
        if "playerClass" not in y:
            neutralCardsDict.append(y)

    collection = removeHeroes + neutralCardsDict

    return collection
Exemplo n.º 9
0
def identify_image(inputFileURL):
    response = unirest.post("https://camfind.p.mashape.com/image_requests",
  headers={
    "X-Mashape-Key": "9UyIuOYhCKmshb72Y27ctmWYJReGp1G3LaBjsndZ3QPhPjjHMl"
  },
  params={
    "focus[x]": "480",
    "focus[y]": "480",
    "image_request[language]": "en",
    "image_request[locale]": "en_US",
    "image_request[remote_image_url]": ""+str(inputFileURL)+""
  }
)

    token = response.body['token'] # The parsed response
    print token
    response2 = unirest.get("https://camfind.p.mashape.com/image_responses/"+str(token),
  headers={
    "X-Mashape-Key": "9UyIuOYhCKmshb72Y27ctmWYJReGp1G3LaBjsndZ3QPhPjjHMl"
  }
)
    time.sleep(1)
    while (response2.body['status'] == 'not completed'):
        response2 = unirest.get("https://camfind.p.mashape.com/image_responses/"+str(token),
    headers={
        "X-Mashape-Key": "9UyIuOYhCKmshb72Y27ctmWYJReGp1G3LaBjsndZ3QPhPjjHMl"
    }
    )
    print "Sleeping"
    time.sleep(1)

    #print response2.body
    print response2.raw_body
Exemplo n.º 10
0
def get_information(url):
    """Get information for url using webscraping and API calls."""

    all_info = []

    scrape_info = get_all_recipe_info(url)

    response1 = unirest.get(
        "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/extract?forceExtraction=false&url=%s"
        % url,
        headers={"X-Mashape-Key": os.environ['MASHAPE_KEY']})
    api_info = response1.body
    recipe_api_id = api_info['id']

    #instructions for recipe through api request
    response2 = unirest.get(
        "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/%s/analyzedInstructions?stepBreakdown=true"
        % recipe_api_id,
        headers={
            "X-Mashape-Key": os.environ['MASHAPE_KEY'],
            "Accept": "application/json"
        })
    instruction_info = response2.body[0]['steps']

    all_info.append(scrape_info)
    all_info.append(api_info)
    all_info.append(instruction_info)

    return all_info
Exemplo n.º 11
0
def get_pronunciation(word):
    url = "https://wordsapiv1.p.mashape.com/words/" + word + "/pronunciation"
    print(url)
    try:
        response = unirest.get(
            url,
            headers={
                "X-Mashape-Key":
                "Rxx96iAmPtmsh7QzQ18RyvTyIKLop1tN4Gzjsn99lrgaYA1wq2",
                "Accept": "application/json"
            })
    except:
        print("check word: " + word)
        response = unirest.get(
            "https://jchencha-autosuggest.p.mashape.com/suggest/?word=" + word,
            headers={
                "X-Mashape-Key":
                "Rxx96iAmPtmsh7QzQ18RyvTyIKLop1tN4Gzjsn99lrgaYA1wq2",
                "Accept": "application/json"
            })
        return get_pronunciation(response.body['mispelt']['suggestions'][0])
    else:
        print(response.raw_body)
        if 'pronunciation' in response.body:
            result = response.body['pronunciation']
            if 'all' in result:
                return result['all']
            if 'verb' in result:
                return result['verb']
            return result
        else:
            return "**"
Exemplo n.º 12
0
	def get_concepts_sentiment(url):
		url_encoded = urllib.quote(url, '')
		response = unirest.get("http://access.alchemyapi.com/calls/url/URLGetRankedConcepts",
			headers={
				"Accept": "text/plain"
			},
			params={
				'url': url_encoded,
				'apikey': '',
				'maxRetrieve': 20,
				'outputMode': 'json'
			}
		)

		concept_sentiment = {}

		for c in response.body['concepts']:
			sentiment = unirest.get("http://access.alchemyapi.com/calls/text/TextGetTextSentiment",
				headers={
					"Accept": "text/plain"
				},
				params={
					'apikey': '',
					'text': c['text'],
					'outputMode': 'json'
				}
			)

			try:
				print c['text'] + ': ' + sentiment.body['docSentiment']['score']
				concept_sentiment[c['text']] = sentiment.body['docSentiment']['score']
			except KeyError:
				print c['text'] + ': Neutral'	

		return concept_sentiment
Exemplo n.º 13
0
def describeImage(imgPath):
	response = unirest.post("https://camfind.p.mashape.com/image_requests",
	  headers={
	    "X-Mashape-Key": "You meshape key, register at meshape https://market.mashape.com/imagesearcher/camfind"
	  },
	  params={
	    "image_request[image]": open(imgPath, mode="r"),
	    "image_request[language]": "en",
	    "image_request[locale]": "en_US"
	  }
	)
	
	token=response.body['token']
	
	response = unirest.get("https://camfind.p.mashape.com/image_responses/" + token,
	  headers={
	    "X-Mashape-Key": "aiYZkTIXj7mshNul9uy1GrEoIZYOp1QdFbGjsn3AexvpbfgD3g",
	    "Accept": "application/json"
	  }
	)
	
	while (response.body['status']!="completed" and response.body['status']!="skipped"):
		time.sleep(1) #sleep for 1 seconds
		response = unirest.get("https://camfind.p.mashape.com/image_responses/" + token,
		  headers={
		    "X-Mashape-Key": "aiYZkTIXj7mshNul9uy1GrEoIZYOp1QdFbGjsn3AexvpbfgD3g",
		    "Accept": "application/json"
		  }
		)
	
	#assume completed
	if (response.body['status']!="skipped"):
		return response.body['name']
	else:
		return "unsuccessful"
Exemplo n.º 14
0
 def __init__(self, name, url):
     self.name = name
     self.player_data, self.return_code = json.dumps(unirest.get('http://' + url, header={"Accept":"application/json"}).body), \
     unirest.get('http://' + url).code
     checkCode(self.return_code)
     parsed_data = json.loads(self.player_data)
     self.dict_name=''
     self.setPlayerAttributes(parsed_data)
Exemplo n.º 15
0
    def submit(self, type, msg):
        event_body = {"type": type}
        for k, v in msg.iteritems():
            event_body[k] = v

        sub_json = json.dumps(event_body)
        unirest.get("%s/%s/%s" % (self.base_url, "json", sub_json),
                    callback=lambda s: "Isn't that nice.")
Exemplo n.º 16
0
def question(qid):
    url = settings.API_URL + 'question/' + qid
    response = unirest.get(url, headers={'Content-Type':'application/json'}, params={'embedded':'{"post":1}'})
    answers  = unirest.get(settings.API_URL + 'answer/?question=' + qid, headers={'Content-Type':'application/json'})

    response.body['answer'] = answers.body['data']
    response.body['nAnswers'] = len(response.body['answer'])

    return render_template('question.html', data=response.body)
Exemplo n.º 17
0
    def run(self):
        print "Base Worker Listening"

        while 1:
            # print  "Hey Im working"

            #Keep listening there is no customer yet in store
            if orderQueue.empty():
                #Chill
                time.sleep(random.randint(10, 100) / 80.0)
                continue
            else:
                #Hey there is a Customer in my shop.
                item = self.__queue.get()

                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)

                #parse to get Customer Info
                customer_channel = parseInfo(item)
                print "Connecting to " + customer_channel

                print "Asking Customer (Burrito/Bowl)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask him his requirements Burrito/Bowl
                responseBase = unirest.get(
                    "http://" + customer_channel + "/getBase",
                    headers={"Accept": "application/json"},
                    params={"base": "Tortilla/Bowl"})

                #If customer replies with his choice, Process order and send to next worker
                if responseBase.code == 200:
                    print "I will add Delicious " + responseBase.body + " for you !"
                    baseValue = responseBase.body

                print "Asking Customer (Brown/White Rice)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask user which type of Rice he wants.
                responseRice = unirest.get(
                    "http://" + customer_channel + "/getRice",
                    headers={"Accept": "application/json"},
                    params={"rice": "Brown,White"})

                #If customer replies with his choice, Process order and send to next worker
                if responseRice.code == 200:
                    print "I will add Delicious " + responseRice.body + " for you !"
                    self.cursor = self.connection.cursor()
                    self.cursor.execute(
                        "INSERT INTO Orders(CustomerName, Stage ) VALUES ( '{0}', '{1}')"
                        .format(parseCustomerInfo(item), "1"))
                    self.connection.commit()
                    self.cursor.close()
                    riceValue = responseRice.body
                    sendToNextWorker(item, baseValue, riceValue)
Exemplo n.º 18
0
 def run(self):
     unirest.timeout(100)
     GetRequestTest.start_time = time.time()
     for i in range(self.number_of_requests):
         url = "http://0.0.0.0:5000/predict"
         body = "test" + str(i)
         print "Request: ", url, body
         unirest.get(url,
                     params={"text": body},
                     callback=GetRequestTest.callback_function)
Exemplo n.º 19
0
def show_city(name_city):
    result = ((unirest.get(URL_LL + name_city,
                           headers={"X-Mashape-Key": mashape_key,
                                    "Accept": "application/json"})).body['Results'])[0]
    response = unirest.get(URL_WEATHER.format(result['lat'], result['lon']),
                           headers={
                               "X-Mashape-Key": mashape_key,
                               "Accept": "application/json"})
    print response.body
    return ""
Exemplo n.º 20
0
    def test_timeout(self):
        unirest.timeout(3)
        response = unirest.get("http://httpbin.org/delay/1")
        self.assertEqual(response.code, 200)

        unirest.timeout(1)
        try:
            response = unirest.get("http://httpbin.org/delay/3")
            self.fail("The timeout didn't work")
        except:
            pass
Exemplo n.º 21
0
    def test_timeout(self):
        unirest.timeout(3)
        response = unirest.get('http://httpbin.org/delay/1')
        self.assertEqual(response.code, 200)

        unirest.timeout(1)
        try:
            response = unirest.get('http://httpbin.org/delay/3')
            self.fail("The timeout didn't work")
        except:
            pass
Exemplo n.º 22
0
def searchResult(inputTerm):
    currSearchTerm = getSearchTerm(inputTerm)
    output = 0
    unirest.get(currSearchTerm,
                headers={
                    "X-RapidAPI-Host":
                    "nutritionix-api.p.rapidapi.com",
                    "X-RapidAPI-Key":
                    "288a41cb01msha1a3319656f9913p114f73jsn006586d56e2e"
                },
                callback=callbackFunction).join()
    return getResult()
Exemplo n.º 23
0
def question(qid):
    url = settings.API_URL + 'question/' + qid
    response = unirest.get(url,
                           headers={'Content-Type': 'application/json'},
                           params={'embedded': '{"post":1}'})
    answers = unirest.get(settings.API_URL + 'answer/?question=' + qid,
                          headers={'Content-Type': 'application/json'})

    response.body['answer'] = answers.body['data']
    response.body['nAnswers'] = len(response.body['answer'])

    return render_template('question.html', data=response.body)
Exemplo n.º 24
0
	def runApiRequest(self,request):
		"""
		Method that run a api request
		"""
		#print "Getting information..."
		#We launch a first request
		try:
			self.response = unirest.get(request,
				  headers={
					"X-Mashape-Key": self.apiKey,
					"Accept": "text/plain"
				  }
				)
			#print "OK"
		except Exception:
			print "Error! Can't get any response from the api!"

		#if there is a response
		if self.response != None:
			#if this response is good
			if self.response.code == 200:
				#we notify the user that the request was successful
				return True
		else:

			#else we try again for a fixed number of try
			numberOfTry=1

			while (numberOfTry <self.maxTry):

				print "Try number {0}".format(numberOfTry)
				time.sleep(self.timeout)

				try:
					self.response = unirest.get(request,
						  headers={
							"X-Mashape-Key": self.apiKey,
							"Accept": "text/plain"
						  }
						)

					if self.response.code == 200:
						return True

				except Exception:
					print "Failed ! Try again in {0} secs".format(self.timeout)


				numberOfTry+=1


			return False
Exemplo n.º 25
0
 def __init__(self, urls):
     stats_data, self.return_code = unirest.get(urls[0], headers={"Accept":"application/json"}).body['data'], \
                                    unirest.get(urls[0]).code
     checkCode(self.return_code)
     for url in urls:
         self.return_code = unirest.get(url).code
         checkCode(self.return_code)
         if urls.index(url) == 0:
             continue
         stats_data += unirest.get(url, headers={"Accept":"application/json"}).body['data']
     self.setStats(stats_data)
     self.stats = stats_data
     print 'Retreived information for ' + str(len(stats_data)) + ' players.'
Exemplo n.º 26
0
    def run(self):
        print "Base Worker Listening"

        while 1:
           # print  "Hey Im working"

            #Keep listening there is no customer yet in store
            if orderQueue.empty():
                #Chill
                time.sleep(random.randint(10, 100) / 80.0)
                continue
            else:
                #Hey there is a Customer in my shop.
                item = self.__queue.get()

                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)


                #parse to get Customer Info
                customer_channel = parseInfo(item)
                print "Connecting to "+customer_channel

                print "Asking Customer (Burrito/Bowl)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask him his requirements Burrito/Bowl
                responseBase = unirest.get("http://"+customer_channel+"/getBase", headers={ "Accept": "application/json" },
                                       params={ "base": "Tortilla/Bowl" })

                #If customer replies with his choice, Process order and send to next worker
                if responseBase.code==200:
                    print "I will add Delicious "+responseBase.body+" for you !"
                    baseValue = responseBase.body

                print "Asking Customer (Brown/White Rice)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask user which type of Rice he wants.
                responseRice = unirest.get("http://"+customer_channel+"/getRice", headers={ "Accept": "application/json" },
                                       params={ "rice": "Brown,White" })

                #If customer replies with his choice, Process order and send to next worker
                if responseRice.code==200:
                    print "I will add Delicious "+responseRice.body+" for you !"
                    self.cursor = self.connection.cursor()
                    self.cursor.execute("INSERT INTO Orders(CustomerName, Stage ) VALUES ( '{0}', '{1}')".format(parseCustomerInfo(item),"1"))
                    self.connection.commit()
                    self.cursor.close()
                    riceValue = responseRice.body
                    sendToNextWorker(item,baseValue,riceValue)
Exemplo n.º 27
0
    def run(self):
        print "Meat Worker Listening"
        while 1:
            #   print  "Hey Im working: MeatWorker"

            #Keep listening there is no customer yet in store
            if meatQueue.empty():
                #Chill
                time.sleep(random.randint(10, 100) / 50.0)
                continue
            else:
                #Hey there is a Customer in my shop.
                item = self.__queue.get()
                #parse to get Customer Info
                customer_channel = parseInfo(item)
                print "Connecting to " + customer_channel

                print "Asking Customer (Chicken/Beef/Pork)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask him his requirements Burrito/Bowl
                responseMeat = unirest.get(
                    "http://" + customer_channel + "/getMeat",
                    headers={"Accept": "application/json"},
                    params={"meat": "Chicken/Beef/Pork"})

                #If customer replies with his choice, Process order and send to next worker
                if responseMeat.code == 200:
                    meatValue = responseMeat._body
                    print "I will add Delicious " + responseMeat.body + " for you !"

                print "Asking Customer (Pinto/Black Beans)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask user which type of Rice he wants.
                responseBeans = unirest.get(
                    "http://" + customer_channel + "/getBeans",
                    headers={"Accept": "application/json"},
                    params={"beans": "Pinto,Black"})

                #If customer replies with his choice, Process order and send to next worker
                if responseBeans.code == 200:
                    print "I will add Delicious " + responseBeans.body + " for you !"
                    beanValue = responseBeans.body
                    self.cursor = self.connection.cursor()
                    self.cursor.execute(
                        "UPDATE  Orders SET Stage ='{0}' WHERE CustomerName = '{1}'"
                        .format("2", parseCustomerInfo(item)))
                    self.connection.commit()
                    self.cursor.close()
                    sendToNextWorker(item, meatValue, beanValue)
Exemplo n.º 28
0
def test_not_your_objects():
    first_image_response = unirest.post(hostname + '/enroll-image/',
        params={"image": open("./arnold.jpg", mode="r"), "label":"Arnold Schwarzenegger"})
    assert first_image_response.code == 200
    training_set_id = first_image_response.body['id']
    training_set_response = unirest.get(hostname + '/trainingset/' + training_set_id + '/')
    assert training_set_response.code == 200
    unirest.clear_default_headers()
    random_username = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))
    permissions_response = unirest.get(hostname + '/trainingset/' + training_set_id + '/',
        headers={"X-Mashape-User":random_username, "X-Mashape-Proxy-Secret":"DEBUG"})
    print permissions_response.code
    print permissions_response.body
    assert permissions_response.code != 200
Exemplo n.º 29
0
def spell(src_file, string):
    l = string.split(' ')
    l = [x.replace("\r", "") for x in l]
    l = [x.replace("\n", " ") for x in l]
    l = [x.replace("\s", "") for x in l]
    l = [x.replace("\u", "") for x in l]
    #print(l)
    try:
        os.remove(src_file + "_spell" + ".txt")
        f = open(src_file + "_spell" + ".txt", "a")
    except:
        f = open(src_file + "_spell" + ".txt", "a")
    for i in l:
        if i.find(" ") != -1:
            temp = i.split(" ")
            for x in i:
                if len(x) <= 1:
                    pass
                else:
                    try:
                        response = unirest.get(
                            "https://montanaflynn-spellcheck.p.rapidapi.com/check/?text="
                            + str(x.lower()),
                            headers={
                                "X-RapidAPI-Key":
                                "3f9bb1c780msh4a63fc983a53845p122bd3jsn5f78421fed65"
                            })
                    except:
                        pass
                    #print response.raw_body
                    f.write(response.raw_body + "*br*")
        else:
            if len(i) <= 1:
                pass
            else:
                try:
                    response = unirest.get(
                        "https://montanaflynn-spellcheck.p.rapidapi.com/check/?text="
                        + str(i.lower()),
                        headers={
                            "X-RapidAPI-Key":
                            "3f9bb1c780msh4a63fc983a53845p122bd3jsn5f78421fed65"
                        })
                except:
                    pass
                #print response.raw_body
                f.write(response.raw_body + "*br*")
    f.close()
    es.ext_spell(src_file)
Exemplo n.º 30
0
 def test_remove_room_normal(self):
     sucess = 1
     room_num = 5
     res = unirest.get(SERVER_URL + 'removeRoom',
                       headers={},
                       params={"number": room_num})
     for day in range(0, 6):
         res = unirest.get(SERVER_URL + 'getTheSchedulingForASpecificDay',
                           headers={},
                           params={"day": day})
         tmp_res = json.loads(res.raw_body)
         for schedule in tmp_res['data']:
             if (schedule['room_num'] == room_num):
                 sucess = 0
     self.assertEqual(sucess, 1)
Exemplo n.º 31
0
Arquivo: bot.py Projeto: opk1/mal_bot
def getData(name):
    try:
        print "fetching " + name + " data..."
        get_data = unirest.get("https://vikhyat-hummingbird-v2.p.mashape.com/anime/" + name, 
                               headers={"X-Mashape-Key": "key"})
        if(get_data.code == 404):
            name = re.sub('s-', '-s-', name, 1)
            print "trying " + name + "..."
            get_data = unirest.get("https://vikhyat-hummingbird-v2.p.mashape.com/anime/" + name, 
                                   headers={"X-Mashape-Key": "key"})
        return get_data

    except Exception as err:
        print err()
        return None
Exemplo n.º 32
0
 def __init__(self, urls):
     print urls
     self.teams_data, self.return_code = json.dumps(unirest.get(urls[0],  headers={'Accept':'application/json'}).body), unirest.get(urls[0]).code
     checkCode(self.return_code)
     self.parsed_data = json.loads(self.teams_data)
     for url in urls:
         if urls.index(url) == 0:
             pass
         else:
             self.parsed_data['data'] += json.loads(json.dumps(unirest.get(url, headers={'Accept':'application/json'}).body))['data']
             self.return_code = unirest.get(url).code
             checkCode(self.return_code)
     self.teams = {}
     self.team_list = []
     self.setTeamList(self.parsed_data)
    def run(self):
        print "Garnish Worker Listening"
        while 1:
         #   print  "Hey Im working: MeatWorker"

            #Keep listening there is no customer yet in store
            if garnishQueue.empty():
                #Chill
                time.sleep(random.randint(10, 100) / 50.0)
                continue
            else:
                #Hey there is a Customer in my shop.
                item = self.__queue.get()
                #parse to get Customer Info
                customer_channel = parseInfo(item)
             #   print "Connecting to "+customer_channel

                print "Asking Customer (Cheese/Guacamole/Lettuce)"
                #for demo sleep
                time.sleep(random.randint(10, 100) / 50.0)
                #Lets ask him his requirements Burrito/Bowl
                responseGarnish = unirest.get("http://"+customer_channel+"/getGarnish", headers={ "Accept": "application/json" },
                                       params={ "sauce": "Cheese,Guacamole,Lettuce" })
                #If customer replies with his choice, Process order and send to next worker
                if responseGarnish.code==200:
                    garnishValue = responseGarnish._body
                    self.cursor = self.connection.cursor()
                    print "I will add Delicious "+responseGarnish.body+" for you !"
                    self.cursor.execute("UPDATE  Orders SET Stage ='{0}' WHERE CustomerName = '{1}'".format("4",parseCustomerInfo(item)))
                    self.connection.commit()
                    self.cursor.close()
                    sendToNextWorker(item,garnishValue)
Exemplo n.º 34
0
def image_view(request):
    # クエリで送るパラメータを辞書形式で指定
    query_string = urllib.urlencode({"format": "xml", "mkt": "ja-JP", "n": 20})

    # APIを呼び出してレスポンスオブジェクトを得る
    response = unirest.get(API_URL + "?" + query_string)
    xml_data = response.body
    root = ET.fromstring(xml_data)

    image_urls = []
    for idx, obj in enumerate(root):
        image_url = obj[3].text
        image_url = str(BING_URL) + str(image_url)
        if idx < len(root) - 1:
            image_urls.append(image_url)

    image_json = json.dumps({'image_urls': image_urls})

    # HTTPコードをチェックして200以外だったらエラーということで例外を上げる
    if response.code != 200:
        raise Exception("HTTP Error %d : %s" %
                        (response.code, response.raw_body))

    result = {"data": image_json}

    return render(request, 'drawing/render_image.html', result)
Exemplo n.º 35
0
def get_rosters_from_url(rosters_outfile):
	global PLAYERS, TEAM_CODES
	for team, code in TEAM_CODES.iteritems():
		print 'Fetching roster for %s...' % team
		url = BASE_URL+code
		try:		
			result = unirest.get(url).body
		except Exception as e:
			print 'ERROR: could not access %s' % url
			continue
		soup = BeautifulSoup(result)
		results = soup.find_all('tr', {'class': 'evenrow'}) + soup.find_all('tr', {'class': 'oddrow'})
		for result in results:
			player = {}
			temp = result.contents
			player['SPORT'] = 'NBA'
			player['TEAM'] = team
			player['JERSEY'] = temp[0].contents[0].encode('utf-8')
			player['URL'] = temp[1].contents[0]['href'].replace('_', 'stats/_')
			player['POSITION'] = temp[2].contents[0].encode('utf-8')
			player['SUCCESS'] = False
			PLAYERS.append(player)
	print 'Finished fetching rosters.'
	print 'Saving rosters to file...'
	json_data = open(rosters_outfile, 'w+')
	json_data.write(json.dumps(PLAYERS))
	json_data.close()
	print 'Finished saving rosters to file.'
Exemplo n.º 36
0
def File(url):
    token = 'xoxp-128968699074-129647659430-130721698532-39f199c8591c8dcebd0a203adf0b1a96'
    response = requests.get(url,
                            stream=True,
                            headers={'Authorization': 'Bearer %s' % token})
    if response.status_code == 200:
        print 200
        with open('a.jpg', 'wb') as f:
            shutil.copyfileobj(response.raw, f)
        app = ClarifaiApp("vRFXZQ1VC4WEBnurtH1XiehfUL7DgZoV4oMHcX7n",
                          "DFzeuPqmt0T3UoMODZiCX904IV84SYOHXz0gkdTO")
        model = app.models.get('food-items-v1.0')
        image = app.inputs.create_image_from_filename("/home/aashay/a.jpg")
        a = model.predict([image])
        for i in a['outputs'][0]['data']['concepts']:
            print i['name']
            j = i['name']
            r = unirest.get(
                "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?ingredients="
                + j + "&number=2&ranking=1",
                headers={
                    "X-Mashape-Key":
                    "6FqK3rSNW1mshw87nHsd9cXFsuXUp1TjKIvjsnkWYXlmgbVO41",
                    "Accept": "application/json"
                })

            print r.body

            break
    del response
Exemplo n.º 37
0
def removeActions(stocks, lookback):
	cleanList = []
	for s in stocks:
		urlSym = s["SYMBOL"]
		# urlSym = urllib.quote_plus(s["SYMBOL"])
		# print "downloading actions for", urlSym
		
		pResponse = unirest.get("https://stockviz.p.mashape.com/news/corporateActions", 
			params={
				"symbol": urlSym
			},
			headers={
				"X-Mashape-Authorization": mashape_auth,
				"Accept": "application/json"
			}
		);
		
		if pResponse.code == 200:
			d=datetime.date.today()-datetime.timedelta(days=lookback)
			ca = pResponse.body[len(pResponse.body)-1]
			lcad = datetime.datetime.strptime(ca["EX_DATE"], "%Y-%m-%dT%H:%M:%S").date()
			if d > lcad:
				# print " adding", s["SYMBOL"]
				cleanList.append(s)
				
	return cleanList
Exemplo n.º 38
0
def text_messages(message):
    last_message = message.text

    if "-" in last_message:
        list_items = []
        for item in last_message.split('-'):
            list_items.append(item)

        response = unirest.get(
            "https://musixmatchcom-musixmatch.p.mashape.com/wsr/1.1/matcher.lyrics.get?q_artist={}&q_track={}"
            .format(list_items[0], list_items[1]),
            headers={
                "X-Mashape-Key":
                "FAcV4trxZUmshiGXuWRh5NtlRoADp1YZ3kvjsnTezlPZM4aSv6",
                "Accept": "application/json"
            }).body
        if response != "":
            lyricsText = response['lyrics_body']
            lyricsText = lyricsText.split('*****')
            bot.send_message(message.chat.id, lyricsText)
        else:
            bot.send_message(
                message.chat.id,
                "У нашому каталозі немає такої пісні. \nПеревірте правильність вводу, або введіть іншу пісню"
            )

    else:
        bot.send_message(
            message.chat.id,
            "Введіть ім'я артиста та назву треку через тире ' - ' \nНаприклад: \nArmin van Buuren - I Need you"
        )
Exemplo n.º 39
0
def info(ip_list):
    '''
    return list of ip information:
    -> [{info1}, {info2}, ...]

    the info* format:
    {
        "ip":           "x.x.x.x",
        "city":         "xxxxx",
        "area_id":      "xxxxxx",
        "region_id":    "xxxxxx",
        "area":         "xxxxxxxxxxxx",
        "city_id":      "xxxxxx",
        "country":      "xxxxxxxxxxxx",
        "region":       "xxxxxxxxxxxxxxxxxx",
        "isp":          "xxxxxxxxxxxxxxxxxx",
        "country_id":   "xx",
        "county":       "",
        "isp_id":       "xxxxxx",
        "county_id":    "xx"
    }
    '''
    data = []
    for ip in ip_list:
        response = unirest.get(URL, params={'ip': ip})
        json_data = response.body
        info = {}
        if json_data['code'] == 0:  # success
            info = json_data['data']
        data.append(info)
        time.sleep(0.1)  # 为了保障服务正常运行,每个用户的访问频率需小于10qps。
    return data
Exemplo n.º 40
0
def recognize_and_save_person(image_fname):
    faces_data = detect_faces(image_fname)["images"][0]
    if not faces_data["faces"]:
        print "NO FACES DETECTED! Finishing..."
        return
    im = Image.open(image_fname)
    for face in faces_data["faces"]:
        query_uri = """https://animetrics.p.mashape.com/recognize?
                        api_key=%s&
                        gallery_id=%s&
                        image_id=%s&
                        height=%d&
                        width=%d&
                        topLeftX=%d&
                        topLeftY=%d
                        """ % (api_key, "Designers", faces_data["image_id"],
                               face["height"], face["width"], face["topLeftX"], face["topLeftY"])
        query_uri = query_uri.replace("\t", "").replace(" ", "").replace("\n", "")
        response = unirest.get(query_uri,
                               headers={
                                   "X-Mashape-Key": mashape_key,
                                   "Accept": "application/json"
                               }
                               )
        candidates_probs = response.body["images"][0]["candidates"]
        max_prob, selected_candidate = max([(prob, cand_name) for cand_name, prob in candidates_probs.items()])
        im = show_faces(im, face["topLeftX"], face["topLeftY"], face["height"], face["width"], selected_candidate + ":" + str(max_prob)[:4])
        import time
        time.sleep(3)
    im.save("recognized/" + image_fname.split("/")[-1])
Exemplo n.º 41
0
def hello_world():
	response = unirest.get("https://daxeel-abbreviations-v1.p.mashape.com/all/" + request.args.get('a'),
	  headers={
	    "X-Mashape-Key": "key"
	  }
	)    
	return response.raw_body
Exemplo n.º 42
0
 def MashapeBreakingNews(self):
     url = "https://myallies-breaking-news-v1.p.mashape.com/news"
     headers = {"X-Mashape-Key": MashapeKey, "Accept": "application/json"}
     response = unirest.get(url, headers=headers)
     if response.code is not 200:
         abort(response.code, response.body)
     return response.body
Exemplo n.º 43
0
	def run(self):
		
		for subs in getFrontPage():
			subArray = subs.title.split()
			for i in subArray:
				print "i is: " + i
				matchO = re.match("^((?![,.?!;:]).)*$", i)
				if matchO:

					url = "https://wordsapiv1.p.mashape.com/words/" + i + "/syllables"
					print "url is: " + url
					# These code snippets use an open-source library. http://unirest.io/python
					
					try:
						response = unirest.get(url,
						  headers={
						    "X-Mashape-Key": "MqocUSZZ8vmshdZKANtf2ay0cP9jp1JGrdcjsn0faXKxsOlkoC",
						    "Accept": "application/json"
						  }
						)

						print json.loads(response.raw_body["syllables"])
					except:
						print "something happened"
				else:
					print "no match!"
Exemplo n.º 44
0
def get_drink(drink):
	
	"""
	Gets a list of possible drinks, and returns the first one.
	"""
	
	# Do a quick search of our currently loaded drinks
	
	if drinks:
		for d in drinks:
			if drink.lower() == d['name'].lower() or drink.lower().replace(' ', '') == d['name'].lower().replace(' ', ''):
				print "Returning from dict!"
				print ""
				return d
				
	# If there isn't a good match, search for it using the API
	
	response = unirest.get("https://absolutedrinks.p.mashape.com/quickSearch/drinks/" + 
			drink + "?Apikey=" + api_key + "&pageSize=1",
		headers={
			"X-Mashape-Key": mashape_key,
			"Accept": "text/plain"
		}
	)
	
	if response.body and 'result' in response.body:
		return response.body['result'][0]
Exemplo n.º 45
0
def get_corpus_score(close_sentences):
    closest_sentences = []
    # print close_sentences
    for line in close_sentences:
        unirest.timeout(10)
        try:
            response = unirest.get("https://twinword-sentiment-analysis.p.mashape.com/analyze/?text=%s" % line,
            headers={
            "X-Mashape-Key": "ur8eDH4fVCmshtOozaz1zoWSjS79p1U8IGljsnA2aJAoTuh4Fc",
            "Accept": "application/json"
            }
            )
        except Exception, e:
            # print "exception thrown"
            continue
        if response.code != 200:
            continue
        t = response.body
        score = t['score']
        if 0.05 < score < 0.5:
            score = 1
        elif 0.5 < score < 2.0:
            score = 2
        elif score > 2.0:
            score = 3
        elif -0.05 < score < 0.5:
            score = 0
        elif -0.5 < score < -0.05:
            score = -1
        elif -0.5 < score < -2.0:
            score = -2
        else:
            score = -3
        closest_sentences.append((score, line))
Exemplo n.º 46
0
def display_recipes():
    """Find recipes using Spoonacular API"""

    user_id = session['user']
    user_refrigerator = (Refrigerator.query.filter_by(user_id=user_id)).all()
    ingredients = ""

    # create ingredients list to pass to API request
    for item in user_refrigerator:
        ingredients += item.food.food + ", "

    payload = {
        'fillIngredients': 'false',
        'ingredients': ingredients,
        'limitLicense': 'false',
        'number': 6,
        'ranking': 1
    }

    r = unirest.get(
        "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients",
        headers={
            "X-Mashape-Key": os.environ['X_Mashape_Key'],
            "Accept": "application/json"
        },
        params=payload)

    body = r.body

    return jsonify(body)
Exemplo n.º 47
0
def info(ip_list):
    '''
    return list of ip information:
    -> [{info1}, {info2}, ...]

    the info* format:
    {
        "ip":           "x.x.x.x",
        "city":         "xxxxx",
        "area_id":      "xxxxxx",
        "region_id":    "xxxxxx",
        "area":         "xxxxxxxxxxxx",
        "city_id":      "xxxxxx",
        "country":      "xxxxxxxxxxxx",
        "region":       "xxxxxxxxxxxxxxxxxx",
        "isp":          "xxxxxxxxxxxxxxxxxx",
        "country_id":   "xx",
        "county":       "",
        "isp_id":       "xxxxxx",
        "county_id":    "xx"
    }
    '''
    data = []
    for ip in ip_list:
        response = unirest.get(URL, params={'ip': ip})
        json_data = response.body
        info = {}
        if json_data['code'] == 0:  # success
            info = json_data['data']
        data.append(info)
        time.sleep(0.1)  # 为了保障服务正常运行,每个用户的访问频率需小于10qps。
    return data
Exemplo n.º 48
0
    def GetCurrentScore(self, word):

        url = "https://montanaflynn-dictionary.p.mashape.com/define?word=" + word

        # These code snippets use an open-source library.
        response = unirest.get(url,
            headers={
                "X-Mashape-Key": "j6rDcjfVcVmshxp0Y102O2cL6vDrp16mL1FjsnsgRqpcl6fC3L",
                "Accept": "application/json"
            }
        )

        resp = word + '\n\n'

        data = json.dumps(response.body, separators=(',',':'))
        meanings = (json.loads(data))["definitions"]
        
        count = 0
        for meaning in meanings:
            count = count + 1
            resp = resp + 'm' + str(count) +' : ' + str(meaning["text"]) + '\n\n'

        # Create Text response
        text_response = str(resp)

        #Return details
        return str(text_response)
def enroll_person(image_fname, person_id):
   faces_data = detect_faces(image_fname)["images"][0]
   if not faces_data["faces"]:
       print "NO FACES DETECTED! Finishing..."
       return
   for face in faces_data["faces"]:
       query_uri = """https://animetrics.p.mashape.com/enroll?
                        api_key=%s&
                        gallery_id=%s&
                        image_id=%s&
                        subject_id=%s&
                        height=%d&
                        width=%d&
                        topLeftX=%d&
                        topLeftY=%d
                        """ % (api_key, "Designers", faces_data["image_id"], person_id,
                               face["height"], face["width"], face["topLeftX"], face["topLeftY"])
       query_uri = query_uri.replace("\t", "").replace(" ", "").replace("\n", "")
       response = unirest.get(query_uri,
         headers={
           "X-Mashape-Key": mashape_key,
           "Accept": "application/json"
         }
       )
       return response.body
Exemplo n.º 50
0
def handleFact(msg, chatID, bot):
	
	# Choose from 4 possible categories
	factType = random.choice(["trivia","math","date","year"])
	
	# Fetch fact in plain text
	response = unirest.get("https://numbersapi.p.mashape.com/random/"+factType+"?fragment=false&json=true",headers={"X-Mashape-Key":"DuskHHYl5DmshhsjvJ4LaVXZinfpp1KnC92jsndIqrz6pC0CDa","Accept": "text/plain"}).body
	
	# Handle "year" type facts
	if response["type"] == "year":
		if "year" in response:
			fact = "Year: " + str(response["year"]) + "\n" + response["text"].title() + "."
		else:
			fact = response["text"].title() + "."
	# Handle "math" type facts
	elif response["type"] == "math":
		fact = response["text"].title() + " is " + str(response["number"]) + "."
	# Handle "trivia" type facts
	elif response["type"] == "trivia":
		fact = response["text"].title() + " is " + str(response["number"]) + "."
	# Handle "date" type facts
	else:
		if "year" in response:
			fact = "Year: " + str(response["year"]) + "\n" + response["text"].title() + "."
		else:
			fact = response["text"].title() + "."

	bot.sendMessage(chatID, fact)
Exemplo n.º 51
0
def sms(request):
    pid = str(request.POST.get("pid", ""))
    phno = str(request.POST.get("phno", ""))
    plast = str(request.POST.get("plast", ""))
    pnext = str(request.POST.get("pnext", ""))
    pstatus = str(request.POST.get("pstatus", ""))

    print (phno)
    msg = (
        "YOUR PARCEL WITH ID : "
        + pid
        + " IS AT "
        + plast
        + ". NEXT STATION : "
        + pnext
        + ". STATUS : "
        + pstatus
        + "- Regards : MIST Courier Services."
    )

    print (msg)

    response = unirest.get(
        "https://site2sms.p.mashape.com/index.php?msg=" + msg + "&phone=" + phno + "&pwd=nsknsp10&uid=9494473579",
        headers={"X-Mashape-Key": "8Mm8na6YEamsh3KZtQjBfHVXQjl4p1nM6G7jsntyy4P1F2By56", "Accept": "application/json"},
    )

    cont = {"phno": phno, "pid": pid}
    return render(request, "profile.html", cont)
Exemplo n.º 52
0
def nutritions():
    response = unirest.get(
        "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/541691/information?includeNutrition=true",
        headers={
            "X-Mashape-Key":
            "uI9T1GTt8nmshcUUWJOjq8TQNGBgp1P9Zffjsn7dAbkmTSDt1k",
            "Accept": "application/json"
        })
    recipeInfo = response.body

    selectedNutritions = ['Calories', 'Fat', 'Saturated Fat', 'Sugar']
    recipeNutritions = recipeInfo['nutrition']['nutrients']
    nutritionsDict = {
        nutrition['title']: nutrition['amount']
        for nutrition in recipeNutritions
        if nutrition['title'] in selectedNutritions
    }
    nutritionsDict

    recipeNutritions = recipeInfo['nutrition']['ingredients']
    for ingredient in recipeNutritions:
        nutrients = ingredient['nutrients']
        ingrNutritions = [nut['name'] for nut in nutrients]
        #print len(ingrNutritions)
    print(ingrNutritions)
def recognize_and_save_person(image_fname):
   faces_data = detect_faces(image_fname)["images"][0]
   if not faces_data["faces"]:
       print "NO FACES DETECTED! Finishing..."
       return
   for face in faces_data["faces"]:
       query_uri = """https://animetrics.p.mashape.com/recognize?
                        api_key=%s&
                        gallery_id=%s&
                        image_id=%s&
                        height=%d&
                        width=%d&
                        topLeftX=%d&
                        topLeftY=%d
                        """ % (api_key, "Designers", faces_data["image_id"],
                               face["height"], face["width"], face["topLeftX"], face["topLeftY"])
       query_uri = query_uri.replace("\t", "").replace(" ", "").replace("\n", "")
       response = unirest.get(query_uri,
         headers={
           "X-Mashape-Key": mashape_key,
           "Accept": "application/json"
         }
       )
       candidates_probs = response.body["images"][0]["candidates"]
       selected_candidate = max([(prob, cand_name) for cand_name, prob in candidates_probs.items()])[1]
       crop(image_fname, face["topLeftX"], face["topLeftY"], face["height"], face["width"], make_filename(selected_candidate))
       import time
       #to not exceed maximum request frequency
       time.sleep(1)
Exemplo n.º 54
0
    def get_score(self, item):
        response = unirest.get(
            "https://montanaflynn-gender-guesser.p.mashape.com/?name={0}".format(
                urllib.quote_plus(item)),
            headers={
                "X-Mashape-Key": "SuRl5yqxrrmsh4S2wAFlX9vmDWFUp1zg4Nsjsn9pi3WOXUUhwW",
                "Accept": "application/json"
            }
        )

        try:
            gender = response.body["gender"]
        except:
            # no gender response (or any error) means neutral
            return 1.0

        if not gender:
            return 1.0
        elif gender == "female":
            return 1.5
        elif gender == "male":
            return 0.5
        else:
            # non-binary genders get a bonus
            return 2.0
Exemplo n.º 55
0
def get_stats(player):
	unirest.timeout(3)
	try:
		response = unirest.get(player['URL']).body;
	except Exception as e:
		print 'ERROR: %s for url: %s' % (str(e), player['URL'])
		player['SUCCESS'] = False
		return player
	player['SUCCESS'] = True
	soup = BeautifulSoup(response);
	player['NAME'] = soup.find_all('h1')[1].contents[0].encode('utf-8')
	results = soup.find_all('tr', {'class':'oddrow'})
	for result in results:
		if result.contents[0].contents[0] == '2014 Regular Season':
			qb_stats = result.contents[1:] 
			try:	
				player['YDS'] = int(qb_stats[2].contents[0].replace(',', ''))
			except Exception as e:
				player['YDS'] = 0
			try:
				player['TD'] = int(qb_stats[5].contents[0].replace(',', ''))
			except Exception as e:
				player['TD'] = 0
			return player
	player['YDS'] = 0
	player['TD'] = 0
	return player
Exemplo n.º 56
0
    def listen_notes_favorite(self, n='All'):
        #These code snippets use an open-source library. http://unirest.io/python
        #find most popular podcast from listen notes
        response = unirest.get("https://listennotes.p.mashape.com/api/v1/best_podcasts?page=1",
                           headers={
                           "X-Mashape-Key": "",
                           "Accept": "application/json"
                           }
                           )
        
        listen_notes_pods = response.body['channels']
       # print(listen_notes_pods[1]['website'])
        response_listen_notes=[]
        if len(listen_notes_pods) > 5:
           
           for i in range(3):
               response_listen_notes.append(listen_notes_pods[i][u'website'])

        else:
    
            for i in range(len(listen_notes_pods)):
                response_listen_notes.append(listen_notes_pods[i][u'website'])
    
        url_string = str();
        if n == 'All' or n == 0:
            
            for i in response_listen_notes:
                url_string = url_string + " " + str(i)

        else:
            for i in range(n):
                _url = response_listen_notes[i]
                url_string = url_string + " " + str(_url)

            return url_string
Exemplo n.º 57
0
def get_lyrics(artist):
	"""https://market.mashape.com/musixmatch-com/musixmatch"""
	song_list = songs(artist)
	print song_list
	artist_info(artist)
	for song in song_list:
		d = {}
		song = song.replace(" ", "+")
		response = unirest.get("https://musixmatchcom-musixmatch.p.mashape.com/wsr/1.1/matcher.lyrics.get?q_artist=" + artist + "&q_track=" + song,
		  headers={
		    "X-Mashape-Key": "DgoyXd9bunmshI9yT2CZbaGMDhTPp1x6YvIjsnmUnx2XbEtDw4",
		    "Accept": "application/json"
		  }
		)
		song = song.replace("+", " ")
		print "			***"
		print song
		print "			***" 
		text = response.body['lyrics_body']
		if len(text) == 0:
			print "			No lyrics found"
		else:
			lines = text.split("\n")
			for line in lines:
				if len(line) > 1:
					d = get_emotions(d, line)
			for item in d:
				print item, d[item]