id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,400 | Miserlou/SoundScrape | soundscrape/soundscrape.py | process_bandcamp | def process_bandcamp(vargs):
"""
Main BandCamp path.
"""
artist_url = vargs['artist_url']
if 'bandcamp.com' in artist_url or ('://' in artist_url and vargs['bandcamp']):
bc_url = artist_url
else:
bc_url = 'https://' + artist_url + '.bandcamp.com/music'
filenames = scrape_bandcamp_url(bc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
# check if we have lists inside a list, which indicates the
# scraping has gone recursive, so we must format the output
# ( reference: http://stackoverflow.com/a/5251706 )
if any(isinstance(elem, list) for elem in filenames):
# first, remove any empty sublists inside our outter list
# ( reference: http://stackoverflow.com/a/19875634 )
filenames = [sub for sub in filenames if sub]
# now, make sure we "flatten" the list
# ( reference: http://stackoverflow.com/a/11264751 )
filenames = [val for sub in filenames for val in sub]
if vargs['open']:
open_files(filenames)
return | python | def process_bandcamp(vargs):
artist_url = vargs['artist_url']
if 'bandcamp.com' in artist_url or ('://' in artist_url and vargs['bandcamp']):
bc_url = artist_url
else:
bc_url = 'https://' + artist_url + '.bandcamp.com/music'
filenames = scrape_bandcamp_url(bc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
# check if we have lists inside a list, which indicates the
# scraping has gone recursive, so we must format the output
# ( reference: http://stackoverflow.com/a/5251706 )
if any(isinstance(elem, list) for elem in filenames):
# first, remove any empty sublists inside our outter list
# ( reference: http://stackoverflow.com/a/19875634 )
filenames = [sub for sub in filenames if sub]
# now, make sure we "flatten" the list
# ( reference: http://stackoverflow.com/a/11264751 )
filenames = [val for sub in filenames for val in sub]
if vargs['open']:
open_files(filenames)
return | [
"def",
"process_bandcamp",
"(",
"vargs",
")",
":",
"artist_url",
"=",
"vargs",
"[",
"'artist_url'",
"]",
"if",
"'bandcamp.com'",
"in",
"artist_url",
"or",
"(",
"'://'",
"in",
"artist_url",
"and",
"vargs",
"[",
"'bandcamp'",
"]",
")",
":",
"bc_url",
"=",
"a... | Main BandCamp path. | [
"Main",
"BandCamp",
"path",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L536-L564 |
229,401 | Miserlou/SoundScrape | soundscrape/soundscrape.py | scrape_bandcamp_url | def scrape_bandcamp_url(url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Pull out artist and track info from a Bandcamp URL.
Returns:
list: filenames to open
"""
filenames = []
album_data = get_bandcamp_metadata(url)
# If it's a list, we're dealing with a list of Album URLs,
# so we call the scrape_bandcamp_url() method for each one
if type(album_data) is list:
for album_url in album_data:
filenames.append(scrape_bandcamp_url(album_url, num_tracks, folders, custom_path))
return filenames
artist = album_data["artist"]
album_name = album_data["album_name"]
if folders:
if album_name:
directory = artist + " - " + album_name
else:
directory = artist
directory = sanitize_filename(directory)
directory = join(custom_path, directory)
if not exists(directory):
mkdir(directory)
for i, track in enumerate(album_data["trackinfo"]):
if i > num_tracks - 1:
continue
try:
track_name = track["title"]
if track["track_num"]:
track_number = str(track["track_num"]).zfill(2)
else:
track_number = None
if track_number and folders:
track_filename = '%s - %s.mp3' % (track_number, track_name)
else:
track_filename = '%s.mp3' % (track_name)
track_filename = sanitize_filename(track_filename)
if folders:
path = join(directory, track_filename)
else:
path = join(custom_path, sanitize_filename(artist) + ' - ' + track_filename)
if exists(path):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_name))
continue
if not track['file']:
puts_safe(colored.yellow("Track unavailble for scraping: ") + colored.white(track_name))
continue
puts_safe(colored.green("Downloading") + colored.white(": " + track_name))
path = download_file(track['file']['mp3-128'], path)
album_year = album_data['album_release_date']
if album_year:
album_year = datetime.strptime(album_year, "%d %b %Y %H:%M:%S GMT").year
tag_file(path,
artist,
track_name,
album=album_name,
year=album_year,
genre=album_data['genre'],
artwork_url=album_data['artFullsizeUrl'],
track_number=track_number,
url=album_data['url'])
filenames.append(path)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + colored.white(track_name))
print(e)
return filenames | python | def scrape_bandcamp_url(url, num_tracks=sys.maxsize, folders=False, custom_path=''):
filenames = []
album_data = get_bandcamp_metadata(url)
# If it's a list, we're dealing with a list of Album URLs,
# so we call the scrape_bandcamp_url() method for each one
if type(album_data) is list:
for album_url in album_data:
filenames.append(scrape_bandcamp_url(album_url, num_tracks, folders, custom_path))
return filenames
artist = album_data["artist"]
album_name = album_data["album_name"]
if folders:
if album_name:
directory = artist + " - " + album_name
else:
directory = artist
directory = sanitize_filename(directory)
directory = join(custom_path, directory)
if not exists(directory):
mkdir(directory)
for i, track in enumerate(album_data["trackinfo"]):
if i > num_tracks - 1:
continue
try:
track_name = track["title"]
if track["track_num"]:
track_number = str(track["track_num"]).zfill(2)
else:
track_number = None
if track_number and folders:
track_filename = '%s - %s.mp3' % (track_number, track_name)
else:
track_filename = '%s.mp3' % (track_name)
track_filename = sanitize_filename(track_filename)
if folders:
path = join(directory, track_filename)
else:
path = join(custom_path, sanitize_filename(artist) + ' - ' + track_filename)
if exists(path):
puts_safe(colored.yellow("Track already downloaded: ") + colored.white(track_name))
continue
if not track['file']:
puts_safe(colored.yellow("Track unavailble for scraping: ") + colored.white(track_name))
continue
puts_safe(colored.green("Downloading") + colored.white(": " + track_name))
path = download_file(track['file']['mp3-128'], path)
album_year = album_data['album_release_date']
if album_year:
album_year = datetime.strptime(album_year, "%d %b %Y %H:%M:%S GMT").year
tag_file(path,
artist,
track_name,
album=album_name,
year=album_year,
genre=album_data['genre'],
artwork_url=album_data['artFullsizeUrl'],
track_number=track_number,
url=album_data['url'])
filenames.append(path)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + colored.white(track_name))
print(e)
return filenames | [
"def",
"scrape_bandcamp_url",
"(",
"url",
",",
"num_tracks",
"=",
"sys",
".",
"maxsize",
",",
"folders",
"=",
"False",
",",
"custom_path",
"=",
"''",
")",
":",
"filenames",
"=",
"[",
"]",
"album_data",
"=",
"get_bandcamp_metadata",
"(",
"url",
")",
"# If i... | Pull out artist and track info from a Bandcamp URL.
Returns:
list: filenames to open | [
"Pull",
"out",
"artist",
"and",
"track",
"info",
"from",
"a",
"Bandcamp",
"URL",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L568-L651 |
229,402 | Miserlou/SoundScrape | soundscrape/soundscrape.py | process_mixcloud | def process_mixcloud(vargs):
"""
Main MixCloud path.
"""
artist_url = vargs['artist_url']
if 'mixcloud.com' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://mixcloud.com/' + artist_url
filenames = scrape_mixcloud_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return | python | def process_mixcloud(vargs):
artist_url = vargs['artist_url']
if 'mixcloud.com' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://mixcloud.com/' + artist_url
filenames = scrape_mixcloud_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return | [
"def",
"process_mixcloud",
"(",
"vargs",
")",
":",
"artist_url",
"=",
"vargs",
"[",
"'artist_url'",
"]",
"if",
"'mixcloud.com'",
"in",
"artist_url",
":",
"mc_url",
"=",
"artist_url",
"else",
":",
"mc_url",
"=",
"'https://mixcloud.com/'",
"+",
"artist_url",
"file... | Main MixCloud path. | [
"Main",
"MixCloud",
"path",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L711-L728 |
229,403 | Miserlou/SoundScrape | soundscrape/soundscrape.py | process_audiomack | def process_audiomack(vargs):
"""
Main Audiomack path.
"""
artist_url = vargs['artist_url']
if 'audiomack.com' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://audiomack.com/' + artist_url
filenames = scrape_audiomack_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return | python | def process_audiomack(vargs):
artist_url = vargs['artist_url']
if 'audiomack.com' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://audiomack.com/' + artist_url
filenames = scrape_audiomack_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return | [
"def",
"process_audiomack",
"(",
"vargs",
")",
":",
"artist_url",
"=",
"vargs",
"[",
"'artist_url'",
"]",
"if",
"'audiomack.com'",
"in",
"artist_url",
":",
"mc_url",
"=",
"artist_url",
"else",
":",
"mc_url",
"=",
"'https://audiomack.com/'",
"+",
"artist_url",
"f... | Main Audiomack path. | [
"Main",
"Audiomack",
"path",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L825-L842 |
229,404 | Miserlou/SoundScrape | soundscrape/soundscrape.py | process_hive | def process_hive(vargs):
"""
Main Hive.co path.
"""
artist_url = vargs['artist_url']
if 'hive.co' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://www.hive.co/downloads/download/' + artist_url
filenames = scrape_hive_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return | python | def process_hive(vargs):
artist_url = vargs['artist_url']
if 'hive.co' in artist_url:
mc_url = artist_url
else:
mc_url = 'https://www.hive.co/downloads/download/' + artist_url
filenames = scrape_hive_url(mc_url, num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames)
return | [
"def",
"process_hive",
"(",
"vargs",
")",
":",
"artist_url",
"=",
"vargs",
"[",
"'artist_url'",
"]",
"if",
"'hive.co'",
"in",
"artist_url",
":",
"mc_url",
"=",
"artist_url",
"else",
":",
"mc_url",
"=",
"'https://www.hive.co/downloads/download/'",
"+",
"artist_url"... | Main Hive.co path. | [
"Main",
"Hive",
".",
"co",
"path",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L919-L936 |
229,405 | Miserlou/SoundScrape | soundscrape/soundscrape.py | scrape_hive_url | def scrape_hive_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
"""
Scrape a Hive.co download page.
Returns:
list: filenames to open
"""
try:
data = get_hive_data(mc_url)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + mc_url)
print(e)
filenames = []
# track_artist = sanitize_filename(data['artist'])
# track_title = sanitize_filename(data['title'])
# track_filename = track_artist + ' - ' + track_title + '.mp3'
# if folders:
# track_artist_path = join(custom_path, track_artist)
# if not exists(track_artist_path):
# mkdir(track_artist_path)
# track_filename = join(track_artist_path, track_filename)
# if exists(track_filename):
# puts_safe(colored.yellow("Skipping") + colored.white(': ' + data['title'] + " - it already exists!"))
# return []
# puts_safe(colored.green("Downloading") + colored.white(': ' + data['artist'] + " - " + data['title']))
# download_file(data['mp3_url'], track_filename)
# tag_file(track_filename,
# artist=data['artist'],
# title=data['title'],
# year=data['year'],
# genre=None,
# artwork_url=data['artwork_url'])
# filenames.append(track_filename)
return filenames | python | def scrape_hive_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''):
try:
data = get_hive_data(mc_url)
except Exception as e:
puts_safe(colored.red("Problem downloading ") + mc_url)
print(e)
filenames = []
# track_artist = sanitize_filename(data['artist'])
# track_title = sanitize_filename(data['title'])
# track_filename = track_artist + ' - ' + track_title + '.mp3'
# if folders:
# track_artist_path = join(custom_path, track_artist)
# if not exists(track_artist_path):
# mkdir(track_artist_path)
# track_filename = join(track_artist_path, track_filename)
# if exists(track_filename):
# puts_safe(colored.yellow("Skipping") + colored.white(': ' + data['title'] + " - it already exists!"))
# return []
# puts_safe(colored.green("Downloading") + colored.white(': ' + data['artist'] + " - " + data['title']))
# download_file(data['mp3_url'], track_filename)
# tag_file(track_filename,
# artist=data['artist'],
# title=data['title'],
# year=data['year'],
# genre=None,
# artwork_url=data['artwork_url'])
# filenames.append(track_filename)
return filenames | [
"def",
"scrape_hive_url",
"(",
"mc_url",
",",
"num_tracks",
"=",
"sys",
".",
"maxsize",
",",
"folders",
"=",
"False",
",",
"custom_path",
"=",
"''",
")",
":",
"try",
":",
"data",
"=",
"get_hive_data",
"(",
"mc_url",
")",
"except",
"Exception",
"as",
"e",... | Scrape a Hive.co download page.
Returns:
list: filenames to open | [
"Scrape",
"a",
"Hive",
".",
"co",
"download",
"page",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L939-L979 |
229,406 | Miserlou/SoundScrape | soundscrape/soundscrape.py | process_musicbed | def process_musicbed(vargs):
"""
Main MusicBed path.
"""
# let's validate given MusicBed url
validated = False
if vargs['artist_url'].startswith( 'https://www.musicbed.com/' ):
splitted = vargs['artist_url'][len('https://www.musicbed.com/'):].split( '/' )
if len( splitted ) == 3:
if ( splitted[0] == 'artists' or splitted[0] == 'albums' or splitted[0] == 'songs' ) and splitted[2].isdigit():
validated = True
if not validated:
puts( colored.red( 'process_musicbed: you provided incorrect MusicBed url. Aborting.' ) )
puts( colored.white( 'Please make sure that url is either artist-url, album-url or song-url.' ) )
puts( colored.white( 'Example of correct artist-url: https://www.musicbed.com/artists/lights-motion/5188' ) )
puts( colored.white( 'Example of correct album-url: https://www.musicbed.com/albums/be-still/2828' ) )
puts( colored.white( 'Example of correct song-url: https://www.musicbed.com/songs/be-still/24540' ) )
return
filenames = scrape_musicbed_url(vargs['artist_url'], vargs['login'], vargs['password'], num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames) | python | def process_musicbed(vargs):
# let's validate given MusicBed url
validated = False
if vargs['artist_url'].startswith( 'https://www.musicbed.com/' ):
splitted = vargs['artist_url'][len('https://www.musicbed.com/'):].split( '/' )
if len( splitted ) == 3:
if ( splitted[0] == 'artists' or splitted[0] == 'albums' or splitted[0] == 'songs' ) and splitted[2].isdigit():
validated = True
if not validated:
puts( colored.red( 'process_musicbed: you provided incorrect MusicBed url. Aborting.' ) )
puts( colored.white( 'Please make sure that url is either artist-url, album-url or song-url.' ) )
puts( colored.white( 'Example of correct artist-url: https://www.musicbed.com/artists/lights-motion/5188' ) )
puts( colored.white( 'Example of correct album-url: https://www.musicbed.com/albums/be-still/2828' ) )
puts( colored.white( 'Example of correct song-url: https://www.musicbed.com/songs/be-still/24540' ) )
return
filenames = scrape_musicbed_url(vargs['artist_url'], vargs['login'], vargs['password'], num_tracks=vargs['num_tracks'], folders=vargs['folders'], custom_path=vargs['path'])
if vargs['open']:
open_files(filenames) | [
"def",
"process_musicbed",
"(",
"vargs",
")",
":",
"# let's validate given MusicBed url",
"validated",
"=",
"False",
"if",
"vargs",
"[",
"'artist_url'",
"]",
".",
"startswith",
"(",
"'https://www.musicbed.com/'",
")",
":",
"splitted",
"=",
"vargs",
"[",
"'artist_url... | Main MusicBed path. | [
"Main",
"MusicBed",
"path",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L1016-L1040 |
229,407 | Miserlou/SoundScrape | soundscrape/soundscrape.py | download_file | def download_file(url, path, session=None, params=None):
"""
Download an individual file.
"""
if url[0:2] == '//':
url = 'https://' + url[2:]
# Use a temporary file so that we don't import incomplete files.
tmp_path = path + '.tmp'
if session and params:
r = session.get( url, params=params, stream=True )
elif session and not params:
r = session.get( url, stream=True )
else:
r = requests.get(url, stream=True)
with open(tmp_path, 'wb') as f:
total_length = int(r.headers.get('content-length', 0))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
os.rename(tmp_path, path)
return path | python | def download_file(url, path, session=None, params=None):
if url[0:2] == '//':
url = 'https://' + url[2:]
# Use a temporary file so that we don't import incomplete files.
tmp_path = path + '.tmp'
if session and params:
r = session.get( url, params=params, stream=True )
elif session and not params:
r = session.get( url, stream=True )
else:
r = requests.get(url, stream=True)
with open(tmp_path, 'wb') as f:
total_length = int(r.headers.get('content-length', 0))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
os.rename(tmp_path, path)
return path | [
"def",
"download_file",
"(",
"url",
",",
"path",
",",
"session",
"=",
"None",
",",
"params",
"=",
"None",
")",
":",
"if",
"url",
"[",
"0",
":",
"2",
"]",
"==",
"'//'",
":",
"url",
"=",
"'https://'",
"+",
"url",
"[",
"2",
":",
"]",
"# Use a tempor... | Download an individual file. | [
"Download",
"an",
"individual",
"file",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L1177-L1203 |
229,408 | Miserlou/SoundScrape | soundscrape/soundscrape.py | tag_file | def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None):
"""
Attempt to put ID3 tags on a file.
Args:
artist (str):
title (str):
year (int):
genre (str):
artwork_url (str):
album (str):
track_number (str):
filename (str):
url (str):
"""
try:
audio = EasyMP3(filename)
audio.tags = None
audio["artist"] = artist
audio["title"] = title
if year:
audio["date"] = str(year)
if album:
audio["album"] = album
if track_number:
audio["tracknumber"] = track_number
if genre:
audio["genre"] = genre
if url: # saves the tag as WOAR
audio["website"] = url
audio.save()
if artwork_url:
artwork_url = artwork_url.replace('https', 'http')
mime = 'image/jpeg'
if '.jpg' in artwork_url:
mime = 'image/jpeg'
if '.png' in artwork_url:
mime = 'image/png'
if '-large' in artwork_url:
new_artwork_url = artwork_url.replace('-large', '-t500x500')
try:
image_data = requests.get(new_artwork_url).content
except Exception as e:
# No very large image available.
image_data = requests.get(artwork_url).content
else:
image_data = requests.get(artwork_url).content
audio = MP3(filename, ID3=OldID3)
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime=mime,
type=3, # 3 is for the cover image
desc='Cover',
data=image_data
)
)
audio.save()
# because there is software that doesn't seem to use WOAR we save url tag again as WXXX
if url:
audio = MP3(filename, ID3=OldID3)
audio.tags.add( WXXX( encoding=3, url=url ) )
audio.save()
return True
except Exception as e:
puts(colored.red("Problem tagging file: ") + colored.white("Is this file a WAV?"))
return False | python | def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None):
try:
audio = EasyMP3(filename)
audio.tags = None
audio["artist"] = artist
audio["title"] = title
if year:
audio["date"] = str(year)
if album:
audio["album"] = album
if track_number:
audio["tracknumber"] = track_number
if genre:
audio["genre"] = genre
if url: # saves the tag as WOAR
audio["website"] = url
audio.save()
if artwork_url:
artwork_url = artwork_url.replace('https', 'http')
mime = 'image/jpeg'
if '.jpg' in artwork_url:
mime = 'image/jpeg'
if '.png' in artwork_url:
mime = 'image/png'
if '-large' in artwork_url:
new_artwork_url = artwork_url.replace('-large', '-t500x500')
try:
image_data = requests.get(new_artwork_url).content
except Exception as e:
# No very large image available.
image_data = requests.get(artwork_url).content
else:
image_data = requests.get(artwork_url).content
audio = MP3(filename, ID3=OldID3)
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime=mime,
type=3, # 3 is for the cover image
desc='Cover',
data=image_data
)
)
audio.save()
# because there is software that doesn't seem to use WOAR we save url tag again as WXXX
if url:
audio = MP3(filename, ID3=OldID3)
audio.tags.add( WXXX( encoding=3, url=url ) )
audio.save()
return True
except Exception as e:
puts(colored.red("Problem tagging file: ") + colored.white("Is this file a WAV?"))
return False | [
"def",
"tag_file",
"(",
"filename",
",",
"artist",
",",
"title",
",",
"year",
"=",
"None",
",",
"genre",
"=",
"None",
",",
"artwork_url",
"=",
"None",
",",
"album",
"=",
"None",
",",
"track_number",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"... | Attempt to put ID3 tags on a file.
Args:
artist (str):
title (str):
year (int):
genre (str):
artwork_url (str):
album (str):
track_number (str):
filename (str):
url (str): | [
"Attempt",
"to",
"put",
"ID3",
"tags",
"on",
"a",
"file",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L1206-L1281 |
229,409 | Miserlou/SoundScrape | soundscrape/soundscrape.py | open_files | def open_files(filenames):
"""
Call the system 'open' command on a file.
"""
command = ['open'] + filenames
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate() | python | def open_files(filenames):
command = ['open'] + filenames
process = Popen(command, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate() | [
"def",
"open_files",
"(",
"filenames",
")",
":",
"command",
"=",
"[",
"'open'",
"]",
"+",
"filenames",
"process",
"=",
"Popen",
"(",
"command",
",",
"stdout",
"=",
"PIPE",
",",
"stderr",
"=",
"PIPE",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
... | Call the system 'open' command on a file. | [
"Call",
"the",
"system",
"open",
"command",
"on",
"a",
"file",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L1283-L1289 |
229,410 | Miserlou/SoundScrape | soundscrape/soundscrape.py | sanitize_filename | def sanitize_filename(filename):
"""
Make sure filenames are valid paths.
Returns:
str:
"""
sanitized_filename = re.sub(r'[/\\:*?"<>|]', '-', filename)
sanitized_filename = sanitized_filename.replace('&', 'and')
sanitized_filename = sanitized_filename.replace('"', '')
sanitized_filename = sanitized_filename.replace("'", '')
sanitized_filename = sanitized_filename.replace("/", '')
sanitized_filename = sanitized_filename.replace("\\", '')
# Annoying.
if sanitized_filename[0] == '.':
sanitized_filename = u'dot' + sanitized_filename[1:]
return sanitized_filename | python | def sanitize_filename(filename):
sanitized_filename = re.sub(r'[/\\:*?"<>|]', '-', filename)
sanitized_filename = sanitized_filename.replace('&', 'and')
sanitized_filename = sanitized_filename.replace('"', '')
sanitized_filename = sanitized_filename.replace("'", '')
sanitized_filename = sanitized_filename.replace("/", '')
sanitized_filename = sanitized_filename.replace("\\", '')
# Annoying.
if sanitized_filename[0] == '.':
sanitized_filename = u'dot' + sanitized_filename[1:]
return sanitized_filename | [
"def",
"sanitize_filename",
"(",
"filename",
")",
":",
"sanitized_filename",
"=",
"re",
".",
"sub",
"(",
"r'[/\\\\:*?\"<>|]'",
",",
"'-'",
",",
"filename",
")",
"sanitized_filename",
"=",
"sanitized_filename",
".",
"replace",
"(",
"'&'",
",",
"'and'",
")",
"sa... | Make sure filenames are valid paths.
Returns:
str: | [
"Make",
"sure",
"filenames",
"are",
"valid",
"paths",
"."
] | efc63b99ce7e78b352e2ba22d5e51f83445546d7 | https://github.com/Miserlou/SoundScrape/blob/efc63b99ce7e78b352e2ba22d5e51f83445546d7/soundscrape/soundscrape.py#L1292-L1310 |
229,411 | dtcooper/python-fitparse | fitparse/records.py | Crc.update | def update(self, byte_arr):
"""Read bytes and update the CRC computed."""
if byte_arr:
self.value = self.calculate(byte_arr, self.value) | python | def update(self, byte_arr):
if byte_arr:
self.value = self.calculate(byte_arr, self.value) | [
"def",
"update",
"(",
"self",
",",
"byte_arr",
")",
":",
"if",
"byte_arr",
":",
"self",
".",
"value",
"=",
"self",
".",
"calculate",
"(",
"byte_arr",
",",
"self",
".",
"value",
")"
] | Read bytes and update the CRC computed. | [
"Read",
"bytes",
"and",
"update",
"the",
"CRC",
"computed",
"."
] | 40fa2918c3e91bd8f89908ad3bad81c1c1189dd2 | https://github.com/dtcooper/python-fitparse/blob/40fa2918c3e91bd8f89908ad3bad81c1c1189dd2/fitparse/records.py#L365-L368 |
229,412 | dtcooper/python-fitparse | fitparse/records.py | Crc.calculate | def calculate(cls, byte_arr, crc=0):
"""Compute CRC for input bytes."""
for byte in byte_iter(byte_arr):
# Taken verbatim from FIT SDK docs
tmp = cls.CRC_TABLE[crc & 0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ cls.CRC_TABLE[byte & 0xF]
tmp = cls.CRC_TABLE[crc & 0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ cls.CRC_TABLE[(byte >> 4) & 0xF]
return crc | python | def calculate(cls, byte_arr, crc=0):
for byte in byte_iter(byte_arr):
# Taken verbatim from FIT SDK docs
tmp = cls.CRC_TABLE[crc & 0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ cls.CRC_TABLE[byte & 0xF]
tmp = cls.CRC_TABLE[crc & 0xF]
crc = (crc >> 4) & 0x0FFF
crc = crc ^ tmp ^ cls.CRC_TABLE[(byte >> 4) & 0xF]
return crc | [
"def",
"calculate",
"(",
"cls",
",",
"byte_arr",
",",
"crc",
"=",
"0",
")",
":",
"for",
"byte",
"in",
"byte_iter",
"(",
"byte_arr",
")",
":",
"# Taken verbatim from FIT SDK docs",
"tmp",
"=",
"cls",
".",
"CRC_TABLE",
"[",
"crc",
"&",
"0xF",
"]",
"crc",
... | Compute CRC for input bytes. | [
"Compute",
"CRC",
"for",
"input",
"bytes",
"."
] | 40fa2918c3e91bd8f89908ad3bad81c1c1189dd2 | https://github.com/dtcooper/python-fitparse/blob/40fa2918c3e91bd8f89908ad3bad81c1c1189dd2/fitparse/records.py#L376-L387 |
229,413 | dtcooper/python-fitparse | fitparse/processors.py | FitFileDataProcessor._scrub_method_name | def _scrub_method_name(self, method_name):
"""Scrubs a method name, returning result from local cache if available.
This method wraps fitparse.utils.scrub_method_name and memoizes results,
as scrubbing a method name is expensive.
Args:
method_name: Method name to scrub.
Returns:
Scrubbed method name.
"""
if method_name not in self._scrubbed_method_names:
self._scrubbed_method_names[method_name] = (
scrub_method_name(method_name))
return self._scrubbed_method_names[method_name] | python | def _scrub_method_name(self, method_name):
if method_name not in self._scrubbed_method_names:
self._scrubbed_method_names[method_name] = (
scrub_method_name(method_name))
return self._scrubbed_method_names[method_name] | [
"def",
"_scrub_method_name",
"(",
"self",
",",
"method_name",
")",
":",
"if",
"method_name",
"not",
"in",
"self",
".",
"_scrubbed_method_names",
":",
"self",
".",
"_scrubbed_method_names",
"[",
"method_name",
"]",
"=",
"(",
"scrub_method_name",
"(",
"method_name",... | Scrubs a method name, returning result from local cache if available.
This method wraps fitparse.utils.scrub_method_name and memoizes results,
as scrubbing a method name is expensive.
Args:
method_name: Method name to scrub.
Returns:
Scrubbed method name. | [
"Scrubs",
"a",
"method",
"name",
"returning",
"result",
"from",
"local",
"cache",
"if",
"available",
"."
] | 40fa2918c3e91bd8f89908ad3bad81c1c1189dd2 | https://github.com/dtcooper/python-fitparse/blob/40fa2918c3e91bd8f89908ad3bad81c1c1189dd2/fitparse/processors.py#L25-L41 |
229,414 | dschep/ntfy | ntfy/backends/systemlog.py | notify | def notify(title,
message,
prio='ALERT',
facility='LOCAL5',
fmt='[{title}] {message}',
retcode=None):
"""
Uses the ``syslog`` core Python module, which is not available on Windows
platforms.
Optional parameters:
* ``prio`` - Syslog prority level. Default is ``ALERT``. Possible
values are:
* EMERG
* ALERT
* CRIT
* ERR
* WARNING
* NOTICE
* INFO
* DEBUG
* ``facility`` - Syslog facility. Default is ``LOCAL5``. Possible
values are:
* KERN
* USER
* MAIL
* DAEMON
* AUTH
* LPR
* NEWS
* UUCP
* CRON
* SYSLOG
* LOCAL0
* LOCAL1
* LOCAL2
* LOCAL3
* LOCAL4
* LOCAL5
* LOCAL6
* LOCAL7
* ``fmt`` - Format of the message to be sent to the system logger. The
title and the message are specified using the following placeholders:
* ``{title}``
* ``{message}``
Default is ``[{title}] {message}``.
"""
prio_map = {
'EMERG': syslog.LOG_EMERG,
'ALERT': syslog.LOG_ALERT,
'CRIT': syslog.LOG_CRIT,
'ERR': syslog.LOG_ERR,
'WARNING': syslog.LOG_WARNING,
'NOTICE': syslog.LOG_NOTICE,
'INFO': syslog.LOG_INFO,
'DEBUG': syslog.LOG_DEBUG,
}
facility_map = {
'KERN': syslog.LOG_KERN,
'USER': syslog.LOG_USER,
'MAIL': syslog.LOG_MAIL,
'DAEMON': syslog.LOG_DAEMON,
'AUTH': syslog.LOG_AUTH,
'LPR': syslog.LOG_LPR,
'NEWS': syslog.LOG_NEWS,
'UUCP': syslog.LOG_UUCP,
'CRON': syslog.LOG_CRON,
'SYSLOG': syslog.LOG_SYSLOG,
'LOCAL0': syslog.LOG_LOCAL0,
'LOCAL1': syslog.LOG_LOCAL1,
'LOCAL2': syslog.LOG_LOCAL2,
'LOCAL3': syslog.LOG_LOCAL3,
'LOCAL4': syslog.LOG_LOCAL4,
'LOCAL5': syslog.LOG_LOCAL5,
'LOCAL6': syslog.LOG_LOCAL6,
'LOCAL7': syslog.LOG_LOCAL7,
}
if prio not in prio_map:
raise ValueError('invalid syslog priority')
elif facility not in facility_map:
raise ValueError('invalid syslog facility')
msg = fmt.format(title=title, message=message)
for line in msg.splitlines():
syslog.syslog(facility_map[facility] | prio_map[prio], line) | python | def notify(title,
message,
prio='ALERT',
facility='LOCAL5',
fmt='[{title}] {message}',
retcode=None):
prio_map = {
'EMERG': syslog.LOG_EMERG,
'ALERT': syslog.LOG_ALERT,
'CRIT': syslog.LOG_CRIT,
'ERR': syslog.LOG_ERR,
'WARNING': syslog.LOG_WARNING,
'NOTICE': syslog.LOG_NOTICE,
'INFO': syslog.LOG_INFO,
'DEBUG': syslog.LOG_DEBUG,
}
facility_map = {
'KERN': syslog.LOG_KERN,
'USER': syslog.LOG_USER,
'MAIL': syslog.LOG_MAIL,
'DAEMON': syslog.LOG_DAEMON,
'AUTH': syslog.LOG_AUTH,
'LPR': syslog.LOG_LPR,
'NEWS': syslog.LOG_NEWS,
'UUCP': syslog.LOG_UUCP,
'CRON': syslog.LOG_CRON,
'SYSLOG': syslog.LOG_SYSLOG,
'LOCAL0': syslog.LOG_LOCAL0,
'LOCAL1': syslog.LOG_LOCAL1,
'LOCAL2': syslog.LOG_LOCAL2,
'LOCAL3': syslog.LOG_LOCAL3,
'LOCAL4': syslog.LOG_LOCAL4,
'LOCAL5': syslog.LOG_LOCAL5,
'LOCAL6': syslog.LOG_LOCAL6,
'LOCAL7': syslog.LOG_LOCAL7,
}
if prio not in prio_map:
raise ValueError('invalid syslog priority')
elif facility not in facility_map:
raise ValueError('invalid syslog facility')
msg = fmt.format(title=title, message=message)
for line in msg.splitlines():
syslog.syslog(facility_map[facility] | prio_map[prio], line) | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"prio",
"=",
"'ALERT'",
",",
"facility",
"=",
"'LOCAL5'",
",",
"fmt",
"=",
"'[{title}] {message}'",
",",
"retcode",
"=",
"None",
")",
":",
"prio_map",
"=",
"{",
"'EMERG'",
":",
"syslog",
".",
"LOG_EMERG... | Uses the ``syslog`` core Python module, which is not available on Windows
platforms.
Optional parameters:
* ``prio`` - Syslog prority level. Default is ``ALERT``. Possible
values are:
* EMERG
* ALERT
* CRIT
* ERR
* WARNING
* NOTICE
* INFO
* DEBUG
* ``facility`` - Syslog facility. Default is ``LOCAL5``. Possible
values are:
* KERN
* USER
* MAIL
* DAEMON
* AUTH
* LPR
* NEWS
* UUCP
* CRON
* SYSLOG
* LOCAL0
* LOCAL1
* LOCAL2
* LOCAL3
* LOCAL4
* LOCAL5
* LOCAL6
* LOCAL7
* ``fmt`` - Format of the message to be sent to the system logger. The
title and the message are specified using the following placeholders:
* ``{title}``
* ``{message}``
Default is ``[{title}] {message}``. | [
"Uses",
"the",
"syslog",
"core",
"Python",
"module",
"which",
"is",
"not",
"available",
"on",
"Windows",
"platforms",
"."
] | ecfeee960af406a27ebb123495e0ec2733286889 | https://github.com/dschep/ntfy/blob/ecfeee960af406a27ebb123495e0ec2733286889/ntfy/backends/systemlog.py#L4-L97 |
229,415 | dschep/ntfy | ntfy/backends/default.py | notify | def notify(title, message, **kwargs):
"""
This backend automatically selects the correct desktop notification backend
for your operating system.
"""
for os in ['linux', 'win32', 'darwin']:
if platform.startswith(os):
module = import_module('ntfy.backends.{}'.format(os))
try:
module.notify(title=title, message=message, **kwargs)
except Exception as e:
raise DefaultNotifierError(e, module)
break | python | def notify(title, message, **kwargs):
for os in ['linux', 'win32', 'darwin']:
if platform.startswith(os):
module = import_module('ntfy.backends.{}'.format(os))
try:
module.notify(title=title, message=message, **kwargs)
except Exception as e:
raise DefaultNotifierError(e, module)
break | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"os",
"in",
"[",
"'linux'",
",",
"'win32'",
",",
"'darwin'",
"]",
":",
"if",
"platform",
".",
"startswith",
"(",
"os",
")",
":",
"module",
"=",
"import_module",
... | This backend automatically selects the correct desktop notification backend
for your operating system. | [
"This",
"backend",
"automatically",
"selects",
"the",
"correct",
"desktop",
"notification",
"backend",
"for",
"your",
"operating",
"system",
"."
] | ecfeee960af406a27ebb123495e0ec2733286889 | https://github.com/dschep/ntfy/blob/ecfeee960af406a27ebb123495e0ec2733286889/ntfy/backends/default.py#L11-L23 |
229,416 | dschep/ntfy | ntfy/backends/telegram.py | notify | def notify(title, message, retcode=None):
"""Sends message over Telegram using telegram-send, title is ignored."""
if not path.exists(config_file):
if not path.exists(config_dir):
makedirs(config_dir)
print("Follow the instructions to configure the Telegram backend.\n")
configure(config_file)
send(messages=[message], conf=config_file) | python | def notify(title, message, retcode=None):
if not path.exists(config_file):
if not path.exists(config_dir):
makedirs(config_dir)
print("Follow the instructions to configure the Telegram backend.\n")
configure(config_file)
send(messages=[message], conf=config_file) | [
"def",
"notify",
"(",
"title",
",",
"message",
",",
"retcode",
"=",
"None",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"if",
"not",
"path",
".",
"exists",
"(",
"config_dir",
")",
":",
"makedirs",
"(",
"config_dir",
")... | Sends message over Telegram using telegram-send, title is ignored. | [
"Sends",
"message",
"over",
"Telegram",
"using",
"telegram",
"-",
"send",
"title",
"is",
"ignored",
"."
] | ecfeee960af406a27ebb123495e0ec2733286889 | https://github.com/dschep/ntfy/blob/ecfeee960af406a27ebb123495e0ec2733286889/ntfy/backends/telegram.py#L11-L18 |
229,417 | rm-hull/luma.led_matrix | examples/silly_clock.py | minute_change | def minute_change(device):
'''When we reach a minute change, animate it.'''
hours = datetime.now().strftime('%H')
minutes = datetime.now().strftime('%M')
def helper(current_y):
with canvas(device) as draw:
text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT))
text(draw, (15, 1), ":", fill="white", font=proportional(TINY_FONT))
text(draw, (17, current_y), minutes, fill="white", font=proportional(CP437_FONT))
time.sleep(0.1)
for current_y in range(1, 9):
helper(current_y)
minutes = datetime.now().strftime('%M')
for current_y in range(9, 1, -1):
helper(current_y) | python | def minute_change(device):
'''When we reach a minute change, animate it.'''
hours = datetime.now().strftime('%H')
minutes = datetime.now().strftime('%M')
def helper(current_y):
with canvas(device) as draw:
text(draw, (0, 1), hours, fill="white", font=proportional(CP437_FONT))
text(draw, (15, 1), ":", fill="white", font=proportional(TINY_FONT))
text(draw, (17, current_y), minutes, fill="white", font=proportional(CP437_FONT))
time.sleep(0.1)
for current_y in range(1, 9):
helper(current_y)
minutes = datetime.now().strftime('%M')
for current_y in range(9, 1, -1):
helper(current_y) | [
"def",
"minute_change",
"(",
"device",
")",
":",
"hours",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%H'",
")",
"minutes",
"=",
"datetime",
".",
"now",
"(",
")",
".",
"strftime",
"(",
"'%M'",
")",
"def",
"helper",
"(",
"current_y"... | When we reach a minute change, animate it. | [
"When",
"we",
"reach",
"a",
"minute",
"change",
"animate",
"it",
"."
] | 62e90aa0c052c869856a936bd76d6d86baf4ad8e | https://github.com/rm-hull/luma.led_matrix/blob/62e90aa0c052c869856a936bd76d6d86baf4ad8e/examples/silly_clock.py#L12-L27 |
229,418 | rm-hull/luma.led_matrix | examples/sevensegment_demo.py | clock | def clock(seg, seconds):
"""
Display current time on device.
"""
interval = 0.5
for i in range(int(seconds / interval)):
now = datetime.now()
seg.text = now.strftime("%H-%M-%S")
# calculate blinking dot
if i % 2 == 0:
seg.text = now.strftime("%H-%M-%S")
else:
seg.text = now.strftime("%H %M %S")
time.sleep(interval) | python | def clock(seg, seconds):
interval = 0.5
for i in range(int(seconds / interval)):
now = datetime.now()
seg.text = now.strftime("%H-%M-%S")
# calculate blinking dot
if i % 2 == 0:
seg.text = now.strftime("%H-%M-%S")
else:
seg.text = now.strftime("%H %M %S")
time.sleep(interval) | [
"def",
"clock",
"(",
"seg",
",",
"seconds",
")",
":",
"interval",
"=",
"0.5",
"for",
"i",
"in",
"range",
"(",
"int",
"(",
"seconds",
"/",
"interval",
")",
")",
":",
"now",
"=",
"datetime",
".",
"now",
"(",
")",
"seg",
".",
"text",
"=",
"now",
"... | Display current time on device. | [
"Display",
"current",
"time",
"on",
"device",
"."
] | 62e90aa0c052c869856a936bd76d6d86baf4ad8e | https://github.com/rm-hull/luma.led_matrix/blob/62e90aa0c052c869856a936bd76d6d86baf4ad8e/examples/sevensegment_demo.py#L26-L41 |
229,419 | rm-hull/luma.led_matrix | luma/led_matrix/device.py | ws2812.hide | def hide(self):
"""
Simulates switching the display mode OFF; this is achieved by setting
the contrast level to zero.
"""
if self._prev_contrast is None:
self._prev_contrast = self._contrast
self.contrast(0x00) | python | def hide(self):
if self._prev_contrast is None:
self._prev_contrast = self._contrast
self.contrast(0x00) | [
"def",
"hide",
"(",
"self",
")",
":",
"if",
"self",
".",
"_prev_contrast",
"is",
"None",
":",
"self",
".",
"_prev_contrast",
"=",
"self",
".",
"_contrast",
"self",
".",
"contrast",
"(",
"0x00",
")"
] | Simulates switching the display mode OFF; this is achieved by setting
the contrast level to zero. | [
"Simulates",
"switching",
"the",
"display",
"mode",
"OFF",
";",
"this",
"is",
"achieved",
"by",
"setting",
"the",
"contrast",
"level",
"to",
"zero",
"."
] | 62e90aa0c052c869856a936bd76d6d86baf4ad8e | https://github.com/rm-hull/luma.led_matrix/blob/62e90aa0c052c869856a936bd76d6d86baf4ad8e/luma/led_matrix/device.py#L291-L298 |
229,420 | rm-hull/luma.led_matrix | luma/led_matrix/device.py | ws2812.cleanup | def cleanup(self):
"""
Attempt to reset the device & switching it off prior to exiting the
python process.
"""
self.hide()
self.clear()
if self._leds is not None:
self._ws.ws2811_fini(self._leds)
self._ws.delete_ws2811_t(self._leds)
self._leds = None
self._channel = None | python | def cleanup(self):
self.hide()
self.clear()
if self._leds is not None:
self._ws.ws2811_fini(self._leds)
self._ws.delete_ws2811_t(self._leds)
self._leds = None
self._channel = None | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"hide",
"(",
")",
"self",
".",
"clear",
"(",
")",
"if",
"self",
".",
"_leds",
"is",
"not",
"None",
":",
"self",
".",
"_ws",
".",
"ws2811_fini",
"(",
"self",
".",
"_leds",
")",
"self",
".",
"... | Attempt to reset the device & switching it off prior to exiting the
python process. | [
"Attempt",
"to",
"reset",
"the",
"device",
"&",
"switching",
"it",
"off",
"prior",
"to",
"exiting",
"the",
"python",
"process",
"."
] | 62e90aa0c052c869856a936bd76d6d86baf4ad8e | https://github.com/rm-hull/luma.led_matrix/blob/62e90aa0c052c869856a936bd76d6d86baf4ad8e/luma/led_matrix/device.py#L324-L336 |
229,421 | quatanium/python-onvif | examples/rotate_image.py | rotate_image_180 | def rotate_image_180():
''' Rotate the image '''
# Create the media service
mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345')
media_service = mycam.create_media_service()
profiles = media_service.GetProfiles()
# Use the first profile and Profiles have at least one
token = profiles[0]._token
# Get all video source configurations
configurations_list = media_service.GetVideoSourceConfigurations()
# Use the first profile and Profiles have at least one
video_source_configuration = configurations_list[0]
# Enable rotate
video_source_configuration.Extension[0].Rotate[0].Mode[0] = 'OFF'
# Create request type instance
request = media_service.create_type('SetVideoSourceConfiguration')
request.Configuration = video_source_configuration
# ForcePersistence is obsolete and should always be assumed to be True
request.ForcePersistence = True
# Set the video source configuration
media_service.SetVideoSourceConfiguration(request) | python | def rotate_image_180():
''' Rotate the image '''
# Create the media service
mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345')
media_service = mycam.create_media_service()
profiles = media_service.GetProfiles()
# Use the first profile and Profiles have at least one
token = profiles[0]._token
# Get all video source configurations
configurations_list = media_service.GetVideoSourceConfigurations()
# Use the first profile and Profiles have at least one
video_source_configuration = configurations_list[0]
# Enable rotate
video_source_configuration.Extension[0].Rotate[0].Mode[0] = 'OFF'
# Create request type instance
request = media_service.create_type('SetVideoSourceConfiguration')
request.Configuration = video_source_configuration
# ForcePersistence is obsolete and should always be assumed to be True
request.ForcePersistence = True
# Set the video source configuration
media_service.SetVideoSourceConfiguration(request) | [
"def",
"rotate_image_180",
"(",
")",
":",
"# Create the media service",
"mycam",
"=",
"ONVIFCamera",
"(",
"'192.168.0.112'",
",",
"80",
",",
"'admin'",
",",
"'12345'",
")",
"media_service",
"=",
"mycam",
".",
"create_media_service",
"(",
")",
"profiles",
"=",
"m... | Rotate the image | [
"Rotate",
"the",
"image"
] | daf3ac87d998d5dc61c40cee130ce3fed93111aa | https://github.com/quatanium/python-onvif/blob/daf3ac87d998d5dc61c40cee130ce3fed93111aa/examples/rotate_image.py#L3-L32 |
229,422 | quatanium/python-onvif | onvif/client.py | ONVIFService.set_wsse | def set_wsse(self, user=None, passwd=None):
''' Basic ws-security auth '''
if user:
self.user = user
if passwd:
self.passwd = passwd
security = Security()
if self.encrypt:
token = UsernameDigestTokenDtDiff(self.user, self.passwd, dt_diff=self.dt_diff)
else:
token = UsernameToken(self.user, self.passwd)
token.setnonce()
token.setcreated()
security.tokens.append(token)
self.ws_client.set_options(wsse=security) | python | def set_wsse(self, user=None, passwd=None):
''' Basic ws-security auth '''
if user:
self.user = user
if passwd:
self.passwd = passwd
security = Security()
if self.encrypt:
token = UsernameDigestTokenDtDiff(self.user, self.passwd, dt_diff=self.dt_diff)
else:
token = UsernameToken(self.user, self.passwd)
token.setnonce()
token.setcreated()
security.tokens.append(token)
self.ws_client.set_options(wsse=security) | [
"def",
"set_wsse",
"(",
"self",
",",
"user",
"=",
"None",
",",
"passwd",
"=",
"None",
")",
":",
"if",
"user",
":",
"self",
".",
"user",
"=",
"user",
"if",
"passwd",
":",
"self",
".",
"passwd",
"=",
"passwd",
"security",
"=",
"Security",
"(",
")",
... | Basic ws-security auth | [
"Basic",
"ws",
"-",
"security",
"auth"
] | daf3ac87d998d5dc61c40cee130ce3fed93111aa | https://github.com/quatanium/python-onvif/blob/daf3ac87d998d5dc61c40cee130ce3fed93111aa/onvif/client.py#L138-L155 |
229,423 | quatanium/python-onvif | onvif/client.py | ONVIFCamera.get_definition | def get_definition(self, name):
'''Returns xaddr and wsdl of specified service'''
# Check if the service is supported
if name not in SERVICES:
raise ONVIFError('Unknown service %s' % name)
wsdl_file = SERVICES[name]['wsdl']
ns = SERVICES[name]['ns']
wsdlpath = os.path.join(self.wsdl_dir, wsdl_file)
if not os.path.isfile(wsdlpath):
raise ONVIFError('No such file: %s' % wsdlpath)
# XAddr for devicemgmt is fixed:
if name == 'devicemgmt':
xaddr = 'http://%s:%s/onvif/device_service' % (self.host, self.port)
return xaddr, wsdlpath
# Get other XAddr
xaddr = self.xaddrs.get(ns)
if not xaddr:
raise ONVIFError('Device doesn`t support service: %s' % name)
return xaddr, wsdlpath | python | def get_definition(self, name):
'''Returns xaddr and wsdl of specified service'''
# Check if the service is supported
if name not in SERVICES:
raise ONVIFError('Unknown service %s' % name)
wsdl_file = SERVICES[name]['wsdl']
ns = SERVICES[name]['ns']
wsdlpath = os.path.join(self.wsdl_dir, wsdl_file)
if not os.path.isfile(wsdlpath):
raise ONVIFError('No such file: %s' % wsdlpath)
# XAddr for devicemgmt is fixed:
if name == 'devicemgmt':
xaddr = 'http://%s:%s/onvif/device_service' % (self.host, self.port)
return xaddr, wsdlpath
# Get other XAddr
xaddr = self.xaddrs.get(ns)
if not xaddr:
raise ONVIFError('Device doesn`t support service: %s' % name)
return xaddr, wsdlpath | [
"def",
"get_definition",
"(",
"self",
",",
"name",
")",
":",
"# Check if the service is supported",
"if",
"name",
"not",
"in",
"SERVICES",
":",
"raise",
"ONVIFError",
"(",
"'Unknown service %s'",
"%",
"name",
")",
"wsdl_file",
"=",
"SERVICES",
"[",
"name",
"]",
... | Returns xaddr and wsdl of specified service | [
"Returns",
"xaddr",
"and",
"wsdl",
"of",
"specified",
"service"
] | daf3ac87d998d5dc61c40cee130ce3fed93111aa | https://github.com/quatanium/python-onvif/blob/daf3ac87d998d5dc61c40cee130ce3fed93111aa/onvif/client.py#L336-L358 |
229,424 | quatanium/python-onvif | onvif/client.py | ONVIFCamera.create_onvif_service | def create_onvif_service(self, name, from_template=True, portType=None):
'''Create ONVIF service client'''
name = name.lower()
xaddr, wsdl_file = self.get_definition(name)
with self.services_lock:
svt = self.services_template.get(name)
# Has a template, clone from it. Faster.
if svt and from_template and self.use_services_template.get(name):
service = ONVIFService.clone(svt, xaddr, self.user,
self.passwd, wsdl_file,
self.cache_location,
self.cache_duration,
self.encrypt,
self.daemon,
no_cache=self.no_cache, portType=portType, dt_diff=self.dt_diff)
# No template, create new service from wsdl document.
# A little time-comsuming
else:
service = ONVIFService(xaddr, self.user, self.passwd,
wsdl_file, self.cache_location,
self.cache_duration, self.encrypt,
self.daemon, no_cache=self.no_cache, portType=portType, dt_diff=self.dt_diff)
self.services[name] = service
setattr(self, name, service)
if not self.services_template.get(name):
self.services_template[name] = service
return service | python | def create_onvif_service(self, name, from_template=True, portType=None):
'''Create ONVIF service client'''
name = name.lower()
xaddr, wsdl_file = self.get_definition(name)
with self.services_lock:
svt = self.services_template.get(name)
# Has a template, clone from it. Faster.
if svt and from_template and self.use_services_template.get(name):
service = ONVIFService.clone(svt, xaddr, self.user,
self.passwd, wsdl_file,
self.cache_location,
self.cache_duration,
self.encrypt,
self.daemon,
no_cache=self.no_cache, portType=portType, dt_diff=self.dt_diff)
# No template, create new service from wsdl document.
# A little time-comsuming
else:
service = ONVIFService(xaddr, self.user, self.passwd,
wsdl_file, self.cache_location,
self.cache_duration, self.encrypt,
self.daemon, no_cache=self.no_cache, portType=portType, dt_diff=self.dt_diff)
self.services[name] = service
setattr(self, name, service)
if not self.services_template.get(name):
self.services_template[name] = service
return service | [
"def",
"create_onvif_service",
"(",
"self",
",",
"name",
",",
"from_template",
"=",
"True",
",",
"portType",
"=",
"None",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"xaddr",
",",
"wsdl_file",
"=",
"self",
".",
"get_definition",
"(",
"name",
... | Create ONVIF service client | [
"Create",
"ONVIF",
"service",
"client"
] | daf3ac87d998d5dc61c40cee130ce3fed93111aa | https://github.com/quatanium/python-onvif/blob/daf3ac87d998d5dc61c40cee130ce3fed93111aa/onvif/client.py#L360-L391 |
229,425 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.build_rectangle_dict | def build_rectangle_dict(self,
north,
west,
south,
east,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=.3,
):
""" Set a dictionary with the javascript class Rectangle parameters
This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish so.
Args:
north (float): The north latitude bound
west (float): The west longitude bound
south (float): The south latitude bound
east (float): The east longitude bound
stroke_color (str): Sets the color of the rectangle border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the rectangle fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the rectangle fill
"""
rectangle = {
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
'fill_color': fill_color,
'fill_opacity': fill_opacity,
'bounds': {'north': north,
'west': west,
'south': south,
'east': east,
}
}
return rectangle | python | def build_rectangle_dict(self,
north,
west,
south,
east,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=.3,
):
rectangle = {
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
'fill_color': fill_color,
'fill_opacity': fill_opacity,
'bounds': {'north': north,
'west': west,
'south': south,
'east': east,
}
}
return rectangle | [
"def",
"build_rectangle_dict",
"(",
"self",
",",
"north",
",",
"west",
",",
"south",
",",
"east",
",",
"stroke_color",
"=",
"'#FF0000'",
",",
"stroke_opacity",
"=",
".8",
",",
"stroke_weight",
"=",
"2",
",",
"fill_color",
"=",
"'#FF0000'",
",",
"fill_opacity... | Set a dictionary with the javascript class Rectangle parameters
This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish so.
Args:
north (float): The north latitude bound
west (float): The west longitude bound
south (float): The south latitude bound
east (float): The east longitude bound
stroke_color (str): Sets the color of the rectangle border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the rectangle fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the rectangle fill | [
"Set",
"a",
"dictionary",
"with",
"the",
"javascript",
"class",
"Rectangle",
"parameters"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L192-L236 |
229,426 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.add_rectangle | def add_rectangle(self,
north=None,
west=None,
south=None,
east=None,
**kwargs):
""" Adds a rectangle dict to the Map.rectangles attribute
The Google Maps API describes a rectangle using the LatLngBounds
object, which defines the bounds to be drawn. The bounds use the
concept of 2 delimiting points, a northwest and a southeast points,
were each coordinate is defined by each parameter.
It accepts a rectangle dict representation as well.
Args:
north (float): The north latitude
west (float): The west longitude
south (float): The south latitude
east (float): The east longitude
.. _LatLngBoundsLiteral:
https://developers.google.com/maps/documen
tation/javascript/reference#LatLngBoundsLiteral
.. _Rectangles:
https://developers.google.com/maps/documen
tation/javascript/shapes#rectangles
"""
kwargs.setdefault('bounds', {})
if north:
kwargs['bounds']['north'] = north
if west:
kwargs['bounds']['west'] = west
if south:
kwargs['bounds']['south'] = south
if east:
kwargs['bounds']['east'] = east
if set(
('north', 'east', 'south', 'west')
) != set(kwargs['bounds'].keys()):
raise AttributeError('rectangle bounds required to rectangles')
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
kwargs.setdefault('fill_color', '#FF0000')
kwargs.setdefault('fill_opacity', .3)
self.rectangles.append(kwargs) | python | def add_rectangle(self,
north=None,
west=None,
south=None,
east=None,
**kwargs):
kwargs.setdefault('bounds', {})
if north:
kwargs['bounds']['north'] = north
if west:
kwargs['bounds']['west'] = west
if south:
kwargs['bounds']['south'] = south
if east:
kwargs['bounds']['east'] = east
if set(
('north', 'east', 'south', 'west')
) != set(kwargs['bounds'].keys()):
raise AttributeError('rectangle bounds required to rectangles')
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
kwargs.setdefault('fill_color', '#FF0000')
kwargs.setdefault('fill_opacity', .3)
self.rectangles.append(kwargs) | [
"def",
"add_rectangle",
"(",
"self",
",",
"north",
"=",
"None",
",",
"west",
"=",
"None",
",",
"south",
"=",
"None",
",",
"east",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'bounds'",
",",
"{",
"}",
")",
"i... | Adds a rectangle dict to the Map.rectangles attribute
The Google Maps API describes a rectangle using the LatLngBounds
object, which defines the bounds to be drawn. The bounds use the
concept of 2 delimiting points, a northwest and a southeast points,
were each coordinate is defined by each parameter.
It accepts a rectangle dict representation as well.
Args:
north (float): The north latitude
west (float): The west longitude
south (float): The south latitude
east (float): The east longitude
.. _LatLngBoundsLiteral:
https://developers.google.com/maps/documen
tation/javascript/reference#LatLngBoundsLiteral
.. _Rectangles:
https://developers.google.com/maps/documen
tation/javascript/shapes#rectangles | [
"Adds",
"a",
"rectangle",
"dict",
"to",
"the",
"Map",
".",
"rectangles",
"attribute"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L238-L289 |
229,427 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.build_circle_dict | def build_circle_dict(self,
center_lat,
center_lng,
radius,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=.3,
):
""" Set a dictionary with the javascript class Circle parameters
This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish so.
Args:
center_lat (float): The circle center latitude
center_lng (float): The circle center longitude
radius (float): The circle radius, in meters
stroke_color (str): Sets the color of the rectangle border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the circle fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the circle fill
"""
circle = {
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
'fill_color': fill_color,
'fill_opacity': fill_opacity,
'center': {'lat': center_lat,
'lng': center_lng},
'radius': radius,
}
return circle | python | def build_circle_dict(self,
center_lat,
center_lng,
radius,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=.3,
):
circle = {
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
'fill_color': fill_color,
'fill_opacity': fill_opacity,
'center': {'lat': center_lat,
'lng': center_lng},
'radius': radius,
}
return circle | [
"def",
"build_circle_dict",
"(",
"self",
",",
"center_lat",
",",
"center_lng",
",",
"radius",
",",
"stroke_color",
"=",
"'#FF0000'",
",",
"stroke_opacity",
"=",
".8",
",",
"stroke_weight",
"=",
"2",
",",
"fill_color",
"=",
"'#FF0000'",
",",
"fill_opacity",
"="... | Set a dictionary with the javascript class Circle parameters
This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish so.
Args:
center_lat (float): The circle center latitude
center_lng (float): The circle center longitude
radius (float): The circle radius, in meters
stroke_color (str): Sets the color of the rectangle border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the circle fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the circle fill | [
"Set",
"a",
"dictionary",
"with",
"the",
"javascript",
"class",
"Circle",
"parameters"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L333-L374 |
229,428 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.add_circle | def add_circle(self,
center_lat=None,
center_lng=None,
radius=None,
**kwargs):
""" Adds a circle dict to the Map.circles attribute
The circle in a sphere is called "spherical cap" and is defined in the
Google Maps API by at least the center coordinates and its radius, in
meters. A circle has color and opacity both for the border line and the
inside area.
It accepts a circle dict representation as well.
Args:
center_lat (float): The circle center latitude
center_lng (float): The circle center longitude
radius (float): The circle radius, in meters
.. _Circle:
https://developers.google.com/maps/documen
tation/javascript/reference#Circle
"""
kwargs.setdefault('center', {})
if center_lat:
kwargs['center']['lat'] = center_lat
if center_lng:
kwargs['center']['lng'] = center_lng
if radius:
kwargs['radius'] = radius
if set(('lat', 'lng')) != set(kwargs['center'].keys()):
raise AttributeError('circle center coordinates required')
if 'radius' not in kwargs:
raise AttributeError('circle radius definition required')
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
kwargs.setdefault('fill_color', '#FF0000')
kwargs.setdefault('fill_opacity', .3)
self.circles.append(kwargs) | python | def add_circle(self,
center_lat=None,
center_lng=None,
radius=None,
**kwargs):
kwargs.setdefault('center', {})
if center_lat:
kwargs['center']['lat'] = center_lat
if center_lng:
kwargs['center']['lng'] = center_lng
if radius:
kwargs['radius'] = radius
if set(('lat', 'lng')) != set(kwargs['center'].keys()):
raise AttributeError('circle center coordinates required')
if 'radius' not in kwargs:
raise AttributeError('circle radius definition required')
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
kwargs.setdefault('fill_color', '#FF0000')
kwargs.setdefault('fill_opacity', .3)
self.circles.append(kwargs) | [
"def",
"add_circle",
"(",
"self",
",",
"center_lat",
"=",
"None",
",",
"center_lng",
"=",
"None",
",",
"radius",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'center'",
",",
"{",
"}",
")",
"if",
"center_lat",
":"... | Adds a circle dict to the Map.circles attribute
The circle in a sphere is called "spherical cap" and is defined in the
Google Maps API by at least the center coordinates and its radius, in
meters. A circle has color and opacity both for the border line and the
inside area.
It accepts a circle dict representation as well.
Args:
center_lat (float): The circle center latitude
center_lng (float): The circle center longitude
radius (float): The circle radius, in meters
.. _Circle:
https://developers.google.com/maps/documen
tation/javascript/reference#Circle | [
"Adds",
"a",
"circle",
"dict",
"to",
"the",
"Map",
".",
"circles",
"attribute"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L376-L419 |
229,429 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.build_polylines | def build_polylines(self, polylines):
""" Process data to construct polylines
This method is built from the assumption that the polylines parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,lng], [lat, lng], (lat, lng), ...
tuple of lists or tuples : a tuple of path points, each one
indicating the point coordinates -- (lat,lng), [lat, lng],
(lat, lng), ...
dicts: a dictionary with polylines attributes
So, for instance, we have this general scenario as a input parameter:
polyline = {
'stroke_color': '#0AB0DE',
'stroke_opacity': 1.0,
'stroke_weight': 3,
'path': [{'lat': 33.678, 'lng': -116.243},
{'lat': 33.679, 'lng': -116.244},
{'lat': 33.680, 'lng': -116.250},
{'lat': 33.681, 'lng': -116.239},
{'lat': 33.678, 'lng': -116.243}]
}
path1 = [(33.665, -116.235), (33.666, -116.256),
(33.667, -116.250), (33.668, -116.229)]
path2 = ((33.659, -116.243), (33.660, -116.244),
(33.649, -116.250), (33.644, -116.239))
path3 = ([33.688, -116.243], [33.680, -116.244],
[33.682, -116.250], [33.690, -116.239])
path4 = [[33.690, -116.243], [33.691, -116.244],
[33.692, -116.250], [33.693, -116.239]]
polylines = [polyline, path1, path2, path3, path4]
"""
if not polylines:
return
if not isinstance(polylines, (list, tuple)):
raise AttributeError('A list or tuple of polylines is required')
for points in polylines:
if isinstance(points, dict):
self.add_polyline(**points)
elif isinstance(points, (tuple, list)):
path = []
for coords in points:
if len(coords) != 2:
raise AttributeError('A point needs two coordinates')
path.append({'lat': coords[0],
'lng': coords[1]})
polyline_dict = self.build_polyline_dict(path)
self.add_polyline(**polyline_dict) | python | def build_polylines(self, polylines):
if not polylines:
return
if not isinstance(polylines, (list, tuple)):
raise AttributeError('A list or tuple of polylines is required')
for points in polylines:
if isinstance(points, dict):
self.add_polyline(**points)
elif isinstance(points, (tuple, list)):
path = []
for coords in points:
if len(coords) != 2:
raise AttributeError('A point needs two coordinates')
path.append({'lat': coords[0],
'lng': coords[1]})
polyline_dict = self.build_polyline_dict(path)
self.add_polyline(**polyline_dict) | [
"def",
"build_polylines",
"(",
"self",
",",
"polylines",
")",
":",
"if",
"not",
"polylines",
":",
"return",
"if",
"not",
"isinstance",
"(",
"polylines",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"AttributeError",
"(",
"'A list or tuple of polyl... | Process data to construct polylines
This method is built from the assumption that the polylines parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,lng], [lat, lng], (lat, lng), ...
tuple of lists or tuples : a tuple of path points, each one
indicating the point coordinates -- (lat,lng), [lat, lng],
(lat, lng), ...
dicts: a dictionary with polylines attributes
So, for instance, we have this general scenario as a input parameter:
polyline = {
'stroke_color': '#0AB0DE',
'stroke_opacity': 1.0,
'stroke_weight': 3,
'path': [{'lat': 33.678, 'lng': -116.243},
{'lat': 33.679, 'lng': -116.244},
{'lat': 33.680, 'lng': -116.250},
{'lat': 33.681, 'lng': -116.239},
{'lat': 33.678, 'lng': -116.243}]
}
path1 = [(33.665, -116.235), (33.666, -116.256),
(33.667, -116.250), (33.668, -116.229)]
path2 = ((33.659, -116.243), (33.660, -116.244),
(33.649, -116.250), (33.644, -116.239))
path3 = ([33.688, -116.243], [33.680, -116.244],
[33.682, -116.250], [33.690, -116.239])
path4 = [[33.690, -116.243], [33.691, -116.244],
[33.692, -116.250], [33.693, -116.239]]
polylines = [polyline, path1, path2, path3, path4] | [
"Process",
"data",
"to",
"construct",
"polylines"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L421-L481 |
229,430 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.build_polyline_dict | def build_polyline_dict(self,
path,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2):
""" Set a dictionary with the javascript class Polyline parameters
This function sets a default drawing configuration if the user just
pass the polyline path, but also allows to set each parameter
individually if the user wish so.
Args:
path (list): A list of latitude and longitude point for the
polyline stroke_color (str): Sets the color of the rectangle
border using hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
"""
if not isinstance(path, list):
raise AttributeError('To build a map path a list of dictionaries'
' of latitude and logitudes is required')
polyline = {
'path': path,
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
}
return polyline | python | def build_polyline_dict(self,
path,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2):
if not isinstance(path, list):
raise AttributeError('To build a map path a list of dictionaries'
' of latitude and logitudes is required')
polyline = {
'path': path,
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
}
return polyline | [
"def",
"build_polyline_dict",
"(",
"self",
",",
"path",
",",
"stroke_color",
"=",
"'#FF0000'",
",",
"stroke_opacity",
"=",
".8",
",",
"stroke_weight",
"=",
"2",
")",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"list",
")",
":",
"raise",
"AttributeErr... | Set a dictionary with the javascript class Polyline parameters
This function sets a default drawing configuration if the user just
pass the polyline path, but also allows to set each parameter
individually if the user wish so.
Args:
path (list): A list of latitude and longitude point for the
polyline stroke_color (str): Sets the color of the rectangle
border using hexadecimal color notation
stroke_opacity (float): Sets the opacity of the rectangle border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels. | [
"Set",
"a",
"dictionary",
"with",
"the",
"javascript",
"class",
"Polyline",
"parameters"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L483-L514 |
229,431 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.add_polyline | def add_polyline(self, path=None, **kwargs):
""" Adds a polyline dict to the Map.polylines attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map". The linear paths are defined
by a list of Latitude and Longitude coordinate pairs, like so:
{ 'lat': y, 'lng': x }
with each one being a point of the polyline path.
It accepts a polyline dict representation as well.
Args:
path (list(dict)): The set of points of the path
.. _Polyline:
https://developers.google.com/maps/documen
tation/javascript/reference#Polyline
"""
if path:
if not isinstance(path, list):
raise AttributeError('The path is a list of dictionary of'
'latitude and longitudes por path points')
for i, point in enumerate(path):
if not isinstance(point, dict):
if isinstance(point, (list, tuple)) and len(point) == 2:
path[i] = {'lat': point[0], 'lng': point[1]}
else:
raise AttributeError(
'All points in the path must be dicts'
' of latitudes and longitudes, list or tuple'
)
kwargs['path'] = path
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
self.polylines.append(kwargs) | python | def add_polyline(self, path=None, **kwargs):
if path:
if not isinstance(path, list):
raise AttributeError('The path is a list of dictionary of'
'latitude and longitudes por path points')
for i, point in enumerate(path):
if not isinstance(point, dict):
if isinstance(point, (list, tuple)) and len(point) == 2:
path[i] = {'lat': point[0], 'lng': point[1]}
else:
raise AttributeError(
'All points in the path must be dicts'
' of latitudes and longitudes, list or tuple'
)
kwargs['path'] = path
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
self.polylines.append(kwargs) | [
"def",
"add_polyline",
"(",
"self",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"list",
")",
":",
"raise",
"AttributeError",
"(",
"'The path is a list of dictionary of'",
"'la... | Adds a polyline dict to the Map.polylines attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map". The linear paths are defined
by a list of Latitude and Longitude coordinate pairs, like so:
{ 'lat': y, 'lng': x }
with each one being a point of the polyline path.
It accepts a polyline dict representation as well.
Args:
path (list(dict)): The set of points of the path
.. _Polyline:
https://developers.google.com/maps/documen
tation/javascript/reference#Polyline | [
"Adds",
"a",
"polyline",
"dict",
"to",
"the",
"Map",
".",
"polylines",
"attribute"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L516-L556 |
229,432 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.build_polygons | def build_polygons(self, polygons):
""" Process data to construct polygons
This method is built from the assumption that the polygons parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,lng], [lat, lng], (lat, lng), ...
tuple of lists or tuples : a tuple of path points, each one
indicating the point coordinates -- (lat,lng), [lat, lng],
(lat, lng), ...
dicts: a dictionary with polylines attributes
So, for instance, we have this general scenario as a input parameter:
polygon = {
'stroke_color': '#0AB0DE',
'stroke_opacity': 1.0,
'stroke_weight': 3,
'fill_color': '#FFABCD',
'fill_opacity': 0.5,
'path': [{'lat': 33.678, 'lng': -116.243},
{'lat': 33.679, 'lng': -116.244},
{'lat': 33.680, 'lng': -116.250},
{'lat': 33.681, 'lng': -116.239},
{'lat': 33.678, 'lng': -116.243}]
}
path1 = [(33.665, -116.235), (33.666, -116.256),
(33.667, -116.250), (33.668, -116.229)]
path2 = ((33.659, -116.243), (33.660, -116.244),
(33.649, -116.250), (33.644, -116.239))
path3 = ([33.688, -116.243], [33.680, -116.244],
[33.682, -116.250], [33.690, -116.239])
path4 = [[33.690, -116.243], [33.691, -116.244],
[33.692, -116.250], [33.693, -116.239]]
polygons = [polygon, path1, path2, path3, path4]
"""
if not polygons:
return
if not isinstance(polygons, (list, tuple)):
raise AttributeError('A list or tuple of polylines is required')
for points in polygons:
if isinstance(points, dict):
self.add_polygon(**points)
elif isinstance(points, (tuple, list)):
path = []
for coords in points:
if len(coords) != 2:
raise AttributeError('A point needs two coordinates')
path.append({'lat': coords[0],
'lng': coords[1]})
polygon_dict = self.build_polygon_dict(path)
self.add_polygon(**polygon_dict) | python | def build_polygons(self, polygons):
if not polygons:
return
if not isinstance(polygons, (list, tuple)):
raise AttributeError('A list or tuple of polylines is required')
for points in polygons:
if isinstance(points, dict):
self.add_polygon(**points)
elif isinstance(points, (tuple, list)):
path = []
for coords in points:
if len(coords) != 2:
raise AttributeError('A point needs two coordinates')
path.append({'lat': coords[0],
'lng': coords[1]})
polygon_dict = self.build_polygon_dict(path)
self.add_polygon(**polygon_dict) | [
"def",
"build_polygons",
"(",
"self",
",",
"polygons",
")",
":",
"if",
"not",
"polygons",
":",
"return",
"if",
"not",
"isinstance",
"(",
"polygons",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"AttributeError",
"(",
"'A list or tuple of polylines... | Process data to construct polygons
This method is built from the assumption that the polygons parameter
is a list of:
list of lists or tuples : a list of path points, each one
indicating the point coordinates --
[lat,lng], [lat, lng], (lat, lng), ...
tuple of lists or tuples : a tuple of path points, each one
indicating the point coordinates -- (lat,lng), [lat, lng],
(lat, lng), ...
dicts: a dictionary with polylines attributes
So, for instance, we have this general scenario as a input parameter:
polygon = {
'stroke_color': '#0AB0DE',
'stroke_opacity': 1.0,
'stroke_weight': 3,
'fill_color': '#FFABCD',
'fill_opacity': 0.5,
'path': [{'lat': 33.678, 'lng': -116.243},
{'lat': 33.679, 'lng': -116.244},
{'lat': 33.680, 'lng': -116.250},
{'lat': 33.681, 'lng': -116.239},
{'lat': 33.678, 'lng': -116.243}]
}
path1 = [(33.665, -116.235), (33.666, -116.256),
(33.667, -116.250), (33.668, -116.229)]
path2 = ((33.659, -116.243), (33.660, -116.244),
(33.649, -116.250), (33.644, -116.239))
path3 = ([33.688, -116.243], [33.680, -116.244],
[33.682, -116.250], [33.690, -116.239])
path4 = [[33.690, -116.243], [33.691, -116.244],
[33.692, -116.250], [33.693, -116.239]]
polygons = [polygon, path1, path2, path3, path4] | [
"Process",
"data",
"to",
"construct",
"polygons"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L558-L620 |
229,433 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.build_polygon_dict | def build_polygon_dict(self,
path,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=0.3):
""" Set a dictionary with the javascript class Polygon parameters
This function sets a default drawing configuration if the user just
pass the polygon path, but also allows to set each parameter
individually if the user wish so.
Args:
path (list): A list of latitude and longitude point for the polygon
stroke_color (str): Sets the color of the polygon border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the polygon border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the polygon fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the polygon fill
"""
if not isinstance(path, list):
raise AttributeError('To build a map path a list of dictionaries'
' of latitude and logitudes is required')
polygon = {
'path': path,
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
'fill_color': fill_color,
'fill_opacity': fill_opacity
}
return polygon | python | def build_polygon_dict(self,
path,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
fill_color='#FF0000',
fill_opacity=0.3):
if not isinstance(path, list):
raise AttributeError('To build a map path a list of dictionaries'
' of latitude and logitudes is required')
polygon = {
'path': path,
'stroke_color': stroke_color,
'stroke_opacity': stroke_opacity,
'stroke_weight': stroke_weight,
'fill_color': fill_color,
'fill_opacity': fill_opacity
}
return polygon | [
"def",
"build_polygon_dict",
"(",
"self",
",",
"path",
",",
"stroke_color",
"=",
"'#FF0000'",
",",
"stroke_opacity",
"=",
".8",
",",
"stroke_weight",
"=",
"2",
",",
"fill_color",
"=",
"'#FF0000'",
",",
"fill_opacity",
"=",
"0.3",
")",
":",
"if",
"not",
"is... | Set a dictionary with the javascript class Polygon parameters
This function sets a default drawing configuration if the user just
pass the polygon path, but also allows to set each parameter
individually if the user wish so.
Args:
path (list): A list of latitude and longitude point for the polygon
stroke_color (str): Sets the color of the polygon border using
hexadecimal color notation
stroke_opacity (float): Sets the opacity of the polygon border
in percentage. If stroke_opacity = 0, the border is transparent
stroke_weight (int): Sets the stroke girth in pixels.
fill_color (str): Sets the color of the polygon fill using
hexadecimal color notation
fill_opacity (float): Sets the opacity of the polygon fill | [
"Set",
"a",
"dictionary",
"with",
"the",
"javascript",
"class",
"Polygon",
"parameters"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L622-L661 |
229,434 | rochacbruno/Flask-GoogleMaps | flask_googlemaps/__init__.py | Map.add_polygon | def add_polygon(self, path=None, **kwargs):
""" Adds a polygon dict to the Map.polygons attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map" and "form a closed loop and define
a filled region.". The linear paths are defined by a list of Latitude
and Longitude coordinate pairs, like so:
{ 'lat': y, 'lng': x }
with each one being a point of the polyline path.
It accepts a polygon dict representation as well.
Args:
path (list(dict)): The set of points of the path
.. _Polygon:
https://developers.google.com/maps/documen
tation/javascript/reference#Polygon
"""
if path:
if not isinstance(path, list):
raise AttributeError('The path is a list of dictionary of'
'latitude and longitudes por path points')
for i, point in enumerate(path):
if not isinstance(point, dict):
if isinstance(point, (list, tuple)) and len(point) == 2:
path[i] = {'lat': point[0], 'lng': point[1]}
else:
raise AttributeError(
'All points in the path must be dicts'
' of latitudes and longitudes, list or tuple'
)
kwargs['path'] = path
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
kwargs.setdefault('fill_color', '#FF0000')
kwargs.setdefault('fill_opacity', .3)
self.polygons.append(kwargs) | python | def add_polygon(self, path=None, **kwargs):
if path:
if not isinstance(path, list):
raise AttributeError('The path is a list of dictionary of'
'latitude and longitudes por path points')
for i, point in enumerate(path):
if not isinstance(point, dict):
if isinstance(point, (list, tuple)) and len(point) == 2:
path[i] = {'lat': point[0], 'lng': point[1]}
else:
raise AttributeError(
'All points in the path must be dicts'
' of latitudes and longitudes, list or tuple'
)
kwargs['path'] = path
kwargs.setdefault('stroke_color', '#FF0000')
kwargs.setdefault('stroke_opacity', .8)
kwargs.setdefault('stroke_weight', 2)
kwargs.setdefault('fill_color', '#FF0000')
kwargs.setdefault('fill_opacity', .3)
self.polygons.append(kwargs) | [
"def",
"add_polygon",
"(",
"self",
",",
"path",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"path",
":",
"if",
"not",
"isinstance",
"(",
"path",
",",
"list",
")",
":",
"raise",
"AttributeError",
"(",
"'The path is a list of dictionary of'",
"'lat... | Adds a polygon dict to the Map.polygons attribute
The Google Maps API describes a polyline as a "linear overlay of
connected line segments on the map" and "form a closed loop and define
a filled region.". The linear paths are defined by a list of Latitude
and Longitude coordinate pairs, like so:
{ 'lat': y, 'lng': x }
with each one being a point of the polyline path.
It accepts a polygon dict representation as well.
Args:
path (list(dict)): The set of points of the path
.. _Polygon:
https://developers.google.com/maps/documen
tation/javascript/reference#Polygon | [
"Adds",
"a",
"polygon",
"dict",
"to",
"the",
"Map",
".",
"polygons",
"attribute"
] | 8b1c7c50c04219aac3d58ab5af569933e55ad464 | https://github.com/rochacbruno/Flask-GoogleMaps/blob/8b1c7c50c04219aac3d58ab5af569933e55ad464/flask_googlemaps/__init__.py#L663-L706 |
229,435 | lepture/captcha | captcha/image.py | _Captcha.generate | def generate(self, chars, format='png'):
"""Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format
"""
im = self.generate_image(chars)
out = BytesIO()
im.save(out, format=format)
out.seek(0)
return out | python | def generate(self, chars, format='png'):
im = self.generate_image(chars)
out = BytesIO()
im.save(out, format=format)
out.seek(0)
return out | [
"def",
"generate",
"(",
"self",
",",
"chars",
",",
"format",
"=",
"'png'",
")",
":",
"im",
"=",
"self",
".",
"generate_image",
"(",
"chars",
")",
"out",
"=",
"BytesIO",
"(",
")",
"im",
".",
"save",
"(",
"out",
",",
"format",
"=",
"format",
")",
"... | Generate an Image Captcha of the given characters.
:param chars: text to be generated.
:param format: image file format | [
"Generate",
"an",
"Image",
"Captcha",
"of",
"the",
"given",
"characters",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/image.py#L39-L49 |
229,436 | lepture/captcha | captcha/image.py | _Captcha.write | def write(self, chars, output, format='png'):
"""Generate and write an image CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destination.
:param format: image file format
"""
im = self.generate_image(chars)
return im.save(output, format=format) | python | def write(self, chars, output, format='png'):
im = self.generate_image(chars)
return im.save(output, format=format) | [
"def",
"write",
"(",
"self",
",",
"chars",
",",
"output",
",",
"format",
"=",
"'png'",
")",
":",
"im",
"=",
"self",
".",
"generate_image",
"(",
"chars",
")",
"return",
"im",
".",
"save",
"(",
"output",
",",
"format",
"=",
"format",
")"
] | Generate and write an image CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destination.
:param format: image file format | [
"Generate",
"and",
"write",
"an",
"image",
"CAPTCHA",
"data",
"to",
"the",
"output",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/image.py#L51-L59 |
229,437 | lepture/captcha | captcha/image.py | ImageCaptcha.generate_image | def generate_image(self, chars):
"""Generate the image of the given characters.
:param chars: text to be generated.
"""
background = random_color(238, 255)
color = random_color(10, 200, random.randint(220, 255))
im = self.create_captcha_image(chars, color, background)
self.create_noise_dots(im, color)
self.create_noise_curve(im, color)
im = im.filter(ImageFilter.SMOOTH)
return im | python | def generate_image(self, chars):
background = random_color(238, 255)
color = random_color(10, 200, random.randint(220, 255))
im = self.create_captcha_image(chars, color, background)
self.create_noise_dots(im, color)
self.create_noise_curve(im, color)
im = im.filter(ImageFilter.SMOOTH)
return im | [
"def",
"generate_image",
"(",
"self",
",",
"chars",
")",
":",
"background",
"=",
"random_color",
"(",
"238",
",",
"255",
")",
"color",
"=",
"random_color",
"(",
"10",
",",
"200",
",",
"random",
".",
"randint",
"(",
"220",
",",
"255",
")",
")",
"im",
... | Generate the image of the given characters.
:param chars: text to be generated. | [
"Generate",
"the",
"image",
"of",
"the",
"given",
"characters",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/image.py#L221-L232 |
229,438 | lepture/captcha | captcha/audio.py | change_speed | def change_speed(body, speed=1):
"""Change the voice speed of the wave body."""
if speed == 1:
return body
length = int(len(body) * speed)
rv = bytearray(length)
step = 0
for v in body:
i = int(step)
while i < int(step + speed) and i < length:
rv[i] = v
i += 1
step += speed
return rv | python | def change_speed(body, speed=1):
if speed == 1:
return body
length = int(len(body) * speed)
rv = bytearray(length)
step = 0
for v in body:
i = int(step)
while i < int(step + speed) and i < length:
rv[i] = v
i += 1
step += speed
return rv | [
"def",
"change_speed",
"(",
"body",
",",
"speed",
"=",
"1",
")",
":",
"if",
"speed",
"==",
"1",
":",
"return",
"body",
"length",
"=",
"int",
"(",
"len",
"(",
"body",
")",
"*",
"speed",
")",
"rv",
"=",
"bytearray",
"(",
"length",
")",
"step",
"=",... | Change the voice speed of the wave body. | [
"Change",
"the",
"voice",
"speed",
"of",
"the",
"wave",
"body",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L42-L57 |
229,439 | lepture/captcha | captcha/audio.py | patch_wave_header | def patch_wave_header(body):
"""Patch header to the given wave body.
:param body: the wave content body, it should be bytearray.
"""
length = len(body)
padded = length + length % 2
total = WAVE_HEADER_LENGTH + padded
header = copy.copy(WAVE_HEADER)
# fill the total length position
header[4:8] = bytearray(struct.pack('<I', total))
header += bytearray(struct.pack('<I', length))
data = header + body
# the total length is even
if length != padded:
data = data + bytearray([0])
return data | python | def patch_wave_header(body):
length = len(body)
padded = length + length % 2
total = WAVE_HEADER_LENGTH + padded
header = copy.copy(WAVE_HEADER)
# fill the total length position
header[4:8] = bytearray(struct.pack('<I', total))
header += bytearray(struct.pack('<I', length))
data = header + body
# the total length is even
if length != padded:
data = data + bytearray([0])
return data | [
"def",
"patch_wave_header",
"(",
"body",
")",
":",
"length",
"=",
"len",
"(",
"body",
")",
"padded",
"=",
"length",
"+",
"length",
"%",
"2",
"total",
"=",
"WAVE_HEADER_LENGTH",
"+",
"padded",
"header",
"=",
"copy",
".",
"copy",
"(",
"WAVE_HEADER",
")",
... | Patch header to the given wave body.
:param body: the wave content body, it should be bytearray. | [
"Patch",
"header",
"to",
"the",
"given",
"wave",
"body",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L60-L81 |
229,440 | lepture/captcha | captcha/audio.py | create_noise | def create_noise(length, level=4):
"""Create white noise for background"""
noise = bytearray(length)
adjust = 128 - int(level / 2)
i = 0
while i < length:
v = random.randint(0, 256)
noise[i] = v % level + adjust
i += 1
return noise | python | def create_noise(length, level=4):
noise = bytearray(length)
adjust = 128 - int(level / 2)
i = 0
while i < length:
v = random.randint(0, 256)
noise[i] = v % level + adjust
i += 1
return noise | [
"def",
"create_noise",
"(",
"length",
",",
"level",
"=",
"4",
")",
":",
"noise",
"=",
"bytearray",
"(",
"length",
")",
"adjust",
"=",
"128",
"-",
"int",
"(",
"level",
"/",
"2",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"length",
":",
"v",
"=",
"ra... | Create white noise for background | [
"Create",
"white",
"noise",
"for",
"background"
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L84-L93 |
229,441 | lepture/captcha | captcha/audio.py | create_silence | def create_silence(length):
"""Create a piece of silence."""
data = bytearray(length)
i = 0
while i < length:
data[i] = 128
i += 1
return data | python | def create_silence(length):
data = bytearray(length)
i = 0
while i < length:
data[i] = 128
i += 1
return data | [
"def",
"create_silence",
"(",
"length",
")",
":",
"data",
"=",
"bytearray",
"(",
"length",
")",
"i",
"=",
"0",
"while",
"i",
"<",
"length",
":",
"data",
"[",
"i",
"]",
"=",
"128",
"i",
"+=",
"1",
"return",
"data"
] | Create a piece of silence. | [
"Create",
"a",
"piece",
"of",
"silence",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L96-L103 |
229,442 | lepture/captcha | captcha/audio.py | mix_wave | def mix_wave(src, dst):
"""Mix two wave body into one."""
if len(src) > len(dst):
# output should be longer
dst, src = src, dst
for i, sv in enumerate(src):
dv = dst[i]
if sv < 128 and dv < 128:
dst[i] = int(sv * dv / 128)
else:
dst[i] = int(2 * (sv + dv) - sv * dv / 128 - 256)
return dst | python | def mix_wave(src, dst):
if len(src) > len(dst):
# output should be longer
dst, src = src, dst
for i, sv in enumerate(src):
dv = dst[i]
if sv < 128 and dv < 128:
dst[i] = int(sv * dv / 128)
else:
dst[i] = int(2 * (sv + dv) - sv * dv / 128 - 256)
return dst | [
"def",
"mix_wave",
"(",
"src",
",",
"dst",
")",
":",
"if",
"len",
"(",
"src",
")",
">",
"len",
"(",
"dst",
")",
":",
"# output should be longer",
"dst",
",",
"src",
"=",
"src",
",",
"dst",
"for",
"i",
",",
"sv",
"in",
"enumerate",
"(",
"src",
")"... | Mix two wave body into one. | [
"Mix",
"two",
"wave",
"body",
"into",
"one",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L124-L136 |
229,443 | lepture/captcha | captcha/audio.py | AudioCaptcha.choices | def choices(self):
"""Available choices for characters to be generated."""
if self._choices:
return self._choices
for n in os.listdir(self._voicedir):
if len(n) == 1 and os.path.isdir(os.path.join(self._voicedir, n)):
self._choices.append(n)
return self._choices | python | def choices(self):
if self._choices:
return self._choices
for n in os.listdir(self._voicedir):
if len(n) == 1 and os.path.isdir(os.path.join(self._voicedir, n)):
self._choices.append(n)
return self._choices | [
"def",
"choices",
"(",
"self",
")",
":",
"if",
"self",
".",
"_choices",
":",
"return",
"self",
".",
"_choices",
"for",
"n",
"in",
"os",
".",
"listdir",
"(",
"self",
".",
"_voicedir",
")",
":",
"if",
"len",
"(",
"n",
")",
"==",
"1",
"and",
"os",
... | Available choices for characters to be generated. | [
"Available",
"choices",
"for",
"characters",
"to",
"be",
"generated",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L178-L185 |
229,444 | lepture/captcha | captcha/audio.py | AudioCaptcha.generate | def generate(self, chars):
"""Generate audio CAPTCHA data. The return data is a bytearray.
:param chars: text to be generated.
"""
if not self._cache:
self.load()
body = self.create_wave_body(chars)
return patch_wave_header(body) | python | def generate(self, chars):
if not self._cache:
self.load()
body = self.create_wave_body(chars)
return patch_wave_header(body) | [
"def",
"generate",
"(",
"self",
",",
"chars",
")",
":",
"if",
"not",
"self",
".",
"_cache",
":",
"self",
".",
"load",
"(",
")",
"body",
"=",
"self",
".",
"create_wave_body",
"(",
"chars",
")",
"return",
"patch_wave_header",
"(",
"body",
")"
] | Generate audio CAPTCHA data. The return data is a bytearray.
:param chars: text to be generated. | [
"Generate",
"audio",
"CAPTCHA",
"data",
".",
"The",
"return",
"data",
"is",
"a",
"bytearray",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L264-L272 |
229,445 | lepture/captcha | captcha/audio.py | AudioCaptcha.write | def write(self, chars, output):
"""Generate and write audio CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destionation.
"""
data = self.generate(chars)
with open(output, 'wb') as f:
return f.write(data) | python | def write(self, chars, output):
data = self.generate(chars)
with open(output, 'wb') as f:
return f.write(data) | [
"def",
"write",
"(",
"self",
",",
"chars",
",",
"output",
")",
":",
"data",
"=",
"self",
".",
"generate",
"(",
"chars",
")",
"with",
"open",
"(",
"output",
",",
"'wb'",
")",
"as",
"f",
":",
"return",
"f",
".",
"write",
"(",
"data",
")"
] | Generate and write audio CAPTCHA data to the output.
:param chars: text to be generated.
:param output: output destionation. | [
"Generate",
"and",
"write",
"audio",
"CAPTCHA",
"data",
"to",
"the",
"output",
"."
] | fb6238e741c7e264eba117b27fa911c25c76c527 | https://github.com/lepture/captcha/blob/fb6238e741c7e264eba117b27fa911c25c76c527/captcha/audio.py#L274-L282 |
229,446 | umap-project/umap | umap/views.py | render_to_json | def render_to_json(templates, context, request):
"""
Generate a JSON HttpResponse with rendered template HTML.
"""
html = render_to_string(
templates,
context=context,
request=request
)
_json = json.dumps({
"html": html
})
return HttpResponse(_json) | python | def render_to_json(templates, context, request):
html = render_to_string(
templates,
context=context,
request=request
)
_json = json.dumps({
"html": html
})
return HttpResponse(_json) | [
"def",
"render_to_json",
"(",
"templates",
",",
"context",
",",
"request",
")",
":",
"html",
"=",
"render_to_string",
"(",
"templates",
",",
"context",
"=",
"context",
",",
"request",
"=",
"request",
")",
"_json",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"... | Generate a JSON HttpResponse with rendered template HTML. | [
"Generate",
"a",
"JSON",
"HttpResponse",
"with",
"rendered",
"template",
"HTML",
"."
] | 0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607 | https://github.com/umap-project/umap/blob/0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607/umap/views.py#L320-L332 |
229,447 | umap-project/umap | umap/views.py | GZipMixin.path | def path(self):
"""
Serve gzip file if client accept it.
Generate or update the gzip file if needed.
"""
path = self._path()
statobj = os.stat(path)
ae = self.request.META.get('HTTP_ACCEPT_ENCODING', '')
if re_accepts_gzip.search(ae) and getattr(settings, 'UMAP_GZIP', True):
gzip_path = "{path}{ext}".format(path=path, ext=self.EXT)
up_to_date = True
if not os.path.exists(gzip_path):
up_to_date = False
else:
gzip_statobj = os.stat(gzip_path)
if statobj.st_mtime > gzip_statobj.st_mtime:
up_to_date = False
if not up_to_date:
gzip_file(path, gzip_path)
path = gzip_path
return path | python | def path(self):
path = self._path()
statobj = os.stat(path)
ae = self.request.META.get('HTTP_ACCEPT_ENCODING', '')
if re_accepts_gzip.search(ae) and getattr(settings, 'UMAP_GZIP', True):
gzip_path = "{path}{ext}".format(path=path, ext=self.EXT)
up_to_date = True
if not os.path.exists(gzip_path):
up_to_date = False
else:
gzip_statobj = os.stat(gzip_path)
if statobj.st_mtime > gzip_statobj.st_mtime:
up_to_date = False
if not up_to_date:
gzip_file(path, gzip_path)
path = gzip_path
return path | [
"def",
"path",
"(",
"self",
")",
":",
"path",
"=",
"self",
".",
"_path",
"(",
")",
"statobj",
"=",
"os",
".",
"stat",
"(",
"path",
")",
"ae",
"=",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_ACCEPT_ENCODING'",
",",
"''",
")",
"if... | Serve gzip file if client accept it.
Generate or update the gzip file if needed. | [
"Serve",
"gzip",
"file",
"if",
"client",
"accept",
"it",
".",
"Generate",
"or",
"update",
"the",
"gzip",
"file",
"if",
"needed",
"."
] | 0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607 | https://github.com/umap-project/umap/blob/0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607/umap/views.py#L697-L717 |
229,448 | umap-project/umap | umap/views.py | DataLayerUpdate.if_match | def if_match(self):
"""Optimistic concurrency control."""
match = True
if_match = self.request.META.get('HTTP_IF_MATCH')
if if_match:
etag = self.etag()
if etag != if_match:
match = False
return match | python | def if_match(self):
match = True
if_match = self.request.META.get('HTTP_IF_MATCH')
if if_match:
etag = self.etag()
if etag != if_match:
match = False
return match | [
"def",
"if_match",
"(",
"self",
")",
":",
"match",
"=",
"True",
"if_match",
"=",
"self",
".",
"request",
".",
"META",
".",
"get",
"(",
"'HTTP_IF_MATCH'",
")",
"if",
"if_match",
":",
"etag",
"=",
"self",
".",
"etag",
"(",
")",
"if",
"etag",
"!=",
"i... | Optimistic concurrency control. | [
"Optimistic",
"concurrency",
"control",
"."
] | 0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607 | https://github.com/umap-project/umap/blob/0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607/umap/views.py#L782-L790 |
229,449 | umap-project/umap | umap/decorators.py | map_permissions_check | def map_permissions_check(view_func):
"""
Used for URLs dealing with the map.
"""
@wraps(view_func)
def wrapper(request, *args, **kwargs):
map_inst = get_object_or_404(Map, pk=kwargs['map_id'])
user = request.user
kwargs['map_inst'] = map_inst # Avoid rerequesting the map in the view
if map_inst.edit_status >= map_inst.EDITORS:
can_edit = map_inst.can_edit(user=user, request=request)
if not can_edit:
if map_inst.owner and not user.is_authenticated:
return simple_json_response(login_required=str(LOGIN_URL))
return HttpResponseForbidden()
return view_func(request, *args, **kwargs)
return wrapper | python | def map_permissions_check(view_func):
@wraps(view_func)
def wrapper(request, *args, **kwargs):
map_inst = get_object_or_404(Map, pk=kwargs['map_id'])
user = request.user
kwargs['map_inst'] = map_inst # Avoid rerequesting the map in the view
if map_inst.edit_status >= map_inst.EDITORS:
can_edit = map_inst.can_edit(user=user, request=request)
if not can_edit:
if map_inst.owner and not user.is_authenticated:
return simple_json_response(login_required=str(LOGIN_URL))
return HttpResponseForbidden()
return view_func(request, *args, **kwargs)
return wrapper | [
"def",
"map_permissions_check",
"(",
"view_func",
")",
":",
"@",
"wraps",
"(",
"view_func",
")",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"map_inst",
"=",
"get_object_or_404",
"(",
"Map",
",",
"pk",
"=",
"k... | Used for URLs dealing with the map. | [
"Used",
"for",
"URLs",
"dealing",
"with",
"the",
"map",
"."
] | 0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607 | https://github.com/umap-project/umap/blob/0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607/umap/decorators.py#L27-L43 |
229,450 | umap-project/umap | umap/utils.py | get_uri_template | def get_uri_template(urlname, args=None, prefix=""):
'''
Utility function to return an URI Template from a named URL in django
Copied from django-digitalpaper.
Restrictions:
- Only supports named urls! i.e. url(... name="toto")
- Only support one namespace level
- Only returns the first URL possibility.
- Supports multiple pattern possibilities (i.e., patterns with
non-capturing parenthesis in them) by trying to find a pattern
whose optional parameters match those you specified (a parameter
is considered optional if it doesn't appear in every pattern possibility)
'''
def _convert(template, args=None):
"""URI template converter"""
if not args:
args = []
paths = template % dict([p, "{%s}" % p] for p in args)
return u'%s/%s' % (prefix, paths)
resolver = get_resolver(None)
parts = urlname.split(':')
if len(parts) > 1 and parts[0] in resolver.namespace_dict:
namespace = parts[0]
urlname = parts[1]
nprefix, resolver = resolver.namespace_dict[namespace]
prefix = prefix + '/' + nprefix.rstrip('/')
possibilities = resolver.reverse_dict.getlist(urlname)
for tmp in possibilities:
possibility, pattern = tmp[:2]
if not args:
# If not args are specified, we only consider the first pattern
# django gives us
result, params = possibility[0]
return _convert(result, params)
else:
# If there are optionnal arguments passed, use them to try to find
# the correct pattern.
# First, we need to build a list with all the arguments
seen_params = []
for result, params in possibility:
seen_params.append(params)
# Then build a set to find the common ones, and use it to build the
# list of all the expected params
common_params = reduce(lambda x, y: set(x) & set(y), seen_params)
expected_params = sorted(common_params.union(args))
# Then loop again over the pattern possibilities and return
# the first one that strictly match expected params
for result, params in possibility:
if sorted(params) == expected_params:
return _convert(result, params)
return None | python | def get_uri_template(urlname, args=None, prefix=""):
'''
Utility function to return an URI Template from a named URL in django
Copied from django-digitalpaper.
Restrictions:
- Only supports named urls! i.e. url(... name="toto")
- Only support one namespace level
- Only returns the first URL possibility.
- Supports multiple pattern possibilities (i.e., patterns with
non-capturing parenthesis in them) by trying to find a pattern
whose optional parameters match those you specified (a parameter
is considered optional if it doesn't appear in every pattern possibility)
'''
def _convert(template, args=None):
"""URI template converter"""
if not args:
args = []
paths = template % dict([p, "{%s}" % p] for p in args)
return u'%s/%s' % (prefix, paths)
resolver = get_resolver(None)
parts = urlname.split(':')
if len(parts) > 1 and parts[0] in resolver.namespace_dict:
namespace = parts[0]
urlname = parts[1]
nprefix, resolver = resolver.namespace_dict[namespace]
prefix = prefix + '/' + nprefix.rstrip('/')
possibilities = resolver.reverse_dict.getlist(urlname)
for tmp in possibilities:
possibility, pattern = tmp[:2]
if not args:
# If not args are specified, we only consider the first pattern
# django gives us
result, params = possibility[0]
return _convert(result, params)
else:
# If there are optionnal arguments passed, use them to try to find
# the correct pattern.
# First, we need to build a list with all the arguments
seen_params = []
for result, params in possibility:
seen_params.append(params)
# Then build a set to find the common ones, and use it to build the
# list of all the expected params
common_params = reduce(lambda x, y: set(x) & set(y), seen_params)
expected_params = sorted(common_params.union(args))
# Then loop again over the pattern possibilities and return
# the first one that strictly match expected params
for result, params in possibility:
if sorted(params) == expected_params:
return _convert(result, params)
return None | [
"def",
"get_uri_template",
"(",
"urlname",
",",
"args",
"=",
"None",
",",
"prefix",
"=",
"\"\"",
")",
":",
"def",
"_convert",
"(",
"template",
",",
"args",
"=",
"None",
")",
":",
"\"\"\"URI template converter\"\"\"",
"if",
"not",
"args",
":",
"args",
"=",
... | Utility function to return an URI Template from a named URL in django
Copied from django-digitalpaper.
Restrictions:
- Only supports named urls! i.e. url(... name="toto")
- Only support one namespace level
- Only returns the first URL possibility.
- Supports multiple pattern possibilities (i.e., patterns with
non-capturing parenthesis in them) by trying to find a pattern
whose optional parameters match those you specified (a parameter
is considered optional if it doesn't appear in every pattern possibility) | [
"Utility",
"function",
"to",
"return",
"an",
"URI",
"Template",
"from",
"a",
"named",
"URL",
"in",
"django",
"Copied",
"from",
"django",
"-",
"digitalpaper",
"."
] | 0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607 | https://github.com/umap-project/umap/blob/0b2f9b5c12fcf67e24b7a674e01a7b7efd3ba607/umap/utils.py#L7-L59 |
229,451 | WhyNotHugo/python-barcode | barcode/writer.py | BaseWriter.calculate_size | def calculate_size(self, modules_per_line, number_of_lines, dpi=300):
"""Calculates the size of the barcode in pixel.
:parameters:
modules_per_line : Integer
Number of modules in one line.
number_of_lines : Integer
Number of lines of the barcode.
dpi : Integer
DPI to calculate.
:returns: Width and height of the barcode in pixel.
:rtype: Tuple
"""
width = 2 * self.quiet_zone + modules_per_line * self.module_width
height = 2.0 + self.module_height * number_of_lines
if self.font_size and self.text:
height += pt2mm(self.font_size) / 2 + self.text_distance
return int(mm2px(width, dpi)), int(mm2px(height, dpi)) | python | def calculate_size(self, modules_per_line, number_of_lines, dpi=300):
width = 2 * self.quiet_zone + modules_per_line * self.module_width
height = 2.0 + self.module_height * number_of_lines
if self.font_size and self.text:
height += pt2mm(self.font_size) / 2 + self.text_distance
return int(mm2px(width, dpi)), int(mm2px(height, dpi)) | [
"def",
"calculate_size",
"(",
"self",
",",
"modules_per_line",
",",
"number_of_lines",
",",
"dpi",
"=",
"300",
")",
":",
"width",
"=",
"2",
"*",
"self",
".",
"quiet_zone",
"+",
"modules_per_line",
"*",
"self",
".",
"module_width",
"height",
"=",
"2.0",
"+"... | Calculates the size of the barcode in pixel.
:parameters:
modules_per_line : Integer
Number of modules in one line.
number_of_lines : Integer
Number of lines of the barcode.
dpi : Integer
DPI to calculate.
:returns: Width and height of the barcode in pixel.
:rtype: Tuple | [
"Calculates",
"the",
"size",
"of",
"the",
"barcode",
"in",
"pixel",
"."
] | 0b237016f32b4d0f3425dab10d52e291070c0558 | https://github.com/WhyNotHugo/python-barcode/blob/0b237016f32b4d0f3425dab10d52e291070c0558/barcode/writer.py#L99-L117 |
229,452 | WhyNotHugo/python-barcode | barcode/writer.py | BaseWriter.render | def render(self, code):
"""Renders the barcode to whatever the inheriting writer provides,
using the registered callbacks.
:parameters:
code : List
List of strings matching the writer spec
(only contain 0 or 1).
"""
if self._callbacks['initialize'] is not None:
self._callbacks['initialize'](code)
ypos = 1.0
for cc, line in enumerate(code):
"""
Pack line to list give better gfx result, otherwise in can
result in aliasing gaps
'11010111' -> [2, -1, 1, -1, 3]
"""
line += ' '
c = 1
mlist = []
for i in range(0, len(line) - 1):
if line[i] == line[i+1]:
c += 1
else:
if line[i] == "1":
mlist.append(c)
else:
mlist.append(-c)
c = 1
# Left quiet zone is x startposition
xpos = self.quiet_zone
bxs = xpos # x start of barcode
for mod in mlist:
if mod < 1:
color = self.background
else:
color = self.foreground
# remove painting for background colored tiles?
self._callbacks['paint_module'](
xpos, ypos, self.module_width * abs(mod), color
)
xpos += self.module_width * abs(mod)
bxe = xpos
# Add right quiet zone to every line, except last line,
# quiet zone already provided with background,
# should it be removed complety?
if (cc + 1) != len(code):
self._callbacks['paint_module'](
xpos, ypos, self.quiet_zone, self.background
)
ypos += self.module_height
if self.text and self._callbacks['paint_text'] is not None:
ypos += self.text_distance
if self.center_text:
# better center position for text
xpos = bxs + ((bxe - bxs) / 2.0)
else:
xpos = bxs
self._callbacks['paint_text'](xpos, ypos)
return self._callbacks['finish']() | python | def render(self, code):
if self._callbacks['initialize'] is not None:
self._callbacks['initialize'](code)
ypos = 1.0
for cc, line in enumerate(code):
"""
Pack line to list give better gfx result, otherwise in can
result in aliasing gaps
'11010111' -> [2, -1, 1, -1, 3]
"""
line += ' '
c = 1
mlist = []
for i in range(0, len(line) - 1):
if line[i] == line[i+1]:
c += 1
else:
if line[i] == "1":
mlist.append(c)
else:
mlist.append(-c)
c = 1
# Left quiet zone is x startposition
xpos = self.quiet_zone
bxs = xpos # x start of barcode
for mod in mlist:
if mod < 1:
color = self.background
else:
color = self.foreground
# remove painting for background colored tiles?
self._callbacks['paint_module'](
xpos, ypos, self.module_width * abs(mod), color
)
xpos += self.module_width * abs(mod)
bxe = xpos
# Add right quiet zone to every line, except last line,
# quiet zone already provided with background,
# should it be removed complety?
if (cc + 1) != len(code):
self._callbacks['paint_module'](
xpos, ypos, self.quiet_zone, self.background
)
ypos += self.module_height
if self.text and self._callbacks['paint_text'] is not None:
ypos += self.text_distance
if self.center_text:
# better center position for text
xpos = bxs + ((bxe - bxs) / 2.0)
else:
xpos = bxs
self._callbacks['paint_text'](xpos, ypos)
return self._callbacks['finish']() | [
"def",
"render",
"(",
"self",
",",
"code",
")",
":",
"if",
"self",
".",
"_callbacks",
"[",
"'initialize'",
"]",
"is",
"not",
"None",
":",
"self",
".",
"_callbacks",
"[",
"'initialize'",
"]",
"(",
"code",
")",
"ypos",
"=",
"1.0",
"for",
"cc",
",",
"... | Renders the barcode to whatever the inheriting writer provides,
using the registered callbacks.
:parameters:
code : List
List of strings matching the writer spec
(only contain 0 or 1). | [
"Renders",
"the",
"barcode",
"to",
"whatever",
"the",
"inheriting",
"writer",
"provides",
"using",
"the",
"registered",
"callbacks",
"."
] | 0b237016f32b4d0f3425dab10d52e291070c0558 | https://github.com/WhyNotHugo/python-barcode/blob/0b237016f32b4d0f3425dab10d52e291070c0558/barcode/writer.py#L161-L221 |
229,453 | WhyNotHugo/python-barcode | barcode/base.py | Barcode.save | def save(self, filename, options=None, text=None):
"""Renders the barcode and saves it in `filename`.
:parameters:
filename : String
Filename to save the barcode in (without filename
extension).
options : Dict
The same as in `self.render`.
text : str (unicode on Python 2)
Text to render under the barcode.
:returns: The full filename with extension.
:rtype: String
"""
if text:
output = self.render(options, text)
else:
output = self.render(options)
_filename = self.writer.save(filename, output)
return _filename | python | def save(self, filename, options=None, text=None):
if text:
output = self.render(options, text)
else:
output = self.render(options)
_filename = self.writer.save(filename, output)
return _filename | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"options",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"if",
"text",
":",
"output",
"=",
"self",
".",
"render",
"(",
"options",
",",
"text",
")",
"else",
":",
"output",
"=",
"self",
".",
"ren... | Renders the barcode and saves it in `filename`.
:parameters:
filename : String
Filename to save the barcode in (without filename
extension).
options : Dict
The same as in `self.render`.
text : str (unicode on Python 2)
Text to render under the barcode.
:returns: The full filename with extension.
:rtype: String | [
"Renders",
"the",
"barcode",
"and",
"saves",
"it",
"in",
"filename",
"."
] | 0b237016f32b4d0f3425dab10d52e291070c0558 | https://github.com/WhyNotHugo/python-barcode/blob/0b237016f32b4d0f3425dab10d52e291070c0558/barcode/base.py#L53-L74 |
229,454 | WhyNotHugo/python-barcode | barcode/base.py | Barcode.write | def write(self, fp, options=None, text=None):
"""Renders the barcode and writes it to the file like object
`fp`.
:parameters:
fp : File like object
Object to write the raw data in.
options : Dict
The same as in `self.render`.
text : str (unicode on Python 2)
Text to render under the barcode.
"""
output = self.render(options, text)
if hasattr(output, 'tostring'):
output.save(fp, format=self.writer.format)
else:
fp.write(output) | python | def write(self, fp, options=None, text=None):
output = self.render(options, text)
if hasattr(output, 'tostring'):
output.save(fp, format=self.writer.format)
else:
fp.write(output) | [
"def",
"write",
"(",
"self",
",",
"fp",
",",
"options",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"output",
"=",
"self",
".",
"render",
"(",
"options",
",",
"text",
")",
"if",
"hasattr",
"(",
"output",
",",
"'tostring'",
")",
":",
"output",
... | Renders the barcode and writes it to the file like object
`fp`.
:parameters:
fp : File like object
Object to write the raw data in.
options : Dict
The same as in `self.render`.
text : str (unicode on Python 2)
Text to render under the barcode. | [
"Renders",
"the",
"barcode",
"and",
"writes",
"it",
"to",
"the",
"file",
"like",
"object",
"fp",
"."
] | 0b237016f32b4d0f3425dab10d52e291070c0558 | https://github.com/WhyNotHugo/python-barcode/blob/0b237016f32b4d0f3425dab10d52e291070c0558/barcode/base.py#L76-L92 |
229,455 | WhyNotHugo/python-barcode | barcode/upc.py | UniversalProductCodeA.build | def build(self):
"""Builds the barcode pattern from 'self.upc'
:return: The pattern as string
:rtype: String
"""
code = _upc.EDGE[:]
for i, number in enumerate(self.upc[0:6]):
code += _upc.CODES['L'][int(number)]
code += _upc.MIDDLE
for number in self.upc[6:]:
code += _upc.CODES['R'][int(number)]
code += _upc.EDGE
return [code] | python | def build(self):
code = _upc.EDGE[:]
for i, number in enumerate(self.upc[0:6]):
code += _upc.CODES['L'][int(number)]
code += _upc.MIDDLE
for number in self.upc[6:]:
code += _upc.CODES['R'][int(number)]
code += _upc.EDGE
return [code] | [
"def",
"build",
"(",
"self",
")",
":",
"code",
"=",
"_upc",
".",
"EDGE",
"[",
":",
"]",
"for",
"i",
",",
"number",
"in",
"enumerate",
"(",
"self",
".",
"upc",
"[",
"0",
":",
"6",
"]",
")",
":",
"code",
"+=",
"_upc",
".",
"CODES",
"[",
"'L'",
... | Builds the barcode pattern from 'self.upc'
:return: The pattern as string
:rtype: String | [
"Builds",
"the",
"barcode",
"pattern",
"from",
"self",
".",
"upc"
] | 0b237016f32b4d0f3425dab10d52e291070c0558 | https://github.com/WhyNotHugo/python-barcode/blob/0b237016f32b4d0f3425dab10d52e291070c0558/barcode/upc.py#L78-L96 |
229,456 | psss/did | did/plugins/jira.py | Issue.search | def search(query, stats):
""" Perform issue search for given stats instance """
log.debug("Search query: {0}".format(query))
issues = []
# Fetch data from the server in batches of MAX_RESULTS issues
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(
"{0}/rest/api/latest/search?{1}".format(
stats.parent.url, urllib.urlencode({
"jql": query,
"fields": "summary,comment",
"maxResults": MAX_RESULTS,
"startAt": batch * MAX_RESULTS})))
data = response.json()
log.debug("Batch {0} result: {1} fetched".format(
batch, listed(data["issues"], "issue")))
log.data(pretty(data))
issues.extend(data["issues"])
# If all issues fetched, we're done
if len(issues) >= data["total"]:
break
# Return the list of issue objects
return [Issue(issue, prefix=stats.parent.prefix) for issue in issues] | python | def search(query, stats):
log.debug("Search query: {0}".format(query))
issues = []
# Fetch data from the server in batches of MAX_RESULTS issues
for batch in range(MAX_BATCHES):
response = stats.parent.session.get(
"{0}/rest/api/latest/search?{1}".format(
stats.parent.url, urllib.urlencode({
"jql": query,
"fields": "summary,comment",
"maxResults": MAX_RESULTS,
"startAt": batch * MAX_RESULTS})))
data = response.json()
log.debug("Batch {0} result: {1} fetched".format(
batch, listed(data["issues"], "issue")))
log.data(pretty(data))
issues.extend(data["issues"])
# If all issues fetched, we're done
if len(issues) >= data["total"]:
break
# Return the list of issue objects
return [Issue(issue, prefix=stats.parent.prefix) for issue in issues] | [
"def",
"search",
"(",
"query",
",",
"stats",
")",
":",
"log",
".",
"debug",
"(",
"\"Search query: {0}\"",
".",
"format",
"(",
"query",
")",
")",
"issues",
"=",
"[",
"]",
"# Fetch data from the server in batches of MAX_RESULTS issues",
"for",
"batch",
"in",
"rang... | Perform issue search for given stats instance | [
"Perform",
"issue",
"search",
"for",
"given",
"stats",
"instance"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/jira.py#L91-L113 |
229,457 | psss/did | did/plugins/jira.py | Issue.updated | def updated(self, user, options):
""" True if the issue was commented by given user """
for comment in self.comments:
created = dateutil.parser.parse(comment["created"]).date()
try:
if (comment["author"]["emailAddress"] == user.email and
created >= options.since.date and
created < options.until.date):
return True
except KeyError:
pass
return False | python | def updated(self, user, options):
for comment in self.comments:
created = dateutil.parser.parse(comment["created"]).date()
try:
if (comment["author"]["emailAddress"] == user.email and
created >= options.since.date and
created < options.until.date):
return True
except KeyError:
pass
return False | [
"def",
"updated",
"(",
"self",
",",
"user",
",",
"options",
")",
":",
"for",
"comment",
"in",
"self",
".",
"comments",
":",
"created",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"comment",
"[",
"\"created\"",
"]",
")",
".",
"date",
"(",
")",
... | True if the issue was commented by given user | [
"True",
"if",
"the",
"issue",
"was",
"commented",
"by",
"given",
"user"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/jira.py#L115-L126 |
229,458 | psss/did | did/plugins/bitly.py | Bitly.user_link_history | def user_link_history(self, created_before=None, created_after=None,
limit=100, **kwargs):
""" Bit.ly API - user_link_history wrapper"""
""" Bit.ly link
Link History Keys
-----------------
[u'aggregate_link', u'archived', u'campaign_ids',
u'client_id', u'created_at', u'keyword_link',
u'link', u'long_url', u'modified_at',
u'private', u'tags', u'title', u'user_ts']
"""
# bit.ly API doesn't seem to like anything other than int's
limit = int(limit)
created_after = int(created_after)
created_before = int(created_before)
hist = self.api.user_link_history(
limit=limit, created_before=created_before,
created_after=created_after)
# FIXME: if we have more than 100 objects we need to PAGINATE
record = "{0} - {1}"
links = []
for r in hist:
link = r.get('keyword_link') or r['link']
title = r['title'] or '<< NO TITLE >>'
links.append(record.format(link, title))
log.debug("First 3 Links fetched:")
log.debug(pretty(hist[0:3], indent=4))
return links | python | def user_link_history(self, created_before=None, created_after=None,
limit=100, **kwargs):
""" Bit.ly link
Link History Keys
-----------------
[u'aggregate_link', u'archived', u'campaign_ids',
u'client_id', u'created_at', u'keyword_link',
u'link', u'long_url', u'modified_at',
u'private', u'tags', u'title', u'user_ts']
"""
# bit.ly API doesn't seem to like anything other than int's
limit = int(limit)
created_after = int(created_after)
created_before = int(created_before)
hist = self.api.user_link_history(
limit=limit, created_before=created_before,
created_after=created_after)
# FIXME: if we have more than 100 objects we need to PAGINATE
record = "{0} - {1}"
links = []
for r in hist:
link = r.get('keyword_link') or r['link']
title = r['title'] or '<< NO TITLE >>'
links.append(record.format(link, title))
log.debug("First 3 Links fetched:")
log.debug(pretty(hist[0:3], indent=4))
return links | [
"def",
"user_link_history",
"(",
"self",
",",
"created_before",
"=",
"None",
",",
"created_after",
"=",
"None",
",",
"limit",
"=",
"100",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\" Bit.ly link\n\n Link History Keys\n -----------------\n\n [u'aggre... | Bit.ly API - user_link_history wrapper | [
"Bit",
".",
"ly",
"API",
"-",
"user_link_history",
"wrapper"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bitly.py#L69-L99 |
229,459 | psss/did | did/plugins/bitly.py | SavedLinks.fetch | def fetch(self):
'''
Bit.ly API expect unix timestamps
'''
since = time.mktime(self.options.since.datetime.timetuple())
until = time.mktime(self.options.until.datetime.timetuple())
log.info("Searching for links saved by {0}".format(self.user))
self.stats = self.parent.bitly.user_link_history(created_after=since,
created_before=until) | python | def fetch(self):
'''
Bit.ly API expect unix timestamps
'''
since = time.mktime(self.options.since.datetime.timetuple())
until = time.mktime(self.options.until.datetime.timetuple())
log.info("Searching for links saved by {0}".format(self.user))
self.stats = self.parent.bitly.user_link_history(created_after=since,
created_before=until) | [
"def",
"fetch",
"(",
"self",
")",
":",
"since",
"=",
"time",
".",
"mktime",
"(",
"self",
".",
"options",
".",
"since",
".",
"datetime",
".",
"timetuple",
"(",
")",
")",
"until",
"=",
"time",
".",
"mktime",
"(",
"self",
".",
"options",
".",
"until",... | Bit.ly API expect unix timestamps | [
"Bit",
".",
"ly",
"API",
"expect",
"unix",
"timestamps"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bitly.py#L108-L116 |
229,460 | psss/did | did/plugins/sentry.py | Sentry.issues | def issues(self, kind, email):
""" Filter unique issues for given activity type and email """
return list(set([unicode(activity.issue)
for activity in self.activities()
if kind == activity.kind and activity.user['email'] == email])) | python | def issues(self, kind, email):
return list(set([unicode(activity.issue)
for activity in self.activities()
if kind == activity.kind and activity.user['email'] == email])) | [
"def",
"issues",
"(",
"self",
",",
"kind",
",",
"email",
")",
":",
"return",
"list",
"(",
"set",
"(",
"[",
"unicode",
"(",
"activity",
".",
"issue",
")",
"for",
"activity",
"in",
"self",
".",
"activities",
"(",
")",
"if",
"kind",
"==",
"activity",
... | Filter unique issues for given activity type and email | [
"Filter",
"unique",
"issues",
"for",
"given",
"activity",
"type",
"and",
"email"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/sentry.py#L81-L85 |
229,461 | psss/did | did/plugins/sentry.py | Sentry._fetch_activities | def _fetch_activities(self):
""" Get organization activity, handle pagination """
activities = []
# Prepare url of the first page
url = '{0}/organizations/{1}/activity/'.format(
self.url, self.organization)
while url:
# Fetch one page of activities
try:
log.debug('Fetching activity data: {0}'.format(url))
response = requests.get(url, headers=self.headers)
if not response.ok:
log.error(response.text)
raise ReportError('Failed to fetch Sentry activities.')
data = response.json()
log.data("Response headers:\n{0}".format(
pretty(response.headers)))
log.debug("Fetched {0}.".format(listed(len(data), 'activity')))
log.data(pretty(data))
for activity in [Activity(item) for item in data]:
# We've reached the last page, older records not relevant
if activity.created < self.stats.options.since.date:
return activities
# Store only relevant activites (before until date)
if activity.created < self.stats.options.until.date:
log.details("Activity: {0}".format(activity))
activities.append(activity)
except requests.RequestException as error:
log.debug(error)
raise ReportError(
'Failed to fetch Sentry activities from {0}'.format(url))
# Check for possible next page
try:
url = NEXT_PAGE.search(response.headers['Link']).groups()[0]
except AttributeError:
url = None
return activities | python | def _fetch_activities(self):
activities = []
# Prepare url of the first page
url = '{0}/organizations/{1}/activity/'.format(
self.url, self.organization)
while url:
# Fetch one page of activities
try:
log.debug('Fetching activity data: {0}'.format(url))
response = requests.get(url, headers=self.headers)
if not response.ok:
log.error(response.text)
raise ReportError('Failed to fetch Sentry activities.')
data = response.json()
log.data("Response headers:\n{0}".format(
pretty(response.headers)))
log.debug("Fetched {0}.".format(listed(len(data), 'activity')))
log.data(pretty(data))
for activity in [Activity(item) for item in data]:
# We've reached the last page, older records not relevant
if activity.created < self.stats.options.since.date:
return activities
# Store only relevant activites (before until date)
if activity.created < self.stats.options.until.date:
log.details("Activity: {0}".format(activity))
activities.append(activity)
except requests.RequestException as error:
log.debug(error)
raise ReportError(
'Failed to fetch Sentry activities from {0}'.format(url))
# Check for possible next page
try:
url = NEXT_PAGE.search(response.headers['Link']).groups()[0]
except AttributeError:
url = None
return activities | [
"def",
"_fetch_activities",
"(",
"self",
")",
":",
"activities",
"=",
"[",
"]",
"# Prepare url of the first page",
"url",
"=",
"'{0}/organizations/{1}/activity/'",
".",
"format",
"(",
"self",
".",
"url",
",",
"self",
".",
"organization",
")",
"while",
"url",
":"... | Get organization activity, handle pagination | [
"Get",
"organization",
"activity",
"handle",
"pagination"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/sentry.py#L87-L123 |
229,462 | psss/did | did/plugins/nitrate.py | NitrateStats.cases | def cases(self):
""" All test cases created by the user """
import nitrate
if self._cases is None:
log.info(u"Searching for cases created by {0}".format(self.user))
self._cases = [
case for case in nitrate.TestCase.search(
author__email=self.user.email,
create_date__gt=str(self.options.since),
create_date__lt=str(self.options.until))
if case.status != nitrate.CaseStatus("DISABLED")]
return self._cases | python | def cases(self):
import nitrate
if self._cases is None:
log.info(u"Searching for cases created by {0}".format(self.user))
self._cases = [
case for case in nitrate.TestCase.search(
author__email=self.user.email,
create_date__gt=str(self.options.since),
create_date__lt=str(self.options.until))
if case.status != nitrate.CaseStatus("DISABLED")]
return self._cases | [
"def",
"cases",
"(",
"self",
")",
":",
"import",
"nitrate",
"if",
"self",
".",
"_cases",
"is",
"None",
":",
"log",
".",
"info",
"(",
"u\"Searching for cases created by {0}\"",
".",
"format",
"(",
"self",
".",
"user",
")",
")",
"self",
".",
"_cases",
"=",... | All test cases created by the user | [
"All",
"test",
"cases",
"created",
"by",
"the",
"user"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/nitrate.py#L100-L111 |
229,463 | psss/did | did/plugins/nitrate.py | NitrateStats.copies | def copies(self):
""" All test case copies created by the user """
import nitrate
if self._copies is None:
log.info(u"Searching for cases copied by {0}".format(self.user))
self._copies = [
case for case in nitrate.TestCase.search(
author__email=self.user.email,
create_date__gt=str(self.options.since),
create_date__lt=str(self.options.until),
tag__name=TEST_CASE_COPY_TAG)]
return self._copies | python | def copies(self):
import nitrate
if self._copies is None:
log.info(u"Searching for cases copied by {0}".format(self.user))
self._copies = [
case for case in nitrate.TestCase.search(
author__email=self.user.email,
create_date__gt=str(self.options.since),
create_date__lt=str(self.options.until),
tag__name=TEST_CASE_COPY_TAG)]
return self._copies | [
"def",
"copies",
"(",
"self",
")",
":",
"import",
"nitrate",
"if",
"self",
".",
"_copies",
"is",
"None",
":",
"log",
".",
"info",
"(",
"u\"Searching for cases copied by {0}\"",
".",
"format",
"(",
"self",
".",
"user",
")",
")",
"self",
".",
"_copies",
"=... | All test case copies created by the user | [
"All",
"test",
"case",
"copies",
"created",
"by",
"the",
"user"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/nitrate.py#L114-L125 |
229,464 | psss/did | did/plugins/google.py | authorized_http | def authorized_http(client_id, client_secret, apps, file=None):
"""
Start an authorized HTTP session.
Try fetching valid user credentials from storage. If nothing has been
stored, or if the stored credentials are invalid, complete the OAuth2 flow
to obtain new credentials.
"""
if not os.path.exists(CREDENTIAL_DIR):
os.makedirs(CREDENTIAL_DIR)
credential_path = file or CREDENTIAL_PATH
storage = Storage(credential_path)
credentials = storage.get()
scopes = set([
"https://www.googleapis.com/auth/{0}.readonly".format(app)
for app in apps
])
if (not credentials or credentials.invalid
or not scopes <= credentials.scopes):
flow = OAuth2WebServerFlow(
client_id=client_id,
client_secret=client_secret,
scope=scopes,
redirect_uri=REDIRECT_URI)
flow.user_agent = USER_AGENT
# Do not parse did command-line options by OAuth client
flags = tools.argparser.parse_args(args=[])
credentials = tools.run_flow(flow, storage, flags)
return credentials.authorize(httplib2.Http()) | python | def authorized_http(client_id, client_secret, apps, file=None):
if not os.path.exists(CREDENTIAL_DIR):
os.makedirs(CREDENTIAL_DIR)
credential_path = file or CREDENTIAL_PATH
storage = Storage(credential_path)
credentials = storage.get()
scopes = set([
"https://www.googleapis.com/auth/{0}.readonly".format(app)
for app in apps
])
if (not credentials or credentials.invalid
or not scopes <= credentials.scopes):
flow = OAuth2WebServerFlow(
client_id=client_id,
client_secret=client_secret,
scope=scopes,
redirect_uri=REDIRECT_URI)
flow.user_agent = USER_AGENT
# Do not parse did command-line options by OAuth client
flags = tools.argparser.parse_args(args=[])
credentials = tools.run_flow(flow, storage, flags)
return credentials.authorize(httplib2.Http()) | [
"def",
"authorized_http",
"(",
"client_id",
",",
"client_secret",
",",
"apps",
",",
"file",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"CREDENTIAL_DIR",
")",
":",
"os",
".",
"makedirs",
"(",
"CREDENTIAL_DIR",
")",
"credent... | Start an authorized HTTP session.
Try fetching valid user credentials from storage. If nothing has been
stored, or if the stored credentials are invalid, complete the OAuth2 flow
to obtain new credentials. | [
"Start",
"an",
"authorized",
"HTTP",
"session",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/google.py#L77-L110 |
229,465 | psss/did | did/plugins/google.py | GoogleCalendar.events | def events(self, **kwargs):
""" Fetch events meeting specified criteria """
events_result = self.service.events().list(**kwargs).execute()
return [Event(event) for event in events_result.get("items", [])] | python | def events(self, **kwargs):
events_result = self.service.events().list(**kwargs).execute()
return [Event(event) for event in events_result.get("items", [])] | [
"def",
"events",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"events_result",
"=",
"self",
".",
"service",
".",
"events",
"(",
")",
".",
"list",
"(",
"*",
"*",
"kwargs",
")",
".",
"execute",
"(",
")",
"return",
"[",
"Event",
"(",
"event",
")"... | Fetch events meeting specified criteria | [
"Fetch",
"events",
"meeting",
"specified",
"criteria"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/google.py#L121-L124 |
229,466 | psss/did | did/plugins/google.py | Event.attended_by | def attended_by(self, email):
""" Check if user attended the event """
for attendee in self["attendees"] or []:
if (attendee["email"] == email
and attendee["responseStatus"] == "accepted"):
return True
return False | python | def attended_by(self, email):
for attendee in self["attendees"] or []:
if (attendee["email"] == email
and attendee["responseStatus"] == "accepted"):
return True
return False | [
"def",
"attended_by",
"(",
"self",
",",
"email",
")",
":",
"for",
"attendee",
"in",
"self",
"[",
"\"attendees\"",
"]",
"or",
"[",
"]",
":",
"if",
"(",
"attendee",
"[",
"\"email\"",
"]",
"==",
"email",
"and",
"attendee",
"[",
"\"responseStatus\"",
"]",
... | Check if user attended the event | [
"Check",
"if",
"user",
"attended",
"the",
"event"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/google.py#L151-L157 |
229,467 | psss/did | did/plugins/google.py | GoogleTasks.tasks | def tasks(self, **kwargs):
""" Fetch tasks specified criteria """
tasks_result = self.service.tasks().list(**kwargs).execute()
return [Task(task) for task in tasks_result.get("items", [])] | python | def tasks(self, **kwargs):
tasks_result = self.service.tasks().list(**kwargs).execute()
return [Task(task) for task in tasks_result.get("items", [])] | [
"def",
"tasks",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"tasks_result",
"=",
"self",
".",
"service",
".",
"tasks",
"(",
")",
".",
"list",
"(",
"*",
"*",
"kwargs",
")",
".",
"execute",
"(",
")",
"return",
"[",
"Task",
"(",
"task",
")",
"... | Fetch tasks specified criteria | [
"Fetch",
"tasks",
"specified",
"criteria"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/google.py#L168-L171 |
229,468 | psss/did | did/plugins/google.py | GoogleStatsBase.events | def events(self):
""" All events in calendar within specified time range """
if self._events is None:
self._events = self.parent.calendar.events(
calendarId="primary", singleEvents=True, orderBy="startTime",
timeMin=self.since, timeMax=self.until)
return self._events | python | def events(self):
if self._events is None:
self._events = self.parent.calendar.events(
calendarId="primary", singleEvents=True, orderBy="startTime",
timeMin=self.since, timeMax=self.until)
return self._events | [
"def",
"events",
"(",
"self",
")",
":",
"if",
"self",
".",
"_events",
"is",
"None",
":",
"self",
".",
"_events",
"=",
"self",
".",
"parent",
".",
"calendar",
".",
"events",
"(",
"calendarId",
"=",
"\"primary\"",
",",
"singleEvents",
"=",
"True",
",",
... | All events in calendar within specified time range | [
"All",
"events",
"in",
"calendar",
"within",
"specified",
"time",
"range"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/google.py#L208-L214 |
229,469 | psss/did | did/plugins/google.py | GoogleStatsBase.tasks | def tasks(self):
""" All completed tasks within specified time range """
if self._tasks is None:
self._tasks = self.parent.tasks.tasks(
tasklist="@default", showCompleted="true", showHidden="true",
completedMin=self.since, completedMax=self.until)
log.info(u"NB TASKS {0}".format(len(self._tasks)))
return self._tasks | python | def tasks(self):
if self._tasks is None:
self._tasks = self.parent.tasks.tasks(
tasklist="@default", showCompleted="true", showHidden="true",
completedMin=self.since, completedMax=self.until)
log.info(u"NB TASKS {0}".format(len(self._tasks)))
return self._tasks | [
"def",
"tasks",
"(",
"self",
")",
":",
"if",
"self",
".",
"_tasks",
"is",
"None",
":",
"self",
".",
"_tasks",
"=",
"self",
".",
"parent",
".",
"tasks",
".",
"tasks",
"(",
"tasklist",
"=",
"\"@default\"",
",",
"showCompleted",
"=",
"\"true\"",
",",
"s... | All completed tasks within specified time range | [
"All",
"completed",
"tasks",
"within",
"specified",
"time",
"range"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/google.py#L217-L224 |
229,470 | psss/did | did/stats.py | Stats.name | def name(self):
""" Use the first line of docs string unless name set. """
if self._name:
return self._name
return [
line.strip() for line in self.__doc__.split("\n")
if line.strip()][0] | python | def name(self):
if self._name:
return self._name
return [
line.strip() for line in self.__doc__.split("\n")
if line.strip()][0] | [
"def",
"name",
"(",
"self",
")",
":",
"if",
"self",
".",
"_name",
":",
"return",
"self",
".",
"_name",
"return",
"[",
"line",
".",
"strip",
"(",
")",
"for",
"line",
"in",
"self",
".",
"__doc__",
".",
"split",
"(",
"\"\\n\"",
")",
"if",
"line",
".... | Use the first line of docs string unless name set. | [
"Use",
"the",
"first",
"line",
"of",
"docs",
"string",
"unless",
"name",
"set",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L46-L52 |
229,471 | psss/did | did/stats.py | Stats.add_option | def add_option(self, group):
""" Add option for self to the parser group object. """
group.add_argument(
"--{0}".format(self.option), action="store_true", help=self.name) | python | def add_option(self, group):
group.add_argument(
"--{0}".format(self.option), action="store_true", help=self.name) | [
"def",
"add_option",
"(",
"self",
",",
"group",
")",
":",
"group",
".",
"add_argument",
"(",
"\"--{0}\"",
".",
"format",
"(",
"self",
".",
"option",
")",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"self",
".",
"name",
")"
] | Add option for self to the parser group object. | [
"Add",
"option",
"for",
"self",
"to",
"the",
"parser",
"group",
"object",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L54-L57 |
229,472 | psss/did | did/stats.py | Stats.check | def check(self):
""" Check the stats if enabled. """
if not self.enabled():
return
try:
self.fetch()
except (xmlrpclib.Fault, did.base.ConfigError) as error:
log.error(error)
self._error = True
# Raise the exception if debugging
if not self.options or self.options.debug:
raise
# Show the results stats (unless merging)
if self.options and not self.options.merge:
self.show() | python | def check(self):
if not self.enabled():
return
try:
self.fetch()
except (xmlrpclib.Fault, did.base.ConfigError) as error:
log.error(error)
self._error = True
# Raise the exception if debugging
if not self.options or self.options.debug:
raise
# Show the results stats (unless merging)
if self.options and not self.options.merge:
self.show() | [
"def",
"check",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"enabled",
"(",
")",
":",
"return",
"try",
":",
"self",
".",
"fetch",
"(",
")",
"except",
"(",
"xmlrpclib",
".",
"Fault",
",",
"did",
".",
"base",
".",
"ConfigError",
")",
"as",
"er... | Check the stats if enabled. | [
"Check",
"the",
"stats",
"if",
"enabled",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L74-L88 |
229,473 | psss/did | did/stats.py | Stats.show | def show(self):
""" Display indented statistics. """
if not self._error and not self.stats:
return
self.header()
for stat in self.stats:
utils.item(stat, level=1, options=self.options) | python | def show(self):
if not self._error and not self.stats:
return
self.header()
for stat in self.stats:
utils.item(stat, level=1, options=self.options) | [
"def",
"show",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_error",
"and",
"not",
"self",
".",
"stats",
":",
"return",
"self",
".",
"header",
"(",
")",
"for",
"stat",
"in",
"self",
".",
"stats",
":",
"utils",
".",
"item",
"(",
"stat",
",",
... | Display indented statistics. | [
"Display",
"indented",
"statistics",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L96-L102 |
229,474 | psss/did | did/stats.py | StatsGroup.add_option | def add_option(self, parser):
""" Add option group and all children options. """
group = parser.add_argument_group(self.name)
for stat in self.stats:
stat.add_option(group)
group.add_argument(
"--{0}".format(self.option), action="store_true", help="All above") | python | def add_option(self, parser):
group = parser.add_argument_group(self.name)
for stat in self.stats:
stat.add_option(group)
group.add_argument(
"--{0}".format(self.option), action="store_true", help="All above") | [
"def",
"add_option",
"(",
"self",
",",
"parser",
")",
":",
"group",
"=",
"parser",
".",
"add_argument_group",
"(",
"self",
".",
"name",
")",
"for",
"stat",
"in",
"self",
".",
"stats",
":",
"stat",
".",
"add_option",
"(",
"group",
")",
"group",
".",
"... | Add option group and all children options. | [
"Add",
"option",
"group",
"and",
"all",
"children",
"options",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L123-L131 |
229,475 | psss/did | did/stats.py | StatsGroup.merge | def merge(self, other):
""" Merge all children stats. """
for this, other in zip(self.stats, other.stats):
this.merge(other) | python | def merge(self, other):
for this, other in zip(self.stats, other.stats):
this.merge(other) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"for",
"this",
",",
"other",
"in",
"zip",
"(",
"self",
".",
"stats",
",",
"other",
".",
"stats",
")",
":",
"this",
".",
"merge",
"(",
"other",
")"
] | Merge all children stats. | [
"Merge",
"all",
"children",
"stats",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/stats.py#L143-L146 |
229,476 | psss/did | did/plugins/rt.py | RequestTracker.get | def get(self, path):
""" Perform a GET request with GSSAPI authentication """
# Generate token
service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
gssapi.NameType.hostbased_service)
ctx = gssapi.SecurityContext(usage="initiate", name=service_name)
data = b64encode(ctx.step()).decode()
# Make the connection
connection = httplib.HTTPSConnection(self.url.netloc, 443)
log.debug("GET {0}".format(path))
connection.putrequest("GET", path)
connection.putheader("Authorization", "Negotiate {0}".format(data))
connection.putheader("Referer", self.url_string)
connection.endheaders()
# Perform the request, convert response into lines
response = connection.getresponse()
if response.status != 200:
raise ReportError(
"Failed to fetch tickets: {0}".format(response.status))
lines = response.read().decode("utf8").strip().split("\n")[1:]
log.debug("Tickets fetched:")
log.debug(pretty(lines))
return lines | python | def get(self, path):
# Generate token
service_name = gssapi.Name('HTTP@{0}'.format(self.url.netloc),
gssapi.NameType.hostbased_service)
ctx = gssapi.SecurityContext(usage="initiate", name=service_name)
data = b64encode(ctx.step()).decode()
# Make the connection
connection = httplib.HTTPSConnection(self.url.netloc, 443)
log.debug("GET {0}".format(path))
connection.putrequest("GET", path)
connection.putheader("Authorization", "Negotiate {0}".format(data))
connection.putheader("Referer", self.url_string)
connection.endheaders()
# Perform the request, convert response into lines
response = connection.getresponse()
if response.status != 200:
raise ReportError(
"Failed to fetch tickets: {0}".format(response.status))
lines = response.read().decode("utf8").strip().split("\n")[1:]
log.debug("Tickets fetched:")
log.debug(pretty(lines))
return lines | [
"def",
"get",
"(",
"self",
",",
"path",
")",
":",
"# Generate token",
"service_name",
"=",
"gssapi",
".",
"Name",
"(",
"'HTTP@{0}'",
".",
"format",
"(",
"self",
".",
"url",
".",
"netloc",
")",
",",
"gssapi",
".",
"NameType",
".",
"hostbased_service",
")"... | Perform a GET request with GSSAPI authentication | [
"Perform",
"a",
"GET",
"request",
"with",
"GSSAPI",
"authentication"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/rt.py#L40-L64 |
229,477 | psss/did | did/plugins/rt.py | RequestTracker.search | def search(self, query):
""" Perform request tracker search """
# Prepare the path
log.debug("Query: {0}".format(query))
path = self.url.path + '?Format=__id__+__Subject__'
path += "&Order=ASC&OrderBy=id&Query=" + urllib.quote(query)
# Get the tickets
lines = self.get(path)
log.info(u"Fetched tickets: {0}".format(len(lines)))
return [self.parent.ticket(line, self.parent) for line in lines] | python | def search(self, query):
# Prepare the path
log.debug("Query: {0}".format(query))
path = self.url.path + '?Format=__id__+__Subject__'
path += "&Order=ASC&OrderBy=id&Query=" + urllib.quote(query)
# Get the tickets
lines = self.get(path)
log.info(u"Fetched tickets: {0}".format(len(lines)))
return [self.parent.ticket(line, self.parent) for line in lines] | [
"def",
"search",
"(",
"self",
",",
"query",
")",
":",
"# Prepare the path",
"log",
".",
"debug",
"(",
"\"Query: {0}\"",
".",
"format",
"(",
"query",
")",
")",
"path",
"=",
"self",
".",
"url",
".",
"path",
"+",
"'?Format=__id__+__Subject__'",
"path",
"+=",
... | Perform request tracker search | [
"Perform",
"request",
"tracker",
"search"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/rt.py#L66-L76 |
229,478 | psss/did | did/plugins/bugzilla.py | Bugzilla.server | def server(self):
""" Connection to the server """
if self._server is None:
self._server = bugzilla.Bugzilla(url=self.parent.url)
return self._server | python | def server(self):
if self._server is None:
self._server = bugzilla.Bugzilla(url=self.parent.url)
return self._server | [
"def",
"server",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"self",
".",
"_server",
"=",
"bugzilla",
".",
"Bugzilla",
"(",
"url",
"=",
"self",
".",
"parent",
".",
"url",
")",
"return",
"self",
".",
"_server"
] | Connection to the server | [
"Connection",
"to",
"the",
"server"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L75-L79 |
229,479 | psss/did | did/plugins/bugzilla.py | Bugzilla.search | def search(self, query, options):
""" Perform Bugzilla search """
query["query_format"] = "advanced"
log.debug("Search query:")
log.debug(pretty(query))
# Fetch bug info
try:
result = self.server.query(query)
except xmlrpclib.Fault as error:
# Ignore non-existent users (this is necessary for users with
# several email aliases to allow them using --merge/--total)
if "not a valid username" in unicode(error):
log.debug(error)
return []
# Otherwise suggest to bake bugzilla cookies
log.error("An error encountered, while searching for bugs.")
log.debug(error)
raise ReportError(
"Have you baked cookies using the 'bugzilla login' command?")
log.debug("Search result:")
log.debug(pretty(result))
bugs = dict((bug.id, bug) for bug in result)
# Fetch bug history
log.debug("Fetching bug history")
result = self.server._proxy.Bug.history({'ids': bugs.keys()})
log.debug(pretty(result))
history = dict((bug["id"], bug["history"]) for bug in result["bugs"])
# Fetch bug comments
log.debug("Fetching bug comments")
result = self.server._proxy.Bug.comments({'ids': bugs.keys()})
log.debug(pretty(result))
comments = dict(
(int(bug), data["comments"])
for bug, data in result["bugs"].items())
# Create bug objects
return [
self.parent.bug(
bugs[id], history[id], comments[id], parent=self.parent)
for id in bugs] | python | def search(self, query, options):
query["query_format"] = "advanced"
log.debug("Search query:")
log.debug(pretty(query))
# Fetch bug info
try:
result = self.server.query(query)
except xmlrpclib.Fault as error:
# Ignore non-existent users (this is necessary for users with
# several email aliases to allow them using --merge/--total)
if "not a valid username" in unicode(error):
log.debug(error)
return []
# Otherwise suggest to bake bugzilla cookies
log.error("An error encountered, while searching for bugs.")
log.debug(error)
raise ReportError(
"Have you baked cookies using the 'bugzilla login' command?")
log.debug("Search result:")
log.debug(pretty(result))
bugs = dict((bug.id, bug) for bug in result)
# Fetch bug history
log.debug("Fetching bug history")
result = self.server._proxy.Bug.history({'ids': bugs.keys()})
log.debug(pretty(result))
history = dict((bug["id"], bug["history"]) for bug in result["bugs"])
# Fetch bug comments
log.debug("Fetching bug comments")
result = self.server._proxy.Bug.comments({'ids': bugs.keys()})
log.debug(pretty(result))
comments = dict(
(int(bug), data["comments"])
for bug, data in result["bugs"].items())
# Create bug objects
return [
self.parent.bug(
bugs[id], history[id], comments[id], parent=self.parent)
for id in bugs] | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"options",
")",
":",
"query",
"[",
"\"query_format\"",
"]",
"=",
"\"advanced\"",
"log",
".",
"debug",
"(",
"\"Search query:\"",
")",
"log",
".",
"debug",
"(",
"pretty",
"(",
"query",
")",
")",
"# Fetch bug... | Perform Bugzilla search | [
"Perform",
"Bugzilla",
"search"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L81-L119 |
229,480 | psss/did | did/plugins/bugzilla.py | Bug.summary | def summary(self):
""" Bug summary including resolution if enabled """
if not self.bug.resolution:
return self.bug.summary
if (self.bug.resolution.lower() in self.parent.resolutions
or "all" in self.parent.resolutions):
return "{0} [{1}]".format(
self.bug.summary, self.bug.resolution.lower())
return self.bug.summary | python | def summary(self):
if not self.bug.resolution:
return self.bug.summary
if (self.bug.resolution.lower() in self.parent.resolutions
or "all" in self.parent.resolutions):
return "{0} [{1}]".format(
self.bug.summary, self.bug.resolution.lower())
return self.bug.summary | [
"def",
"summary",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"bug",
".",
"resolution",
":",
"return",
"self",
".",
"bug",
".",
"summary",
"if",
"(",
"self",
".",
"bug",
".",
"resolution",
".",
"lower",
"(",
")",
"in",
"self",
".",
"parent",
... | Bug summary including resolution if enabled | [
"Bug",
"summary",
"including",
"resolution",
"if",
"enabled"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L148-L156 |
229,481 | psss/did | did/plugins/bugzilla.py | Bug.logs | def logs(self):
""" Return relevant who-did-what pairs from the bug history """
for record in self.history:
if (record["when"] >= self.options.since.date
and record["when"] < self.options.until.date):
for change in record["changes"]:
yield record["who"], change | python | def logs(self):
for record in self.history:
if (record["when"] >= self.options.since.date
and record["when"] < self.options.until.date):
for change in record["changes"]:
yield record["who"], change | [
"def",
"logs",
"(",
"self",
")",
":",
"for",
"record",
"in",
"self",
".",
"history",
":",
"if",
"(",
"record",
"[",
"\"when\"",
"]",
">=",
"self",
".",
"options",
".",
"since",
".",
"date",
"and",
"record",
"[",
"\"when\"",
"]",
"<",
"self",
".",
... | Return relevant who-did-what pairs from the bug history | [
"Return",
"relevant",
"who",
"-",
"did",
"-",
"what",
"pairs",
"from",
"the",
"bug",
"history"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L159-L165 |
229,482 | psss/did | did/plugins/bugzilla.py | Bug.verified | def verified(self):
""" True if bug was verified in given time frame """
for who, record in self.logs:
if record["field_name"] == "status" \
and record["added"] == "VERIFIED":
return True
return False | python | def verified(self):
for who, record in self.logs:
if record["field_name"] == "status" \
and record["added"] == "VERIFIED":
return True
return False | [
"def",
"verified",
"(",
"self",
")",
":",
"for",
"who",
",",
"record",
"in",
"self",
".",
"logs",
":",
"if",
"record",
"[",
"\"field_name\"",
"]",
"==",
"\"status\"",
"and",
"record",
"[",
"\"added\"",
"]",
"==",
"\"VERIFIED\"",
":",
"return",
"True",
... | True if bug was verified in given time frame | [
"True",
"if",
"bug",
"was",
"verified",
"in",
"given",
"time",
"frame"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L167-L173 |
229,483 | psss/did | did/plugins/bugzilla.py | Bug.fixed | def fixed(self):
""" Moved to MODIFIED and not later moved to ASSIGNED """
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to MODIFIED (unless already found)
if not decision and record["when"] < self.options.until.date:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["added"] == "MODIFIED"
and change["removed"] != "CLOSED"):
decision = True
# Make sure that the bug has not been later moved to ASSIGNED.
# (This would mean the issue has not been fixed properly.)
else:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["added"] == "ASSIGNED"):
decision = False
return decision | python | def fixed(self):
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to MODIFIED (unless already found)
if not decision and record["when"] < self.options.until.date:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["added"] == "MODIFIED"
and change["removed"] != "CLOSED"):
decision = True
# Make sure that the bug has not been later moved to ASSIGNED.
# (This would mean the issue has not been fixed properly.)
else:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["added"] == "ASSIGNED"):
decision = False
return decision | [
"def",
"fixed",
"(",
"self",
")",
":",
"decision",
"=",
"False",
"for",
"record",
"in",
"self",
".",
"history",
":",
"# Completely ignore older changes",
"if",
"record",
"[",
"\"when\"",
"]",
"<",
"self",
".",
"options",
".",
"since",
".",
"date",
":",
"... | Moved to MODIFIED and not later moved to ASSIGNED | [
"Moved",
"to",
"MODIFIED",
"and",
"not",
"later",
"moved",
"to",
"ASSIGNED"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L185-L206 |
229,484 | psss/did | did/plugins/bugzilla.py | Bug.closed | def closed(self, user):
""" Moved to CLOSED and not later moved to ASSIGNED """
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to CLOSED (unless already found)
if not decision and record["when"] < self.options.until.date:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["added"] == "CLOSED"
and record["who"] in [user.email, user.name]):
decision = True
# Make sure that the bug has not been later moved from CLOSED.
# (This would mean the bug was not closed for a proper reason.)
else:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["removed"] == "CLOSED"):
decision = False
return decision | python | def closed(self, user):
decision = False
for record in self.history:
# Completely ignore older changes
if record["when"] < self.options.since.date:
continue
# Look for status change to CLOSED (unless already found)
if not decision and record["when"] < self.options.until.date:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["added"] == "CLOSED"
and record["who"] in [user.email, user.name]):
decision = True
# Make sure that the bug has not been later moved from CLOSED.
# (This would mean the bug was not closed for a proper reason.)
else:
for change in record["changes"]:
if (change["field_name"] == "status"
and change["removed"] == "CLOSED"):
decision = False
return decision | [
"def",
"closed",
"(",
"self",
",",
"user",
")",
":",
"decision",
"=",
"False",
"for",
"record",
"in",
"self",
".",
"history",
":",
"# Completely ignore older changes",
"if",
"record",
"[",
"\"when\"",
"]",
"<",
"self",
".",
"options",
".",
"since",
".",
... | Moved to CLOSED and not later moved to ASSIGNED | [
"Moved",
"to",
"CLOSED",
"and",
"not",
"later",
"moved",
"to",
"ASSIGNED"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L208-L229 |
229,485 | psss/did | did/plugins/bugzilla.py | Bug.posted | def posted(self):
""" True if bug was moved to POST in given time frame """
for who, record in self.logs:
if record["field_name"] == "status" and record["added"] == "POST":
return True
return False | python | def posted(self):
for who, record in self.logs:
if record["field_name"] == "status" and record["added"] == "POST":
return True
return False | [
"def",
"posted",
"(",
"self",
")",
":",
"for",
"who",
",",
"record",
"in",
"self",
".",
"logs",
":",
"if",
"record",
"[",
"\"field_name\"",
"]",
"==",
"\"status\"",
"and",
"record",
"[",
"\"added\"",
"]",
"==",
"\"POST\"",
":",
"return",
"True",
"retur... | True if bug was moved to POST in given time frame | [
"True",
"if",
"bug",
"was",
"moved",
"to",
"POST",
"in",
"given",
"time",
"frame"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L231-L236 |
229,486 | psss/did | did/plugins/bugzilla.py | Bug.commented | def commented(self, user):
""" True if comment was added in given time frame """
for comment in self.comments:
# Description (comment #0) is not considered as a comment
if comment["count"] == 0:
continue
if (comment.get('author', comment.get('creator')) == user.email and
comment["creation_time"] >= self.options.since.date and
comment["creation_time"] < self.options.until.date):
return True
return False | python | def commented(self, user):
for comment in self.comments:
# Description (comment #0) is not considered as a comment
if comment["count"] == 0:
continue
if (comment.get('author', comment.get('creator')) == user.email and
comment["creation_time"] >= self.options.since.date and
comment["creation_time"] < self.options.until.date):
return True
return False | [
"def",
"commented",
"(",
"self",
",",
"user",
")",
":",
"for",
"comment",
"in",
"self",
".",
"comments",
":",
"# Description (comment #0) is not considered as a comment",
"if",
"comment",
"[",
"\"count\"",
"]",
"==",
"0",
":",
"continue",
"if",
"(",
"comment",
... | True if comment was added in given time frame | [
"True",
"if",
"comment",
"was",
"added",
"in",
"given",
"time",
"frame"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L246-L256 |
229,487 | psss/did | did/plugins/bugzilla.py | Bug.subscribed | def subscribed(self, user):
""" True if CC was added in given time frame """
for who, record in self.logs:
if (record["field_name"] == "cc" and
user.email in record["added"]):
return True
return False | python | def subscribed(self, user):
for who, record in self.logs:
if (record["field_name"] == "cc" and
user.email in record["added"]):
return True
return False | [
"def",
"subscribed",
"(",
"self",
",",
"user",
")",
":",
"for",
"who",
",",
"record",
"in",
"self",
".",
"logs",
":",
"if",
"(",
"record",
"[",
"\"field_name\"",
"]",
"==",
"\"cc\"",
"and",
"user",
".",
"email",
"in",
"record",
"[",
"\"added\"",
"]",... | True if CC was added in given time frame | [
"True",
"if",
"CC",
"was",
"added",
"in",
"given",
"time",
"frame"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/bugzilla.py#L258-L264 |
229,488 | psss/did | examples/mr.bob/hooks.py | set_name_email | def set_name_email(configurator, question, answer):
'''
prepare "Full Name" <email@eg.com>" string
'''
name = configurator.variables['author.name']
configurator.variables['author.name_email'] = '"{0}" <{1}>'.format(
name, answer)
return answer | python | def set_name_email(configurator, question, answer):
'''
prepare "Full Name" <email@eg.com>" string
'''
name = configurator.variables['author.name']
configurator.variables['author.name_email'] = '"{0}" <{1}>'.format(
name, answer)
return answer | [
"def",
"set_name_email",
"(",
"configurator",
",",
"question",
",",
"answer",
")",
":",
"name",
"=",
"configurator",
".",
"variables",
"[",
"'author.name'",
"]",
"configurator",
".",
"variables",
"[",
"'author.name_email'",
"]",
"=",
"'\"{0}\" <{1}>'",
".",
"for... | prepare "Full Name" <email@eg.com>" string | [
"prepare",
"Full",
"Name",
"<email"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/examples/mr.bob/hooks.py#L29-L36 |
229,489 | psss/did | did/plugins/__init__.py | load | def load():
""" Check available plugins and attempt to import them """
# Code is based on beaker-client's command.py script
plugins = []
for filename in os.listdir(PLUGINS_PATH):
if not filename.endswith(".py") or filename.startswith("_"):
continue
if not os.path.isfile(os.path.join(PLUGINS_PATH, filename)):
continue
plugin = filename[:-3]
if plugin in FAILED_PLUGINS:
# Skip loading plugins that already failed before
continue
try:
__import__(PLUGINS.__name__, {}, {}, [plugin])
plugins.append(plugin)
log.debug("Successfully imported {0} plugin".format(plugin))
except (ImportError, SyntaxError) as error:
# Give a warning only when the plugin is configured
message = "Failed to import {0} plugin ({1})".format(plugin, error)
if Config().sections(kind=plugin):
log.warn(message)
else:
log.debug(message)
FAILED_PLUGINS.append(plugin)
return plugins | python | def load():
# Code is based on beaker-client's command.py script
plugins = []
for filename in os.listdir(PLUGINS_PATH):
if not filename.endswith(".py") or filename.startswith("_"):
continue
if not os.path.isfile(os.path.join(PLUGINS_PATH, filename)):
continue
plugin = filename[:-3]
if plugin in FAILED_PLUGINS:
# Skip loading plugins that already failed before
continue
try:
__import__(PLUGINS.__name__, {}, {}, [plugin])
plugins.append(plugin)
log.debug("Successfully imported {0} plugin".format(plugin))
except (ImportError, SyntaxError) as error:
# Give a warning only when the plugin is configured
message = "Failed to import {0} plugin ({1})".format(plugin, error)
if Config().sections(kind=plugin):
log.warn(message)
else:
log.debug(message)
FAILED_PLUGINS.append(plugin)
return plugins | [
"def",
"load",
"(",
")",
":",
"# Code is based on beaker-client's command.py script",
"plugins",
"=",
"[",
"]",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"PLUGINS_PATH",
")",
":",
"if",
"not",
"filename",
".",
"endswith",
"(",
"\".py\"",
")",
"or",
... | Check available plugins and attempt to import them | [
"Check",
"available",
"plugins",
"and",
"attempt",
"to",
"import",
"them"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/__init__.py#L69-L94 |
229,490 | psss/did | did/plugins/github.py | GitHub.search | def search(self, query):
""" Perform GitHub query """
url = self.url + "/" + query
log.debug("GitHub query: {0}".format(url))
try:
request = urllib2.Request(url, headers=self.headers)
response = urllib2.urlopen(request)
log.debug("Response headers:\n{0}".format(
unicode(response.info()).strip()))
except urllib2.URLError as error:
log.debug(error)
raise ReportError(
"GitHub search on {0} failed.".format(self.url))
result = json.loads(response.read())["items"]
log.debug("Result: {0} fetched".format(listed(len(result), "item")))
log.data(pretty(result))
return result | python | def search(self, query):
url = self.url + "/" + query
log.debug("GitHub query: {0}".format(url))
try:
request = urllib2.Request(url, headers=self.headers)
response = urllib2.urlopen(request)
log.debug("Response headers:\n{0}".format(
unicode(response.info()).strip()))
except urllib2.URLError as error:
log.debug(error)
raise ReportError(
"GitHub search on {0} failed.".format(self.url))
result = json.loads(response.read())["items"]
log.debug("Result: {0} fetched".format(listed(len(result), "item")))
log.data(pretty(result))
return result | [
"def",
"search",
"(",
"self",
",",
"query",
")",
":",
"url",
"=",
"self",
".",
"url",
"+",
"\"/\"",
"+",
"query",
"log",
".",
"debug",
"(",
"\"GitHub query: {0}\"",
".",
"format",
"(",
"url",
")",
")",
"try",
":",
"request",
"=",
"urllib2",
".",
"R... | Perform GitHub query | [
"Perform",
"GitHub",
"query"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/github.py#L52-L68 |
229,491 | psss/did | did/base.py | Config.item | def item(self, section, it):
""" Return content of given item in selected section """
for key, value in self.section(section, skip=[]):
if key == it:
return value
raise ConfigError(
"Item '{0}' not found in section '{1}'".format(it, section)) | python | def item(self, section, it):
for key, value in self.section(section, skip=[]):
if key == it:
return value
raise ConfigError(
"Item '{0}' not found in section '{1}'".format(it, section)) | [
"def",
"item",
"(",
"self",
",",
"section",
",",
"it",
")",
":",
"for",
"key",
",",
"value",
"in",
"self",
".",
"section",
"(",
"section",
",",
"skip",
"=",
"[",
"]",
")",
":",
"if",
"key",
"==",
"it",
":",
"return",
"value",
"raise",
"ConfigErro... | Return content of given item in selected section | [
"Return",
"content",
"of",
"given",
"item",
"in",
"selected",
"section"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L153-L159 |
229,492 | psss/did | did/base.py | Config.path | def path():
""" Detect config file path """
# Detect config directory
try:
directory = os.environ["DID_DIR"]
except KeyError:
directory = CONFIG
# Detect config file (even before options are parsed)
filename = "config"
matched = re.search("--confi?g?[ =](\S+)", " ".join(sys.argv))
if matched:
filename = matched.groups()[0]
return directory.rstrip("/") + "/" + filename | python | def path():
# Detect config directory
try:
directory = os.environ["DID_DIR"]
except KeyError:
directory = CONFIG
# Detect config file (even before options are parsed)
filename = "config"
matched = re.search("--confi?g?[ =](\S+)", " ".join(sys.argv))
if matched:
filename = matched.groups()[0]
return directory.rstrip("/") + "/" + filename | [
"def",
"path",
"(",
")",
":",
"# Detect config directory",
"try",
":",
"directory",
"=",
"os",
".",
"environ",
"[",
"\"DID_DIR\"",
"]",
"except",
"KeyError",
":",
"directory",
"=",
"CONFIG",
"# Detect config file (even before options are parsed)",
"filename",
"=",
"... | Detect config file path | [
"Detect",
"config",
"file",
"path"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L162-L174 |
229,493 | psss/did | did/base.py | Date.this_week | def this_week():
""" Return start and end date of the current week. """
since = TODAY + delta(weekday=MONDAY(-1))
until = since + delta(weeks=1)
return Date(since), Date(until) | python | def this_week():
since = TODAY + delta(weekday=MONDAY(-1))
until = since + delta(weeks=1)
return Date(since), Date(until) | [
"def",
"this_week",
"(",
")",
":",
"since",
"=",
"TODAY",
"+",
"delta",
"(",
"weekday",
"=",
"MONDAY",
"(",
"-",
"1",
")",
")",
"until",
"=",
"since",
"+",
"delta",
"(",
"weeks",
"=",
"1",
")",
"return",
"Date",
"(",
"since",
")",
",",
"Date",
... | Return start and end date of the current week. | [
"Return",
"start",
"and",
"end",
"date",
"of",
"the",
"current",
"week",
"."
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L224-L228 |
229,494 | psss/did | did/base.py | Date.this_year | def this_year():
""" Return start and end date of this fiscal year """
since = TODAY
while since.month != 3 or since.day != 1:
since -= delta(days=1)
until = since + delta(years=1)
return Date(since), Date(until) | python | def this_year():
since = TODAY
while since.month != 3 or since.day != 1:
since -= delta(days=1)
until = since + delta(years=1)
return Date(since), Date(until) | [
"def",
"this_year",
"(",
")",
":",
"since",
"=",
"TODAY",
"while",
"since",
".",
"month",
"!=",
"3",
"or",
"since",
".",
"day",
"!=",
"1",
":",
"since",
"-=",
"delta",
"(",
"days",
"=",
"1",
")",
"until",
"=",
"since",
"+",
"delta",
"(",
"years",... | Return start and end date of this fiscal year | [
"Return",
"start",
"and",
"end",
"date",
"of",
"this",
"fiscal",
"year"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L269-L275 |
229,495 | psss/did | did/base.py | Date.last_year | def last_year():
""" Return start and end date of the last fiscal year """
since, until = Date.this_year()
since = since.date - delta(years=1)
until = until.date - delta(years=1)
return Date(since), Date(until) | python | def last_year():
since, until = Date.this_year()
since = since.date - delta(years=1)
until = until.date - delta(years=1)
return Date(since), Date(until) | [
"def",
"last_year",
"(",
")",
":",
"since",
",",
"until",
"=",
"Date",
".",
"this_year",
"(",
")",
"since",
"=",
"since",
".",
"date",
"-",
"delta",
"(",
"years",
"=",
"1",
")",
"until",
"=",
"until",
".",
"date",
"-",
"delta",
"(",
"years",
"=",... | Return start and end date of the last fiscal year | [
"Return",
"start",
"and",
"end",
"date",
"of",
"the",
"last",
"fiscal",
"year"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L278-L283 |
229,496 | psss/did | did/base.py | Date.period | def period(argument):
""" Detect desired time period for the argument """
since, until, period = None, None, None
if "today" in argument:
since = Date("today")
until = Date("today")
until.date += delta(days=1)
period = "today"
elif "yesterday" in argument:
since = Date("yesterday")
until = Date("yesterday")
until.date += delta(days=1)
period = "yesterday"
elif "year" in argument:
if "last" in argument:
since, until = Date.last_year()
period = "the last fiscal year"
else:
since, until = Date.this_year()
period = "this fiscal year"
elif "quarter" in argument:
if "last" in argument:
since, until = Date.last_quarter()
period = "the last quarter"
else:
since, until = Date.this_quarter()
period = "this quarter"
elif "month" in argument:
if "last" in argument:
since, until = Date.last_month()
else:
since, until = Date.this_month()
period = since.datetime.strftime("%B")
else:
if "last" in argument:
since, until = Date.last_week()
else:
since, until = Date.this_week()
period = "the week {0}".format(since.datetime.strftime("%V"))
return since, until, period | python | def period(argument):
since, until, period = None, None, None
if "today" in argument:
since = Date("today")
until = Date("today")
until.date += delta(days=1)
period = "today"
elif "yesterday" in argument:
since = Date("yesterday")
until = Date("yesterday")
until.date += delta(days=1)
period = "yesterday"
elif "year" in argument:
if "last" in argument:
since, until = Date.last_year()
period = "the last fiscal year"
else:
since, until = Date.this_year()
period = "this fiscal year"
elif "quarter" in argument:
if "last" in argument:
since, until = Date.last_quarter()
period = "the last quarter"
else:
since, until = Date.this_quarter()
period = "this quarter"
elif "month" in argument:
if "last" in argument:
since, until = Date.last_month()
else:
since, until = Date.this_month()
period = since.datetime.strftime("%B")
else:
if "last" in argument:
since, until = Date.last_week()
else:
since, until = Date.this_week()
period = "the week {0}".format(since.datetime.strftime("%V"))
return since, until, period | [
"def",
"period",
"(",
"argument",
")",
":",
"since",
",",
"until",
",",
"period",
"=",
"None",
",",
"None",
",",
"None",
"if",
"\"today\"",
"in",
"argument",
":",
"since",
"=",
"Date",
"(",
"\"today\"",
")",
"until",
"=",
"Date",
"(",
"\"today\"",
")... | Detect desired time period for the argument | [
"Detect",
"desired",
"time",
"period",
"for",
"the",
"argument"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/base.py#L286-L325 |
229,497 | psss/did | did/plugins/trac.py | Trac.search | def search(query, parent, options):
""" Perform Trac search """
# Extend the default max number of tickets to be fetched
query = "{0}&max={1}".format(query, MAX_TICKETS)
log.debug("Search query: {0}".format(query))
try:
result = parent.proxy.ticket.query(query)
except xmlrpclib.Fault as error:
log.error("An error encountered, while searching for tickets.")
raise ReportError(error)
except xmlrpclib.ProtocolError as error:
log.debug(error)
log.error("Trac url: {0}".format(parent.url))
raise ReportError(
"Unable to contact Trac server. Is the url above correct?")
log.debug("Search result: {0}".format(result))
# Fetch tickets and their history using multicall
multicall = xmlrpclib.MultiCall(parent.proxy)
for ticket_id in sorted(result):
multicall.ticket.get(ticket_id)
multicall.ticket.changeLog(ticket_id)
log.debug(u"Fetching trac tickets and their history")
result = list(multicall())
tickets = result[::2]
changelogs = result[1::2]
# Print debugging info
for ticket, changelog in zip(tickets, changelogs):
log.debug("Fetched ticket #{0}".format(ticket[0]))
log.debug(pretty(ticket))
log.debug("Changelog:")
log.debug(pretty(changelog))
# Return the list of ticket objects
return [
Trac(ticket, changelg, parent=parent, options=options)
for ticket, changelg in zip(tickets, changelogs)] | python | def search(query, parent, options):
# Extend the default max number of tickets to be fetched
query = "{0}&max={1}".format(query, MAX_TICKETS)
log.debug("Search query: {0}".format(query))
try:
result = parent.proxy.ticket.query(query)
except xmlrpclib.Fault as error:
log.error("An error encountered, while searching for tickets.")
raise ReportError(error)
except xmlrpclib.ProtocolError as error:
log.debug(error)
log.error("Trac url: {0}".format(parent.url))
raise ReportError(
"Unable to contact Trac server. Is the url above correct?")
log.debug("Search result: {0}".format(result))
# Fetch tickets and their history using multicall
multicall = xmlrpclib.MultiCall(parent.proxy)
for ticket_id in sorted(result):
multicall.ticket.get(ticket_id)
multicall.ticket.changeLog(ticket_id)
log.debug(u"Fetching trac tickets and their history")
result = list(multicall())
tickets = result[::2]
changelogs = result[1::2]
# Print debugging info
for ticket, changelog in zip(tickets, changelogs):
log.debug("Fetched ticket #{0}".format(ticket[0]))
log.debug(pretty(ticket))
log.debug("Changelog:")
log.debug(pretty(changelog))
# Return the list of ticket objects
return [
Trac(ticket, changelg, parent=parent, options=options)
for ticket, changelg in zip(tickets, changelogs)] | [
"def",
"search",
"(",
"query",
",",
"parent",
",",
"options",
")",
":",
"# Extend the default max number of tickets to be fetched",
"query",
"=",
"\"{0}&max={1}\"",
".",
"format",
"(",
"query",
",",
"MAX_TICKETS",
")",
"log",
".",
"debug",
"(",
"\"Search query: {0}\... | Perform Trac search | [
"Perform",
"Trac",
"search"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/trac.py#L60-L94 |
229,498 | psss/did | did/plugins/trac.py | Trac.history | def history(self, user=None):
""" Return relevant who-did-what logs from the ticket history """
for event in self.changelog:
when, who, what, old, new, ignore = event
if (when >= self.options.since.date and
when <= self.options.until.date):
if user is None or who.startswith(user.login):
yield who, what, old, new | python | def history(self, user=None):
for event in self.changelog:
when, who, what, old, new, ignore = event
if (when >= self.options.since.date and
when <= self.options.until.date):
if user is None or who.startswith(user.login):
yield who, what, old, new | [
"def",
"history",
"(",
"self",
",",
"user",
"=",
"None",
")",
":",
"for",
"event",
"in",
"self",
".",
"changelog",
":",
"when",
",",
"who",
",",
"what",
",",
"old",
",",
"new",
",",
"ignore",
"=",
"event",
"if",
"(",
"when",
">=",
"self",
".",
... | Return relevant who-did-what logs from the ticket history | [
"Return",
"relevant",
"who",
"-",
"did",
"-",
"what",
"logs",
"from",
"the",
"ticket",
"history"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/trac.py#L96-L103 |
229,499 | psss/did | did/plugins/trac.py | Trac.updated | def updated(self, user):
""" True if the user commented the ticket in given time frame """
for who, what, old, new in self.history(user):
if (what == "comment" or what == "description") and new != "":
return True
return False | python | def updated(self, user):
for who, what, old, new in self.history(user):
if (what == "comment" or what == "description") and new != "":
return True
return False | [
"def",
"updated",
"(",
"self",
",",
"user",
")",
":",
"for",
"who",
",",
"what",
",",
"old",
",",
"new",
"in",
"self",
".",
"history",
"(",
"user",
")",
":",
"if",
"(",
"what",
"==",
"\"comment\"",
"or",
"what",
"==",
"\"description\"",
")",
"and",... | True if the user commented the ticket in given time frame | [
"True",
"if",
"the",
"user",
"commented",
"the",
"ticket",
"in",
"given",
"time",
"frame"
] | 04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb | https://github.com/psss/did/blob/04e4ee6f1aa14c0cae3ba9f9803871f3f98279cb/did/plugins/trac.py#L112-L117 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.