Python: Google Contacts API only retrieving 3 contacts - python

I am new to Python and to the Google APIs.
I have the following code from https://developers.google.com/google-apps/contacts/v3/?hl=en:
def PrintAllContacts(gd_client):
feed = gd_client.GetContacts()
for i, entry in enumerate(feed.entry):
print '\n%s %s' % (i+1, entry.name.full_name.text)
if entry.content:
print ' %s' % (entry.content.text)
# Display the primary email address for the contact.
for email in entry.email:
if email.primary and email.primary == 'true':
print ' %s' % (email.address)
# Show the contact groups that this contact is a member of.
for group in entry.group_membership_info:
print ' Member of group: %s' % (group.href)
# Display extended properties.
for extended_property in entry.extended_property:
if extended_property.value:
value = extended_property.value
else:
value = extended_property.GetXmlBlob()
print ' Extended Property - %s: %s' % (extended_property.name, value)
This is only returning 3 contacts out of c. 850. Any thoughts, anyone?

This works:
def PrintAllContacts(gc):
max_results = 20000
start_index = 1
query = gdata.contacts.client.ContactsQuery()
query.max_results = max_results
query.start_index = start_index
feed = gc.GetContacts(q=query)
print len(feed.entry)
for e in feed.entry:
print e.name
for email in e.email:
print email.address
Useful link: https://gdata-python-client.googlecode.com/hg/pydocs/gdata.contacts.data.html#ContactEntry

Related

Requests to Foursquare API is producing no output when called from the terminal

The following code doesn't produce any output when I run python findArestaurant.py in the terminal
It's supposed to produce an output that lists restaurants in places around the world.
I signed up for a Foursqure dev account, created an app, and was then able to copy both the client id, and client secret. However, no output?
filename: findArestaurant.py
from geocode import getGeocodeLocation
import json
import httplib2
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)
foursquare_client_id = "entered_here"
foursquare_client_secret = "entered_here"
def findARestaurant(mealType,location):
#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
latitude, longitude = getGeocodeLocation(location)
#2. Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType))
h = httplib2.Http()
result = json.loads(h.request(url,'GET')[1])
if result['response']['venues']:
#3. Grab the first restaurant
restaurant = result['response']['venues'][0]
venue_id = restaurant['id']
restaurant_name = restaurant['name']
restaurant_address = restaurant['location']['formattedAddress']
address = ""
for i in restaurant_address:
address += i + " "
restaurant_address = address
#4. Get a 300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
result = json.loads(h.request(url, 'GET')[1])
#5. Grab the first image
if result['response']['photos']['items']:
firstpic = result['response']['photos']['items'][0]
prefix = firstpic['prefix']
suffix = firstpic['suffix']
imageURL = prefix + "300x300" + suffix
else:
#6. if no image available, insert default image url
imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
#7. return a dictionary containing the restaurant name, address, and image url
restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
print ("Restaurant Name: %s" % restaurantInfo['name'] )
print ("Restaurant Address: %s" % restaurantInfo['address'] )
print ("Image: %s \n" % restaurantInfo['image'] )
return restaurantInfo
else:
print ( "No Restaurants Found for %s" % location )
return "No Restaurants Found"
if __name__ == '__main__':
findARestaurant("Pizza", "Tokyo, Japan")
findARestaurant("Tacos", "Jakarta, Indonesia")
findARestaurant("Tapas", "Maputo, Mozambique")
findARestaurant("Falafel", "Cairo, Egypt")
findARestaurant("Spaghetti", "New Delhi, India")
findARestaurant("Cappuccino", "Geneva, Switzerland")
findARestaurant("Sushi", "Los Angeles, California")
findARestaurant("Steak", "La Paz, Bolivia")
findARestaurant("Gyros", "Sydney, Australia")

Write to Mifare sector NFC RFIDIOT Python

I'm trying to write a number to sector 10 / block 40 on a Mifare 4k classic card
Any ideas on how I can get this working?
Here is my code:
BLOCK = 40
KEY = 'FFFFFFFFFFFF'
TYPE = 'AA'
import rfidiot
import re
card = rfidiot.card
if card.select():
'card selected UID: ' + str(card.uid)
if card.login(BLOCK, TYPE, KEY):
if card.readMIFAREblock(BLOCK):
print card.MIFAREdata
data = card.ReadablePrint(card.ToBinary(card.MIFAREdata))
id = re.findall('\d+', data)[0]
print id
if card.writeblock(BLOCK, '1234567'):
print 'write success'
else:
print 'error %s %s' % (card.errorcode , card.ISO7816ErrorCodes[card.errorcode])
else:
print 'read failed'
else:
print 'Login failed'
ouput+ error message:
card selected UID: DBF93873
33333735353334000000000000000000
3375534
error 6300 No information given

Python / json : Check content of keys that may or may not exist

For those familiar with imageboards, an OP post may or may not contain a 'subject' and a 'comment'
I wrote this to search all pages of a given board for thread subjects and OP posts.
If my search term exists on one of them but the other key is inexistent it will not get appended to my res list.
So how do I search json keys where 1 key or the other may not exist?
import urllib, json, HTMLParser
def s4Chan(board, search):
logo = '3::54chan'
res = []
p = HTMLParser.HTMLParser()
catalog = json.load(urllib.urlopen('https://api.4chan.org/%s/catalog.json' % board))
for i in catalog:
for j in i['threads']:
try:
if search.lower() in j['sub'].lower() or search.lower() in j['com'].lower():
subject = j['sub']
post = p.unescape(str(j['com'])).replace('<br>', ' ')
if len(post) > 300:
post = post[0:300]
post = post + '...'
text = str('%s /%s/ %s | %s | %s (R:%s, I:%s)' % (logo, board, subject, post, 'https://4chan.org/%s/res/%s' % (board, j['no']), j['replies'], j['images']))
res.append(text)
except(KeyError):
continue
return res
json.load returns objects as Python dictionaries. You can, for example, use the get method of dict:
if search.lower() in j.get('sub', '').lower() or search.lower() in j.get('com', '').lower():

Taking These Tables and Associating Their Appropriate Teams Together

I was recently assisted with getting the scores from a yahoo NHL page that would print out the teams and their aforementioned scores in a respective manner. Here is my code:
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = urlopen("http://sports.yahoo.com/nhl/scoreboard?d=2013-01-19")
content = url.read()
soup = BeautifulSoup(content)
def yahooscores():
results = {}
for table in soup.find_all('table', class_='scores'):
for row in table.find_all('tr'):
scores = []
name = None
for cell in row.find_all('td', class_='yspscores'):
link = cell.find('a')
if link:
name = link.text
elif cell.text.isdigit():
scores.append(cell.text)
if name is not None:
results[name] = scores
for name, scores in results.items():
print ('%s: %s' % (name, ', '.join(scores)) + '.')
yahooscores()
Now, first of all: I am associating this stuff in a function because I am going to have to change the url constantly to get all the values of every day of the January month.
The issue here is that while I can print the scores and team text fine, I am trying to accomplish this:
Ottawa: 1, 1, 2.
Winnipeg: 1, 0, 0.
Pittsburgh: 2, 0, 1
Philadelphia: 0, 1, 0.
See, my code doesn't do that. I was in the process of trying to get that to happen, but what is complicating the process is that the tables are all under the same class of "scores" and seemingly, I can't find anything different amongst them.
In a nutshell, associate teams correctly with each other and have a space in-between for organization.
The trouble is, you're putting the results for each team into a dict, but there's no order in a dict and so you loose track of which scores came from which table on the page (i.e. which game).
To get around this, you could just print the results directly instead of storing them, and add an extra newline in the outer for loop:
def yahooscores():
results = {}
for table in soup.find_all('table', class_='scores'):
for row in table.find_all('tr'):
scores = []
name = None
for cell in row.find_all('td', class_='yspscores'):
link = cell.find('a')
if link:
name = link.text
elif cell.text.isdigit():
scores.append(cell.text)
if name is not None:
print ('%s: %s' % (name, ', '.join(scores)) + '.')
print ""
yahooscores()
Or, if you want to store the scores and show them later, you can store the teams for each game as well and use them to group the results:
def yahooscores():
results = {}
games = []
for table in soup.find_all('table', class_='scores'):
teams = []
for row in table.find_all('tr'):
scores = []
name = None
for cell in row.find_all('td', class_='yspscores'):
link = cell.find('a')
if link:
name = link.text
elif cell.text.isdigit():
scores.append(cell.text)
if name is not None:
results[name] = scores
teams.append(name)
games.append(teams)
for teams in games:
for name in teams:
scores = results[name]
print ('%s: %s' % (name, ', '.join(scores)) + '.')
print ""
yahooscores()
The problem is that you're treating the table as a flat list of teams, rather than as a list of scores, each of which has two teams in it.
The clean way to fix that is to change the way you parse the page so you loop over the games, then, for each game, store something like a pair of names-and-scores.
But there's also a quick&dirty solution: If you kept the teams in order, you could just pair them up after the fact. A dict has no inherent order, but an OrderedDict preserves the order of insertion. So, just change results = {} to results = collections.OrderedDict.
(Although if the only thing you ever do with this dict is iterate its items(), I'm not sure why you want a dictionary at all. Just do results = [], replace results[name] = scores with results.append((name, scores)), and then iterate over results instead of results.items().)
And now, if you want to print them out in pairs… well, you can make an iterator over pairs from any iterable very easily. For example:
def pairs(iterable):
return zip(*[iter(iterable)]*2)
for (name1, score1), (name2, score2) in pairs(results.items()):
print ('%s: %s' % (n1, ', '.join(s1)) + '.')
print ('%s: %s' % (n2, ', '.join(s2)) + '.')
print
Or, if you can't figure out what that means, something hacky like this works fine too:
pair_done = False
for name, scores in results.items():
print ('%s: %s' % (name, ', '.join(scores)) + '.')
if pair_done:
print
pair_done = not pair_done
… or:
for i, (name, scores) in enumerate(results.items()):
print ('%s: %s' % (name, ', '.join(scores)) + '.')
if i % 2:
print

Python ljust not displaying properly when including a lin

I am using Django creating a site for records for football teams, I have a "pretty" display with CSS, etc, but as a backup / old school version I am trying to have the code write the information to a basic .html file that is using rjust, ljust, etc to format text. In the code below if I remove the link code, and just display the string for the team's name everything lines up properly. Once I add the HTML for the link though the columns do not line up and are completely out of whack. What have I done wrong?
standings = Team.objects.filter(active=True).order_by('-wp')
output += '<pre>\n'
output += '%s %s %s %s\n' % (str('Rk').rjust(3), str('Team').ljust(50), str('W').rjust(2), str('L').rjust(2))
output += '%s %s %s %s\n' % (str('--').rjust(3), str('----').ljust(50), str('-').rjust(2), str('-').rjust(2))
for row in mpi:
the_team = "%s" % (row.slug, row.name)
output += '%s %s %s %s\n' % (str(row.rank).rjust(3), str(the_team).ljust(50), str(row.won).rjust(2), str(row.lost).rjust(2))
output += '</pre>'
The string "%s" contains some characters that aren't rendered on browser, you're formatting the source code, not the visualization.
Replace str(row.the_team).ljust(50) by str(row.the_team).ljust(50+len(row.slug)+15) because there are 15 invisible chars (ie. ) plus the slug.
Update: You may want to remove some str. If some value is already a string, you didn't need to (re)transform it in string again.. You may also split long lines in shorten ones.
output = '<pre>\n'
output += '%s %s%s%s\n' % ('Rk'.rjust(3), 'Team'.ljust(50), 'W'.rjust(2), 'L'.rjust(2))
output += '%s %s%s%s\n' % ('--'.rjust(3), '----'.ljust(50), '-'.rjust(2), '-'.rjust(2))
for team in teams:
link = '%s' % (team.slug, team.name)
link = link.ljust(50 + len(team.slug) + 15)
rank, won, lost = str(team.rank).rjust(3), str(team.won).rjust(2), str(team.lost).rjust(2)
output += '%s %s%s%s\n' % (rank, link, won, lost)
output += '</pre>'
print output

Categories