text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_i2str(ilist):
""" Convert an integer list into a string list. """ |
slist = []
for el in ilist:
slist.append(str(el))
return slist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shellne(command):
""" Runs 'commands' on the underlying shell; any stderr is echo'd to the console. Raises a RuntimeException on any shell exec errors. """ |
child = os.popen(command)
data = child.read()
err = child.close()
if err:
raise RuntimeError('%s failed w/ exit code %d' % (command, err))
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def find(pattern, root=os.curdir):
'''Helper around 'locate' '''
hits = ''
for F in locate(pattern, root):
hits = hits + F + '\n'
l = hits.split('\n')
if(not len(l[-1])): l.pop()
if len(l) == 1 and not len(l[0]):
return None
else:
return l |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(self, *args):
"""Indicate whether or not to enter a case suite""" |
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def process_slice(self, b_rot90=None):
'''
Processes a single slice.
'''
if b_rot90:
self._Mnp_2Dslice = np.rot90(self._Mnp_2Dslice)
if self.func == 'invertIntensities':
self.invert_slice_intensities() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def slice_save(self, astr_outputFile):
'''
Saves a single slice.
ARGS
o astr_output
The output filename to save the slice to.
'''
self._log('Outputfile = %s\n' % astr_outputFile)
fformat = astr_outputFile.split('.')[-1]
if fformat == 'dcm':
if self._dcm:
self._dcm.pixel_array.flat = self._Mnp_2Dslice.flat
self._dcm.PixelData = self._dcm.pixel_array.tostring()
self._dcm.save_as(astr_outputFile)
else:
raise ValueError('dcm output format only available for DICOM files')
else:
pylab.imsave(astr_outputFile, self._Mnp_2Dslice, format=fformat, cmap = cm.Greys_r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self):
'''
Runs the DICOM conversion based on internal state.
'''
self._log('Converting DICOM image.\n')
try:
self._log('PatientName: %s\n' % self._dcm.PatientName)
except AttributeError:
self._log('PatientName: %s\n' % 'PatientName not found in DCM header.')
error.warn(self, 'PatientNameTag')
try:
self._log('PatientAge: %s\n' % self._dcm.PatientAge)
except AttributeError:
self._log('PatientAge: %s\n' % 'PatientAge not found in DCM header.')
error.warn(self, 'PatientAgeTag')
try:
self._log('PatientSex: %s\n' % self._dcm.PatientSex)
except AttributeError:
self._log('PatientSex: %s\n' % 'PatientSex not found in DCM header.')
error.warn(self, 'PatientSexTag')
try:
self._log('PatientID: %s\n' % self._dcm.PatientID)
except AttributeError:
self._log('PatientID: %s\n' % 'PatientID not found in DCM header.')
error.warn(self, 'PatientIDTag')
try:
self._log('SeriesDescription: %s\n' % self._dcm.SeriesDescription)
except AttributeError:
self._log('SeriesDescription: %s\n' % 'SeriesDescription not found in DCM header.')
error.warn(self, 'SeriesDescriptionTag')
try:
self._log('ProtocolName: %s\n' % self._dcm.ProtocolName)
except AttributeError:
self._log('ProtocolName: %s\n' % 'ProtocolName not found in DCM header.')
error.warn(self, 'ProtocolNameTag')
if self._b_convertMiddleSlice:
self._log('Converting middle slice in DICOM series: %d\n' % self._sliceToConvert)
l_rot90 = [ True, True, False ]
misc.mkdir(self._str_outputDir)
if not self._b_3D:
str_outputFile = '%s/%s.%s' % (self._str_outputDir,
self._str_outputFileStem,
self._str_outputFileType)
self.process_slice()
self.slice_save(str_outputFile)
if self._b_3D:
rotCount = 0
if self._b_reslice:
for dim in ['x', 'y', 'z']:
self.dim_save(dimension = dim, makeSubDir = True, rot90 = l_rot90[rotCount], indexStart = 0, indexStop = -1)
rotCount += 1
else:
self.dim_save(dimension = 'z', makeSubDir = False, rot90 = False, indexStart = 0, indexStop = -1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def run(self):
'''
Runs the NIfTI conversion based on internal state.
'''
self._log('About to perform NifTI to %s conversion...\n' %
self._str_outputFileType)
frames = 1
frameStart = 0
frameEnd = 0
sliceStart = 0
sliceEnd = 0
if self._b_4D:
self._log('4D volume detected.\n')
frames = self._Vnp_4DVol.shape[3]
if self._b_3D:
self._log('3D volume detected.\n')
if self._b_convertMiddleFrame:
self._frameToConvert = int(frames/2)
if self._frameToConvert == -1:
frameEnd = frames
else:
frameStart = self._frameToConvert
frameEnd = self._frameToConvert + 1
for f in range(frameStart, frameEnd):
if self._b_4D:
self._Vnp_3DVol = self._Vnp_4DVol[:,:,:,f]
slices = self._Vnp_3DVol.shape[2]
if self._b_convertMiddleSlice:
self._sliceToConvert = int(slices/2)
if self._sliceToConvert == -1:
sliceEnd = -1
else:
sliceStart = self._sliceToConvert
sliceEnd = self._sliceToConvert + 1
misc.mkdir(self._str_outputDir)
if self._b_reslice:
for dim in ['x', 'y', 'z']:
self.dim_save(dimension = dim, makeSubDir = True, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True)
else:
self.dim_save(dimension = 'z', makeSubDir = False, indexStart = sliceStart, indexStop = sliceEnd, rot90 = True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_logger(name):
"""Return a logger with a file handler.""" |
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
# File output handler
file_handler = logging.FileHandler(log_path)
file_handler.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s %(name)12s %(levelname)8s %(lineno)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timeit(method):
"""Compute the download time.""" |
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs)
end = time.time()
click.echo('Cost {}s'.format(int(end-start)))
return result
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(method):
"""Require user to login.""" |
def wrapper(*args, **kwargs):
crawler = args[0].crawler # args[0] is a NetEase object
try:
if os.path.isfile(cookie_path):
with open(cookie_path, 'r') as cookie_file:
cookie = cookie_file.read()
expire_time = re.compile(r'\d{4}-\d{2}-\d{2}').findall(cookie)
now = time.strftime('%Y-%m-%d', time.localtime(time.time()))
if expire_time[0] > now:
crawler.session.cookies.load()
else:
crawler.login()
else:
crawler.login()
except RequestException:
click.echo('Maybe password error, please try again.')
sys.exit(1)
result = method(*args, **kwargs)
return result
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_song_by_search(self, song_name):
"""Download a song by its name. :params song_name: song name. """ |
try:
song = self.crawler.search_song(song_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_song_by_id(song.song_id, song.song_name, self.folder) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_song_by_id(self, song_id, song_name, folder='.'):
"""Download a song by id and save it to disk. :params song_id: song id. :params song_name: song name. :params folder: storage path. """ |
try:
url = self.crawler.get_song_url(song_id)
if self.lyric:
# use old api
lyric_info = self.crawler.get_song_lyric(song_id)
else:
lyric_info = None
song_name = song_name.replace('/', '')
song_name = song_name.replace('.', '')
self.crawler.get_song_by_url(url, song_name, folder, lyric_info)
except RequestException as exception:
click.echo(exception) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_playlist_by_search(self, playlist_name):
"""Download a playlist's songs by its name. :params playlist_name: playlist name. """ |
try:
playlist = self.crawler.search_playlist(
playlist_name, self.quiet)
except RequestException as exception:
click.echo(exception)
else:
self.download_playlist_by_id(
playlist.playlist_id, playlist.playlist_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_playlist_by_id(self, playlist_id, playlist_name):
"""Download a playlist's songs by its id. :params playlist_id: playlist id. :params playlist_name: playlist name. """ |
try:
songs = self.crawler.get_playlist_songs(
playlist_id)
except RequestException as exception:
click.echo(exception)
else:
folder = os.path.join(self.folder, playlist_name)
for song in songs:
self.download_song_by_id(song.song_id, song.song_name, folder) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download_person_playlists(self):
"""Download person playlist including private playlist. note: login required. """ |
with open(person_info_path, 'r') as person_info:
user_id = int(person_info.read())
self.download_user_playlists_by_id(user_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def signal_handler(sign, frame):
"""Capture Ctrl+C.""" |
LOG.info('%s => %s', sign, frame)
click.echo('Bye')
sys.exit(0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli(ctx, timeout, proxy, output, quiet, lyric, again):
"""A command tool to download NetEase-Music's songs.""" |
ctx.obj = NetEase(timeout, proxy, output, quiet, lyric, again) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def song(netease, name, id):
"""Download a song by name or id.""" |
if name:
netease.download_song_by_search(name)
if id:
netease.download_song_by_id(id, 'song'+str(id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def album(netease, name, id):
"""Download a album's songs by name or id.""" |
if name:
netease.download_album_by_search(name)
if id:
netease.download_album_by_id(id, 'album'+str(id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def artist(netease, name, id):
"""Download a artist's hot songs by name or id.""" |
if name:
netease.download_artist_by_search(name)
if id:
netease.download_artist_by_id(id, 'artist'+str(id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def playlist(netease, name, id):
"""Download a playlist's songs by id.""" |
if name:
netease.download_playlist_by_search(name)
if id:
netease.download_playlist_by_id(id, 'playlist'+str(id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def user(netease, name, id):
"""Download a user\'s playlists by id.""" |
if name:
netease.download_user_playlists_by_search(name)
if id:
netease.download_user_playlists_by_id(id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_one_song(songs):
"""Display the songs returned by search api. :params songs: API['result']['songs'] :return: a Song object. """ |
if len(songs) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Song Name', 'Artist Name'])
for i, song in enumerate(songs, 1):
table.add_row([i, song['name'], song['ar'][0]['name']])
click.echo(table)
select_i = click.prompt('Select one song', type=int, default=1)
while select_i < 1 or select_i > len(songs):
select_i = click.prompt('Error Select! Select Again', type=int)
song_id, song_name = songs[select_i-1]['id'], songs[select_i-1]['name']
song = Song(song_id, song_name)
return song |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_one_album(albums):
"""Display the albums returned by search api. :params albums: API['result']['albums'] :return: a Album object. """ |
if len(albums) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Album Name', 'Artist Name'])
for i, album in enumerate(albums, 1):
table.add_row([i, album['name'], album['artist']['name']])
click.echo(table)
select_i = click.prompt('Select one album', type=int, default=1)
while select_i < 1 or select_i > len(albums):
select_i = click.prompt('Error Select! Select Again', type=int)
album_id = albums[select_i-1]['id']
album_name = albums[select_i-1]['name']
album = Album(album_id, album_name)
return album |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_one_artist(artists):
"""Display the artists returned by search api. :params artists: API['result']['artists'] :return: a Artist object. """ |
if len(artists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Artist Name'])
for i, artist in enumerate(artists, 1):
table.add_row([i, artist['name']])
click.echo(table)
select_i = click.prompt('Select one artist', type=int, default=1)
while select_i < 1 or select_i > len(artists):
select_i = click.prompt('Error Select! Select Again', type=int)
artist_id = artists[select_i-1]['id']
artist_name = artists[select_i-1]['name']
artist = Artist(artist_id, artist_name)
return artist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_one_playlist(playlists):
"""Display the playlists returned by search api or user playlist. :params playlists: API['result']['playlists'] or API['playlist'] :return: a Playlist object. """ |
if len(playlists) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, playlist in enumerate(playlists, 1):
table.add_row([i, playlist['name']])
click.echo(table)
select_i = click.prompt('Select one playlist', type=int, default=1)
while select_i < 1 or select_i > len(playlists):
select_i = click.prompt('Error Select! Select Again', type=int)
playlist_id = playlists[select_i-1]['id']
playlist_name = playlists[select_i-1]['name']
playlist = Playlist(playlist_id, playlist_name)
return playlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_one_user(users):
"""Display the users returned by search api. :params users: API['result']['userprofiles'] :return: a User object. """ |
if len(users) == 1:
select_i = 0
else:
table = PrettyTable(['Sequence', 'Name'])
for i, user in enumerate(users, 1):
table.add_row([i, user['nickname']])
click.echo(table)
select_i = click.prompt('Select one user', type=int, default=1)
while select_i < 1 or select_i > len(users):
select_i = click.prompt('Error Select! Select Again', type=int)
user_id = users[select_i-1]['userId']
user_name = users[select_i-1]['nickname']
user = User(user_id, user_name)
return user |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exception_handle(method):
"""Handle exception raised by requests library.""" |
def wrapper(*args, **kwargs):
try:
result = method(*args, **kwargs)
return result
except ProxyError:
LOG.exception('ProxyError when try to get %s.', args)
raise ProxyError('A proxy error occurred.')
except ConnectionException:
LOG.exception('ConnectionError when try to get %s.', args)
raise ConnectionException('DNS failure, refused connection, etc.')
except Timeout:
LOG.exception('Timeout when try to get %s', args)
raise Timeout('The request timed out.')
except RequestException:
LOG.exception('RequestException when try to get %s.', args)
raise RequestException('Please check out your network.')
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_request(self, url):
"""Send a get request. warning: old api. :return: a dict or raise Exception. """ |
resp = self.session.get(url, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to get %s', result, url)
raise GetRequestIllegal(result)
else:
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def post_request(self, url, params):
"""Send a post request. :return: a dict or raise Exception. """ |
data = encrypted_request(params)
resp = self.session.post(url, data=data, timeout=self.timeout,
proxies=self.proxies)
result = resp.json()
if result['code'] != 200:
LOG.error('Return %s when try to post %s => %s',
result, url, params)
raise PostRequestIllegal(result)
else:
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search(self, search_content, search_type, limit=9):
"""Search entrance. :params search_content: search content. :params search_type: search type. :params limit: result count returned by weapi. :return: a dict. """ |
url = 'http://music.163.com/weapi/cloudsearch/get/web?csrf_token='
params = {'s': search_content, 'type': search_type, 'offset': 0,
'sub': 'false', 'limit': limit}
result = self.post_request(url, params)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_song(self, song_name, quiet=False, limit=9):
"""Search song by song name. :params song_name: song name. :params quiet: automatically select the best one. :params limit: song count returned by weapi. :return: a Song object. """ |
result = self.search(song_name, search_type=1, limit=limit)
if result['result']['songCount'] <= 0:
LOG.warning('Song %s not existed!', song_name)
raise SearchNotFound('Song {} not existed.'.format(song_name))
else:
songs = result['result']['songs']
if quiet:
song_id, song_name = songs[0]['id'], songs[0]['name']
song = Song(song_id, song_name)
return song
else:
return self.display.select_one_song(songs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_album(self, album_name, quiet=False, limit=9):
"""Search album by album name. :params album_name: album name. :params quiet: automatically select the best one. :params limit: album count returned by weapi. :return: a Album object. """ |
result = self.search(album_name, search_type=10, limit=limit)
if result['result']['albumCount'] <= 0:
LOG.warning('Album %s not existed!', album_name)
raise SearchNotFound('Album {} not existed'.format(album_name))
else:
albums = result['result']['albums']
if quiet:
album_id, album_name = albums[0]['id'], albums[0]['name']
album = Album(album_id, album_name)
return album
else:
return self.display.select_one_album(albums) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_artist(self, artist_name, quiet=False, limit=9):
"""Search artist by artist name. :params artist_name: artist name. :params quiet: automatically select the best one. :params limit: artist count returned by weapi. :return: a Artist object. """ |
result = self.search(artist_name, search_type=100, limit=limit)
if result['result']['artistCount'] <= 0:
LOG.warning('Artist %s not existed!', artist_name)
raise SearchNotFound('Artist {} not existed.'.format(artist_name))
else:
artists = result['result']['artists']
if quiet:
artist_id, artist_name = artists[0]['id'], artists[0]['name']
artist = Artist(artist_id, artist_name)
return artist
else:
return self.display.select_one_artist(artists) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_playlist(self, playlist_name, quiet=False, limit=9):
"""Search playlist by playlist name. :params playlist_name: playlist name. :params quiet: automatically select the best one. :params limit: playlist count returned by weapi. :return: a Playlist object. """ |
result = self.search(playlist_name, search_type=1000, limit=limit)
if result['result']['playlistCount'] <= 0:
LOG.warning('Playlist %s not existed!', playlist_name)
raise SearchNotFound('playlist {} not existed'.format(playlist_name))
else:
playlists = result['result']['playlists']
if quiet:
playlist_id, playlist_name = playlists[0]['id'], playlists[0]['name']
playlist = Playlist(playlist_id, playlist_name)
return playlist
else:
return self.display.select_one_playlist(playlists) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_user(self, user_name, quiet=False, limit=9):
"""Search user by user name. :params user_name: user name. :params quiet: automatically select the best one. :params limit: user count returned by weapi. :return: a User object. """ |
result = self.search(user_name, search_type=1002, limit=limit)
if result['result']['userprofileCount'] <= 0:
LOG.warning('User %s not existed!', user_name)
raise SearchNotFound('user {} not existed'.format(user_name))
else:
users = result['result']['userprofiles']
if quiet:
user_id, user_name = users[0]['userId'], users[0]['nickname']
user = User(user_id, user_name)
return user
else:
return self.display.select_one_user(users) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_user_playlists(self, user_id, limit=1000):
"""Get a user's all playlists. warning: login is required for private playlist. :params user_id: user id. :params limit: playlist count returned by weapi. :return: a Playlist Object. """ |
url = 'http://music.163.com/weapi/user/playlist?csrf_token='
csrf = ''
params = {'offset': 0, 'uid': user_id, 'limit': limit,
'csrf_token': csrf}
result = self.post_request(url, params)
playlists = result['playlist']
return self.display.select_one_playlist(playlists) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_playlist_songs(self, playlist_id, limit=1000):
"""Get a playlists's all songs. :params playlist_id: playlist id. :params limit: length of result returned by weapi. :return: a list of Song object. """ |
url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_token='
csrf = ''
params = {'id': playlist_id, 'offset': 0, 'total': True,
'limit': limit, 'n': 1000, 'csrf_token': csrf}
result = self.post_request(url, params)
songs = result['playlist']['tracks']
songs = [Song(song['id'], song['name']) for song in songs]
return songs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_album_songs(self, album_id):
"""Get a album's all songs. warning: use old api. :params album_id: album id. :return: a list of Song object. """ |
url = 'http://music.163.com/api/album/{}/'.format(album_id)
result = self.get_request(url)
songs = result['album']['songs']
songs = [Song(song['id'], song['name']) for song in songs]
return songs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_artists_hot_songs(self, artist_id):
"""Get a artist's top50 songs. warning: use old api. :params artist_id: artist id. :return: a list of Song object. """ |
url = 'http://music.163.com/api/artist/{}'.format(artist_id)
result = self.get_request(url)
hot_songs = result['hotSongs']
songs = [Song(song['id'], song['name']) for song in hot_songs]
return songs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_song_url(self, song_id, bit_rate=320000):
"""Get a song's download address. :params song_id: song id<int>. :params bit_rate: {'MD 128k': 128000, 'HD 320k': 320000} :return: a song's download address. """ |
url = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='
csrf = ''
params = {'ids': [song_id], 'br': bit_rate, 'csrf_token': csrf}
result = self.post_request(url, params)
song_url = result['data'][0]['url'] # download address
if song_url is None: # Taylor Swift's song is not available
LOG.warning(
'Song %s is not available due to copyright issue. => %s',
song_id, result)
raise SongNotAvailable(
'Song {} is not available due to copyright issue.'.format(song_id))
else:
return song_url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_song_lyric(self, song_id):
"""Get a song's lyric. warning: use old api. :params song_id: song id. :return: a song's lyric. """ |
url = 'http://music.163.com/api/song/lyric?os=osx&id={}&lv=-1&kv=-1&tv=-1'.format( # NOQA
song_id)
result = self.get_request(url)
if 'lrc' in result and result['lrc']['lyric'] is not None:
lyric_info = result['lrc']['lyric']
else:
lyric_info = 'Lyric not found.'
return lyric_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_song_by_url(self, song_url, song_name, folder, lyric_info):
"""Download a song and save it to disk. :params song_url: download address. :params song_name: song name. :params folder: storage path. :params lyric: lyric info. """ |
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, song_name+'.mp3')
if sys.platform == 'win32' or sys.platform == 'cygwin':
valid_name = re.sub(r'[<>:"/\\|?*]', '', song_name)
if valid_name != song_name:
click.echo('{} will be saved as: {}.mp3'.format(song_name, valid_name))
fpath = os.path.join(folder, valid_name + '.mp3')
if not os.path.exists(fpath):
resp = self.download_session.get(
song_url, timeout=self.timeout, stream=True)
length = int(resp.headers.get('content-length'))
label = 'Downloading {} {}kb'.format(song_name, int(length/1024))
with click.progressbar(length=length, label=label) as progressbar:
with open(fpath, 'wb') as song_file:
for chunk in resp.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
song_file.write(chunk)
progressbar.update(1024)
if lyric_info:
folder = os.path.join(folder, 'lyric')
if not os.path.exists(folder):
os.makedirs(folder)
fpath = os.path.join(folder, song_name+'.lrc')
with open(fpath, 'w') as lyric_file:
lyric_file.write(lyric_info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login(self):
"""Login entrance.""" |
username = click.prompt('Please enter your email or phone number')
password = click.prompt('Please enter your password', hide_input=True)
pattern = re.compile(r'^0\d{2,3}\d{7,8}$|^1[34578]\d{9}$')
if pattern.match(username): # use phone number to login
url = 'https://music.163.com/weapi/login/cellphone'
params = {
'phone': username,
'password': hashlib.md5(password.encode('utf-8')).hexdigest(),
'rememberLogin': 'true'}
else: # use email to login
url = 'https://music.163.com/weapi/login?csrf_token='
params = {
'username': username,
'password': hashlib.md5(password.encode('utf-8')).hexdigest(),
'rememberLogin': 'true'}
try:
result = self.post_request(url, params)
except PostRequestIllegal:
click.echo('Password Error!')
sys.exit(1)
self.session.cookies.save()
uid = result['account']['id']
with open(person_info_path, 'w') as person_info:
person_info.write(str(uid)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_representation(self, instance):
""" Serialize objects -> primitives. """ |
# prepare OrderedDict geojson structure
feature = OrderedDict()
# the list of fields that will be processed by get_properties
# we will remove fields that have been already processed
# to increase performance on large numbers
fields = list(self.fields.values())
# optional id attribute
if self.Meta.id_field:
field = self.fields[self.Meta.id_field]
value = field.get_attribute(instance)
feature["id"] = field.to_representation(value)
fields.remove(field)
# required type attribute
# must be "Feature" according to GeoJSON spec
feature["type"] = "Feature"
# required geometry attribute
# MUST be present in output according to GeoJSON spec
field = self.fields[self.Meta.geo_field]
geo_value = field.get_attribute(instance)
feature["geometry"] = field.to_representation(geo_value)
fields.remove(field)
# Bounding Box
# if auto_bbox feature is enabled
# bbox will be determined automatically automatically
if self.Meta.auto_bbox and geo_value:
feature["bbox"] = geo_value.extent
# otherwise it can be determined via another field
elif self.Meta.bbox_geo_field:
field = self.fields[self.Meta.bbox_geo_field]
value = field.get_attribute(instance)
feature["bbox"] = value.extent if hasattr(value, 'extent') else None
fields.remove(field)
# GeoJSON properties
feature["properties"] = self.get_properties(instance, fields)
return feature |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_properties(self, instance, fields):
""" Get the feature metadata which will be used for the GeoJSON "properties" key. By default it returns all serializer fields excluding those used for the ID, the geometry and the bounding box. :param instance: The current Django model instance :param fields: The list of fields to process (fields already processed have been removed) :return: OrderedDict containing the properties of the current feature :rtype: OrderedDict """ |
properties = OrderedDict()
for field in fields:
if field.write_only:
continue
value = field.get_attribute(instance)
representation = None
if value is not None:
representation = field.to_representation(value)
properties[field.field_name] = representation
return properties |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_internal_value(self, data):
""" Override the parent method to first remove the GeoJSON formatting """ |
if 'properties' in data:
data = self.unformat_geojson(data)
return super(GeoFeatureModelSerializer, self).to_internal_value(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unformat_geojson(self, feature):
""" This function should return a dictionary containing keys which maps to serializer fields. Remember that GeoJSON contains a key "properties" which contains the feature metadata. This should be flattened to make sure this metadata is stored in the right serializer fields. :param feature: The dictionary containing the feature data directly from the GeoJSON data. :return: A new dictionary which maps the GeoJSON values to serializer fields """ |
attrs = feature["properties"]
if 'geometry' in feature:
attrs[self.Meta.geo_field] = feature['geometry']
if self.Meta.bbox_geo_field and 'bbox' in feature:
attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature['bbox'])
return attrs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ready(self):
""" update Django Rest Framework serializer mappings """ |
from django.contrib.gis.db import models
from rest_framework.serializers import ModelSerializer
from .fields import GeometryField
try:
# drf 3.0
field_mapping = ModelSerializer._field_mapping.mapping
except AttributeError:
# drf 3.1
field_mapping = ModelSerializer.serializer_field_mapping
# map GeoDjango fields to drf-gis GeometryField
field_mapping.update({
models.GeometryField: GeometryField,
models.PointField: GeometryField,
models.LineStringField: GeometryField,
models.PolygonField: GeometryField,
models.MultiPointField: GeometryField,
models.MultiLineStringField: GeometryField,
models.MultiPolygonField: GeometryField,
models.GeometryCollectionField: GeometryField
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dist_to_deg(self, distance, latitude):
""" distance = distance in meters latitude = latitude in degrees at the equator, the distance of one degree is equal in latitude and longitude. at higher latitudes, a degree longitude is shorter in length, proportional to cos(latitude) http://en.wikipedia.org/wiki/Decimal_degrees This function is part of a distance filter where the database 'distance' is in degrees. There's no good single-valued answer to this problem. The distance/ degree is quite constant N/S around the earth (latitude), but varies over a huge range E/W (longitude). Split the difference: I'm going to average the the degrees latitude and degrees longitude corresponding to the given distance. At high latitudes, this will be too short N/S and too long E/W. It splits the errors between the two axes. Errors are < 25 percent for latitudes < 60 degrees N/S. """ |
# d * (180 / pi) / earthRadius ==> degrees longitude
# (degrees longitude) / cos(latitude) ==> degrees latitude
lat = latitude if latitude >= 0 else -1 * latitude
rad2deg = 180 / pi
earthRadius = 6378160.0
latitudeCorrection = 0.5 * (1 + cos(lat * pi / 180))
return (distance / (earthRadius * latitudeCorrection) * rad2deg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SetCredentials(self, **kwds):
"""Fetch credentials, and set them for this client. Note that we can't simply return credentials, since creating them may involve side-effecting self. Args: **kwds: Additional keyword arguments are passed on to GetCredentials. Returns: None. Sets self._credentials. """ |
args = {
'api_key': self._API_KEY,
'client': self,
'client_id': self._CLIENT_ID,
'client_secret': self._CLIENT_SECRET,
'package_name': self._PACKAGE,
'scopes': self._SCOPES,
'user_agent': self._USER_AGENT,
}
args.update(kwds)
# credentials_lib can be expensive to import so do it only if needed.
from apitools.base.py import credentials_lib
# TODO(craigcitro): It's a bit dangerous to pass this
# still-half-initialized self into this method, but we might need
# to set attributes on it associated with our credentials.
# Consider another way around this (maybe a callback?) and whether
# or not it's worth it.
self._credentials = credentials_lib.GetCredentials(**args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def JsonResponseModel(self):
"""In this context, return raw JSON instead of proto.""" |
old_model = self.response_type_model
self.__response_type_model = 'json'
yield
self.__response_type_model = old_model |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ProcessRequest(self, method_config, request):
"""Hook for pre-processing of requests.""" |
if self.log_request:
logging.info(
'Calling method %s with %s: %s', method_config.method_id,
method_config.request_type_name, request)
return request |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ProcessHttpRequest(self, http_request):
"""Hook for pre-processing of http requests.""" |
http_request.headers.update(self.additional_http_headers)
if self.log_request:
logging.info('Making http %s to %s',
http_request.http_method, http_request.url)
logging.info('Headers: %s', pprint.pformat(http_request.headers))
if http_request.body:
# TODO(craigcitro): Make this safe to print in the case of
# non-printable body characters.
logging.info('Body:\n%s',
http_request.loggable_body or http_request.body)
else:
logging.info('Body: (none)')
return http_request |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DeserializeMessage(self, response_type, data):
"""Deserialize the given data as method_config.response_type.""" |
try:
message = encoding.JsonToMessage(response_type, data)
except (exceptions.InvalidDataFromServerError,
messages.ValidationError, ValueError) as e:
raise exceptions.InvalidDataFromServerError(
'Error decoding response "%s" as type %s: %s' % (
data, response_type.__name__, e))
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FinalizeTransferUrl(self, url):
"""Modify the url for a given transfer, based on auth and version.""" |
url_builder = _UrlBuilder.FromUrl(url)
if self.global_params.key:
url_builder.query_params['key'] = self.global_params.key
return url_builder.url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetMethodConfig(self, method):
"""Returns service cached method config for given method.""" |
method_config = self._method_configs.get(method)
if method_config:
return method_config
func = getattr(self, method, None)
if func is None:
raise KeyError(method)
method_config = getattr(func, 'method_config', None)
if method_config is None:
raise KeyError(method)
self._method_configs[method] = config = method_config()
return config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __CombineGlobalParams(self, global_params, default_params):
"""Combine the given params with the defaults.""" |
util.Typecheck(global_params, (type(None), self.__client.params_type))
result = self.__client.params_type()
global_params = global_params or self.__client.params_type()
for field in result.all_fields():
value = global_params.get_assigned_value(field.name)
if value is None:
value = default_params.get_assigned_value(field.name)
if value not in (None, [], ()):
setattr(result, field.name, value)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __FinalUrlValue(self, value, field):
"""Encode value for the URL, using field to skip encoding for bytes.""" |
if isinstance(field, messages.BytesField) and value is not None:
return base64.urlsafe_b64encode(value)
elif isinstance(value, six.text_type):
return value.encode('utf8')
elif isinstance(value, six.binary_type):
return value.decode('utf8')
elif isinstance(value, datetime.datetime):
return value.isoformat()
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __ConstructQueryParams(self, query_params, request, global_params):
"""Construct a dictionary of query parameters for this request.""" |
# First, handle the global params.
global_params = self.__CombineGlobalParams(
global_params, self.__client.global_params)
global_param_names = util.MapParamNames(
[x.name for x in self.__client.params_type.all_fields()],
self.__client.params_type)
global_params_type = type(global_params)
query_info = dict(
(param,
self.__FinalUrlValue(getattr(global_params, param),
getattr(global_params_type, param)))
for param in global_param_names)
# Next, add the query params.
query_param_names = util.MapParamNames(query_params, type(request))
request_type = type(request)
query_info.update(
(param,
self.__FinalUrlValue(getattr(request, param, None),
getattr(request_type, param)))
for param in query_param_names)
query_info = dict((k, v) for k, v in query_info.items()
if v is not None)
query_info = self.__EncodePrettyPrint(query_info)
query_info = util.MapRequestParams(query_info, type(request))
return query_info |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __FinalizeRequest(self, http_request, url_builder):
"""Make any final general adjustments to the request.""" |
if (http_request.http_method == 'GET' and
len(http_request.url) > _MAX_URL_LENGTH):
http_request.http_method = 'POST'
http_request.headers['x-http-method-override'] = 'GET'
http_request.headers[
'content-type'] = 'application/x-www-form-urlencoded'
http_request.body = url_builder.query
url_builder.query_params = {}
http_request.url = url_builder.url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __ProcessHttpResponse(self, method_config, http_response, request):
"""Process the given http response.""" |
if http_response.status_code not in (http_client.OK,
http_client.CREATED,
http_client.NO_CONTENT):
raise exceptions.HttpError.FromResponse(
http_response, method_config=method_config, request=request)
if http_response.status_code == http_client.NO_CONTENT:
# TODO(craigcitro): Find out why _replace doesn't seem to work
# here.
http_response = http_wrapper.Response(
info=http_response.info, content='{}',
request_url=http_response.request_url)
content = http_response.content
if self._client.response_encoding and isinstance(content, bytes):
content = content.decode(self._client.response_encoding)
if self.__client.response_type_model == 'json':
return content
response_type = _LoadClass(method_config.response_type_name,
self.__client.MESSAGES_MODULE)
return self.__client.DeserializeMessage(response_type, content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __SetBaseHeaders(self, http_request, client):
"""Fill in the basic headers on http_request.""" |
# TODO(craigcitro): Make the default a little better here, and
# include the apitools version.
user_agent = client.user_agent or 'apitools-client/1.0'
http_request.headers['user-agent'] = user_agent
http_request.headers['accept'] = 'application/json'
http_request.headers['accept-encoding'] = 'gzip, deflate' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __SetBody(self, http_request, method_config, request, upload):
"""Fill in the body on http_request.""" |
if not method_config.request_field:
return
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
if method_config.request_field == REQUEST_IS_BODY:
body_value = request
body_type = request_type
else:
body_value = getattr(request, method_config.request_field)
body_field = request_type.field_by_name(
method_config.request_field)
util.Typecheck(body_field, messages.MessageField)
body_type = body_field.type
# If there was no body provided, we use an empty message of the
# appropriate type.
body_value = body_value or body_type()
if upload and not body_value:
# We're going to fill in the body later.
return
util.Typecheck(body_value, body_type)
http_request.headers['content-type'] = 'application/json'
http_request.body = self.__client.SerializeMessage(body_value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PrepareHttpRequest(self, method_config, request, global_params=None, upload=None, upload_config=None, download=None):
"""Prepares an HTTP request to be sent.""" |
request_type = _LoadClass(
method_config.request_type_name, self.__client.MESSAGES_MODULE)
util.Typecheck(request, request_type)
request = self.__client.ProcessRequest(method_config, request)
http_request = http_wrapper.Request(
http_method=method_config.http_method)
self.__SetBaseHeaders(http_request, self.__client)
self.__SetBody(http_request, method_config, request, upload)
url_builder = _UrlBuilder(
self.__client.url, relative_path=method_config.relative_path)
url_builder.query_params = self.__ConstructQueryParams(
method_config.query_params, request, global_params)
# It's important that upload and download go before we fill in the
# relative path, so that they can replace it.
if upload is not None:
upload.ConfigureRequest(upload_config, http_request, url_builder)
if download is not None:
download.ConfigureRequest(http_request, url_builder)
url_builder.relative_path = self.__ConstructRelativePath(
method_config, request, relative_path=url_builder.relative_path)
self.__FinalizeRequest(http_request, url_builder)
return self.__client.ProcessHttpRequest(http_request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _RunMethod(self, method_config, request, global_params=None, upload=None, upload_config=None, download=None):
"""Call this method with request.""" |
if upload is not None and download is not None:
# TODO(craigcitro): This just involves refactoring the logic
# below into callbacks that we can pass around; in particular,
# the order should be that the upload gets the initial request,
# and then passes its reply to a download if one exists, and
# then that goes to ProcessResponse and is returned.
raise exceptions.NotYetImplementedError(
'Cannot yet use both upload and download at once')
http_request = self.PrepareHttpRequest(
method_config, request, global_params, upload, upload_config,
download)
# TODO(craigcitro): Make num_retries customizable on Transfer
# objects, and pass in self.__client.num_retries when initializing
# an upload or download.
if download is not None:
download.InitializeDownload(http_request, client=self.client)
return
http_response = None
if upload is not None:
http_response = upload.InitializeUpload(
http_request, client=self.client)
if http_response is None:
http = self.__client.http
if upload and upload.bytes_http:
http = upload.bytes_http
opts = {
'retries': self.__client.num_retries,
'max_retry_wait': self.__client.max_retry_wait,
}
if self.__client.check_response_func:
opts['check_response_func'] = self.__client.check_response_func
if self.__client.retry_func:
opts['retry_func'] = self.__client.retry_func
http_response = http_wrapper.MakeRequest(
http, http_request, **opts)
return self.ProcessHttpResponse(method_config, http_response, request) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ProcessHttpResponse(self, method_config, http_response, request=None):
"""Convert an HTTP response to the expected message type.""" |
return self.__client.ProcessResponse(
method_config,
self.__ProcessHttpResponse(method_config, http_response, request)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_enum_value(enum_value):
"""Build descriptor for Enum instance. Args: enum_value: Enum value to provide descriptor for. Returns: Initialized EnumValueDescriptor instance describing the Enum instance. """ |
enum_value_descriptor = EnumValueDescriptor()
enum_value_descriptor.name = six.text_type(enum_value.name)
enum_value_descriptor.number = enum_value.number
return enum_value_descriptor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_enum(enum_definition):
"""Build descriptor for Enum class. Args: enum_definition: Enum class to provide descriptor for. Returns: Initialized EnumDescriptor instance describing the Enum class. """ |
enum_descriptor = EnumDescriptor()
enum_descriptor.name = enum_definition.definition_name().split('.')[-1]
values = []
for number in enum_definition.numbers():
value = enum_definition.lookup_by_number(number)
values.append(describe_enum_value(value))
if values:
enum_descriptor.values = values
return enum_descriptor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_field(field_definition):
"""Build descriptor for Field instance. Args: field_definition: Field instance to provide descriptor for. Returns: Initialized FieldDescriptor instance describing the Field instance. """ |
field_descriptor = FieldDescriptor()
field_descriptor.name = field_definition.name
field_descriptor.number = field_definition.number
field_descriptor.variant = field_definition.variant
if isinstance(field_definition, messages.EnumField):
field_descriptor.type_name = field_definition.type.definition_name()
if isinstance(field_definition, messages.MessageField):
field_descriptor.type_name = (
field_definition.message_type.definition_name())
if field_definition.default is not None:
field_descriptor.default_value = _DEFAULT_TO_STRING_MAP[
type(field_definition)](field_definition.default)
# Set label.
if field_definition.repeated:
field_descriptor.label = FieldDescriptor.Label.REPEATED
elif field_definition.required:
field_descriptor.label = FieldDescriptor.Label.REQUIRED
else:
field_descriptor.label = FieldDescriptor.Label.OPTIONAL
return field_descriptor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_message(message_definition):
"""Build descriptor for Message class. Args: message_definition: Message class to provide descriptor for. Returns: Initialized MessageDescriptor instance describing the Message class. """ |
message_descriptor = MessageDescriptor()
message_descriptor.name = message_definition.definition_name().split(
'.')[-1]
fields = sorted(message_definition.all_fields(),
key=lambda v: v.number)
if fields:
message_descriptor.fields = [describe_field(field) for field in fields]
try:
nested_messages = message_definition.__messages__
except AttributeError:
pass
else:
message_descriptors = []
for name in nested_messages:
value = getattr(message_definition, name)
message_descriptors.append(describe_message(value))
message_descriptor.message_types = message_descriptors
try:
nested_enums = message_definition.__enums__
except AttributeError:
pass
else:
enum_descriptors = []
for name in nested_enums:
value = getattr(message_definition, name)
enum_descriptors.append(describe_enum(value))
message_descriptor.enum_types = enum_descriptors
return message_descriptor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_file(module):
"""Build a file from a specified Python module. Args: module: Python module to describe. Returns: Initialized FileDescriptor instance describing the module. """ |
descriptor = FileDescriptor()
descriptor.package = util.get_package_for_module(module)
if not descriptor.package:
descriptor.package = None
message_descriptors = []
enum_descriptors = []
# Need to iterate over all top level attributes of the module looking for
# message and enum definitions. Each definition must be itself described.
for name in sorted(dir(module)):
value = getattr(module, name)
if isinstance(value, type):
if issubclass(value, messages.Message):
message_descriptors.append(describe_message(value))
elif issubclass(value, messages.Enum):
enum_descriptors.append(describe_enum(value))
if message_descriptors:
descriptor.message_types = message_descriptors
if enum_descriptors:
descriptor.enum_types = enum_descriptors
return descriptor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe_file_set(modules):
"""Build a file set from a specified Python modules. Args: modules: Iterable of Python module to describe. Returns: Initialized FileSet instance describing the modules. """ |
descriptor = FileSet()
file_descriptors = []
for module in modules:
file_descriptors.append(describe_file(module))
if file_descriptors:
descriptor.files = file_descriptors
return descriptor |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def describe(value):
"""Describe any value as a descriptor. Helper function for describing any object with an appropriate descriptor object. Args: value: Value to describe as a descriptor. Returns: Descriptor message class if object is describable as a descriptor, else None. """ |
if isinstance(value, types.ModuleType):
return describe_file(value)
elif isinstance(value, messages.Field):
return describe_field(value)
elif isinstance(value, messages.Enum):
return describe_enum_value(value)
elif isinstance(value, type):
if issubclass(value, messages.Message):
return describe_message(value)
elif issubclass(value, messages.Enum):
return describe_enum(value)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_descriptor_loader(definition_name, importer=__import__):
"""Find objects by importing modules as needed. A definition loader is a function that resolves a definition name to a descriptor. The import finder resolves definitions to their names by importing modules when necessary. Args: definition_name: Name of definition to find. importer: Import function used for importing new modules. Returns: Appropriate descriptor for any describable type located by name. Raises: DefinitionNotFoundError when a name does not refer to either a definition or a module. """ |
# Attempt to import descriptor as a module.
if definition_name.startswith('.'):
definition_name = definition_name[1:]
if not definition_name.startswith('.'):
leaf = definition_name.split('.')[-1]
if definition_name:
try:
module = importer(definition_name, '', '', [leaf])
except ImportError:
pass
else:
return describe(module)
try:
# Attempt to use messages.find_definition to find item.
return describe(messages.find_definition(definition_name,
importer=__import__))
except messages.DefinitionNotFoundError as err:
# There are things that find_definition will not find, but if
# the parent is loaded, its children can be searched for a
# match.
split_name = definition_name.rsplit('.', 1)
if len(split_name) > 1:
parent, child = split_name
try:
parent_definition = import_descriptor_loader(
parent, importer=importer)
except messages.DefinitionNotFoundError:
# Fall through to original error.
pass
else:
# Check the parent definition for a matching descriptor.
if isinstance(parent_definition, EnumDescriptor):
search_list = parent_definition.values or []
elif isinstance(parent_definition, MessageDescriptor):
search_list = parent_definition.fields or []
else:
search_list = []
for definition in search_list:
if definition.name == child:
return definition
# Still didn't find. Reraise original exception.
raise err |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_descriptor(self, definition_name):
"""Lookup descriptor by name. Get descriptor from library by name. If descriptor is not found will attempt to find via descriptor loader if provided. Args: definition_name: Definition name to find. Returns: Descriptor that describes definition name. Raises: DefinitionNotFoundError if not descriptor exists for definition name. """ |
try:
return self.__descriptors[definition_name]
except KeyError:
pass
if self.__descriptor_loader:
definition = self.__descriptor_loader(definition_name)
self.__descriptors[definition_name] = definition
return definition
else:
raise messages.DefinitionNotFoundError(
'Could not find definition for %s' % definition_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lookup_package(self, definition_name):
"""Determines the package name for any definition. Determine the package that any definition name belongs to. May check parent for package name and will resolve missing descriptors if provided descriptor loader. Args: definition_name: Definition name to find package for. """ |
while True:
descriptor = self.lookup_descriptor(definition_name)
if isinstance(descriptor, FileDescriptor):
return descriptor.package
else:
index = definition_name.rfind('.')
if index < 0:
return None
definition_name = definition_name[:index] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_json_module():
"""Try to load a valid json module. There are more than one json modules that might be installed. They are mostly compatible with one another but some versions may be different. This function attempts to load various json modules in a preferred order. It does a basic check to guess if a loaded version of json is compatible. Returns: Compatible json module. Raises: ImportError if there are no json modules or the loaded json module is not compatible with ProtoRPC. """ |
first_import_error = None
for module_name in ['json',
'simplejson']:
try:
module = __import__(module_name, {}, {}, 'json')
if not hasattr(module, 'JSONEncoder'):
message = (
'json library "%s" is not compatible with ProtoRPC' %
module_name)
logging.warning(message)
raise ImportError(message)
else:
return module
except ImportError as err:
if not first_import_error:
first_import_error = err
logging.error('Must use valid json library (json or simplejson)')
raise first_import_error |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default(self, value):
"""Return dictionary instance from a message object. Args: value: Value to get dictionary for. If not encodable, will call superclasses default method. """ |
if isinstance(value, messages.Enum):
return str(value)
if six.PY3 and isinstance(value, bytes):
return value.decode('utf8')
if isinstance(value, messages.Message):
result = {}
for field in value.all_fields():
item = value.get_assigned_value(field.name)
if item not in (None, [], ()):
result[field.name] = (
self.__protojson_protocol.encode_field(field, item))
# Handle unrecognized fields, so they're included when a message is
# decoded then encoded.
for unknown_key in value.all_unrecognized_fields():
unrecognized_field, _ = value.get_unrecognized_field_info(
unknown_key)
# Unknown fields are not encoded as they should have been
# processed before we get to here.
result[unknown_key] = unrecognized_field
return result
return super(MessageJSONEncoder, self).default(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode_message(self, message):
"""Encode Message instance to JSON string. Args: Message instance to encode in to JSON string. Returns: String encoding of Message instance in protocol JSON format. Raises: messages.ValidationError if message is not initialized. """ |
message.check_initialized()
return json.dumps(message, cls=MessageJSONEncoder,
protojson_protocol=self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_message(self, message_type, encoded_message):
"""Merge JSON structure to Message instance. Args: message_type: Message to decode data to. encoded_message: JSON encoded version of message. Returns: Decoded instance of message_type. Raises: ValueError: If encoded_message is not valid JSON. messages.ValidationError if merged message is not initialized. """ |
encoded_message = six.ensure_str(encoded_message)
if not encoded_message.strip():
return message_type()
dictionary = json.loads(encoded_message)
message = self.__decode_dictionary(message_type, dictionary)
message.check_initialized()
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __find_variant(self, value):
"""Find the messages.Variant type that describes this value. Args: value: The value whose variant type is being determined. Returns: The messages.Variant value that best describes value's type, or None if it's a type we don't know how to handle. """ |
if isinstance(value, bool):
return messages.Variant.BOOL
elif isinstance(value, six.integer_types):
return messages.Variant.INT64
elif isinstance(value, float):
return messages.Variant.DOUBLE
elif isinstance(value, six.string_types):
return messages.Variant.STRING
elif isinstance(value, (list, tuple)):
# Find the most specific variant that covers all elements.
variant_priority = [None,
messages.Variant.INT64,
messages.Variant.DOUBLE,
messages.Variant.STRING]
chosen_priority = 0
for v in value:
variant = self.__find_variant(v)
try:
priority = variant_priority.index(variant)
except IndexError:
priority = -1
if priority > chosen_priority:
chosen_priority = priority
return variant_priority[chosen_priority]
# Unrecognized type.
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __decode_dictionary(self, message_type, dictionary):
"""Merge dictionary in to message. Args: message: Message to merge dictionary in to. dictionary: Dictionary to extract information from. Dictionary is as parsed from JSON. Nested objects will also be dictionaries. """ |
message = message_type()
for key, value in six.iteritems(dictionary):
if value is None:
try:
message.reset(key)
except AttributeError:
pass # This is an unrecognized field, skip it.
continue
try:
field = message.field_by_name(key)
except KeyError:
# Save unknown values.
variant = self.__find_variant(value)
if variant:
message.set_unrecognized_field(key, value, variant)
continue
if field.repeated:
# This should be unnecessary? Or in fact become an error.
if not isinstance(value, list):
value = [value]
valid_value = [self.decode_field(field, item)
for item in value]
setattr(message, field.name, valid_value)
continue
# This is just for consistency with the old behavior.
if value == []:
continue
try:
setattr(message, field.name, self.decode_field(field, value))
except messages.DecodeError:
# Save unknown enum values.
if not isinstance(field, messages.EnumField):
raise
variant = self.__find_variant(value)
if variant:
message.set_unrecognized_field(key, value, variant)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def WriteSetupPy(self, out):
"""Write a setup.py for upload to PyPI.""" |
printer = self._GetPrinter(out)
year = datetime.datetime.now().year
printer('# Copyright %s Google Inc. All Rights Reserved.' % year)
printer('#')
printer('# Licensed under the Apache License, Version 2.0 (the'
'"License");')
printer('# you may not use this file except in compliance with '
'the License.')
printer('# You may obtain a copy of the License at')
printer('#')
printer('# http://www.apache.org/licenses/LICENSE-2.0')
printer('#')
printer('# Unless required by applicable law or agreed to in writing, '
'software')
printer('# distributed under the License is distributed on an "AS IS" '
'BASIS,')
printer('# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either '
'express or implied.')
printer('# See the License for the specific language governing '
'permissions and')
printer('# limitations under the License.')
printer()
printer('import setuptools')
printer('REQUIREMENTS = [')
with printer.Indent(indent=' '):
parts = self.apitools_version.split('.')
major = parts.pop(0)
minor = parts.pop(0)
printer('"google-apitools>=%s,~=%s.%s",',
self.apitools_version, major, minor)
printer('"httplib2>=0.9",')
printer('"oauth2client>=1.4.12",')
printer(']')
printer('_PACKAGE = "apitools.clients.%s"' % self.__package)
printer()
printer('setuptools.setup(')
# TODO(craigcitro): Allow customization of these options.
with printer.Indent(indent=' '):
printer('name="google-apitools-%s-%s",',
self.__package, self.__version)
printer('version="%s.%s",',
self.apitools_version, self.__revision)
printer('description="Autogenerated apitools library for %s",' % (
self.__package,))
printer('url="https://github.com/google/apitools",')
printer('author="Craig Citro",')
printer('author_email="craigcitro@google.com",')
printer('packages=setuptools.find_packages(),')
printer('install_requires=REQUIREMENTS,')
printer('classifiers=[')
with printer.Indent(indent=' '):
printer('"Programming Language :: Python :: 2.7",')
printer('"License :: OSI Approved :: Apache Software '
'License",')
printer('],')
printer('license="Apache 2.0",')
printer('keywords="apitools apitools-%s %s",' % (
self.__package, self.__package))
printer(')') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def DownloadProgressPrinter(response, unused_download):
"""Print download progress based on response.""" |
if 'content-range' in response.info:
print('Received %s' % response.info['content-range'])
else:
print('Received %d bytes' % response.length) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _Initialize(self, http, url):
"""Initialize this download by setting self.http and self.url. We want the user to be able to override self.http by having set the value in the constructor; in that case, we ignore the provided http. Args: http: An httplib2.Http instance or None. url: The url for this transfer. Returns: None. Initializes self. """ |
self.EnsureUninitialized()
if self.http is None:
self.__http = http or http_wrapper.GetHttp()
self.__url = url |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FromFile(cls, filename, overwrite=False, auto_transfer=True, **kwds):
"""Create a new download object from a filename.""" |
path = os.path.expanduser(filename)
if os.path.exists(path) and not overwrite:
raise exceptions.InvalidUserInputError(
'File %s exists and overwrite not specified' % path)
return cls(open(path, 'wb'), close_stream=True,
auto_transfer=auto_transfer, **kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FromStream(cls, stream, auto_transfer=True, total_size=None, **kwds):
"""Create a new Download object from a stream.""" |
return cls(stream, auto_transfer=auto_transfer, total_size=total_size,
**kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FromData(cls, stream, json_data, http=None, auto_transfer=None, **kwds):
"""Create a new Download object from a stream and serialized data.""" |
info = json.loads(json_data)
missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys())
if missing_keys:
raise exceptions.InvalidDataError(
'Invalid serialization data, missing keys: %s' % (
', '.join(missing_keys)))
download = cls.FromStream(stream, **kwds)
if auto_transfer is not None:
download.auto_transfer = auto_transfer
else:
download.auto_transfer = info['auto_transfer']
setattr(download, '_Download__progress', info['progress'])
setattr(download, '_Download__total_size', info['total_size'])
download._Initialize( # pylint: disable=protected-access
http, info['url'])
return download |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __SetTotal(self, info):
"""Sets the total size based off info if possible otherwise 0.""" |
if 'content-range' in info:
_, _, total = info['content-range'].rpartition('/')
if total != '*':
self.__total_size = int(total)
# Note "total_size is None" means we don't know it; if no size
# info was returned on our initial range request, that means we
# have a 0-byte file. (That last statement has been verified
# empirically, but is not clearly documented anywhere.)
if self.total_size is None:
self.__total_size = 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def InitializeDownload(self, http_request, http=None, client=None):
"""Initialize this download by making a request. Args: http_request: The HttpRequest to use to initialize this download. http: The httplib2.Http instance for this request. client: If provided, let this client process the final URL before sending any additional requests. If client is provided and http is not, client.http will be used instead. """ |
self.EnsureUninitialized()
if http is None and client is None:
raise exceptions.UserError('Must provide client or http.')
http = http or client.http
if client is not None:
http_request.url = client.FinalizeTransferUrl(http_request.url)
url = http_request.url
if self.auto_transfer:
end_byte = self.__ComputeEndByte(0)
self.__SetRangeHeader(http_request, 0, end_byte)
response = http_wrapper.MakeRequest(
self.bytes_http or http, http_request)
if response.status_code not in self._ACCEPTABLE_STATUSES:
raise exceptions.HttpError.FromResponse(response)
self.__initial_response = response
self.__SetTotal(response.info)
url = response.info.get('content-location', response.request_url)
if client is not None:
url = client.FinalizeTransferUrl(url)
self._Initialize(http, url)
# Unless the user has requested otherwise, we want to just
# go ahead and pump the bytes now.
if self.auto_transfer:
self.StreamInChunks() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __NormalizeStartEnd(self, start, end=None):
"""Normalizes start and end values based on total size.""" |
if end is not None:
if start < 0:
raise exceptions.TransferInvalidError(
'Cannot have end index with negative start index ' +
'[start=%d, end=%d]' % (start, end))
elif start >= self.total_size:
raise exceptions.TransferInvalidError(
'Cannot have start index greater than total size ' +
'[start=%d, total_size=%d]' % (start, self.total_size))
end = min(end, self.total_size - 1)
if end < start:
raise exceptions.TransferInvalidError(
'Range requested with end[%s] < start[%s]' % (end, start))
return start, end
else:
if start < 0:
start = max(0, start + self.total_size)
return start, self.total_size - 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __ComputeEndByte(self, start, end=None, use_chunks=True):
"""Compute the last byte to fetch for this request. This is all based on the HTTP spec for Range and Content-Range. Note that this is potentially confusing in several ways: * the value for the last byte is 0-based, eg "fetch 10 bytes from the beginning" would return 9 here. * if we have no information about size, and don't want to use the chunksize, we'll return None. See the tests for more examples. Args: start: byte to start at. end: (int or None, default: None) Suggested last byte. use_chunks: (bool, default: True) If False, ignore self.chunksize. Returns: Last byte to use in a Range header, or None. """ |
end_byte = end
if start < 0 and not self.total_size:
return end_byte
if use_chunks:
alternate = start + self.chunksize - 1
if end_byte is not None:
end_byte = min(end_byte, alternate)
else:
end_byte = alternate
if self.total_size:
alternate = self.total_size - 1
if end_byte is not None:
end_byte = min(end_byte, alternate)
else:
end_byte = alternate
return end_byte |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __GetChunk(self, start, end, additional_headers=None):
"""Retrieve a chunk, and return the full response.""" |
self.EnsureInitialized()
request = http_wrapper.Request(url=self.url)
self.__SetRangeHeader(request, start, end=end)
if additional_headers is not None:
request.headers.update(additional_headers)
return http_wrapper.MakeRequest(
self.bytes_http, request, retry_func=self.retry_func,
retries=self.num_retries) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GetRange(self, start, end=None, additional_headers=None, use_chunks=True):
"""Retrieve a given byte range from this download, inclusive. Range must be of one of these three forms: * 0 <= start, end = None: Fetch from start to the end of the file. * 0 <= start <= end: Fetch the bytes from start to end. * start < 0, end = None: Fetch the last -start bytes of the file. (These variations correspond to those described in the HTTP 1.1 protocol for range headers in RFC 2616, sec. 14.35.1.) Args: start: (int) Where to start fetching bytes. (See above.) end: (int, optional) Where to stop fetching bytes. (See above.) additional_headers: (bool, optional) Any additional headers to pass with the request. use_chunks: (bool, default: True) If False, ignore self.chunksize and fetch this range in a single request. Returns: None. Streams bytes into self.stream. """ |
self.EnsureInitialized()
progress_end_normalized = False
if self.total_size is not None:
progress, end_byte = self.__NormalizeStartEnd(start, end)
progress_end_normalized = True
else:
progress = start
end_byte = end
while (not progress_end_normalized or end_byte is None or
progress <= end_byte):
end_byte = self.__ComputeEndByte(progress, end=end_byte,
use_chunks=use_chunks)
response = self.__GetChunk(progress, end_byte,
additional_headers=additional_headers)
if not progress_end_normalized:
self.__SetTotal(response.info)
progress, end_byte = self.__NormalizeStartEnd(start, end)
progress_end_normalized = True
response = self.__ProcessResponse(response)
progress += response.length
if response.length == 0:
if response.status_code == http_client.OK:
# There can legitimately be no Content-Length header sent
# in some cases (e.g., when there's a Transfer-Encoding
# header) and if this was a 200 response (as opposed to
# 206 Partial Content) we know we're done now without
# looping further on received length.
return
raise exceptions.TransferRetryError(
'Zero bytes unexpectedly returned in download response') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StreamInChunks(self, callback=None, finish_callback=None, additional_headers=None):
"""Stream the entire download in chunks.""" |
self.StreamMedia(callback=callback, finish_callback=finish_callback,
additional_headers=additional_headers,
use_chunks=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True):
"""Stream the entire download. Args: callback: (default: None) Callback to call as each chunk is completed. finish_callback: (default: None) Callback to call when the download is complete. additional_headers: (default: None) Additional headers to include in fetching bytes. use_chunks: (bool, default: True) If False, ignore self.chunksize and stream this download in a single request. Returns: None. Streams bytes into self.stream. """ |
callback = callback or self.progress_callback
finish_callback = finish_callback or self.finish_callback
self.EnsureInitialized()
while True:
if self.__initial_response is not None:
response = self.__initial_response
self.__initial_response = None
else:
end_byte = self.__ComputeEndByte(self.progress,
use_chunks=use_chunks)
response = self.__GetChunk(
self.progress, end_byte,
additional_headers=additional_headers)
if self.total_size is None:
self.__SetTotal(response.info)
response = self.__ProcessResponse(response)
self._ExecuteCallback(callback, response)
if (response.status_code == http_client.OK or
self.progress >= self.total_size):
break
self._ExecuteCallback(finish_callback, response) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FromFile(cls, filename, mime_type=None, auto_transfer=True, gzip_encoded=False, **kwds):
"""Create a new Upload object from a filename.""" |
path = os.path.expanduser(filename)
if not os.path.exists(path):
raise exceptions.NotFoundError('Could not find file %s' % path)
if not mime_type:
mime_type, _ = mimetypes.guess_type(path)
if mime_type is None:
raise exceptions.InvalidUserInputError(
'Could not guess mime type for %s' % path)
size = os.stat(path).st_size
return cls(open(path, 'rb'), mime_type, total_size=size,
close_stream=True, auto_transfer=auto_transfer,
gzip_encoded=gzip_encoded, **kwds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def FromStream(cls, stream, mime_type, total_size=None, auto_transfer=True, gzip_encoded=False, **kwds):
"""Create a new Upload object from a stream.""" |
if mime_type is None:
raise exceptions.InvalidUserInputError(
'No mime_type specified for stream')
return cls(stream, mime_type, total_size=total_size,
close_stream=False, auto_transfer=auto_transfer,
gzip_encoded=gzip_encoded, **kwds) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.