repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
huntrar/scrape | scrape/utils.py | get_single_outfilename | def get_single_outfilename(args):
"""Use first possible entry in query as filename."""
for arg in args['query']:
if arg in args['files']:
return ('.'.join(arg.split('.')[:-1])).lower()
for url in args['urls']:
if arg.strip('/') in url:
domain = get_domain(url)
return get_outfilename(url, domain)
sys.stderr.write('Failed to construct a single out filename.\n')
return '' | python | def get_single_outfilename(args):
"""Use first possible entry in query as filename."""
for arg in args['query']:
if arg in args['files']:
return ('.'.join(arg.split('.')[:-1])).lower()
for url in args['urls']:
if arg.strip('/') in url:
domain = get_domain(url)
return get_outfilename(url, domain)
sys.stderr.write('Failed to construct a single out filename.\n')
return '' | [
"def",
"get_single_outfilename",
"(",
"args",
")",
":",
"for",
"arg",
"in",
"args",
"[",
"'query'",
"]",
":",
"if",
"arg",
"in",
"args",
"[",
"'files'",
"]",
":",
"return",
"(",
"'.'",
".",
"join",
"(",
"arg",
".",
"split",
"(",
"'.'",
")",
"[",
... | Use first possible entry in query as filename. | [
"Use",
"first",
"possible",
"entry",
"in",
"query",
"as",
"filename",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L429-L439 | train |
huntrar/scrape | scrape/utils.py | modify_filename_id | def modify_filename_id(filename):
"""Modify filename to have a unique numerical identifier."""
split_filename = os.path.splitext(filename)
id_num_re = re.compile('(\(\d\))')
id_num = re.findall(id_num_re, split_filename[-2])
if id_num:
new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1
# Reconstruct filename with incremented id and its extension
filename = ''.join((re.sub(id_num_re, '({0})'.format(new_id_num),
split_filename[-2]), split_filename[-1]))
else:
split_filename = os.path.splitext(filename)
# Reconstruct filename with new id and its extension
filename = ''.join(('{0} (2)'.format(split_filename[-2]),
split_filename[-1]))
return filename | python | def modify_filename_id(filename):
"""Modify filename to have a unique numerical identifier."""
split_filename = os.path.splitext(filename)
id_num_re = re.compile('(\(\d\))')
id_num = re.findall(id_num_re, split_filename[-2])
if id_num:
new_id_num = int(id_num[-1].lstrip('(').rstrip(')')) + 1
# Reconstruct filename with incremented id and its extension
filename = ''.join((re.sub(id_num_re, '({0})'.format(new_id_num),
split_filename[-2]), split_filename[-1]))
else:
split_filename = os.path.splitext(filename)
# Reconstruct filename with new id and its extension
filename = ''.join(('{0} (2)'.format(split_filename[-2]),
split_filename[-1]))
return filename | [
"def",
"modify_filename_id",
"(",
"filename",
")",
":",
"split_filename",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"id_num_re",
"=",
"re",
".",
"compile",
"(",
"'(\\(\\d\\))'",
")",
"id_num",
"=",
"re",
".",
"findall",
"(",
"id_num_re... | Modify filename to have a unique numerical identifier. | [
"Modify",
"filename",
"to",
"have",
"a",
"unique",
"numerical",
"identifier",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L451-L468 | train |
huntrar/scrape | scrape/utils.py | overwrite_file_check | def overwrite_file_check(args, filename):
"""If filename exists, overwrite or modify it to be unique."""
if not args['overwrite'] and os.path.exists(filename):
# Confirm overwriting of the file, or modify filename
if args['no_overwrite']:
overwrite = False
else:
try:
overwrite = confirm_input(input('Overwrite {0}? (yes/no): '
.format(filename)))
except (KeyboardInterrupt, EOFError):
sys.exit()
if not overwrite:
new_filename = modify_filename_id(filename)
while os.path.exists(new_filename):
new_filename = modify_filename_id(new_filename)
return new_filename
return filename | python | def overwrite_file_check(args, filename):
"""If filename exists, overwrite or modify it to be unique."""
if not args['overwrite'] and os.path.exists(filename):
# Confirm overwriting of the file, or modify filename
if args['no_overwrite']:
overwrite = False
else:
try:
overwrite = confirm_input(input('Overwrite {0}? (yes/no): '
.format(filename)))
except (KeyboardInterrupt, EOFError):
sys.exit()
if not overwrite:
new_filename = modify_filename_id(filename)
while os.path.exists(new_filename):
new_filename = modify_filename_id(new_filename)
return new_filename
return filename | [
"def",
"overwrite_file_check",
"(",
"args",
",",
"filename",
")",
":",
"if",
"not",
"args",
"[",
"'overwrite'",
"]",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"# Confirm overwriting of the file, or modify filename",
"if",
"args",
"[",
... | If filename exists, overwrite or modify it to be unique. | [
"If",
"filename",
"exists",
"overwrite",
"or",
"modify",
"it",
"to",
"be",
"unique",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L471-L488 | train |
huntrar/scrape | scrape/utils.py | print_text | def print_text(args, infilenames, outfilename=None):
"""Print text content of infiles to stdout.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- only used for interface purposes (None)
"""
for infilename in infilenames:
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
for line in parsed_text:
print(line)
print('') | python | def print_text(args, infilenames, outfilename=None):
"""Print text content of infiles to stdout.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- only used for interface purposes (None)
"""
for infilename in infilenames:
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
for line in parsed_text:
print(line)
print('') | [
"def",
"print_text",
"(",
"args",
",",
"infilenames",
",",
"outfilename",
"=",
"None",
")",
":",
"for",
"infilename",
"in",
"infilenames",
":",
"parsed_text",
"=",
"get_parsed_text",
"(",
"args",
",",
"infilename",
")",
"if",
"parsed_text",
":",
"for",
"line... | Print text content of infiles to stdout.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- only used for interface purposes (None) | [
"Print",
"text",
"content",
"of",
"infiles",
"to",
"stdout",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L491-L504 | train |
huntrar/scrape | scrape/utils.py | write_pdf_files | def write_pdf_files(args, infilenames, outfilename):
"""Write pdf file(s) to disk using pdfkit.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output pdf file (str)
"""
if not outfilename.endswith('.pdf'):
outfilename = outfilename + '.pdf'
outfilename = overwrite_file_check(args, outfilename)
options = {}
try:
if args['multiple']:
# Multiple files are written one at a time, so infilenames will
# never contain more than one file here
infilename = infilenames[0]
if not args['quiet']:
print('Attempting to write to {0}.'.format(outfilename))
else:
options['quiet'] = None
if args['xpath']:
# Process HTML with XPath before writing
html = parse_html(read_files(infilename), args['xpath'])
if isinstance(html, list):
if isinstance(html[0], str):
pk.from_string('\n'.join(html), outfilename,
options=options)
else:
pk.from_string('\n'.join(lh.tostring(x) for x in html),
outfilename, options=options)
elif isinstance(html, str):
pk.from_string(html, outfilename, options=options)
else:
pk.from_string(lh.tostring(html), outfilename,
options=options)
else:
pk.from_file(infilename, outfilename, options=options)
elif args['single']:
if not args['quiet']:
print('Attempting to write {0} page(s) to {1}.'
.format(len(infilenames), outfilename))
else:
options['quiet'] = None
if args['xpath']:
# Process HTML with XPath before writing
html = parse_html(read_files(infilenames), args['xpath'])
if isinstance(html, list):
if isinstance(html[0], str):
pk.from_string('\n'.join(html), outfilename,
options=options)
else:
pk.from_string('\n'.join(lh.tostring(x) for x in html),
outfilename, options=options)
elif isinstance(html, str):
pk.from_string(html, outfilename, options=options)
else:
pk.from_string(lh.tostring(html), outfilename,
options=options)
else:
pk.from_file(infilenames, outfilename, options=options)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
return False | python | def write_pdf_files(args, infilenames, outfilename):
"""Write pdf file(s) to disk using pdfkit.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output pdf file (str)
"""
if not outfilename.endswith('.pdf'):
outfilename = outfilename + '.pdf'
outfilename = overwrite_file_check(args, outfilename)
options = {}
try:
if args['multiple']:
# Multiple files are written one at a time, so infilenames will
# never contain more than one file here
infilename = infilenames[0]
if not args['quiet']:
print('Attempting to write to {0}.'.format(outfilename))
else:
options['quiet'] = None
if args['xpath']:
# Process HTML with XPath before writing
html = parse_html(read_files(infilename), args['xpath'])
if isinstance(html, list):
if isinstance(html[0], str):
pk.from_string('\n'.join(html), outfilename,
options=options)
else:
pk.from_string('\n'.join(lh.tostring(x) for x in html),
outfilename, options=options)
elif isinstance(html, str):
pk.from_string(html, outfilename, options=options)
else:
pk.from_string(lh.tostring(html), outfilename,
options=options)
else:
pk.from_file(infilename, outfilename, options=options)
elif args['single']:
if not args['quiet']:
print('Attempting to write {0} page(s) to {1}.'
.format(len(infilenames), outfilename))
else:
options['quiet'] = None
if args['xpath']:
# Process HTML with XPath before writing
html = parse_html(read_files(infilenames), args['xpath'])
if isinstance(html, list):
if isinstance(html[0], str):
pk.from_string('\n'.join(html), outfilename,
options=options)
else:
pk.from_string('\n'.join(lh.tostring(x) for x in html),
outfilename, options=options)
elif isinstance(html, str):
pk.from_string(html, outfilename, options=options)
else:
pk.from_string(lh.tostring(html), outfilename,
options=options)
else:
pk.from_file(infilenames, outfilename, options=options)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
return False | [
"def",
"write_pdf_files",
"(",
"args",
",",
"infilenames",
",",
"outfilename",
")",
":",
"if",
"not",
"outfilename",
".",
"endswith",
"(",
"'.pdf'",
")",
":",
"outfilename",
"=",
"outfilename",
"+",
"'.pdf'",
"outfilename",
"=",
"overwrite_file_check",
"(",
"a... | Write pdf file(s) to disk using pdfkit.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output pdf file (str) | [
"Write",
"pdf",
"file",
"(",
"s",
")",
"to",
"disk",
"using",
"pdfkit",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L507-L575 | train |
huntrar/scrape | scrape/utils.py | write_csv_files | def write_csv_files(args, infilenames, outfilename):
"""Write csv file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str)
"""
def csv_convert(line):
"""Strip punctuation and insert commas"""
clean_line = []
for word in line.split(' '):
clean_line.append(word.strip(string.punctuation))
return ', '.join(clean_line)
if not outfilename.endswith('.csv'):
outfilename = outfilename + '.csv'
outfilename = overwrite_file_check(args, outfilename)
all_text = [] # Text must be aggregated if writing to a single output file
for i, infilename in enumerate(infilenames):
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
if args['multiple']:
if not args['quiet']:
print('Attempting to write to {0}.'.format(outfilename))
csv_text = [csv_convert(x) for x in parsed_text]
print(csv_text)
write_file(csv_text, outfilename)
elif args['single']:
all_text += parsed_text
# Newline added between multiple files being aggregated
if len(infilenames) > 1 and i < len(infilenames) - 1:
all_text.append('\n')
# Write all text to a single output file
if args['single'] and all_text:
if not args['quiet']:
print('Attempting to write {0} page(s) to {1}.'
.format(len(infilenames), outfilename))
csv_text = [csv_convert(x) for x in all_text]
print(csv_text)
write_file(csv_text, outfilename) | python | def write_csv_files(args, infilenames, outfilename):
"""Write csv file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str)
"""
def csv_convert(line):
"""Strip punctuation and insert commas"""
clean_line = []
for word in line.split(' '):
clean_line.append(word.strip(string.punctuation))
return ', '.join(clean_line)
if not outfilename.endswith('.csv'):
outfilename = outfilename + '.csv'
outfilename = overwrite_file_check(args, outfilename)
all_text = [] # Text must be aggregated if writing to a single output file
for i, infilename in enumerate(infilenames):
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
if args['multiple']:
if not args['quiet']:
print('Attempting to write to {0}.'.format(outfilename))
csv_text = [csv_convert(x) for x in parsed_text]
print(csv_text)
write_file(csv_text, outfilename)
elif args['single']:
all_text += parsed_text
# Newline added between multiple files being aggregated
if len(infilenames) > 1 and i < len(infilenames) - 1:
all_text.append('\n')
# Write all text to a single output file
if args['single'] and all_text:
if not args['quiet']:
print('Attempting to write {0} page(s) to {1}.'
.format(len(infilenames), outfilename))
csv_text = [csv_convert(x) for x in all_text]
print(csv_text)
write_file(csv_text, outfilename) | [
"def",
"write_csv_files",
"(",
"args",
",",
"infilenames",
",",
"outfilename",
")",
":",
"def",
"csv_convert",
"(",
"line",
")",
":",
"\"\"\"Strip punctuation and insert commas\"\"\"",
"clean_line",
"=",
"[",
"]",
"for",
"word",
"in",
"line",
".",
"split",
"(",
... | Write csv file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str) | [
"Write",
"csv",
"file",
"(",
"s",
")",
"to",
"disk",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L578-L622 | train |
huntrar/scrape | scrape/utils.py | write_text_files | def write_text_files(args, infilenames, outfilename):
"""Write text file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str)
"""
if not outfilename.endswith('.txt'):
outfilename = outfilename + '.txt'
outfilename = overwrite_file_check(args, outfilename)
all_text = [] # Text must be aggregated if writing to a single output file
for i, infilename in enumerate(infilenames):
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
if args['multiple']:
if not args['quiet']:
print('Attempting to write to {0}.'.format(outfilename))
write_file(parsed_text, outfilename)
elif args['single']:
all_text += parsed_text
# Newline added between multiple files being aggregated
if len(infilenames) > 1 and i < len(infilenames) - 1:
all_text.append('\n')
# Write all text to a single output file
if args['single'] and all_text:
if not args['quiet']:
print('Attempting to write {0} page(s) to {1}.'
.format(len(infilenames), outfilename))
write_file(all_text, outfilename) | python | def write_text_files(args, infilenames, outfilename):
"""Write text file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str)
"""
if not outfilename.endswith('.txt'):
outfilename = outfilename + '.txt'
outfilename = overwrite_file_check(args, outfilename)
all_text = [] # Text must be aggregated if writing to a single output file
for i, infilename in enumerate(infilenames):
parsed_text = get_parsed_text(args, infilename)
if parsed_text:
if args['multiple']:
if not args['quiet']:
print('Attempting to write to {0}.'.format(outfilename))
write_file(parsed_text, outfilename)
elif args['single']:
all_text += parsed_text
# Newline added between multiple files being aggregated
if len(infilenames) > 1 and i < len(infilenames) - 1:
all_text.append('\n')
# Write all text to a single output file
if args['single'] and all_text:
if not args['quiet']:
print('Attempting to write {0} page(s) to {1}.'
.format(len(infilenames), outfilename))
write_file(all_text, outfilename) | [
"def",
"write_text_files",
"(",
"args",
",",
"infilenames",
",",
"outfilename",
")",
":",
"if",
"not",
"outfilename",
".",
"endswith",
"(",
"'.txt'",
")",
":",
"outfilename",
"=",
"outfilename",
"+",
"'.txt'",
"outfilename",
"=",
"overwrite_file_check",
"(",
"... | Write text file(s) to disk.
Keyword arguments:
args -- program arguments (dict)
infilenames -- names of user-inputted and/or downloaded files (list)
outfilename -- name of output text file (str) | [
"Write",
"text",
"file",
"(",
"s",
")",
"to",
"disk",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L625-L656 | train |
huntrar/scrape | scrape/utils.py | write_file | def write_file(data, outfilename):
"""Write a single file to disk."""
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
return False | python | def write_file(data, outfilename):
"""Write a single file to disk."""
if not data:
return False
try:
with open(outfilename, 'w') as outfile:
for line in data:
if line:
outfile.write(line)
return True
except (OSError, IOError) as err:
sys.stderr.write('An error occurred while writing {0}:\n{1}'
.format(outfilename, str(err)))
return False | [
"def",
"write_file",
"(",
"data",
",",
"outfilename",
")",
":",
"if",
"not",
"data",
":",
"return",
"False",
"try",
":",
"with",
"open",
"(",
"outfilename",
",",
"'w'",
")",
"as",
"outfile",
":",
"for",
"line",
"in",
"data",
":",
"if",
"line",
":",
... | Write a single file to disk. | [
"Write",
"a",
"single",
"file",
"to",
"disk",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L659-L672 | train |
huntrar/scrape | scrape/utils.py | get_num_part_files | def get_num_part_files():
"""Get the number of PART.html files currently saved to disk."""
num_parts = 0
for filename in os.listdir(os.getcwd()):
if filename.startswith('PART') and filename.endswith('.html'):
num_parts += 1
return num_parts | python | def get_num_part_files():
"""Get the number of PART.html files currently saved to disk."""
num_parts = 0
for filename in os.listdir(os.getcwd()):
if filename.startswith('PART') and filename.endswith('.html'):
num_parts += 1
return num_parts | [
"def",
"get_num_part_files",
"(",
")",
":",
"num_parts",
"=",
"0",
"for",
"filename",
"in",
"os",
".",
"listdir",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"'PART'",
")",
"and",
"filename",
".",
"endswith",... | Get the number of PART.html files currently saved to disk. | [
"Get",
"the",
"number",
"of",
"PART",
".",
"html",
"files",
"currently",
"saved",
"to",
"disk",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L675-L681 | train |
huntrar/scrape | scrape/utils.py | write_part_images | def write_part_images(url, raw_html, html, filename):
"""Write image file(s) associated with HTML to disk, substituting filenames.
Keywords arguments:
url -- the URL from which the HTML has been extracted from (str)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file content (lxml.html.HtmlElement) (default: None)
filename -- the PART.html filename (str)
Return raw HTML with image names replaced with local image filenames.
"""
save_dirname = '{0}_files'.format(os.path.splitext(filename)[0])
if not os.path.exists(save_dirname):
os.makedirs(save_dirname)
images = html.xpath('//img/@src')
internal_image_urls = [x for x in images if x.startswith('/')]
headers = {'User-Agent': random.choice(USER_AGENTS)}
for img_url in images:
img_name = img_url.split('/')[-1]
if "?" in img_name:
img_name = img_name.split('?')[0]
if not os.path.splitext(img_name)[1]:
img_name = '{0}.jpeg'.format(img_name)
try:
full_img_name = os.path.join(save_dirname, img_name)
with open(full_img_name, 'wb') as img:
if img_url in internal_image_urls:
# Internal images need base url added
full_img_url = '{0}{1}'.format(url.rstrip('/'), img_url)
else:
# External image
full_img_url = img_url
img_content = requests.get(full_img_url, headers=headers,
proxies=get_proxies()).content
img.write(img_content)
raw_html = raw_html.replace(escape(img_url), full_img_name)
except (OSError, IOError):
pass
time.sleep(random.uniform(0, 0.5)) # Slight delay between downloads
return raw_html | python | def write_part_images(url, raw_html, html, filename):
"""Write image file(s) associated with HTML to disk, substituting filenames.
Keywords arguments:
url -- the URL from which the HTML has been extracted from (str)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file content (lxml.html.HtmlElement) (default: None)
filename -- the PART.html filename (str)
Return raw HTML with image names replaced with local image filenames.
"""
save_dirname = '{0}_files'.format(os.path.splitext(filename)[0])
if not os.path.exists(save_dirname):
os.makedirs(save_dirname)
images = html.xpath('//img/@src')
internal_image_urls = [x for x in images if x.startswith('/')]
headers = {'User-Agent': random.choice(USER_AGENTS)}
for img_url in images:
img_name = img_url.split('/')[-1]
if "?" in img_name:
img_name = img_name.split('?')[0]
if not os.path.splitext(img_name)[1]:
img_name = '{0}.jpeg'.format(img_name)
try:
full_img_name = os.path.join(save_dirname, img_name)
with open(full_img_name, 'wb') as img:
if img_url in internal_image_urls:
# Internal images need base url added
full_img_url = '{0}{1}'.format(url.rstrip('/'), img_url)
else:
# External image
full_img_url = img_url
img_content = requests.get(full_img_url, headers=headers,
proxies=get_proxies()).content
img.write(img_content)
raw_html = raw_html.replace(escape(img_url), full_img_name)
except (OSError, IOError):
pass
time.sleep(random.uniform(0, 0.5)) # Slight delay between downloads
return raw_html | [
"def",
"write_part_images",
"(",
"url",
",",
"raw_html",
",",
"html",
",",
"filename",
")",
":",
"save_dirname",
"=",
"'{0}_files'",
".",
"format",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
")",
"if",
"not",
"os",
... | Write image file(s) associated with HTML to disk, substituting filenames.
Keywords arguments:
url -- the URL from which the HTML has been extracted from (str)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file content (lxml.html.HtmlElement) (default: None)
filename -- the PART.html filename (str)
Return raw HTML with image names replaced with local image filenames. | [
"Write",
"image",
"file",
"(",
"s",
")",
"associated",
"with",
"HTML",
"to",
"disk",
"substituting",
"filenames",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L684-L725 | train |
huntrar/scrape | scrape/utils.py | write_part_file | def write_part_file(args, url, raw_html, html=None, part_num=None):
"""Write PART.html file(s) to disk, images in PART_files directory.
Keyword arguments:
args -- program arguments (dict)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file content (lxml.html.HtmlElement) (default: None)
part_num -- PART(#).html file number (int) (default: None)
"""
if part_num is None:
part_num = get_num_part_files() + 1
filename = 'PART{0}.html'.format(part_num)
# Decode bytes to string in Python 3 versions
if not PY2 and isinstance(raw_html, bytes):
raw_html = raw_html.encode('ascii', 'ignore')
# Convert html to an lh.HtmlElement object for parsing/saving images
if html is None:
html = lh.fromstring(raw_html)
# Parse HTML if XPath entered
if args['xpath']:
raw_html = parse_html(html, args['xpath'])
if isinstance(raw_html, list):
if not isinstance(raw_html[0], lh.HtmlElement):
raise ValueError('XPath should return an HtmlElement object.')
else:
if not isinstance(raw_html, lh.HtmlElement):
raise ValueError('XPath should return an HtmlElement object.')
# Write HTML and possibly images to disk
if raw_html:
if not args['no_images'] and (args['pdf'] or args['html']):
raw_html = write_part_images(url, raw_html, html, filename)
with open(filename, 'w') as part:
if not isinstance(raw_html, list):
raw_html = [raw_html]
if isinstance(raw_html[0], lh.HtmlElement):
for elem in raw_html:
part.write(lh.tostring(elem))
else:
for line in raw_html:
part.write(line) | python | def write_part_file(args, url, raw_html, html=None, part_num=None):
"""Write PART.html file(s) to disk, images in PART_files directory.
Keyword arguments:
args -- program arguments (dict)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file content (lxml.html.HtmlElement) (default: None)
part_num -- PART(#).html file number (int) (default: None)
"""
if part_num is None:
part_num = get_num_part_files() + 1
filename = 'PART{0}.html'.format(part_num)
# Decode bytes to string in Python 3 versions
if not PY2 and isinstance(raw_html, bytes):
raw_html = raw_html.encode('ascii', 'ignore')
# Convert html to an lh.HtmlElement object for parsing/saving images
if html is None:
html = lh.fromstring(raw_html)
# Parse HTML if XPath entered
if args['xpath']:
raw_html = parse_html(html, args['xpath'])
if isinstance(raw_html, list):
if not isinstance(raw_html[0], lh.HtmlElement):
raise ValueError('XPath should return an HtmlElement object.')
else:
if not isinstance(raw_html, lh.HtmlElement):
raise ValueError('XPath should return an HtmlElement object.')
# Write HTML and possibly images to disk
if raw_html:
if not args['no_images'] and (args['pdf'] or args['html']):
raw_html = write_part_images(url, raw_html, html, filename)
with open(filename, 'w') as part:
if not isinstance(raw_html, list):
raw_html = [raw_html]
if isinstance(raw_html[0], lh.HtmlElement):
for elem in raw_html:
part.write(lh.tostring(elem))
else:
for line in raw_html:
part.write(line) | [
"def",
"write_part_file",
"(",
"args",
",",
"url",
",",
"raw_html",
",",
"html",
"=",
"None",
",",
"part_num",
"=",
"None",
")",
":",
"if",
"part_num",
"is",
"None",
":",
"part_num",
"=",
"get_num_part_files",
"(",
")",
"+",
"1",
"filename",
"=",
"'PAR... | Write PART.html file(s) to disk, images in PART_files directory.
Keyword arguments:
args -- program arguments (dict)
raw_html -- unparsed HTML file content (list)
html -- parsed HTML file content (lxml.html.HtmlElement) (default: None)
part_num -- PART(#).html file number (int) (default: None) | [
"Write",
"PART",
".",
"html",
"file",
"(",
"s",
")",
"to",
"disk",
"images",
"in",
"PART_files",
"directory",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L728-L771 | train |
huntrar/scrape | scrape/utils.py | get_part_filenames | def get_part_filenames(num_parts=None, start_num=0):
"""Get numbered PART.html filenames."""
if num_parts is None:
num_parts = get_num_part_files()
return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+1)] | python | def get_part_filenames(num_parts=None, start_num=0):
"""Get numbered PART.html filenames."""
if num_parts is None:
num_parts = get_num_part_files()
return ['PART{0}.html'.format(i) for i in range(start_num+1, num_parts+1)] | [
"def",
"get_part_filenames",
"(",
"num_parts",
"=",
"None",
",",
"start_num",
"=",
"0",
")",
":",
"if",
"num_parts",
"is",
"None",
":",
"num_parts",
"=",
"get_num_part_files",
"(",
")",
"return",
"[",
"'PART{0}.html'",
".",
"format",
"(",
"i",
")",
"for",
... | Get numbered PART.html filenames. | [
"Get",
"numbered",
"PART",
".",
"html",
"filenames",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L774-L778 | train |
huntrar/scrape | scrape/utils.py | read_files | def read_files(filenames):
"""Read a file into memory."""
if isinstance(filenames, list):
for filename in filenames:
with open(filename, 'r') as infile:
return infile.read()
else:
with open(filenames, 'r') as infile:
return infile.read() | python | def read_files(filenames):
"""Read a file into memory."""
if isinstance(filenames, list):
for filename in filenames:
with open(filename, 'r') as infile:
return infile.read()
else:
with open(filenames, 'r') as infile:
return infile.read() | [
"def",
"read_files",
"(",
"filenames",
")",
":",
"if",
"isinstance",
"(",
"filenames",
",",
"list",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"infile",
":",
"return",
"infile",
".",
"re... | Read a file into memory. | [
"Read",
"a",
"file",
"into",
"memory",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L781-L789 | train |
huntrar/scrape | scrape/utils.py | remove_part_images | def remove_part_images(filename):
"""Remove PART(#)_files directory containing images from disk."""
dirname = '{0}_files'.format(os.path.splitext(filename)[0])
if os.path.exists(dirname):
shutil.rmtree(dirname) | python | def remove_part_images(filename):
"""Remove PART(#)_files directory containing images from disk."""
dirname = '{0}_files'.format(os.path.splitext(filename)[0])
if os.path.exists(dirname):
shutil.rmtree(dirname) | [
"def",
"remove_part_images",
"(",
"filename",
")",
":",
"dirname",
"=",
"'{0}_files'",
".",
"format",
"(",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"[",
"0",
"]",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",... | Remove PART(#)_files directory containing images from disk. | [
"Remove",
"PART",
"(",
"#",
")",
"_files",
"directory",
"containing",
"images",
"from",
"disk",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L792-L796 | train |
huntrar/scrape | scrape/utils.py | remove_part_files | def remove_part_files(num_parts=None):
"""Remove PART(#).html files and image directories from disk."""
filenames = get_part_filenames(num_parts)
for filename in filenames:
remove_part_images(filename)
remove_file(filename) | python | def remove_part_files(num_parts=None):
"""Remove PART(#).html files and image directories from disk."""
filenames = get_part_filenames(num_parts)
for filename in filenames:
remove_part_images(filename)
remove_file(filename) | [
"def",
"remove_part_files",
"(",
"num_parts",
"=",
"None",
")",
":",
"filenames",
"=",
"get_part_filenames",
"(",
"num_parts",
")",
"for",
"filename",
"in",
"filenames",
":",
"remove_part_images",
"(",
"filename",
")",
"remove_file",
"(",
"filename",
")"
] | Remove PART(#).html files and image directories from disk. | [
"Remove",
"PART",
"(",
"#",
")",
".",
"html",
"files",
"and",
"image",
"directories",
"from",
"disk",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L799-L804 | train |
huntrar/scrape | scrape/utils.py | confirm_input | def confirm_input(user_input):
"""Check user input for yes, no, or an exit signal."""
if isinstance(user_input, list):
user_input = ''.join(user_input)
try:
u_inp = user_input.lower().strip()
except AttributeError:
u_inp = user_input
# Check for exit signal
if u_inp in ('q', 'quit', 'exit'):
sys.exit()
if u_inp in ('y', 'yes'):
return True
return False | python | def confirm_input(user_input):
"""Check user input for yes, no, or an exit signal."""
if isinstance(user_input, list):
user_input = ''.join(user_input)
try:
u_inp = user_input.lower().strip()
except AttributeError:
u_inp = user_input
# Check for exit signal
if u_inp in ('q', 'quit', 'exit'):
sys.exit()
if u_inp in ('y', 'yes'):
return True
return False | [
"def",
"confirm_input",
"(",
"user_input",
")",
":",
"if",
"isinstance",
"(",
"user_input",
",",
"list",
")",
":",
"user_input",
"=",
"''",
".",
"join",
"(",
"user_input",
")",
"try",
":",
"u_inp",
"=",
"user_input",
".",
"lower",
"(",
")",
".",
"strip... | Check user input for yes, no, or an exit signal. | [
"Check",
"user",
"input",
"for",
"yes",
"no",
"or",
"an",
"exit",
"signal",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L810-L825 | train |
huntrar/scrape | scrape/utils.py | mkdir_and_cd | def mkdir_and_cd(dirname):
"""Change directory and/or create it if necessary."""
if not os.path.exists(dirname):
os.makedirs(dirname)
os.chdir(dirname)
else:
os.chdir(dirname) | python | def mkdir_and_cd(dirname):
"""Change directory and/or create it if necessary."""
if not os.path.exists(dirname):
os.makedirs(dirname)
os.chdir(dirname)
else:
os.chdir(dirname) | [
"def",
"mkdir_and_cd",
"(",
"dirname",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"os",
".",
"chdir",
"(",
"dirname",
")",
"else",
":",
"os",
".",
"chdir",
"(",
"... | Change directory and/or create it if necessary. | [
"Change",
"directory",
"and",
"/",
"or",
"create",
"it",
"if",
"necessary",
"."
] | bf877f6da5df3ed0f2bea60a95acf7df63c88002 | https://github.com/huntrar/scrape/blob/bf877f6da5df3ed0f2bea60a95acf7df63c88002/scrape/utils.py#L831-L837 | train |
patrickfuller/imolecule | imolecule/format_converter.py | convert | def convert(data, in_format, out_format, name=None, pretty=False):
"""Converts between two inputted chemical formats.
Args:
data: A string representing the chemical file to be converted. If the
`in_format` is "json", this can also be a Python object
in_format: The format of the `data` string. Can be "json" or any format
recognized by Open Babel
out_format: The format to convert to. Can be "json" or any format
recognized by Open Babel
name: (Optional) If `out_format` is "json", will save the specified
value in a "name" property
pretty: (Optional) If True and `out_format` is "json", will pretty-
print the output for human readability
Returns:
A string representing the inputted `data` in the specified `out_format`
"""
# Decide on a json formatter depending on desired prettiness
dumps = json.dumps if pretty else json.compress
# Shortcut for avoiding pybel dependency
if not has_ob and in_format == 'json' and out_format == 'json':
return dumps(json.loads(data) if is_string(data) else data)
elif not has_ob:
raise ImportError("Chemical file format conversion requires pybel.")
# These use the open babel library to interconvert, with additions for json
if in_format == 'json':
mol = json_to_pybel(json.loads(data) if is_string(data) else data)
elif in_format == 'pybel':
mol = data
else:
mol = pybel.readstring(in_format, data)
# Infer structure in cases where the input format has no specification
if not mol.OBMol.HasNonZeroCoords():
mol.make3D()
# Make P1 if that's a thing, recalculating bonds in process
if in_format == 'mmcif' and hasattr(mol, 'unitcell'):
mol.unitcell.FillUnitCell(mol.OBMol)
mol.OBMol.ConnectTheDots()
mol.OBMol.PerceiveBondOrders()
mol.OBMol.Center()
if out_format == 'pybel':
return mol
elif out_format == 'object':
return pybel_to_json(mol, name)
elif out_format == 'json':
return dumps(pybel_to_json(mol, name))
else:
return mol.write(out_format) | python | def convert(data, in_format, out_format, name=None, pretty=False):
"""Converts between two inputted chemical formats.
Args:
data: A string representing the chemical file to be converted. If the
`in_format` is "json", this can also be a Python object
in_format: The format of the `data` string. Can be "json" or any format
recognized by Open Babel
out_format: The format to convert to. Can be "json" or any format
recognized by Open Babel
name: (Optional) If `out_format` is "json", will save the specified
value in a "name" property
pretty: (Optional) If True and `out_format` is "json", will pretty-
print the output for human readability
Returns:
A string representing the inputted `data` in the specified `out_format`
"""
# Decide on a json formatter depending on desired prettiness
dumps = json.dumps if pretty else json.compress
# Shortcut for avoiding pybel dependency
if not has_ob and in_format == 'json' and out_format == 'json':
return dumps(json.loads(data) if is_string(data) else data)
elif not has_ob:
raise ImportError("Chemical file format conversion requires pybel.")
# These use the open babel library to interconvert, with additions for json
if in_format == 'json':
mol = json_to_pybel(json.loads(data) if is_string(data) else data)
elif in_format == 'pybel':
mol = data
else:
mol = pybel.readstring(in_format, data)
# Infer structure in cases where the input format has no specification
if not mol.OBMol.HasNonZeroCoords():
mol.make3D()
# Make P1 if that's a thing, recalculating bonds in process
if in_format == 'mmcif' and hasattr(mol, 'unitcell'):
mol.unitcell.FillUnitCell(mol.OBMol)
mol.OBMol.ConnectTheDots()
mol.OBMol.PerceiveBondOrders()
mol.OBMol.Center()
if out_format == 'pybel':
return mol
elif out_format == 'object':
return pybel_to_json(mol, name)
elif out_format == 'json':
return dumps(pybel_to_json(mol, name))
else:
return mol.write(out_format) | [
"def",
"convert",
"(",
"data",
",",
"in_format",
",",
"out_format",
",",
"name",
"=",
"None",
",",
"pretty",
"=",
"False",
")",
":",
"# Decide on a json formatter depending on desired prettiness",
"dumps",
"=",
"json",
".",
"dumps",
"if",
"pretty",
"else",
"json... | Converts between two inputted chemical formats.
Args:
data: A string representing the chemical file to be converted. If the
`in_format` is "json", this can also be a Python object
in_format: The format of the `data` string. Can be "json" or any format
recognized by Open Babel
out_format: The format to convert to. Can be "json" or any format
recognized by Open Babel
name: (Optional) If `out_format` is "json", will save the specified
value in a "name" property
pretty: (Optional) If True and `out_format` is "json", will pretty-
print the output for human readability
Returns:
A string representing the inputted `data` in the specified `out_format` | [
"Converts",
"between",
"two",
"inputted",
"chemical",
"formats",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/format_converter.py#L19-L72 | train |
patrickfuller/imolecule | imolecule/format_converter.py | json_to_pybel | def json_to_pybel(data, infer_bonds=False):
"""Converts python data structure to pybel.Molecule.
This will infer bond data if not specified.
Args:
data: The loaded json data of a molecule, as a Python object
infer_bonds (Optional): If no bonds specified in input, infer them
Returns:
An instance of `pybel.Molecule`
"""
obmol = ob.OBMol()
obmol.BeginModify()
for atom in data['atoms']:
obatom = obmol.NewAtom()
obatom.SetAtomicNum(table.GetAtomicNum(str(atom['element'])))
obatom.SetVector(*atom['location'])
if 'label' in atom:
pd = ob.OBPairData()
pd.SetAttribute('_atom_site_label')
pd.SetValue(atom['label'])
obatom.CloneData(pd)
# If there is no bond data, try to infer them
if 'bonds' not in data or not data['bonds']:
if infer_bonds:
obmol.ConnectTheDots()
obmol.PerceiveBondOrders()
# Otherwise, use the bonds in the data set
else:
for bond in data['bonds']:
if 'atoms' not in bond:
continue
obmol.AddBond(bond['atoms'][0] + 1, bond['atoms'][1] + 1,
bond['order'])
# Check for unit cell data
if 'unitcell' in data:
uc = ob.OBUnitCell()
uc.SetData(*(ob.vector3(*v) for v in data['unitcell']))
uc.SetSpaceGroup('P1')
obmol.CloneData(uc)
obmol.EndModify()
mol = pybel.Molecule(obmol)
# Add partial charges
if 'charge' in data['atoms'][0]:
mol.OBMol.SetPartialChargesPerceived()
for atom, pyatom in zip(data['atoms'], mol.atoms):
pyatom.OBAtom.SetPartialCharge(atom['charge'])
return mol | python | def json_to_pybel(data, infer_bonds=False):
"""Converts python data structure to pybel.Molecule.
This will infer bond data if not specified.
Args:
data: The loaded json data of a molecule, as a Python object
infer_bonds (Optional): If no bonds specified in input, infer them
Returns:
An instance of `pybel.Molecule`
"""
obmol = ob.OBMol()
obmol.BeginModify()
for atom in data['atoms']:
obatom = obmol.NewAtom()
obatom.SetAtomicNum(table.GetAtomicNum(str(atom['element'])))
obatom.SetVector(*atom['location'])
if 'label' in atom:
pd = ob.OBPairData()
pd.SetAttribute('_atom_site_label')
pd.SetValue(atom['label'])
obatom.CloneData(pd)
# If there is no bond data, try to infer them
if 'bonds' not in data or not data['bonds']:
if infer_bonds:
obmol.ConnectTheDots()
obmol.PerceiveBondOrders()
# Otherwise, use the bonds in the data set
else:
for bond in data['bonds']:
if 'atoms' not in bond:
continue
obmol.AddBond(bond['atoms'][0] + 1, bond['atoms'][1] + 1,
bond['order'])
# Check for unit cell data
if 'unitcell' in data:
uc = ob.OBUnitCell()
uc.SetData(*(ob.vector3(*v) for v in data['unitcell']))
uc.SetSpaceGroup('P1')
obmol.CloneData(uc)
obmol.EndModify()
mol = pybel.Molecule(obmol)
# Add partial charges
if 'charge' in data['atoms'][0]:
mol.OBMol.SetPartialChargesPerceived()
for atom, pyatom in zip(data['atoms'], mol.atoms):
pyatom.OBAtom.SetPartialCharge(atom['charge'])
return mol | [
"def",
"json_to_pybel",
"(",
"data",
",",
"infer_bonds",
"=",
"False",
")",
":",
"obmol",
"=",
"ob",
".",
"OBMol",
"(",
")",
"obmol",
".",
"BeginModify",
"(",
")",
"for",
"atom",
"in",
"data",
"[",
"'atoms'",
"]",
":",
"obatom",
"=",
"obmol",
".",
... | Converts python data structure to pybel.Molecule.
This will infer bond data if not specified.
Args:
data: The loaded json data of a molecule, as a Python object
infer_bonds (Optional): If no bonds specified in input, infer them
Returns:
An instance of `pybel.Molecule` | [
"Converts",
"python",
"data",
"structure",
"to",
"pybel",
".",
"Molecule",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/format_converter.py#L75-L127 | train |
patrickfuller/imolecule | imolecule/format_converter.py | pybel_to_json | def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
"""
# Save atom element type and 3D location.
atoms = [{'element': table.GetSymbol(atom.atomicnum),
'location': list(atom.coords)}
for atom in molecule.atoms]
# Recover auxiliary data, if exists
for json_atom, pybel_atom in zip(atoms, molecule.atoms):
if pybel_atom.partialcharge != 0:
json_atom['charge'] = pybel_atom.partialcharge
if pybel_atom.OBAtom.HasData('_atom_site_label'):
obatom = pybel_atom.OBAtom
json_atom['label'] = obatom.GetData('_atom_site_label').GetValue()
if pybel_atom.OBAtom.HasData('color'):
obatom = pybel_atom.OBAtom
json_atom['color'] = obatom.GetData('color').GetValue()
# Save number of bonds and indices of endpoint atoms
bonds = [{'atoms': [b.GetBeginAtom().GetIndex(),
b.GetEndAtom().GetIndex()],
'order': b.GetBondOrder()}
for b in ob.OBMolBondIter(molecule.OBMol)]
output = {'atoms': atoms, 'bonds': bonds, 'units': {}}
# If there's unit cell data, save it to the json output
if hasattr(molecule, 'unitcell'):
uc = molecule.unitcell
output['unitcell'] = [[v.GetX(), v.GetY(), v.GetZ()]
for v in uc.GetCellVectors()]
density = (sum(atom.atomicmass for atom in molecule.atoms) /
(uc.GetCellVolume() * 0.6022))
output['density'] = density
output['units']['density'] = 'kg / L'
# Save the formula to json. Use Hill notation, just to have a standard.
element_count = Counter(table.GetSymbol(a.atomicnum) for a in molecule)
hill_count = []
for element in ['C', 'H']:
if element in element_count:
hill_count += [(element, element_count[element])]
del element_count[element]
hill_count += sorted(element_count.items())
# If it's a crystal, then reduce the Hill formula
div = (reduce(gcd, (c[1] for c in hill_count))
if hasattr(molecule, 'unitcell') else 1)
output['formula'] = ''.join(n if c / div == 1 else '%s%d' % (n, c / div)
for n, c in hill_count)
output['molecular_weight'] = molecule.molwt / div
output['units']['molecular_weight'] = 'g / mol'
# If the input has been given a name, add that
if name:
output['name'] = name
return output | python | def pybel_to_json(molecule, name=None):
"""Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data
"""
# Save atom element type and 3D location.
atoms = [{'element': table.GetSymbol(atom.atomicnum),
'location': list(atom.coords)}
for atom in molecule.atoms]
# Recover auxiliary data, if exists
for json_atom, pybel_atom in zip(atoms, molecule.atoms):
if pybel_atom.partialcharge != 0:
json_atom['charge'] = pybel_atom.partialcharge
if pybel_atom.OBAtom.HasData('_atom_site_label'):
obatom = pybel_atom.OBAtom
json_atom['label'] = obatom.GetData('_atom_site_label').GetValue()
if pybel_atom.OBAtom.HasData('color'):
obatom = pybel_atom.OBAtom
json_atom['color'] = obatom.GetData('color').GetValue()
# Save number of bonds and indices of endpoint atoms
bonds = [{'atoms': [b.GetBeginAtom().GetIndex(),
b.GetEndAtom().GetIndex()],
'order': b.GetBondOrder()}
for b in ob.OBMolBondIter(molecule.OBMol)]
output = {'atoms': atoms, 'bonds': bonds, 'units': {}}
# If there's unit cell data, save it to the json output
if hasattr(molecule, 'unitcell'):
uc = molecule.unitcell
output['unitcell'] = [[v.GetX(), v.GetY(), v.GetZ()]
for v in uc.GetCellVectors()]
density = (sum(atom.atomicmass for atom in molecule.atoms) /
(uc.GetCellVolume() * 0.6022))
output['density'] = density
output['units']['density'] = 'kg / L'
# Save the formula to json. Use Hill notation, just to have a standard.
element_count = Counter(table.GetSymbol(a.atomicnum) for a in molecule)
hill_count = []
for element in ['C', 'H']:
if element in element_count:
hill_count += [(element, element_count[element])]
del element_count[element]
hill_count += sorted(element_count.items())
# If it's a crystal, then reduce the Hill formula
div = (reduce(gcd, (c[1] for c in hill_count))
if hasattr(molecule, 'unitcell') else 1)
output['formula'] = ''.join(n if c / div == 1 else '%s%d' % (n, c / div)
for n, c in hill_count)
output['molecular_weight'] = molecule.molwt / div
output['units']['molecular_weight'] = 'g / mol'
# If the input has been given a name, add that
if name:
output['name'] = name
return output | [
"def",
"pybel_to_json",
"(",
"molecule",
",",
"name",
"=",
"None",
")",
":",
"# Save atom element type and 3D location.",
"atoms",
"=",
"[",
"{",
"'element'",
":",
"table",
".",
"GetSymbol",
"(",
"atom",
".",
"atomicnum",
")",
",",
"'location'",
":",
"list",
... | Converts a pybel molecule to json.
Args:
molecule: An instance of `pybel.Molecule`
name: (Optional) If specified, will save a "name" property
Returns:
A Python dictionary containing atom and bond data | [
"Converts",
"a",
"pybel",
"molecule",
"to",
"json",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/format_converter.py#L130-L193 | train |
patrickfuller/imolecule | imolecule/json_formatter.py | CustomEncoder.default | def default(self, obj):
"""Fired when an unserializable object is hit."""
if hasattr(obj, '__dict__'):
return obj.__dict__.copy()
elif HAS_NUMPY and isinstance(obj, np.ndarray):
return obj.copy().tolist()
else:
raise TypeError(("Object of type {:s} with value of {:s} is not "
"JSON serializable").format(type(obj), repr(obj))) | python | def default(self, obj):
"""Fired when an unserializable object is hit."""
if hasattr(obj, '__dict__'):
return obj.__dict__.copy()
elif HAS_NUMPY and isinstance(obj, np.ndarray):
return obj.copy().tolist()
else:
raise TypeError(("Object of type {:s} with value of {:s} is not "
"JSON serializable").format(type(obj), repr(obj))) | [
"def",
"default",
"(",
"self",
",",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'__dict__'",
")",
":",
"return",
"obj",
".",
"__dict__",
".",
"copy",
"(",
")",
"elif",
"HAS_NUMPY",
"and",
"isinstance",
"(",
"obj",
",",
"np",
".",
"ndarray",
... | Fired when an unserializable object is hit. | [
"Fired",
"when",
"an",
"unserializable",
"object",
"is",
"hit",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/json_formatter.py#L37-L45 | train |
patrickfuller/imolecule | imolecule/notebook.py | draw | def draw(data, format='auto', size=(400, 300), drawing_type='ball and stick',
camera_type='perspective', shader='lambert', display_html=True,
element_properties=None, show_save=False):
"""Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file representing a chemical.
format: The format of the `data` variable (default is 'auto').
size: Starting dimensions of visualization, in pixels.
drawing_type: Specifies the molecular representation. Can be 'ball and
stick', 'wireframe', or 'space filling'.
camera_type: Can be 'perspective' or 'orthographic'.
shader: Specifies shading algorithm to use. Can be 'toon', 'basic',
'phong', or 'lambert'.
display_html: If True (default), embed the html in a IPython display.
If False, return the html as a string.
element_properites: A dictionary providing color and radius information
for custom elements or overriding the defaults in imolecule.js
show_save: If True, displays a save icon for rendering molecule as an
image.
The `format` can be any value specified by Open Babel
(http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'
option uses the extension for files (ie. my_file.mol -> mol) and defaults
to SMILES (smi) for strings.
"""
# Catch errors on string-based input before getting js involved
draw_options = ['ball and stick', 'wireframe', 'space filling']
camera_options = ['perspective', 'orthographic']
shader_options = ['toon', 'basic', 'phong', 'lambert']
if drawing_type not in draw_options:
raise Exception("Invalid drawing type! Please use one of: " +
", ".join(draw_options))
if camera_type not in camera_options:
raise Exception("Invalid camera type! Please use one of: " +
", ".join(camera_options))
if shader not in shader_options:
raise Exception("Invalid shader! Please use one of: " +
", ".join(shader_options))
json_mol = generate(data, format)
if element_properties is None:
element_properties = dict()
json_element_properties = to_json(element_properties)
div_id = uuid.uuid4()
html = """<div id="molecule_%s"></div>
<script type="text/javascript">
require.config({baseUrl: '/',
paths: {imolecule: ['%s', '%s']}});
require(['imolecule'], function () {
var $d = $('#molecule_%s');
$d.width(%d); $d.height(%d);
$d.imolecule = jQuery.extend({}, imolecule);
$d.imolecule.create($d, {drawingType: '%s',
cameraType: '%s',
shader: '%s',
showSave: %s});
$d.imolecule.addElements(%s);
$d.imolecule.draw(%s);
$d.resizable({
aspectRatio: %d / %d,
resize: function (evt, ui) {
$d.imolecule.renderer.setSize(ui.size.width,
ui.size.height);
}
});
});
</script>""" % (div_id, local_path[:-3], remote_path[:-3],
div_id, size[0], size[1], drawing_type,
camera_type, shader,
'true' if show_save else 'false',
json_element_properties,
json_mol, size[0], size[1])
# Execute js and display the results in a div (see script for more)
if display_html:
try:
__IPYTHON__
except NameError:
# We're running outside ipython, let's generate a static HTML and
# show it in the browser
import shutil
import webbrowser
from tempfile import mkdtemp
from time import time
try: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
except ImportError: # Python 2
from urlparse import urljoin
from urllib import pathname2url
from tornado import template
t = template.Loader(file_path).load('viewer.template')
html = t.generate(title="imolecule", json_mol=json_mol,
drawing_type=drawing_type, shader=shader,
camera_type=camera_type,
json_element_properties=json_element_properties)
tempdir = mkdtemp(prefix='imolecule_{:.0f}_'.format(time()))
html_filename = os.path.join(tempdir, 'index.html')
with open(html_filename, 'wb') as f:
f.write(html)
libs = (('server', 'css', 'chosen.css'),
('server', 'css', 'server.css'),
('js', 'jquery-1.11.1.min.js'),
('server', 'js', 'chosen.jquery.min.js'),
('js', 'build', 'imolecule.min.js'))
for lib in libs:
shutil.copy(os.path.join(file_path, *lib), tempdir)
html_file_url = urljoin('file:', pathname2url(html_filename))
print('Opening html file: {}'.format(html_file_url))
webbrowser.open(html_file_url)
else:
# We're running in ipython: display widget
display(HTML(html))
else:
return html | python | def draw(data, format='auto', size=(400, 300), drawing_type='ball and stick',
camera_type='perspective', shader='lambert', display_html=True,
element_properties=None, show_save=False):
"""Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file representing a chemical.
format: The format of the `data` variable (default is 'auto').
size: Starting dimensions of visualization, in pixels.
drawing_type: Specifies the molecular representation. Can be 'ball and
stick', 'wireframe', or 'space filling'.
camera_type: Can be 'perspective' or 'orthographic'.
shader: Specifies shading algorithm to use. Can be 'toon', 'basic',
'phong', or 'lambert'.
display_html: If True (default), embed the html in a IPython display.
If False, return the html as a string.
element_properites: A dictionary providing color and radius information
for custom elements or overriding the defaults in imolecule.js
show_save: If True, displays a save icon for rendering molecule as an
image.
The `format` can be any value specified by Open Babel
(http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'
option uses the extension for files (ie. my_file.mol -> mol) and defaults
to SMILES (smi) for strings.
"""
# Catch errors on string-based input before getting js involved
draw_options = ['ball and stick', 'wireframe', 'space filling']
camera_options = ['perspective', 'orthographic']
shader_options = ['toon', 'basic', 'phong', 'lambert']
if drawing_type not in draw_options:
raise Exception("Invalid drawing type! Please use one of: " +
", ".join(draw_options))
if camera_type not in camera_options:
raise Exception("Invalid camera type! Please use one of: " +
", ".join(camera_options))
if shader not in shader_options:
raise Exception("Invalid shader! Please use one of: " +
", ".join(shader_options))
json_mol = generate(data, format)
if element_properties is None:
element_properties = dict()
json_element_properties = to_json(element_properties)
div_id = uuid.uuid4()
html = """<div id="molecule_%s"></div>
<script type="text/javascript">
require.config({baseUrl: '/',
paths: {imolecule: ['%s', '%s']}});
require(['imolecule'], function () {
var $d = $('#molecule_%s');
$d.width(%d); $d.height(%d);
$d.imolecule = jQuery.extend({}, imolecule);
$d.imolecule.create($d, {drawingType: '%s',
cameraType: '%s',
shader: '%s',
showSave: %s});
$d.imolecule.addElements(%s);
$d.imolecule.draw(%s);
$d.resizable({
aspectRatio: %d / %d,
resize: function (evt, ui) {
$d.imolecule.renderer.setSize(ui.size.width,
ui.size.height);
}
});
});
</script>""" % (div_id, local_path[:-3], remote_path[:-3],
div_id, size[0], size[1], drawing_type,
camera_type, shader,
'true' if show_save else 'false',
json_element_properties,
json_mol, size[0], size[1])
# Execute js and display the results in a div (see script for more)
if display_html:
try:
__IPYTHON__
except NameError:
# We're running outside ipython, let's generate a static HTML and
# show it in the browser
import shutil
import webbrowser
from tempfile import mkdtemp
from time import time
try: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
except ImportError: # Python 2
from urlparse import urljoin
from urllib import pathname2url
from tornado import template
t = template.Loader(file_path).load('viewer.template')
html = t.generate(title="imolecule", json_mol=json_mol,
drawing_type=drawing_type, shader=shader,
camera_type=camera_type,
json_element_properties=json_element_properties)
tempdir = mkdtemp(prefix='imolecule_{:.0f}_'.format(time()))
html_filename = os.path.join(tempdir, 'index.html')
with open(html_filename, 'wb') as f:
f.write(html)
libs = (('server', 'css', 'chosen.css'),
('server', 'css', 'server.css'),
('js', 'jquery-1.11.1.min.js'),
('server', 'js', 'chosen.jquery.min.js'),
('js', 'build', 'imolecule.min.js'))
for lib in libs:
shutil.copy(os.path.join(file_path, *lib), tempdir)
html_file_url = urljoin('file:', pathname2url(html_filename))
print('Opening html file: {}'.format(html_file_url))
webbrowser.open(html_file_url)
else:
# We're running in ipython: display widget
display(HTML(html))
else:
return html | [
"def",
"draw",
"(",
"data",
",",
"format",
"=",
"'auto'",
",",
"size",
"=",
"(",
"400",
",",
"300",
")",
",",
"drawing_type",
"=",
"'ball and stick'",
",",
"camera_type",
"=",
"'perspective'",
",",
"shader",
"=",
"'lambert'",
",",
"display_html",
"=",
"T... | Draws an interactive 3D visualization of the inputted chemical.
Args:
data: A string or file representing a chemical.
format: The format of the `data` variable (default is 'auto').
size: Starting dimensions of visualization, in pixels.
drawing_type: Specifies the molecular representation. Can be 'ball and
stick', 'wireframe', or 'space filling'.
camera_type: Can be 'perspective' or 'orthographic'.
shader: Specifies shading algorithm to use. Can be 'toon', 'basic',
'phong', or 'lambert'.
display_html: If True (default), embed the html in a IPython display.
If False, return the html as a string.
element_properites: A dictionary providing color and radius information
for custom elements or overriding the defaults in imolecule.js
show_save: If True, displays a save icon for rendering molecule as an
image.
The `format` can be any value specified by Open Babel
(http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'
option uses the extension for files (ie. my_file.mol -> mol) and defaults
to SMILES (smi) for strings. | [
"Draws",
"an",
"interactive",
"3D",
"visualization",
"of",
"the",
"inputted",
"chemical",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/notebook.py#L30-L152 | train |
patrickfuller/imolecule | imolecule/notebook.py | generate | def generate(data, format="auto"):
"""Converts input chemical formats to json and optimizes structure.
Args:
data: A string or file representing a chemical
format: The format of the `data` variable (default is 'auto')
The `format` can be any value specified by Open Babel
(http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'
option uses the extension for files (ie. my_file.mol -> mol) and defaults
to SMILES (smi) for strings.
"""
# Support both files and strings and attempt to infer file type
try:
with open(data) as in_file:
if format == 'auto':
format = data.split('.')[-1]
data = in_file.read()
except:
if format == 'auto':
format = 'smi'
return format_converter.convert(data, format, 'json') | python | def generate(data, format="auto"):
"""Converts input chemical formats to json and optimizes structure.
Args:
data: A string or file representing a chemical
format: The format of the `data` variable (default is 'auto')
The `format` can be any value specified by Open Babel
(http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'
option uses the extension for files (ie. my_file.mol -> mol) and defaults
to SMILES (smi) for strings.
"""
# Support both files and strings and attempt to infer file type
try:
with open(data) as in_file:
if format == 'auto':
format = data.split('.')[-1]
data = in_file.read()
except:
if format == 'auto':
format = 'smi'
return format_converter.convert(data, format, 'json') | [
"def",
"generate",
"(",
"data",
",",
"format",
"=",
"\"auto\"",
")",
":",
"# Support both files and strings and attempt to infer file type",
"try",
":",
"with",
"open",
"(",
"data",
")",
"as",
"in_file",
":",
"if",
"format",
"==",
"'auto'",
":",
"format",
"=",
... | Converts input chemical formats to json and optimizes structure.
Args:
data: A string or file representing a chemical
format: The format of the `data` variable (default is 'auto')
The `format` can be any value specified by Open Babel
(http://openbabel.org/docs/2.3.1/FileFormats/Overview.html). The 'auto'
option uses the extension for files (ie. my_file.mol -> mol) and defaults
to SMILES (smi) for strings. | [
"Converts",
"input",
"chemical",
"formats",
"to",
"json",
"and",
"optimizes",
"structure",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/notebook.py#L155-L176 | train |
patrickfuller/imolecule | imolecule/notebook.py | to_json | def to_json(data, compress=False):
"""Converts the output of `generate(...)` to formatted json.
Floats are rounded to three decimals and positional vectors are printed on
one line with some whitespace buffer.
"""
return json.compress(data) if compress else json.dumps(data) | python | def to_json(data, compress=False):
"""Converts the output of `generate(...)` to formatted json.
Floats are rounded to three decimals and positional vectors are printed on
one line with some whitespace buffer.
"""
return json.compress(data) if compress else json.dumps(data) | [
"def",
"to_json",
"(",
"data",
",",
"compress",
"=",
"False",
")",
":",
"return",
"json",
".",
"compress",
"(",
"data",
")",
"if",
"compress",
"else",
"json",
".",
"dumps",
"(",
"data",
")"
] | Converts the output of `generate(...)` to formatted json.
Floats are rounded to three decimals and positional vectors are printed on
one line with some whitespace buffer. | [
"Converts",
"the",
"output",
"of",
"generate",
"(",
"...",
")",
"to",
"formatted",
"json",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/notebook.py#L179-L185 | train |
patrickfuller/imolecule | imolecule/server/server.py | start_server | def start_server():
"""Starts up the imolecule server, complete with argparse handling."""
parser = argparse.ArgumentParser(description="Opens a browser-based "
"client that interfaces with the "
"chemical format converter.")
parser.add_argument('--debug', action="store_true", help="Prints all "
"transmitted data streams.")
parser.add_argument('--port', type=int, default=8000, help="The port "
"on which to serve the website.")
parser.add_argument('--timeout', type=int, default=5, help="The maximum "
"time, in seconds, allowed for a process to run "
"before returning an error.")
parser.add_argument('--workers', type=int, default=2, help="The number of "
"worker processes to use with the server.")
parser.add_argument('--no-browser', action="store_true", help="Disables "
"opening a browser window on startup.")
global args
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
handlers = [(r'/', IndexHandler), (r'/websocket', WebSocket),
(r'/static/(.*)', tornado.web.StaticFileHandler,
{'path': os.path.normpath(os.path.dirname(__file__))})]
application = tornado.web.Application(handlers)
application.listen(args.port)
if not args.no_browser:
webbrowser.open('http://localhost:%d/' % args.port, new=2)
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
sys.stderr.write("Received keyboard interrupt. Stopping server.\n")
tornado.ioloop.IOLoop.instance().stop()
sys.exit(1) | python | def start_server():
"""Starts up the imolecule server, complete with argparse handling."""
parser = argparse.ArgumentParser(description="Opens a browser-based "
"client that interfaces with the "
"chemical format converter.")
parser.add_argument('--debug', action="store_true", help="Prints all "
"transmitted data streams.")
parser.add_argument('--port', type=int, default=8000, help="The port "
"on which to serve the website.")
parser.add_argument('--timeout', type=int, default=5, help="The maximum "
"time, in seconds, allowed for a process to run "
"before returning an error.")
parser.add_argument('--workers', type=int, default=2, help="The number of "
"worker processes to use with the server.")
parser.add_argument('--no-browser', action="store_true", help="Disables "
"opening a browser window on startup.")
global args
args = parser.parse_args()
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
handlers = [(r'/', IndexHandler), (r'/websocket', WebSocket),
(r'/static/(.*)', tornado.web.StaticFileHandler,
{'path': os.path.normpath(os.path.dirname(__file__))})]
application = tornado.web.Application(handlers)
application.listen(args.port)
if not args.no_browser:
webbrowser.open('http://localhost:%d/' % args.port, new=2)
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
sys.stderr.write("Received keyboard interrupt. Stopping server.\n")
tornado.ioloop.IOLoop.instance().stop()
sys.exit(1) | [
"def",
"start_server",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Opens a browser-based \"",
"\"client that interfaces with the \"",
"\"chemical format converter.\"",
")",
"parser",
".",
"add_argument",
"(",
"'--debug'",
"... | Starts up the imolecule server, complete with argparse handling. | [
"Starts",
"up",
"the",
"imolecule",
"server",
"complete",
"with",
"argparse",
"handling",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/server/server.py#L69-L105 | train |
patrickfuller/imolecule | imolecule/server/server.py | WebSocket.on_message | def on_message(self, message):
"""Evaluates the function pointed to by json-rpc."""
json_rpc = json.loads(message)
logging.log(logging.DEBUG, json_rpc)
if self.pool is None:
self.pool = multiprocessing.Pool(processes=args.workers)
# Spawn a process to protect the server against segfaults
async = self.pool.apply_async(_worker_process, [json_rpc])
try:
result = async.get(timeout=args.timeout)
error = 0
except multiprocessing.TimeoutError:
result = ("File format conversion timed out! This is due "
"either to a large input file or a segmentation "
"fault in the underlying open babel library.")
error = 1
self.pool.terminate()
self.pool = multiprocessing.Pool(processes=args.workers)
except Exception:
result = traceback.format_exc()
error = 1
logging.log(logging.DEBUG, result)
self.write_message(json.dumps({'result': result, 'error': error,
'id': json_rpc['id']},
separators=(',', ':'))) | python | def on_message(self, message):
"""Evaluates the function pointed to by json-rpc."""
json_rpc = json.loads(message)
logging.log(logging.DEBUG, json_rpc)
if self.pool is None:
self.pool = multiprocessing.Pool(processes=args.workers)
# Spawn a process to protect the server against segfaults
async = self.pool.apply_async(_worker_process, [json_rpc])
try:
result = async.get(timeout=args.timeout)
error = 0
except multiprocessing.TimeoutError:
result = ("File format conversion timed out! This is due "
"either to a large input file or a segmentation "
"fault in the underlying open babel library.")
error = 1
self.pool.terminate()
self.pool = multiprocessing.Pool(processes=args.workers)
except Exception:
result = traceback.format_exc()
error = 1
logging.log(logging.DEBUG, result)
self.write_message(json.dumps({'result': result, 'error': error,
'id': json_rpc['id']},
separators=(',', ':'))) | [
"def",
"on_message",
"(",
"self",
",",
"message",
")",
":",
"json_rpc",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"logging",
".",
"log",
"(",
"logging",
".",
"DEBUG",
",",
"json_rpc",
")",
"if",
"self",
".",
"pool",
"is",
"None",
":",
"self",
... | Evaluates the function pointed to by json-rpc. | [
"Evaluates",
"the",
"function",
"pointed",
"to",
"by",
"json",
"-",
"rpc",
"."
] | 07e91600c805123935a78782871414754bd3696d | https://github.com/patrickfuller/imolecule/blob/07e91600c805123935a78782871414754bd3696d/imolecule/server/server.py#L39-L66 | train |
JnyJny/Geometry | Geometry/constants.py | nearly_eq | def nearly_eq(valA, valB, maxf=None, minf=None, epsilon=None):
'''
implementation based on:
http://floating-point-gui.de/errors/comparison/
'''
if valA == valB:
return True
if maxf is None:
maxf = float_info.max
if minf is None:
minf = float_info.min
if epsilon is None:
epsilon = float_info.epsilon
absA = abs(valA)
absB = abs(valB)
delta = abs(valA - valB)
if (valA == 0) or (valB == 0) or (delta < minf):
return delta < (epsilon * minf)
return (delta / min(absA + absB, maxf)) < (epsilon * 2) | python | def nearly_eq(valA, valB, maxf=None, minf=None, epsilon=None):
'''
implementation based on:
http://floating-point-gui.de/errors/comparison/
'''
if valA == valB:
return True
if maxf is None:
maxf = float_info.max
if minf is None:
minf = float_info.min
if epsilon is None:
epsilon = float_info.epsilon
absA = abs(valA)
absB = abs(valB)
delta = abs(valA - valB)
if (valA == 0) or (valB == 0) or (delta < minf):
return delta < (epsilon * minf)
return (delta / min(absA + absB, maxf)) < (epsilon * 2) | [
"def",
"nearly_eq",
"(",
"valA",
",",
"valB",
",",
"maxf",
"=",
"None",
",",
"minf",
"=",
"None",
",",
"epsilon",
"=",
"None",
")",
":",
"if",
"valA",
"==",
"valB",
":",
"return",
"True",
"if",
"maxf",
"is",
"None",
":",
"maxf",
"=",
"float_info",
... | implementation based on:
http://floating-point-gui.de/errors/comparison/ | [
"implementation",
"based",
"on",
":"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/constants.py#L12-L38 | train |
JnyJny/Geometry | Geometry/point.py | Point._convert | def _convert(cls, other, ignoreScalars=False):
'''
:other: Point or point equivalent
:ignorescalars: optional boolean
:return: Point
Class private method for converting 'other' into a Point
subclasss. If 'other' already is a Point subclass, nothing
is done. If ignoreScalars is True and other is a float or int
type, a TypeError exception is raised.
'''
if ignoreScalars:
if isinstance(other, (int, float)):
msg = "unable to convert {} to {}".format(other, cls.__name__)
raise TypeError(msg)
return cls(other) if not issubclass(type(other), cls) else other | python | def _convert(cls, other, ignoreScalars=False):
'''
:other: Point or point equivalent
:ignorescalars: optional boolean
:return: Point
Class private method for converting 'other' into a Point
subclasss. If 'other' already is a Point subclass, nothing
is done. If ignoreScalars is True and other is a float or int
type, a TypeError exception is raised.
'''
if ignoreScalars:
if isinstance(other, (int, float)):
msg = "unable to convert {} to {}".format(other, cls.__name__)
raise TypeError(msg)
return cls(other) if not issubclass(type(other), cls) else other | [
"def",
"_convert",
"(",
"cls",
",",
"other",
",",
"ignoreScalars",
"=",
"False",
")",
":",
"if",
"ignoreScalars",
":",
"if",
"isinstance",
"(",
"other",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"msg",
"=",
"\"unable to convert {} to {}\"",
".",
"for... | :other: Point or point equivalent
:ignorescalars: optional boolean
:return: Point
Class private method for converting 'other' into a Point
subclasss. If 'other' already is a Point subclass, nothing
is done. If ignoreScalars is True and other is a float or int
type, a TypeError exception is raised. | [
":",
"other",
":",
"Point",
"or",
"point",
"equivalent",
":",
"ignorescalars",
":",
"optional",
"boolean",
":",
"return",
":",
"Point"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L115-L131 | train |
JnyJny/Geometry | Geometry/point.py | Point.units | def units(cls, scale=1):
'''
:scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k).
'''
return [cls(x=scale), cls(y=scale), cls(z=scale)] | python | def units(cls, scale=1):
'''
:scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k).
'''
return [cls(x=scale), cls(y=scale), cls(z=scale)] | [
"def",
"units",
"(",
"cls",
",",
"scale",
"=",
"1",
")",
":",
"return",
"[",
"cls",
"(",
"x",
"=",
"scale",
")",
",",
"cls",
"(",
"y",
"=",
"scale",
")",
",",
"cls",
"(",
"z",
"=",
"scale",
")",
"]"
] | :scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k). | [
":",
"scale",
":",
"optional",
"integer",
"scaling",
"factor",
":",
"return",
":",
"list",
"of",
"three",
"Point",
"subclass"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L148-L157 | train |
JnyJny/Geometry | Geometry/point.py | Point.gaussian | def gaussian(cls, mu=0, sigma=1):
'''
:mu: mean
:sigma: standard deviation
:return: Point subclass
Returns a point whose coordinates are picked from a Gaussian
distribution with mean 'mu' and standard deviation 'sigma'.
See random.gauss for further explanation of those parameters.
'''
return cls(random.gauss(mu, sigma),
random.gauss(mu, sigma),
random.gauss(mu, sigma)) | python | def gaussian(cls, mu=0, sigma=1):
'''
:mu: mean
:sigma: standard deviation
:return: Point subclass
Returns a point whose coordinates are picked from a Gaussian
distribution with mean 'mu' and standard deviation 'sigma'.
See random.gauss for further explanation of those parameters.
'''
return cls(random.gauss(mu, sigma),
random.gauss(mu, sigma),
random.gauss(mu, sigma)) | [
"def",
"gaussian",
"(",
"cls",
",",
"mu",
"=",
"0",
",",
"sigma",
"=",
"1",
")",
":",
"return",
"cls",
"(",
"random",
".",
"gauss",
"(",
"mu",
",",
"sigma",
")",
",",
"random",
".",
"gauss",
"(",
"mu",
",",
"sigma",
")",
",",
"random",
".",
"... | :mu: mean
:sigma: standard deviation
:return: Point subclass
Returns a point whose coordinates are picked from a Gaussian
distribution with mean 'mu' and standard deviation 'sigma'.
See random.gauss for further explanation of those parameters. | [
":",
"mu",
":",
"mean",
":",
"sigma",
":",
"standard",
"deviation",
":",
"return",
":",
"Point",
"subclass"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L160-L172 | train |
JnyJny/Geometry | Geometry/point.py | Point.random | def random(cls, origin=None, radius=1):
'''
:origin: optional Point or point equivalent
:radius: optional float, radius around origin
:return: Point subclass
Returns a point with random x, y and z coordinates bounded by
the sphere defined by (origin,radius).
If a sphere is not supplied, a unit sphere at the origin is
used by default.
'''
p = cls(origin)
r = random.uniform(0, radius)
u = random.uniform(0, Two_Pi)
v = random.uniform(-Half_Pi, Half_Pi)
r_cosv = r * math.cos(v)
p.x += r_cosv * math.cos(u)
p.y += r_cosv * math.sin(u)
p.z += radius * math.sin(v)
return p | python | def random(cls, origin=None, radius=1):
'''
:origin: optional Point or point equivalent
:radius: optional float, radius around origin
:return: Point subclass
Returns a point with random x, y and z coordinates bounded by
the sphere defined by (origin,radius).
If a sphere is not supplied, a unit sphere at the origin is
used by default.
'''
p = cls(origin)
r = random.uniform(0, radius)
u = random.uniform(0, Two_Pi)
v = random.uniform(-Half_Pi, Half_Pi)
r_cosv = r * math.cos(v)
p.x += r_cosv * math.cos(u)
p.y += r_cosv * math.sin(u)
p.z += radius * math.sin(v)
return p | [
"def",
"random",
"(",
"cls",
",",
"origin",
"=",
"None",
",",
"radius",
"=",
"1",
")",
":",
"p",
"=",
"cls",
"(",
"origin",
")",
"r",
"=",
"random",
".",
"uniform",
"(",
"0",
",",
"radius",
")",
"u",
"=",
"random",
".",
"uniform",
"(",
"0",
"... | :origin: optional Point or point equivalent
:radius: optional float, radius around origin
:return: Point subclass
Returns a point with random x, y and z coordinates bounded by
the sphere defined by (origin,radius).
If a sphere is not supplied, a unit sphere at the origin is
used by default. | [
":",
"origin",
":",
"optional",
"Point",
"or",
"point",
"equivalent",
":",
"radius",
":",
"optional",
"float",
"radius",
"around",
"origin",
":",
"return",
":",
"Point",
"subclass"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L175-L200 | train |
JnyJny/Geometry | Geometry/point.py | Point._binary_ | def _binary_(self, other, func, inplace=False):
'''
:other: Point or point equivalent
:func: binary function to apply
:inplace: optional boolean
:return: Point
Implementation private method.
All of the binary operations funnel thru this method to
reduce cut-and-paste code and enforce consistent behavior
of binary ops.
Applies 'func' to 'self' and 'other' and returns the result.
If 'inplace' is True the results of will be stored in 'self',
otherwise the results will be stored in a new object.
Returns a Point.
'''
dst = self if inplace else self.__class__(self)
try:
b = self.__class__._convert(other, ignoreScalars=True)
dst.x = func(dst.x, b.x)
dst.y = func(dst.y, b.y)
dst.z = func(dst.z, b.z)
return dst
except TypeError:
pass
dst.x = func(dst.x, other)
dst.y = func(dst.y, other)
dst.z = func(dst.z, other)
return dst | python | def _binary_(self, other, func, inplace=False):
'''
:other: Point or point equivalent
:func: binary function to apply
:inplace: optional boolean
:return: Point
Implementation private method.
All of the binary operations funnel thru this method to
reduce cut-and-paste code and enforce consistent behavior
of binary ops.
Applies 'func' to 'self' and 'other' and returns the result.
If 'inplace' is True the results of will be stored in 'self',
otherwise the results will be stored in a new object.
Returns a Point.
'''
dst = self if inplace else self.__class__(self)
try:
b = self.__class__._convert(other, ignoreScalars=True)
dst.x = func(dst.x, b.x)
dst.y = func(dst.y, b.y)
dst.z = func(dst.z, b.z)
return dst
except TypeError:
pass
dst.x = func(dst.x, other)
dst.y = func(dst.y, other)
dst.z = func(dst.z, other)
return dst | [
"def",
"_binary_",
"(",
"self",
",",
"other",
",",
"func",
",",
"inplace",
"=",
"False",
")",
":",
"dst",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"__class__",
"(",
"self",
")",
"try",
":",
"b",
"=",
"self",
".",
"__class__",
".",
"_conve... | :other: Point or point equivalent
:func: binary function to apply
:inplace: optional boolean
:return: Point
Implementation private method.
All of the binary operations funnel thru this method to
reduce cut-and-paste code and enforce consistent behavior
of binary ops.
Applies 'func' to 'self' and 'other' and returns the result.
If 'inplace' is True the results of will be stored in 'self',
otherwise the results will be stored in a new object.
Returns a Point. | [
":",
"other",
":",
"Point",
"or",
"point",
"equivalent",
":",
"func",
":",
"binary",
"function",
"to",
"apply",
":",
"inplace",
":",
"optional",
"boolean",
":",
"return",
":",
"Point"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L466-L502 | train |
JnyJny/Geometry | Geometry/point.py | Point._unary_ | def _unary_(self, func, inplace=False):
'''
:func: unary function to apply to each coordinate
:inplace: optional boolean
:return: Point
Implementation private method.
All of the unary operations funnel thru this method
to reduce cut-and-paste code and enforce consistent
behavior of unary ops.
Applies 'func' to self and returns the result.
The expected call signature of 'func' is f(a)
If 'inplace' is True, the results are stored in 'self',
otherwise the results will be stored in a new object.
Returns a Point.
'''
dst = self if inplace else self.__class__(self)
dst.x = func(dst.x)
dst.y = func(dst.y)
dst.z = func(dst.z)
return dst | python | def _unary_(self, func, inplace=False):
'''
:func: unary function to apply to each coordinate
:inplace: optional boolean
:return: Point
Implementation private method.
All of the unary operations funnel thru this method
to reduce cut-and-paste code and enforce consistent
behavior of unary ops.
Applies 'func' to self and returns the result.
The expected call signature of 'func' is f(a)
If 'inplace' is True, the results are stored in 'self',
otherwise the results will be stored in a new object.
Returns a Point.
'''
dst = self if inplace else self.__class__(self)
dst.x = func(dst.x)
dst.y = func(dst.y)
dst.z = func(dst.z)
return dst | [
"def",
"_unary_",
"(",
"self",
",",
"func",
",",
"inplace",
"=",
"False",
")",
":",
"dst",
"=",
"self",
"if",
"inplace",
"else",
"self",
".",
"__class__",
"(",
"self",
")",
"dst",
".",
"x",
"=",
"func",
"(",
"dst",
".",
"x",
")",
"dst",
".",
"y... | :func: unary function to apply to each coordinate
:inplace: optional boolean
:return: Point
Implementation private method.
All of the unary operations funnel thru this method
to reduce cut-and-paste code and enforce consistent
behavior of unary ops.
Applies 'func' to self and returns the result.
The expected call signature of 'func' is f(a)
If 'inplace' is True, the results are stored in 'self',
otherwise the results will be stored in a new object.
Returns a Point. | [
":",
"func",
":",
"unary",
"function",
"to",
"apply",
"to",
"each",
"coordinate",
":",
"inplace",
":",
"optional",
"boolean",
":",
"return",
":",
"Point"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L504-L530 | train |
JnyJny/Geometry | Geometry/point.py | Point.cross | def cross(self, other):
'''
:other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
U x V = s1 + s2 + s3
Returns a float.
'''
b = self.__class__._convert(other)
return sum([(self.y * b.z) - (self.z * b.y),
(self.z * b.x) - (self.x * b.z),
(self.x * b.y) - (self.y * b.x)]) | python | def cross(self, other):
'''
:other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
U x V = s1 + s2 + s3
Returns a float.
'''
b = self.__class__._convert(other)
return sum([(self.y * b.z) - (self.z * b.y),
(self.z * b.x) - (self.x * b.z),
(self.x * b.y) - (self.y * b.x)]) | [
"def",
"cross",
"(",
"self",
",",
"other",
")",
":",
"b",
"=",
"self",
".",
"__class__",
".",
"_convert",
"(",
"other",
")",
"return",
"sum",
"(",
"[",
"(",
"self",
".",
"y",
"*",
"b",
".",
"z",
")",
"-",
"(",
"self",
".",
"z",
"*",
"b",
".... | :other: Point or point equivalent
:return: float
Vector cross product of points U (self) and V (other), computed:
U x V = (u1*i + u2*j + u3*k) x (v1*i + v2*j + v3*k)
s1 = u2v3 - u3v2
s2 = u3v1 - u1v3
s3 = u1v2 - u2v1
U x V = s1 + s2 + s3
Returns a float. | [
":",
"other",
":",
"Point",
"or",
"point",
"equivalent",
":",
"return",
":",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1260-L1281 | train |
JnyJny/Geometry | Geometry/point.py | Point.isBetween | def isBetween(self, a, b, axes='xyz'):
'''
:a: Point or point equivalent
:b: Point or point equivalent
:axis: optional string
:return: float
Checks the coordinates specified in 'axes' of 'self' to
determine if they are bounded by 'a' and 'b'. The range
is inclusive of end-points.
Returns boolean.
'''
a = self.__class__._convert(a)
b = self.__class__._convert(b)
fn = lambda k: (self[k] >= min(a[k], b[k])) and (
self[k] <= max(a[k], b[k]))
return all(fn(axis) for axis in axes) | python | def isBetween(self, a, b, axes='xyz'):
'''
:a: Point or point equivalent
:b: Point or point equivalent
:axis: optional string
:return: float
Checks the coordinates specified in 'axes' of 'self' to
determine if they are bounded by 'a' and 'b'. The range
is inclusive of end-points.
Returns boolean.
'''
a = self.__class__._convert(a)
b = self.__class__._convert(b)
fn = lambda k: (self[k] >= min(a[k], b[k])) and (
self[k] <= max(a[k], b[k]))
return all(fn(axis) for axis in axes) | [
"def",
"isBetween",
"(",
"self",
",",
"a",
",",
"b",
",",
"axes",
"=",
"'xyz'",
")",
":",
"a",
"=",
"self",
".",
"__class__",
".",
"_convert",
"(",
"a",
")",
"b",
"=",
"self",
".",
"__class__",
".",
"_convert",
"(",
"b",
")",
"fn",
"=",
"lambda... | :a: Point or point equivalent
:b: Point or point equivalent
:axis: optional string
:return: float
Checks the coordinates specified in 'axes' of 'self' to
determine if they are bounded by 'a' and 'b'. The range
is inclusive of end-points.
Returns boolean. | [
":",
"a",
":",
"Point",
"or",
"point",
"equivalent",
":",
"b",
":",
"Point",
"or",
"point",
"equivalent",
":",
"axis",
":",
"optional",
"string",
":",
"return",
":",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1302-L1321 | train |
JnyJny/Geometry | Geometry/point.py | Point.ccw | def ccw(self, b, c, axis='z'):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: float
CCW - Counter Clockwise
Returns an integer signifying the direction of rotation around 'axis'
described by the angle [b, self, c].
> 0 : counter-clockwise
0 : points are collinear
< 0 : clockwise
Returns an integer.
Raises ValueError if axis is not in 'xyz'.
'''
bsuba = b - self
csuba = c - self
if axis in ['z', 2]:
return (bsuba.x * csuba.y) - (bsuba.y * csuba.x)
if axis in ['y', 1]:
return (bsuba.x * csuba.z) - (bsuba.z * csuba.x)
if axis in ['x', 0]:
return (bsuba.y * csuba.z) - (bsuba.z * csuba.y)
msg = "invalid axis '{!r}', must be one of {}".format(axis, self._keys)
raise ValueError(msg) | python | def ccw(self, b, c, axis='z'):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: float
CCW - Counter Clockwise
Returns an integer signifying the direction of rotation around 'axis'
described by the angle [b, self, c].
> 0 : counter-clockwise
0 : points are collinear
< 0 : clockwise
Returns an integer.
Raises ValueError if axis is not in 'xyz'.
'''
bsuba = b - self
csuba = c - self
if axis in ['z', 2]:
return (bsuba.x * csuba.y) - (bsuba.y * csuba.x)
if axis in ['y', 1]:
return (bsuba.x * csuba.z) - (bsuba.z * csuba.x)
if axis in ['x', 0]:
return (bsuba.y * csuba.z) - (bsuba.z * csuba.y)
msg = "invalid axis '{!r}', must be one of {}".format(axis, self._keys)
raise ValueError(msg) | [
"def",
"ccw",
"(",
"self",
",",
"b",
",",
"c",
",",
"axis",
"=",
"'z'",
")",
":",
"bsuba",
"=",
"b",
"-",
"self",
"csuba",
"=",
"c",
"-",
"self",
"if",
"axis",
"in",
"[",
"'z'",
",",
"2",
"]",
":",
"return",
"(",
"bsuba",
".",
"x",
"*",
"... | :b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: float
CCW - Counter Clockwise
Returns an integer signifying the direction of rotation around 'axis'
described by the angle [b, self, c].
> 0 : counter-clockwise
0 : points are collinear
< 0 : clockwise
Returns an integer.
Raises ValueError if axis is not in 'xyz'. | [
":",
"b",
":",
"Point",
"or",
"point",
"equivalent",
":",
"c",
":",
"Point",
"or",
"point",
"equivalent",
":",
"axis",
":",
"optional",
"string",
"or",
"integer",
"in",
"set",
"(",
"x",
"0",
"y",
"1",
"z",
"2",
")",
":",
"return",
":",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1353-L1387 | train |
JnyJny/Geometry | Geometry/point.py | Point.isCCW | def isCCW(self, b, c, axis='z'):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: boolean
True if the angle determined by a,self,b around 'axis'
describes a counter-clockwise rotation, otherwise False.
Raises CollinearPoints if self, b, c are collinear.
'''
result = self.ccw(b, c, axis)
if result == 0:
raise CollinearPoints(b, self, c)
return result > 0 | python | def isCCW(self, b, c, axis='z'):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: boolean
True if the angle determined by a,self,b around 'axis'
describes a counter-clockwise rotation, otherwise False.
Raises CollinearPoints if self, b, c are collinear.
'''
result = self.ccw(b, c, axis)
if result == 0:
raise CollinearPoints(b, self, c)
return result > 0 | [
"def",
"isCCW",
"(",
"self",
",",
"b",
",",
"c",
",",
"axis",
"=",
"'z'",
")",
":",
"result",
"=",
"self",
".",
"ccw",
"(",
"b",
",",
"c",
",",
"axis",
")",
"if",
"result",
"==",
"0",
":",
"raise",
"CollinearPoints",
"(",
"b",
",",
"self",
",... | :b: Point or point equivalent
:c: Point or point equivalent
:axis: optional string or integer in set('x',0,'y',1,'z',2)
:return: boolean
True if the angle determined by a,self,b around 'axis'
describes a counter-clockwise rotation, otherwise False.
Raises CollinearPoints if self, b, c are collinear. | [
":",
"b",
":",
"Point",
"or",
"point",
"equivalent",
":",
"c",
":",
"Point",
"or",
"point",
"equivalent",
":",
"axis",
":",
"optional",
"string",
"or",
"integer",
"in",
"set",
"(",
"x",
"0",
"y",
"1",
"z",
"2",
")",
":",
"return",
":",
"boolean"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1389-L1407 | train |
JnyJny/Geometry | Geometry/point.py | Point.isCollinear | def isCollinear(self, b, c):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:return: boolean
True if 'self' is collinear with 'b' and 'c', otherwise False.
'''
return all(self.ccw(b, c, axis) == 0 for axis in self._keys) | python | def isCollinear(self, b, c):
'''
:b: Point or point equivalent
:c: Point or point equivalent
:return: boolean
True if 'self' is collinear with 'b' and 'c', otherwise False.
'''
return all(self.ccw(b, c, axis) == 0 for axis in self._keys) | [
"def",
"isCollinear",
"(",
"self",
",",
"b",
",",
"c",
")",
":",
"return",
"all",
"(",
"self",
".",
"ccw",
"(",
"b",
",",
"c",
",",
"axis",
")",
"==",
"0",
"for",
"axis",
"in",
"self",
".",
"_keys",
")"
] | :b: Point or point equivalent
:c: Point or point equivalent
:return: boolean
True if 'self' is collinear with 'b' and 'c', otherwise False. | [
":",
"b",
":",
"Point",
"or",
"point",
"equivalent",
":",
"c",
":",
"Point",
"or",
"point",
"equivalent",
":",
"return",
":",
"boolean"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1409-L1418 | train |
JnyJny/Geometry | Geometry/point.py | Point.rotate2d | def rotate2d(self, theta, origin=None, axis='z', radians=False):
'''
:theta: float radians to rotate self around origin
:origin: optional Point, defaults to 0,0,0
Returns a Point rotated by :theta: around :origin:.
'''
origin = Point._convert(origin)
delta = self - origin
p = Point(origin)
if not radians:
theta = math.radians(theta)
cosT = math.cos(theta)
sinT = math.sin(theta)
if axis == 'z':
p.x += (cosT * delta.x) - (sinT * delta.y)
p.y += (sinT * delta.x) + (cosT * delta.y)
return p
if axis == 'y':
p.z += (cosT * delta.z) - (sinT * delta.x)
p.x += (sinT * delta.z) + (cosT * delta.x)
return p
if axis == 'x':
p.y += (cosT * delta.y) - (sinT * delta.z)
p.z += (sinT * delta.y) + (cosT * delta.z)
return p
raise KeyError('unknown axis {}, expecting x, y or z'.format(axis)) | python | def rotate2d(self, theta, origin=None, axis='z', radians=False):
'''
:theta: float radians to rotate self around origin
:origin: optional Point, defaults to 0,0,0
Returns a Point rotated by :theta: around :origin:.
'''
origin = Point._convert(origin)
delta = self - origin
p = Point(origin)
if not radians:
theta = math.radians(theta)
cosT = math.cos(theta)
sinT = math.sin(theta)
if axis == 'z':
p.x += (cosT * delta.x) - (sinT * delta.y)
p.y += (sinT * delta.x) + (cosT * delta.y)
return p
if axis == 'y':
p.z += (cosT * delta.z) - (sinT * delta.x)
p.x += (sinT * delta.z) + (cosT * delta.x)
return p
if axis == 'x':
p.y += (cosT * delta.y) - (sinT * delta.z)
p.z += (sinT * delta.y) + (cosT * delta.z)
return p
raise KeyError('unknown axis {}, expecting x, y or z'.format(axis)) | [
"def",
"rotate2d",
"(",
"self",
",",
"theta",
",",
"origin",
"=",
"None",
",",
"axis",
"=",
"'z'",
",",
"radians",
"=",
"False",
")",
":",
"origin",
"=",
"Point",
".",
"_convert",
"(",
"origin",
")",
"delta",
"=",
"self",
"-",
"origin",
"p",
"=",
... | :theta: float radians to rotate self around origin
:origin: optional Point, defaults to 0,0,0
Returns a Point rotated by :theta: around :origin:. | [
":",
"theta",
":",
"float",
"radians",
"to",
"rotate",
"self",
"around",
"origin",
":",
"origin",
":",
"optional",
"Point",
"defaults",
"to",
"0",
"0",
"0"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/point.py#L1420-L1455 | train |
JnyJny/Geometry | Geometry/triangle2.py | Triangle.withAngles | def withAngles(cls, origin=None, base=1, alpha=None,
beta=None, gamma=None, inDegrees=False):
'''
:origin: optional Point
:alpha: optional float describing length of the side opposite A
:beta: optional float describing length of the side opposite B
:gamma: optional float describing length of the side opposite C
:return: Triangle initialized with points comprising the triangle
with the specified angles.
'''
raise NotImplementedError("withAngles") | python | def withAngles(cls, origin=None, base=1, alpha=None,
beta=None, gamma=None, inDegrees=False):
'''
:origin: optional Point
:alpha: optional float describing length of the side opposite A
:beta: optional float describing length of the side opposite B
:gamma: optional float describing length of the side opposite C
:return: Triangle initialized with points comprising the triangle
with the specified angles.
'''
raise NotImplementedError("withAngles") | [
"def",
"withAngles",
"(",
"cls",
",",
"origin",
"=",
"None",
",",
"base",
"=",
"1",
",",
"alpha",
"=",
"None",
",",
"beta",
"=",
"None",
",",
"gamma",
"=",
"None",
",",
"inDegrees",
"=",
"False",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"with... | :origin: optional Point
:alpha: optional float describing length of the side opposite A
:beta: optional float describing length of the side opposite B
:gamma: optional float describing length of the side opposite C
:return: Triangle initialized with points comprising the triangle
with the specified angles. | [
":",
"origin",
":",
"optional",
"Point",
":",
"alpha",
":",
"optional",
"float",
"describing",
"length",
"of",
"the",
"side",
"opposite",
"A",
":",
"beta",
":",
"optional",
"float",
"describing",
"length",
"of",
"the",
"side",
"opposite",
"B",
":",
"gamma"... | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle2.py#L45-L55 | train |
JnyJny/Geometry | Geometry/triangle2.py | Triangle.heronsArea | def heronsArea(self):
'''
Heron's forumla for computing the area of a triangle, float.
Performance note: contains a square root.
'''
s = self.semiperimeter
return math.sqrt(s * ((s - self.a) * (s - self.b) * (s - self.c))) | python | def heronsArea(self):
'''
Heron's forumla for computing the area of a triangle, float.
Performance note: contains a square root.
'''
s = self.semiperimeter
return math.sqrt(s * ((s - self.a) * (s - self.b) * (s - self.c))) | [
"def",
"heronsArea",
"(",
"self",
")",
":",
"s",
"=",
"self",
".",
"semiperimeter",
"return",
"math",
".",
"sqrt",
"(",
"s",
"*",
"(",
"(",
"s",
"-",
"self",
".",
"a",
")",
"*",
"(",
"s",
"-",
"self",
".",
"b",
")",
"*",
"(",
"s",
"-",
"sel... | Heron's forumla for computing the area of a triangle, float.
Performance note: contains a square root. | [
"Heron",
"s",
"forumla",
"for",
"computing",
"the",
"area",
"of",
"a",
"triangle",
"float",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle2.py#L182-L191 | train |
JnyJny/Geometry | Geometry/triangle2.py | Triangle.circumradius | def circumradius(self):
'''
Distance from the circumcenter to all the verticies in
the Triangle, float.
'''
return (self.a * self.b * self.c) / (self.area * 4) | python | def circumradius(self):
'''
Distance from the circumcenter to all the verticies in
the Triangle, float.
'''
return (self.a * self.b * self.c) / (self.area * 4) | [
"def",
"circumradius",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"a",
"*",
"self",
".",
"b",
"*",
"self",
".",
"c",
")",
"/",
"(",
"self",
".",
"area",
"*",
"4",
")"
] | Distance from the circumcenter to all the verticies in
the Triangle, float. | [
"Distance",
"from",
"the",
"circumcenter",
"to",
"all",
"the",
"verticies",
"in",
"the",
"Triangle",
"float",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle2.py#L238-L244 | train |
JnyJny/Geometry | Geometry/triangle2.py | Triangle.altitudes | def altitudes(self):
'''
A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it.
'''
A = self.area * 2
return [A / self.a, A / self.b, A / self.c] | python | def altitudes(self):
'''
A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it.
'''
A = self.area * 2
return [A / self.a, A / self.b, A / self.c] | [
"def",
"altitudes",
"(",
"self",
")",
":",
"A",
"=",
"self",
".",
"area",
"*",
"2",
"return",
"[",
"A",
"/",
"self",
".",
"a",
",",
"A",
"/",
"self",
".",
"b",
",",
"A",
"/",
"self",
".",
"c",
"]"
] | A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it. | [
"A",
"list",
"of",
"the",
"altitudes",
"of",
"each",
"vertex",
"[",
"AltA",
"AltB",
"AltC",
"]",
"list",
"of",
"floats",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle2.py#L334-L345 | train |
JnyJny/Geometry | Geometry/triangle2.py | Triangle.isIsosceles | def isIsosceles(self):
'''
True iff two side lengths are equal, boolean.
'''
return (self.a == self.b) or (self.a == self.c) or (self.b == self.c) | python | def isIsosceles(self):
'''
True iff two side lengths are equal, boolean.
'''
return (self.a == self.b) or (self.a == self.c) or (self.b == self.c) | [
"def",
"isIsosceles",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"a",
"==",
"self",
".",
"b",
")",
"or",
"(",
"self",
".",
"a",
"==",
"self",
".",
"c",
")",
"or",
"(",
"self",
".",
"b",
"==",
"self",
".",
"c",
")"
] | True iff two side lengths are equal, boolean. | [
"True",
"iff",
"two",
"side",
"lengths",
"are",
"equal",
"boolean",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle2.py#L355-L359 | train |
JnyJny/Geometry | Geometry/triangle2.py | Triangle.congruent | def congruent(self, other):
'''
A congruent B
True iff all angles of 'A' equal angles in 'B' and
all side lengths of 'A' equal all side lengths of 'B', boolean.
'''
a = set(self.angles)
b = set(other.angles)
if len(a) != len(b) or len(a.difference(b)) != 0:
return False
a = set(self.sides)
b = set(other.sides)
return len(a) == len(b) and len(a.difference(b)) == 0 | python | def congruent(self, other):
'''
A congruent B
True iff all angles of 'A' equal angles in 'B' and
all side lengths of 'A' equal all side lengths of 'B', boolean.
'''
a = set(self.angles)
b = set(other.angles)
if len(a) != len(b) or len(a.difference(b)) != 0:
return False
a = set(self.sides)
b = set(other.sides)
return len(a) == len(b) and len(a.difference(b)) == 0 | [
"def",
"congruent",
"(",
"self",
",",
"other",
")",
":",
"a",
"=",
"set",
"(",
"self",
".",
"angles",
")",
"b",
"=",
"set",
"(",
"other",
".",
"angles",
")",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"or",
"len",
"(",
"a",
"."... | A congruent B
True iff all angles of 'A' equal angles in 'B' and
all side lengths of 'A' equal all side lengths of 'B', boolean. | [
"A",
"congruent",
"B"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle2.py#L393-L411 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.center | def center(self):
'''
Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin.
'''
try:
return self._center
except AttributeError:
pass
self._center = Point()
return self._center | python | def center(self):
'''
Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin.
'''
try:
return self._center
except AttributeError:
pass
self._center = Point()
return self._center | [
"def",
"center",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_center",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_center",
"=",
"Point",
"(",
")",
"return",
"self",
".",
"_center"
] | Center point of the ellipse, equidistant from foci, Point class.\n
Defaults to the origin. | [
"Center",
"point",
"of",
"the",
"ellipse",
"equidistant",
"from",
"foci",
"Point",
"class",
".",
"\\",
"n",
"Defaults",
"to",
"the",
"origin",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L47-L57 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.radius | def radius(self):
'''
Radius of the ellipse, Point class.
'''
try:
return self._radius
except AttributeError:
pass
self._radius = Point(1, 1, 0)
return self._radius | python | def radius(self):
'''
Radius of the ellipse, Point class.
'''
try:
return self._radius
except AttributeError:
pass
self._radius = Point(1, 1, 0)
return self._radius | [
"def",
"radius",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_radius",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_radius",
"=",
"Point",
"(",
"1",
",",
"1",
",",
"0",
")",
"return",
"self",
".",
"_radius"
] | Radius of the ellipse, Point class. | [
"Radius",
"of",
"the",
"ellipse",
"Point",
"class",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L64-L73 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.xAxisIsMajor | def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.x | python | def xAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the X axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.x | [
"def",
"xAxisIsMajor",
"(",
"self",
")",
":",
"return",
"max",
"(",
"self",
".",
"radius",
".",
"x",
",",
"self",
".",
"radius",
".",
"y",
")",
"==",
"self",
".",
"radius",
".",
"x"
] | Returns True if the major axis is parallel to the X axis, boolean. | [
"Returns",
"True",
"if",
"the",
"major",
"axis",
"is",
"parallel",
"to",
"the",
"X",
"axis",
"boolean",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L111-L115 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.xAxisIsMinor | def xAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the X axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.x | python | def xAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the X axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.x | [
"def",
"xAxisIsMinor",
"(",
"self",
")",
":",
"return",
"min",
"(",
"self",
".",
"radius",
".",
"x",
",",
"self",
".",
"radius",
".",
"y",
")",
"==",
"self",
".",
"radius",
".",
"x"
] | Returns True if the minor axis is parallel to the X axis, boolean. | [
"Returns",
"True",
"if",
"the",
"minor",
"axis",
"is",
"parallel",
"to",
"the",
"X",
"axis",
"boolean",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L118-L122 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.yAxisIsMajor | def yAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the Y axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.y | python | def yAxisIsMajor(self):
'''
Returns True if the major axis is parallel to the Y axis, boolean.
'''
return max(self.radius.x, self.radius.y) == self.radius.y | [
"def",
"yAxisIsMajor",
"(",
"self",
")",
":",
"return",
"max",
"(",
"self",
".",
"radius",
".",
"x",
",",
"self",
".",
"radius",
".",
"y",
")",
"==",
"self",
".",
"radius",
".",
"y"
] | Returns True if the major axis is parallel to the Y axis, boolean. | [
"Returns",
"True",
"if",
"the",
"major",
"axis",
"is",
"parallel",
"to",
"the",
"Y",
"axis",
"boolean",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L125-L129 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.yAxisIsMinor | def yAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the Y axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.y | python | def yAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the Y axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.y | [
"def",
"yAxisIsMinor",
"(",
"self",
")",
":",
"return",
"min",
"(",
"self",
".",
"radius",
".",
"x",
",",
"self",
".",
"radius",
".",
"y",
")",
"==",
"self",
".",
"radius",
".",
"y"
] | Returns True if the minor axis is parallel to the Y axis, boolean. | [
"Returns",
"True",
"if",
"the",
"minor",
"axis",
"is",
"parallel",
"to",
"the",
"Y",
"axis",
"boolean",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L132-L136 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.a | def a(self):
'''
Positive antipodal point on the major axis, Point class.
'''
a = Point(self.center)
if self.xAxisIsMajor:
a.x += self.majorRadius
else:
a.y += self.majorRadius
return a | python | def a(self):
'''
Positive antipodal point on the major axis, Point class.
'''
a = Point(self.center)
if self.xAxisIsMajor:
a.x += self.majorRadius
else:
a.y += self.majorRadius
return a | [
"def",
"a",
"(",
"self",
")",
":",
"a",
"=",
"Point",
"(",
"self",
".",
"center",
")",
"if",
"self",
".",
"xAxisIsMajor",
":",
"a",
".",
"x",
"+=",
"self",
".",
"majorRadius",
"else",
":",
"a",
".",
"y",
"+=",
"self",
".",
"majorRadius",
"return"... | Positive antipodal point on the major axis, Point class. | [
"Positive",
"antipodal",
"point",
"on",
"the",
"major",
"axis",
"Point",
"class",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L181-L192 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.a_neg | def a_neg(self):
'''
Negative antipodal point on the major axis, Point class.
'''
na = Point(self.center)
if self.xAxisIsMajor:
na.x -= self.majorRadius
else:
na.y -= self.majorRadius
return na | python | def a_neg(self):
'''
Negative antipodal point on the major axis, Point class.
'''
na = Point(self.center)
if self.xAxisIsMajor:
na.x -= self.majorRadius
else:
na.y -= self.majorRadius
return na | [
"def",
"a_neg",
"(",
"self",
")",
":",
"na",
"=",
"Point",
"(",
"self",
".",
"center",
")",
"if",
"self",
".",
"xAxisIsMajor",
":",
"na",
".",
"x",
"-=",
"self",
".",
"majorRadius",
"else",
":",
"na",
".",
"y",
"-=",
"self",
".",
"majorRadius",
"... | Negative antipodal point on the major axis, Point class. | [
"Negative",
"antipodal",
"point",
"on",
"the",
"major",
"axis",
"Point",
"class",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L195-L206 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.b | def b(self):
'''
Positive antipodal point on the minor axis, Point class.
'''
b = Point(self.center)
if self.xAxisIsMinor:
b.x += self.minorRadius
else:
b.y += self.minorRadius
return b | python | def b(self):
'''
Positive antipodal point on the minor axis, Point class.
'''
b = Point(self.center)
if self.xAxisIsMinor:
b.x += self.minorRadius
else:
b.y += self.minorRadius
return b | [
"def",
"b",
"(",
"self",
")",
":",
"b",
"=",
"Point",
"(",
"self",
".",
"center",
")",
"if",
"self",
".",
"xAxisIsMinor",
":",
"b",
".",
"x",
"+=",
"self",
".",
"minorRadius",
"else",
":",
"b",
".",
"y",
"+=",
"self",
".",
"minorRadius",
"return"... | Positive antipodal point on the minor axis, Point class. | [
"Positive",
"antipodal",
"point",
"on",
"the",
"minor",
"axis",
"Point",
"class",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L209-L220 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.b_neg | def b_neg(self):
'''
Negative antipodal point on the minor axis, Point class.
'''
nb = Point(self.center)
if self.xAxisIsMinor:
nb.x -= self.minorRadius
else:
nb.y -= self.minorRadius
return nb | python | def b_neg(self):
'''
Negative antipodal point on the minor axis, Point class.
'''
nb = Point(self.center)
if self.xAxisIsMinor:
nb.x -= self.minorRadius
else:
nb.y -= self.minorRadius
return nb | [
"def",
"b_neg",
"(",
"self",
")",
":",
"nb",
"=",
"Point",
"(",
"self",
".",
"center",
")",
"if",
"self",
".",
"xAxisIsMinor",
":",
"nb",
".",
"x",
"-=",
"self",
".",
"minorRadius",
"else",
":",
"nb",
".",
"y",
"-=",
"self",
".",
"minorRadius",
"... | Negative antipodal point on the minor axis, Point class. | [
"Negative",
"antipodal",
"point",
"on",
"the",
"minor",
"axis",
"Point",
"class",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L223-L233 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.vertices | def vertices(self):
'''
A dictionary of four points where the axes intersect the ellipse, dict.
'''
return {'a': self.a, 'a_neg': self.a_neg,
'b': self.b, 'b_neg': self.b_neg} | python | def vertices(self):
'''
A dictionary of four points where the axes intersect the ellipse, dict.
'''
return {'a': self.a, 'a_neg': self.a_neg,
'b': self.b, 'b_neg': self.b_neg} | [
"def",
"vertices",
"(",
"self",
")",
":",
"return",
"{",
"'a'",
":",
"self",
".",
"a",
",",
"'a_neg'",
":",
"self",
".",
"a_neg",
",",
"'b'",
":",
"self",
".",
"b",
",",
"'b_neg'",
":",
"self",
".",
"b_neg",
"}"
] | A dictionary of four points where the axes intersect the ellipse, dict. | [
"A",
"dictionary",
"of",
"four",
"points",
"where",
"the",
"axes",
"intersect",
"the",
"ellipse",
"dict",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L236-L241 | train |
JnyJny/Geometry | Geometry/ellipse.py | Ellipse.focus0 | def focus0(self):
'''
First focus of the ellipse, Point class.
'''
f = Point(self.center)
if self.xAxisIsMajor:
f.x -= self.linearEccentricity
else:
f.y -= self.linearEccentricity
return f | python | def focus0(self):
'''
First focus of the ellipse, Point class.
'''
f = Point(self.center)
if self.xAxisIsMajor:
f.x -= self.linearEccentricity
else:
f.y -= self.linearEccentricity
return f | [
"def",
"focus0",
"(",
"self",
")",
":",
"f",
"=",
"Point",
"(",
"self",
".",
"center",
")",
"if",
"self",
".",
"xAxisIsMajor",
":",
"f",
".",
"x",
"-=",
"self",
".",
"linearEccentricity",
"else",
":",
"f",
".",
"y",
"-=",
"self",
".",
"linearEccent... | First focus of the ellipse, Point class. | [
"First",
"focus",
"of",
"the",
"ellipse",
"Point",
"class",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L244-L255 | train |
JnyJny/Geometry | Geometry/ellipse.py | Circle.circumcircleForTriangle | def circumcircleForTriangle(cls, triangle):
'''
:param: triangle - Triangle class
:return: Circle class
Returns the circle where every vertex in the input triangle is
on the radius of that circle.
'''
if triangle.isRight:
# circumcircle origin is the midpoint of the hypotenues
o = triangle.hypotenuse.midpoint
r = o.distance(triangle.A)
return cls(o, r)
# otherwise
# 1. find the normals to two sides
# 2. translate them to the midpoints of those two sides
# 3. intersect those lines for center of circumcircle
# 4. radius is distance from center to any vertex in the triangle
abn = triangle.AB.normal
abn += triangle.AB.midpoint
acn = triangle.AC.normal
acn += triangle.AC.midpoint
o = abn.intersection(acn)
r = o.distance(triangle.A)
return cls(o, r) | python | def circumcircleForTriangle(cls, triangle):
'''
:param: triangle - Triangle class
:return: Circle class
Returns the circle where every vertex in the input triangle is
on the radius of that circle.
'''
if triangle.isRight:
# circumcircle origin is the midpoint of the hypotenues
o = triangle.hypotenuse.midpoint
r = o.distance(triangle.A)
return cls(o, r)
# otherwise
# 1. find the normals to two sides
# 2. translate them to the midpoints of those two sides
# 3. intersect those lines for center of circumcircle
# 4. radius is distance from center to any vertex in the triangle
abn = triangle.AB.normal
abn += triangle.AB.midpoint
acn = triangle.AC.normal
acn += triangle.AC.midpoint
o = abn.intersection(acn)
r = o.distance(triangle.A)
return cls(o, r) | [
"def",
"circumcircleForTriangle",
"(",
"cls",
",",
"triangle",
")",
":",
"if",
"triangle",
".",
"isRight",
":",
"# circumcircle origin is the midpoint of the hypotenues",
"o",
"=",
"triangle",
".",
"hypotenuse",
".",
"midpoint",
"r",
"=",
"o",
".",
"distance",
"("... | :param: triangle - Triangle class
:return: Circle class
Returns the circle where every vertex in the input triangle is
on the radius of that circle. | [
":",
"param",
":",
"triangle",
"-",
"Triangle",
"class",
":",
"return",
":",
"Circle",
"class"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L416-L446 | train |
JnyJny/Geometry | Geometry/ellipse.py | Circle.doesIntersect | def doesIntersect(self, other):
'''
:param: other - Circle class
Returns True iff:
self.center.distance(other.center) <= self.radius+other.radius
'''
otherType = type(other)
if issubclass(otherType, Ellipse):
distance = self.center.distance(other.center)
radiisum = self.radius + other.radius
return distance <= radiisum
if issubclass(otherType, Line):
raise NotImplementedError('doesIntersect,other is Line class')
raise TypeError("unknown type '{t}'".format(t=otherType)) | python | def doesIntersect(self, other):
'''
:param: other - Circle class
Returns True iff:
self.center.distance(other.center) <= self.radius+other.radius
'''
otherType = type(other)
if issubclass(otherType, Ellipse):
distance = self.center.distance(other.center)
radiisum = self.radius + other.radius
return distance <= radiisum
if issubclass(otherType, Line):
raise NotImplementedError('doesIntersect,other is Line class')
raise TypeError("unknown type '{t}'".format(t=otherType)) | [
"def",
"doesIntersect",
"(",
"self",
",",
"other",
")",
":",
"otherType",
"=",
"type",
"(",
"other",
")",
"if",
"issubclass",
"(",
"otherType",
",",
"Ellipse",
")",
":",
"distance",
"=",
"self",
".",
"center",
".",
"distance",
"(",
"other",
".",
"cente... | :param: other - Circle class
Returns True iff:
self.center.distance(other.center) <= self.radius+other.radius | [
":",
"param",
":",
"other",
"-",
"Circle",
"class"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/ellipse.py#L535-L553 | train |
JnyJny/Geometry | Geometry/line.py | Line.AB | def AB(self):
'''
A list containing Points A and B.
'''
try:
return self._AB
except AttributeError:
pass
self._AB = [self.A, self.B]
return self._AB | python | def AB(self):
'''
A list containing Points A and B.
'''
try:
return self._AB
except AttributeError:
pass
self._AB = [self.A, self.B]
return self._AB | [
"def",
"AB",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_AB",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_AB",
"=",
"[",
"self",
".",
"A",
",",
"self",
".",
"B",
"]",
"return",
"self",
".",
"_AB"
] | A list containing Points A and B. | [
"A",
"list",
"containing",
"Points",
"A",
"and",
"B",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L117-L126 | train |
JnyJny/Geometry | Geometry/line.py | Line.normal | def normal(self):
'''
:return: Line
Returns a Line normal (perpendicular) to this Line.
'''
d = self.B - self.A
return Line([-d.y, d.x], [d.y, -d.x]) | python | def normal(self):
'''
:return: Line
Returns a Line normal (perpendicular) to this Line.
'''
d = self.B - self.A
return Line([-d.y, d.x], [d.y, -d.x]) | [
"def",
"normal",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"B",
"-",
"self",
".",
"A",
"return",
"Line",
"(",
"[",
"-",
"d",
".",
"y",
",",
"d",
".",
"x",
"]",
",",
"[",
"d",
".",
"y",
",",
"-",
"d",
".",
"x",
"]",
")"
] | :return: Line
Returns a Line normal (perpendicular) to this Line. | [
":",
"return",
":",
"Line"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L173-L182 | train |
JnyJny/Geometry | Geometry/line.py | Line.t | def t(self, point):
'''
:point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, point is between A and B
if t > 1 point is greater than B
'''
# XXX could use for an ordering on points?
if point not in self:
msg = "'{p}' is not collinear with '{l}'"
raise CollinearPoints(msg.format(p=point, l=self))
# p = A + t ( B - A)
# p - A = t ( B - A)
# p - A / (B -A) = t
return (point - self.A) / self.m | python | def t(self, point):
'''
:point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, point is between A and B
if t > 1 point is greater than B
'''
# XXX could use for an ordering on points?
if point not in self:
msg = "'{p}' is not collinear with '{l}'"
raise CollinearPoints(msg.format(p=point, l=self))
# p = A + t ( B - A)
# p - A = t ( B - A)
# p - A / (B -A) = t
return (point - self.A) / self.m | [
"def",
"t",
"(",
"self",
",",
"point",
")",
":",
"# XXX could use for an ordering on points?",
"if",
"point",
"not",
"in",
"self",
":",
"msg",
"=",
"\"'{p}' is not collinear with '{l}'\"",
"raise",
"CollinearPoints",
"(",
"msg",
".",
"format",
"(",
"p",
"=",
"po... | :point: Point subclass
:return: float
If :point: is collinear, determine the 't' coefficient of
the parametric equation:
xyz = A<xyz> + t ( B<xyz> - A<xyz> )
if t < 0, point is less than A and B on the line
if t >= 0 and <= 1, point is between A and B
if t > 1 point is greater than B | [
":",
"point",
":",
"Point",
"subclass",
":",
"return",
":",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L198-L223 | train |
JnyJny/Geometry | Geometry/line.py | Line.flip | def flip(self):
'''
:returns: None
Swaps the positions of A and B.
'''
tmp = self.A.xyz
self.A = self.B
self.B = tmp | python | def flip(self):
'''
:returns: None
Swaps the positions of A and B.
'''
tmp = self.A.xyz
self.A = self.B
self.B = tmp | [
"def",
"flip",
"(",
"self",
")",
":",
"tmp",
"=",
"self",
".",
"A",
".",
"xyz",
"self",
".",
"A",
"=",
"self",
".",
"B",
"self",
".",
"B",
"=",
"tmp"
] | :returns: None
Swaps the positions of A and B. | [
":",
"returns",
":",
"None"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L294-L302 | train |
JnyJny/Geometry | Geometry/line.py | Line.doesIntersect | def doesIntersect(self, other):
'''
:param: other - Line subclass
:return: boolean
Returns True iff:
ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0
and
ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0
'''
if self.A.ccw(self.B, other.A) * self.A.ccw(self.B, other.B) > 0:
return False
if other.A.ccw(other.B, self.A) * other.A.ccw(other.B, self.B) > 0:
return False
return True | python | def doesIntersect(self, other):
'''
:param: other - Line subclass
:return: boolean
Returns True iff:
ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0
and
ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0
'''
if self.A.ccw(self.B, other.A) * self.A.ccw(self.B, other.B) > 0:
return False
if other.A.ccw(other.B, self.A) * other.A.ccw(other.B, self.B) > 0:
return False
return True | [
"def",
"doesIntersect",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"A",
".",
"ccw",
"(",
"self",
".",
"B",
",",
"other",
".",
"A",
")",
"*",
"self",
".",
"A",
".",
"ccw",
"(",
"self",
".",
"B",
",",
"other",
".",
"B",
")",
">",... | :param: other - Line subclass
:return: boolean
Returns True iff:
ccw(self.A,self.B,other.A) * ccw(self.A,self.B,other.B) <= 0
and
ccw(other.A,other.B,self.A) * ccw(other.A,other.B,self.B) <= 0 | [
":",
"param",
":",
"other",
"-",
"Line",
"subclass",
":",
"return",
":",
"boolean"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L304-L321 | train |
JnyJny/Geometry | Geometry/line.py | Line.intersection | def intersection(self, other):
'''
:param: other - Line subclass
:return: Point subclass
Returns a Point object with the coordinates of the intersection
between the current line and the other line.
Will raise Parallel() if the two lines are parallel.
Will raise Collinear() if the two lines are collinear.
'''
if self.isCollinear(other):
msg = '{!r} and {!r} are collinear'
raise CollinearLines(msg.format(self, other))
d0 = self.A - self.B
d1 = other.A - other.B
denominator = (d0.x * d1.y) - (d0.y * d1.x)
if denominator == 0:
msg = '{!r} and {!r} are parallel'
raise ParallelLines(msg.format(self, other))
cp0 = self.A.cross(self.B)
cp1 = other.A.cross(other.B)
x_num = (cp0 * d1.x) - (d0.x * cp1)
y_num = (cp0 * d1.y) - (d0.y * cp1)
p = Point(x_num / denominator, y_num / denominator)
if p in self and p in other:
return p
msg = "found point {!r} but not in {!r} and {!r}"
raise ParallelLines(msg.format(p, self, other)) | python | def intersection(self, other):
'''
:param: other - Line subclass
:return: Point subclass
Returns a Point object with the coordinates of the intersection
between the current line and the other line.
Will raise Parallel() if the two lines are parallel.
Will raise Collinear() if the two lines are collinear.
'''
if self.isCollinear(other):
msg = '{!r} and {!r} are collinear'
raise CollinearLines(msg.format(self, other))
d0 = self.A - self.B
d1 = other.A - other.B
denominator = (d0.x * d1.y) - (d0.y * d1.x)
if denominator == 0:
msg = '{!r} and {!r} are parallel'
raise ParallelLines(msg.format(self, other))
cp0 = self.A.cross(self.B)
cp1 = other.A.cross(other.B)
x_num = (cp0 * d1.x) - (d0.x * cp1)
y_num = (cp0 * d1.y) - (d0.y * cp1)
p = Point(x_num / denominator, y_num / denominator)
if p in self and p in other:
return p
msg = "found point {!r} but not in {!r} and {!r}"
raise ParallelLines(msg.format(p, self, other)) | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"isCollinear",
"(",
"other",
")",
":",
"msg",
"=",
"'{!r} and {!r} are collinear'",
"raise",
"CollinearLines",
"(",
"msg",
".",
"format",
"(",
"self",
",",
"other",
")",
")",
... | :param: other - Line subclass
:return: Point subclass
Returns a Point object with the coordinates of the intersection
between the current line and the other line.
Will raise Parallel() if the two lines are parallel.
Will raise Collinear() if the two lines are collinear. | [
":",
"param",
":",
"other",
"-",
"Line",
"subclass",
":",
"return",
":",
"Point",
"subclass"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L342-L379 | train |
JnyJny/Geometry | Geometry/line.py | Line.distanceFromPoint | def distanceFromPoint(self, point):
'''
:param: point - Point subclass
:return: float
Distance from the line to the given point.
'''
# XXX planar distance, doesn't take into account z ?
d = self.m
n = (d.y * point.x) - (d.x * point.y) + self.A.cross(self.B)
return abs(n / self.A.distance(self.B)) | python | def distanceFromPoint(self, point):
'''
:param: point - Point subclass
:return: float
Distance from the line to the given point.
'''
# XXX planar distance, doesn't take into account z ?
d = self.m
n = (d.y * point.x) - (d.x * point.y) + self.A.cross(self.B)
return abs(n / self.A.distance(self.B)) | [
"def",
"distanceFromPoint",
"(",
"self",
",",
"point",
")",
":",
"# XXX planar distance, doesn't take into account z ?",
"d",
"=",
"self",
".",
"m",
"n",
"=",
"(",
"d",
".",
"y",
"*",
"point",
".",
"x",
")",
"-",
"(",
"d",
".",
"x",
"*",
"point",
".",
... | :param: point - Point subclass
:return: float
Distance from the line to the given point. | [
":",
"param",
":",
"point",
"-",
"Point",
"subclass",
":",
"return",
":",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L381-L391 | train |
JnyJny/Geometry | Geometry/line.py | Line.radiansBetween | def radiansBetween(self, other):
'''
:param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi].
'''
# a dot b = |a||b| * cos(theta)
# a dot b / |a||b| = cos(theta)
# cos-1(a dot b / |a||b|) = theta
# translate each line so that it passes through the origin and
# produce a new point whose distance (magnitude) from the
# origin is 1.
#
a = Point.unit(self.A, self.B)
b = Point.unit(other.A, other.B)
# in a perfect world, after unit: |A| = |B| = 1
# which is a noop when dividing the dot product of A,B
# but sometimes the lengths are different.
#
# let's just assume things are perfect and the lengths equal 1.
return math.acos(a.dot(b)) | python | def radiansBetween(self, other):
'''
:param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi].
'''
# a dot b = |a||b| * cos(theta)
# a dot b / |a||b| = cos(theta)
# cos-1(a dot b / |a||b|) = theta
# translate each line so that it passes through the origin and
# produce a new point whose distance (magnitude) from the
# origin is 1.
#
a = Point.unit(self.A, self.B)
b = Point.unit(other.A, other.B)
# in a perfect world, after unit: |A| = |B| = 1
# which is a noop when dividing the dot product of A,B
# but sometimes the lengths are different.
#
# let's just assume things are perfect and the lengths equal 1.
return math.acos(a.dot(b)) | [
"def",
"radiansBetween",
"(",
"self",
",",
"other",
")",
":",
"# a dot b = |a||b| * cos(theta)",
"# a dot b / |a||b| = cos(theta)",
"# cos-1(a dot b / |a||b|) = theta",
"# translate each line so that it passes through the origin and",
"# produce a new point whose distance (magnitude) from th... | :param: other - Line subclass
:return: float
Returns the angle measured between two lines in radians
with a range of [0, 2 * math.pi]. | [
":",
"param",
":",
"other",
"-",
"Line",
"subclass",
":",
"return",
":",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/line.py#L403-L430 | train |
JnyJny/Geometry | Geometry/propgen.py | FloatProperty | def FloatProperty(name, default=0.0, readonly=False, docs=None):
'''
:name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initialize a
class instance variable as a property.
'''
private_name = '_' + name
def getf(self):
if not hasattr(self, private_name):
setattr(self, private_name, default)
return getattr(self, private_name)
if readonly:
setf = None
else:
def setf(self, newValue):
def epsilon_set(v):
# epsilon_set: creates a float from v unless that
# float is less than epsilon, which will
# be considered effectively zero.
fv = float(v)
return 0.0 if nearly_zero(fv) else fv
try:
setattr(self, private_name, epsilon_set(newValue))
return
except TypeError:
pass
if isinstance(newValue, collections.Mapping):
try:
setattr(self, private_name, epsilon_set(newValue[name]))
except KeyError:
pass
return
if isinstance(newValue, collections.Iterable):
try:
setattr(self, private_name, epsilon_set(newValue[0]))
return
except (IndexError, TypeError):
pass
try:
mapping = vars(newValue)
setattr(self, private_name, epsilon_set(mapping[name]))
return
except (TypeError, KeyError):
pass
if newValue is None:
setattr(self, private_name, epsilon_set(default))
return
raise ValueError(newValue)
return property(getf, setf, None, docs) | python | def FloatProperty(name, default=0.0, readonly=False, docs=None):
'''
:name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initialize a
class instance variable as a property.
'''
private_name = '_' + name
def getf(self):
if not hasattr(self, private_name):
setattr(self, private_name, default)
return getattr(self, private_name)
if readonly:
setf = None
else:
def setf(self, newValue):
def epsilon_set(v):
# epsilon_set: creates a float from v unless that
# float is less than epsilon, which will
# be considered effectively zero.
fv = float(v)
return 0.0 if nearly_zero(fv) else fv
try:
setattr(self, private_name, epsilon_set(newValue))
return
except TypeError:
pass
if isinstance(newValue, collections.Mapping):
try:
setattr(self, private_name, epsilon_set(newValue[name]))
except KeyError:
pass
return
if isinstance(newValue, collections.Iterable):
try:
setattr(self, private_name, epsilon_set(newValue[0]))
return
except (IndexError, TypeError):
pass
try:
mapping = vars(newValue)
setattr(self, private_name, epsilon_set(mapping[name]))
return
except (TypeError, KeyError):
pass
if newValue is None:
setattr(self, private_name, epsilon_set(default))
return
raise ValueError(newValue)
return property(getf, setf, None, docs) | [
"def",
"FloatProperty",
"(",
"name",
",",
"default",
"=",
"0.0",
",",
"readonly",
"=",
"False",
",",
"docs",
"=",
"None",
")",
":",
"private_name",
"=",
"'_'",
"+",
"name",
"def",
"getf",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
... | :name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initialize a
class instance variable as a property. | [
":",
"name",
":",
"string",
"-",
"property",
"name",
":",
"default",
":",
"float",
"-",
"property",
"default",
"value",
":",
"readonly",
":",
"boolean",
"-",
"if",
"True",
"setter",
"method",
"is",
"NOT",
"generated"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/propgen.py#L25-L86 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.randomSizeAndLocation | def randomSizeAndLocation(cls, radius, widthLimits,
heightLimits, origin=None):
'''
:param: radius - float
:param: widthLimits - iterable of floats with length >= 2
:param: heightLimits - iterable of floats with length >= 2
:param: origin - optional Point subclass
:return: Rectangle
'''
r = cls(widthLimits, heightLimits, origin)
r.origin = Point.randomLocation(radius, origin) | python | def randomSizeAndLocation(cls, radius, widthLimits,
heightLimits, origin=None):
'''
:param: radius - float
:param: widthLimits - iterable of floats with length >= 2
:param: heightLimits - iterable of floats with length >= 2
:param: origin - optional Point subclass
:return: Rectangle
'''
r = cls(widthLimits, heightLimits, origin)
r.origin = Point.randomLocation(radius, origin) | [
"def",
"randomSizeAndLocation",
"(",
"cls",
",",
"radius",
",",
"widthLimits",
",",
"heightLimits",
",",
"origin",
"=",
"None",
")",
":",
"r",
"=",
"cls",
"(",
"widthLimits",
",",
"heightLimits",
",",
"origin",
")",
"r",
".",
"origin",
"=",
"Point",
".",... | :param: radius - float
:param: widthLimits - iterable of floats with length >= 2
:param: heightLimits - iterable of floats with length >= 2
:param: origin - optional Point subclass
:return: Rectangle | [
":",
"param",
":",
"radius",
"-",
"float",
":",
"param",
":",
"widthLimits",
"-",
"iterable",
"of",
"floats",
"with",
"length",
">",
"=",
"2",
":",
"param",
":",
"heightLimits",
"-",
"iterable",
"of",
"floats",
"with",
"length",
">",
"=",
"2",
":",
"... | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L26-L38 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.randomSize | def randomSize(cls, widthLimits, heightLimits, origin=None):
'''
:param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle
'''
r = cls(0, 0, origin)
r.w = random.randint(widthLimits[0], widthLimits[1])
r.h = random.randint(heightLimits[0], heightLimits[1])
return r | python | def randomSize(cls, widthLimits, heightLimits, origin=None):
'''
:param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle
'''
r = cls(0, 0, origin)
r.w = random.randint(widthLimits[0], widthLimits[1])
r.h = random.randint(heightLimits[0], heightLimits[1])
return r | [
"def",
"randomSize",
"(",
"cls",
",",
"widthLimits",
",",
"heightLimits",
",",
"origin",
"=",
"None",
")",
":",
"r",
"=",
"cls",
"(",
"0",
",",
"0",
",",
"origin",
")",
"r",
".",
"w",
"=",
"random",
".",
"randint",
"(",
"widthLimits",
"[",
"0",
"... | :param: widthLimits - iterable of integers with length >= 2
:param: heightLimits - iterable of integers with length >= 2
:param: origin - optional Point subclass
:return: Rectangle | [
":",
"param",
":",
"widthLimits",
"-",
"iterable",
"of",
"integers",
"with",
"length",
">",
"=",
"2",
":",
"param",
":",
"heightLimits",
"-",
"iterable",
"of",
"integers",
"with",
"length",
">",
"=",
"2",
":",
"param",
":",
"origin",
"-",
"optional",
"... | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L41-L54 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.randomLocation | def randomLocation(cls, radius, width, height, origin=None):
'''
:param: radius - float
:param: width - float
:param: height - float
:param: origin - optional Point subclass
:return: Rectangle
'''
return cls(width,
height,
Point.randomLocation(radius, origin)) | python | def randomLocation(cls, radius, width, height, origin=None):
'''
:param: radius - float
:param: width - float
:param: height - float
:param: origin - optional Point subclass
:return: Rectangle
'''
return cls(width,
height,
Point.randomLocation(radius, origin)) | [
"def",
"randomLocation",
"(",
"cls",
",",
"radius",
",",
"width",
",",
"height",
",",
"origin",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"width",
",",
"height",
",",
"Point",
".",
"randomLocation",
"(",
"radius",
",",
"origin",
")",
")"
] | :param: radius - float
:param: width - float
:param: height - float
:param: origin - optional Point subclass
:return: Rectangle | [
":",
"param",
":",
"radius",
"-",
"float",
":",
"param",
":",
"width",
"-",
"float",
":",
"param",
":",
"height",
"-",
"float",
":",
"param",
":",
"origin",
"-",
"optional",
"Point",
"subclass",
":",
"return",
":",
"Rectangle"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L57-L67 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.origin | def origin(self):
'''
Point describing the origin of the rectangle. Defaults to (0,0,0).
'''
try:
return self._origin
except AttributeError:
pass
self._origin = Point()
return self._origin | python | def origin(self):
'''
Point describing the origin of the rectangle. Defaults to (0,0,0).
'''
try:
return self._origin
except AttributeError:
pass
self._origin = Point()
return self._origin | [
"def",
"origin",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_origin",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_origin",
"=",
"Point",
"(",
")",
"return",
"self",
".",
"_origin"
] | Point describing the origin of the rectangle. Defaults to (0,0,0). | [
"Point",
"describing",
"the",
"origin",
"of",
"the",
"rectangle",
".",
"Defaults",
"to",
"(",
"0",
"0",
"0",
")",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L87-L96 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.B | def B(self):
'''
Point whose coordinates are (maxX,minY,origin.z), Point.
'''
return Point(self.maxX, self.minY, self.origin.z) | python | def B(self):
'''
Point whose coordinates are (maxX,minY,origin.z), Point.
'''
return Point(self.maxX, self.minY, self.origin.z) | [
"def",
"B",
"(",
"self",
")",
":",
"return",
"Point",
"(",
"self",
".",
"maxX",
",",
"self",
".",
"minY",
",",
"self",
".",
"origin",
".",
"z",
")"
] | Point whose coordinates are (maxX,minY,origin.z), Point. | [
"Point",
"whose",
"coordinates",
"are",
"(",
"maxX",
"minY",
"origin",
".",
"z",
")",
"Point",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L302-L306 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.C | def C(self):
'''
Point whose coordinates are (maxX,maxY,origin.z), Point.
'''
return Point(self.maxX, self.maxY, self.origin.z) | python | def C(self):
'''
Point whose coordinates are (maxX,maxY,origin.z), Point.
'''
return Point(self.maxX, self.maxY, self.origin.z) | [
"def",
"C",
"(",
"self",
")",
":",
"return",
"Point",
"(",
"self",
".",
"maxX",
",",
"self",
".",
"maxY",
",",
"self",
".",
"origin",
".",
"z",
")"
] | Point whose coordinates are (maxX,maxY,origin.z), Point. | [
"Point",
"whose",
"coordinates",
"are",
"(",
"maxX",
"maxY",
"origin",
".",
"z",
")",
"Point",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L314-L318 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.D | def D(self):
'''
Point whose coordinates are (minX,maxY,origin.Z), Point.
'''
return Point(self.minX, self.maxY, self.origin.z) | python | def D(self):
'''
Point whose coordinates are (minX,maxY,origin.Z), Point.
'''
return Point(self.minX, self.maxY, self.origin.z) | [
"def",
"D",
"(",
"self",
")",
":",
"return",
"Point",
"(",
"self",
".",
"minX",
",",
"self",
".",
"maxY",
",",
"self",
".",
"origin",
".",
"z",
")"
] | Point whose coordinates are (minX,maxY,origin.Z), Point. | [
"Point",
"whose",
"coordinates",
"are",
"(",
"minX",
"maxY",
"origin",
".",
"Z",
")",
"Point",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L327-L331 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.center | def center(self):
'''
Point whose coordinates are (midX,midY,origin.z), Point.
'''
return Point(self.midX, self.midY, self.origin.z) | python | def center(self):
'''
Point whose coordinates are (midX,midY,origin.z), Point.
'''
return Point(self.midX, self.midY, self.origin.z) | [
"def",
"center",
"(",
"self",
")",
":",
"return",
"Point",
"(",
"self",
".",
"midX",
",",
"self",
".",
"midY",
",",
"self",
".",
"origin",
".",
"z",
")"
] | Point whose coordinates are (midX,midY,origin.z), Point. | [
"Point",
"whose",
"coordinates",
"are",
"(",
"midX",
"midY",
"origin",
".",
"z",
")",
"Point",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L339-L343 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.scale | def scale(self, dx=1.0, dy=1.0):
'''
:param: dx - optional float
:param: dy - optional float
Scales the rectangle's width and height by dx and dy.
'''
self.width *= dx
self.height *= dy | python | def scale(self, dx=1.0, dy=1.0):
'''
:param: dx - optional float
:param: dy - optional float
Scales the rectangle's width and height by dx and dy.
'''
self.width *= dx
self.height *= dy | [
"def",
"scale",
"(",
"self",
",",
"dx",
"=",
"1.0",
",",
"dy",
"=",
"1.0",
")",
":",
"self",
".",
"width",
"*=",
"dx",
"self",
".",
"height",
"*=",
"dy"
] | :param: dx - optional float
:param: dy - optional float
Scales the rectangle's width and height by dx and dy. | [
":",
"param",
":",
"dx",
"-",
"optional",
"float",
":",
"param",
":",
"dy",
"-",
"optional",
"float"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L503-L512 | train |
JnyJny/Geometry | Geometry/rectangle.py | Rectangle.containsPoint | def containsPoint(self, point, Zorder=False):
'''
:param: point - Point subclass
:param: Zorder - optional Boolean
Is true if the point is contain in the rectangle or
along the rectangle's edges.
If Zorder is True, the method will check point.z for
equality with the rectangle origin's Z coordinate.
'''
if not point.isBetweenX(self.A, self.B):
return False
if not point.isBetweenY(self.A, self.D):
return False
if Zorder:
return point.z == self.origin.z
return True | python | def containsPoint(self, point, Zorder=False):
'''
:param: point - Point subclass
:param: Zorder - optional Boolean
Is true if the point is contain in the rectangle or
along the rectangle's edges.
If Zorder is True, the method will check point.z for
equality with the rectangle origin's Z coordinate.
'''
if not point.isBetweenX(self.A, self.B):
return False
if not point.isBetweenY(self.A, self.D):
return False
if Zorder:
return point.z == self.origin.z
return True | [
"def",
"containsPoint",
"(",
"self",
",",
"point",
",",
"Zorder",
"=",
"False",
")",
":",
"if",
"not",
"point",
".",
"isBetweenX",
"(",
"self",
".",
"A",
",",
"self",
".",
"B",
")",
":",
"return",
"False",
"if",
"not",
"point",
".",
"isBetweenY",
"... | :param: point - Point subclass
:param: Zorder - optional Boolean
Is true if the point is contain in the rectangle or
along the rectangle's edges.
If Zorder is True, the method will check point.z for
equality with the rectangle origin's Z coordinate. | [
":",
"param",
":",
"point",
"-",
"Point",
"subclass",
":",
"param",
":",
"Zorder",
"-",
"optional",
"Boolean"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/rectangle.py#L536-L556 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.random | def random(cls, origin=None, radius=1):
'''
:origin: - optional Point subclass
:radius: - optional float
:return: Triangle
Creates a triangle with random coordinates in the circle
described by (origin,radius). If origin is unspecified, (0,0)
is assumed. If the radius is unspecified, 1.0 is assumed.
'''
# XXX no collinearity checks, possible to generate a
# line (not likely, just possible).
#
pts = set()
while len(pts) < 3:
p = Point.random(origin, radius)
pts.add(p)
return cls(pts) | python | def random(cls, origin=None, radius=1):
'''
:origin: - optional Point subclass
:radius: - optional float
:return: Triangle
Creates a triangle with random coordinates in the circle
described by (origin,radius). If origin is unspecified, (0,0)
is assumed. If the radius is unspecified, 1.0 is assumed.
'''
# XXX no collinearity checks, possible to generate a
# line (not likely, just possible).
#
pts = set()
while len(pts) < 3:
p = Point.random(origin, radius)
pts.add(p)
return cls(pts) | [
"def",
"random",
"(",
"cls",
",",
"origin",
"=",
"None",
",",
"radius",
"=",
"1",
")",
":",
"# XXX no collinearity checks, possible to generate a",
"# line (not likely, just possible).",
"#",
"pts",
"=",
"set",
"(",
")",
"while",
"len",
"(",
"pts",
")",
"<",... | :origin: - optional Point subclass
:radius: - optional float
:return: Triangle
Creates a triangle with random coordinates in the circle
described by (origin,radius). If origin is unspecified, (0,0)
is assumed. If the radius is unspecified, 1.0 is assumed. | [
":",
"origin",
":",
"-",
"optional",
"Point",
"subclass",
":",
"radius",
":",
"-",
"optional",
"float",
":",
"return",
":",
"Triangle"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L47-L65 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.equilateral | def equilateral(cls, origin=None, side=1):
'''
:origin: optional Point
:side: optional float describing triangle side length
:return: Triangle initialized with points comprising a
equilateral triangle.
XXX equilateral triangle definition
'''
o = Point(origin)
base = o.x + side
h = 0.5 * Sqrt_3 * side + o.y
return cls(o, [base, o.y], [base / 2, h]) | python | def equilateral(cls, origin=None, side=1):
'''
:origin: optional Point
:side: optional float describing triangle side length
:return: Triangle initialized with points comprising a
equilateral triangle.
XXX equilateral triangle definition
'''
o = Point(origin)
base = o.x + side
h = 0.5 * Sqrt_3 * side + o.y
return cls(o, [base, o.y], [base / 2, h]) | [
"def",
"equilateral",
"(",
"cls",
",",
"origin",
"=",
"None",
",",
"side",
"=",
"1",
")",
":",
"o",
"=",
"Point",
"(",
"origin",
")",
"base",
"=",
"o",
".",
"x",
"+",
"side",
"h",
"=",
"0.5",
"*",
"Sqrt_3",
"*",
"side",
"+",
"o",
".",
"y",
... | :origin: optional Point
:side: optional float describing triangle side length
:return: Triangle initialized with points comprising a
equilateral triangle.
XXX equilateral triangle definition | [
":",
"origin",
":",
"optional",
"Point",
":",
"side",
":",
"optional",
"float",
"describing",
"triangle",
"side",
"length",
":",
"return",
":",
"Triangle",
"initialized",
"with",
"points",
"comprising",
"a",
"equilateral",
"triangle",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L68-L83 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.isosceles | def isosceles(cls, origin=None, base=1, alpha=90):
'''
:origin: optional Point
:base: optional float describing triangle base length
:return: Triangle initialized with points comprising a
isosceles triangle.
XXX isoceles triangle definition
'''
o = Point(origin)
base = o.x + base
return cls(o, [base, o.y], [base / 2, o.y + base]) | python | def isosceles(cls, origin=None, base=1, alpha=90):
'''
:origin: optional Point
:base: optional float describing triangle base length
:return: Triangle initialized with points comprising a
isosceles triangle.
XXX isoceles triangle definition
'''
o = Point(origin)
base = o.x + base
return cls(o, [base, o.y], [base / 2, o.y + base]) | [
"def",
"isosceles",
"(",
"cls",
",",
"origin",
"=",
"None",
",",
"base",
"=",
"1",
",",
"alpha",
"=",
"90",
")",
":",
"o",
"=",
"Point",
"(",
"origin",
")",
"base",
"=",
"o",
".",
"x",
"+",
"base",
"return",
"cls",
"(",
"o",
",",
"[",
"base",... | :origin: optional Point
:base: optional float describing triangle base length
:return: Triangle initialized with points comprising a
isosceles triangle.
XXX isoceles triangle definition | [
":",
"origin",
":",
"optional",
"Point",
":",
"base",
":",
"optional",
"float",
"describing",
"triangle",
"base",
"length",
":",
"return",
":",
"Triangle",
"initialized",
"with",
"points",
"comprising",
"a",
"isosceles",
"triangle",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L87-L100 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.C | def C(self):
'''
Third vertex of triangle, Point subclass.
'''
try:
return self._C
except AttributeError:
pass
self._C = Point(0, 1)
return self._C | python | def C(self):
'''
Third vertex of triangle, Point subclass.
'''
try:
return self._C
except AttributeError:
pass
self._C = Point(0, 1)
return self._C | [
"def",
"C",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_C",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_C",
"=",
"Point",
"(",
"0",
",",
"1",
")",
"return",
"self",
".",
"_C"
] | Third vertex of triangle, Point subclass. | [
"Third",
"vertex",
"of",
"triangle",
"Point",
"subclass",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L216-L226 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.ABC | def ABC(self):
'''
A list of the triangle's vertices, list.
'''
try:
return self._ABC
except AttributeError:
pass
self._ABC = [self.A, self.B, self.C]
return self._ABC | python | def ABC(self):
'''
A list of the triangle's vertices, list.
'''
try:
return self._ABC
except AttributeError:
pass
self._ABC = [self.A, self.B, self.C]
return self._ABC | [
"def",
"ABC",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_ABC",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_ABC",
"=",
"[",
"self",
".",
"A",
",",
"self",
".",
"B",
",",
"self",
".",
"C",
"]",
"return",
"self",
".",
... | A list of the triangle's vertices, list. | [
"A",
"list",
"of",
"the",
"triangle",
"s",
"vertices",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L233-L243 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.BA | def BA(self):
'''
Vertices B and A, list.
'''
try:
return self._BA
except AttributeError:
pass
self._BA = [self.B, self.A]
return self._BA | python | def BA(self):
'''
Vertices B and A, list.
'''
try:
return self._BA
except AttributeError:
pass
self._BA = [self.B, self.A]
return self._BA | [
"def",
"BA",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_BA",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_BA",
"=",
"[",
"self",
".",
"B",
",",
"self",
".",
"A",
"]",
"return",
"self",
".",
"_BA"
] | Vertices B and A, list. | [
"Vertices",
"B",
"and",
"A",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L267-L277 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.AC | def AC(self):
'''
Vertices A and C, list.
'''
try:
return self._AC
except AttributeError:
pass
self._AC = [self.A, self.C]
return self._AC | python | def AC(self):
'''
Vertices A and C, list.
'''
try:
return self._AC
except AttributeError:
pass
self._AC = [self.A, self.C]
return self._AC | [
"def",
"AC",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_AC",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_AC",
"=",
"[",
"self",
".",
"A",
",",
"self",
".",
"C",
"]",
"return",
"self",
".",
"_AC"
] | Vertices A and C, list. | [
"Vertices",
"A",
"and",
"C",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L284-L294 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.CA | def CA(self):
'''
Vertices C and A, list.
'''
try:
return self._CA
except AttributeError:
pass
self._CA = [self.C, self.A]
return self._CA | python | def CA(self):
'''
Vertices C and A, list.
'''
try:
return self._CA
except AttributeError:
pass
self._CA = [self.C, self.A]
return self._CA | [
"def",
"CA",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_CA",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_CA",
"=",
"[",
"self",
".",
"C",
",",
"self",
".",
"A",
"]",
"return",
"self",
".",
"_CA"
] | Vertices C and A, list. | [
"Vertices",
"C",
"and",
"A",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L301-L311 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.BC | def BC(self):
'''
Vertices B and C, list.
'''
try:
return self._BC
except AttributeError:
pass
self._BC = [self.B, self.C]
return self._BC | python | def BC(self):
'''
Vertices B and C, list.
'''
try:
return self._BC
except AttributeError:
pass
self._BC = [self.B, self.C]
return self._BC | [
"def",
"BC",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_BC",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_BC",
"=",
"[",
"self",
".",
"B",
",",
"self",
".",
"C",
"]",
"return",
"self",
".",
"_BC"
] | Vertices B and C, list. | [
"Vertices",
"B",
"and",
"C",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L318-L328 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.CB | def CB(self):
'''
Vertices C and B, list.
'''
try:
return self._CB
except AttributeError:
pass
self._CB = [self.C, self.B]
return self._CB | python | def CB(self):
'''
Vertices C and B, list.
'''
try:
return self._CB
except AttributeError:
pass
self._CB = [self.C, self.B]
return self._CB | [
"def",
"CB",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_CB",
"except",
"AttributeError",
":",
"pass",
"self",
".",
"_CB",
"=",
"[",
"self",
".",
"C",
",",
"self",
".",
"B",
"]",
"return",
"self",
".",
"_CB"
] | Vertices C and B, list. | [
"Vertices",
"C",
"and",
"B",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L335-L345 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.segments | def segments(self):
'''
A list of the Triangle's line segments [AB, BC, AC], list.
'''
return [Segment(self.AB),
Segment(self.BC),
Segment(self.AC)] | python | def segments(self):
'''
A list of the Triangle's line segments [AB, BC, AC], list.
'''
return [Segment(self.AB),
Segment(self.BC),
Segment(self.AC)] | [
"def",
"segments",
"(",
"self",
")",
":",
"return",
"[",
"Segment",
"(",
"self",
".",
"AB",
")",
",",
"Segment",
"(",
"self",
".",
"BC",
")",
",",
"Segment",
"(",
"self",
".",
"AC",
")",
"]"
] | A list of the Triangle's line segments [AB, BC, AC], list. | [
"A",
"list",
"of",
"the",
"Triangle",
"s",
"line",
"segments",
"[",
"AB",
"BC",
"AC",
"]",
"list",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L364-L371 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.circumcenter | def circumcenter(self):
'''
The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2
BUG: only finds the circumcenter in the XY plane
'''
if self.isRight:
return self.hypotenuse.midpoint
if self.A.isOrigin:
t = self
else:
# translate triangle to origin
t = Triangle(self.A - self.A, self.B - self.A, self.C - self.A)
# XXX translation would be easier by defining add and sub for points
# t = self - self.A
if not t.A.isOrigin:
raise ValueError('failed to translate {} to origin'.format(t))
BmulC = t.B * t.C.yx
d = 2 * (BmulC.x - BmulC.y)
bSqSum = sum((t.B ** 2).xy)
cSqSum = sum((t.C ** 2).xy)
x = (((t.C.y * bSqSum) - (t.B.y * cSqSum)) / d) + self.A.x
y = (((t.B.x * cSqSum) - (t.C.x * bSqSum)) / d) + self.A.y
return Point(x, y) | python | def circumcenter(self):
'''
The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2
BUG: only finds the circumcenter in the XY plane
'''
if self.isRight:
return self.hypotenuse.midpoint
if self.A.isOrigin:
t = self
else:
# translate triangle to origin
t = Triangle(self.A - self.A, self.B - self.A, self.C - self.A)
# XXX translation would be easier by defining add and sub for points
# t = self - self.A
if not t.A.isOrigin:
raise ValueError('failed to translate {} to origin'.format(t))
BmulC = t.B * t.C.yx
d = 2 * (BmulC.x - BmulC.y)
bSqSum = sum((t.B ** 2).xy)
cSqSum = sum((t.C ** 2).xy)
x = (((t.C.y * bSqSum) - (t.B.y * cSqSum)) / d) + self.A.x
y = (((t.B.x * cSqSum) - (t.C.x * bSqSum)) / d) + self.A.y
return Point(x, y) | [
"def",
"circumcenter",
"(",
"self",
")",
":",
"if",
"self",
".",
"isRight",
":",
"return",
"self",
".",
"hypotenuse",
".",
"midpoint",
"if",
"self",
".",
"A",
".",
"isOrigin",
":",
"t",
"=",
"self",
"else",
":",
"# translate triangle to origin",
"t",
"="... | The intersection of the median perpendicular bisectors, Point.
The center of the circumscribed circle, which is the circle that
passes through all vertices of the triangle.
https://en.wikipedia.org/wiki/Circumscribed_circle#Cartesian_coordinates_2
BUG: only finds the circumcenter in the XY plane | [
"The",
"intersection",
"of",
"the",
"median",
"perpendicular",
"bisectors",
"Point",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L424-L460 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.altitudes | def altitudes(self):
'''
A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it.
'''
a = self.area * 2
return [a / self.a, a / self.b, a / self.c] | python | def altitudes(self):
'''
A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it.
'''
a = self.area * 2
return [a / self.a, a / self.b, a / self.c] | [
"def",
"altitudes",
"(",
"self",
")",
":",
"a",
"=",
"self",
".",
"area",
"*",
"2",
"return",
"[",
"a",
"/",
"self",
".",
"a",
",",
"a",
"/",
"self",
".",
"b",
",",
"a",
"/",
"self",
".",
"c",
"]"
] | A list of the altitudes of each vertex [AltA, AltB, AltC], list of
floats.
An altitude is the shortest distance from a vertex to the side
opposite of it. | [
"A",
"list",
"of",
"the",
"altitudes",
"of",
"each",
"vertex",
"[",
"AltA",
"AltB",
"AltC",
"]",
"list",
"of",
"floats",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L560-L571 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.isEquilateral | def isEquilateral(self):
'''
True if all sides of the triangle are the same length.
All equilateral triangles are also isosceles.
All equilateral triangles are also acute.
'''
if not nearly_eq(self.a, self.b):
return False
if not nearly_eq(self.b, self.c):
return False
return nearly_eq(self.a, self.c) | python | def isEquilateral(self):
'''
True if all sides of the triangle are the same length.
All equilateral triangles are also isosceles.
All equilateral triangles are also acute.
'''
if not nearly_eq(self.a, self.b):
return False
if not nearly_eq(self.b, self.c):
return False
return nearly_eq(self.a, self.c) | [
"def",
"isEquilateral",
"(",
"self",
")",
":",
"if",
"not",
"nearly_eq",
"(",
"self",
".",
"a",
",",
"self",
".",
"b",
")",
":",
"return",
"False",
"if",
"not",
"nearly_eq",
"(",
"self",
".",
"b",
",",
"self",
".",
"c",
")",
":",
"return",
"False... | True if all sides of the triangle are the same length.
All equilateral triangles are also isosceles.
All equilateral triangles are also acute. | [
"True",
"if",
"all",
"sides",
"of",
"the",
"triangle",
"are",
"the",
"same",
"length",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L629-L643 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.swap | def swap(self, side='AB', inplace=False):
'''
:side: - optional string
:inplace: - optional boolean
:return: Triangle with flipped side.
The optional side paramater should have one of three values:
AB, BC, or AC.
Changes the order of the triangle's points, swapping the
specified points. Doing so will change the results of isCCW
and ccw.
'''
try:
flipset = {'AB': (self.B.xyz, self.A.xyz, self.C.xyz),
'BC': (self.A.xyz, self.C.xyz, self.B.xyz),
'AC': (self.C.xyz, self.B.xyz, self.A.xyz)}[side]
except KeyError as e:
raise KeyError(str(e))
if inplace:
self.ABC = flipset
return self
return Triangle(flipset) | python | def swap(self, side='AB', inplace=False):
'''
:side: - optional string
:inplace: - optional boolean
:return: Triangle with flipped side.
The optional side paramater should have one of three values:
AB, BC, or AC.
Changes the order of the triangle's points, swapping the
specified points. Doing so will change the results of isCCW
and ccw.
'''
try:
flipset = {'AB': (self.B.xyz, self.A.xyz, self.C.xyz),
'BC': (self.A.xyz, self.C.xyz, self.B.xyz),
'AC': (self.C.xyz, self.B.xyz, self.A.xyz)}[side]
except KeyError as e:
raise KeyError(str(e))
if inplace:
self.ABC = flipset
return self
return Triangle(flipset) | [
"def",
"swap",
"(",
"self",
",",
"side",
"=",
"'AB'",
",",
"inplace",
"=",
"False",
")",
":",
"try",
":",
"flipset",
"=",
"{",
"'AB'",
":",
"(",
"self",
".",
"B",
".",
"xyz",
",",
"self",
".",
"A",
".",
"xyz",
",",
"self",
".",
"C",
".",
"x... | :side: - optional string
:inplace: - optional boolean
:return: Triangle with flipped side.
The optional side paramater should have one of three values:
AB, BC, or AC.
Changes the order of the triangle's points, swapping the
specified points. Doing so will change the results of isCCW
and ccw. | [
":",
"side",
":",
"-",
"optional",
"string",
":",
"inplace",
":",
"-",
"optional",
"boolean",
":",
"return",
":",
"Triangle",
"with",
"flipped",
"side",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L789-L814 | train |
JnyJny/Geometry | Geometry/triangle.py | Triangle.doesIntersect | def doesIntersect(self, other):
'''
:param: other - Triangle or Line subclass
:return: boolean
Returns True iff:
Any segment in self intersects any segment in other.
'''
otherType = type(other)
if issubclass(otherType, Triangle):
for s in self.segments.values():
for q in other.segments.values():
if s.doesIntersect(q):
return True
return False
if issubclass(otherType, Line):
for s in self.segments.values():
if s.doesIntersect(other):
return True
return False
msg = "expecting Line or Triangle subclasses, got '{}'"
raise TypeError(msg.format(otherType)) | python | def doesIntersect(self, other):
'''
:param: other - Triangle or Line subclass
:return: boolean
Returns True iff:
Any segment in self intersects any segment in other.
'''
otherType = type(other)
if issubclass(otherType, Triangle):
for s in self.segments.values():
for q in other.segments.values():
if s.doesIntersect(q):
return True
return False
if issubclass(otherType, Line):
for s in self.segments.values():
if s.doesIntersect(other):
return True
return False
msg = "expecting Line or Triangle subclasses, got '{}'"
raise TypeError(msg.format(otherType)) | [
"def",
"doesIntersect",
"(",
"self",
",",
"other",
")",
":",
"otherType",
"=",
"type",
"(",
"other",
")",
"if",
"issubclass",
"(",
"otherType",
",",
"Triangle",
")",
":",
"for",
"s",
"in",
"self",
".",
"segments",
".",
"values",
"(",
")",
":",
"for",... | :param: other - Triangle or Line subclass
:return: boolean
Returns True iff:
Any segment in self intersects any segment in other. | [
":",
"param",
":",
"other",
"-",
"Triangle",
"or",
"Line",
"subclass",
":",
"return",
":",
"boolean"
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/triangle.py#L816-L842 | train |
JnyJny/Geometry | Geometry/polygon.py | Polygon.perimeter | def perimeter(self):
'''
Sum of the length of all sides, float.
'''
return sum([a.distance(b) for a, b in self.pairs()]) | python | def perimeter(self):
'''
Sum of the length of all sides, float.
'''
return sum([a.distance(b) for a, b in self.pairs()]) | [
"def",
"perimeter",
"(",
"self",
")",
":",
"return",
"sum",
"(",
"[",
"a",
".",
"distance",
"(",
"b",
")",
"for",
"a",
",",
"b",
"in",
"self",
".",
"pairs",
"(",
")",
"]",
")"
] | Sum of the length of all sides, float. | [
"Sum",
"of",
"the",
"length",
"of",
"all",
"sides",
"float",
"."
] | 3500f815fa56c535b36d1b6fd0afe69ce5d055be | https://github.com/JnyJny/Geometry/blob/3500f815fa56c535b36d1b6fd0afe69ce5d055be/Geometry/polygon.py#L42-L46 | train |
dougalsutherland/vlfeat-ctypes | vlfeat/dsift.py | vl_dsift | def vl_dsift(data, fast=False, norm=False, bounds=None, size=3, step=1,
window_size=None, float_descriptors=False,
verbose=False, matlab_style=True):
'''
Dense sift descriptors from an image.
Returns:
frames: num_frames x (2 or 3) matrix of x, y, (norm)
descrs: num_frames x 128 matrix of descriptors
'''
if not matlab_style:
import warnings
warnings.warn("matlab_style=False gets different results than matlab, "
"not sure why or how incorrect they are.")
order = 'F' if matlab_style else 'C'
data = as_float_image(data, dtype=np.float32, order=order)
if data.ndim != 2:
raise TypeError("data should be a 2d array")
if window_size is not None:
assert np.isscalar(window_size) and window_size >= 0
# construct the dsift object
M, N = data.shape
dsift_p = vl_dsift_new_basic(M, N, step, size)
try:
dsift = dsift_p.contents
# set parameters
if bounds is not None:
if matlab_style:
y0, x0, y1, x1 = bounds # transposed
else:
x0, y0, x1, y1 = bounds
dsift.boundMinX = int(max(x0, 0))
dsift.boundMinY = int(max(y0, 0))
dsift.boundMaxX = int(min(x1, M - 1))
dsift.boundMaxY = int(min(y1, N - 1))
_vl_dsift_update_buffers(dsift_p)
dsift.useFlatWindow = fast
if window_size is not None:
dsift.windowSize = window_size
# get calculated parameters
descr_size = dsift.descrSize
num_frames = dsift.numFrames
geom = dsift.geom
if verbose:
pr = lambda *a, **k: print('vl_dsift:', *a, **k)
pr("image size [W, H] = [{}, {}]".format(N, M))
x0 = dsift.boundMinX + 1
y0 = dsift.boundMinY + 1
x1 = dsift.boundMaxX + 1
y1 = dsift.boundMaxY + 1
bound_args = [y0, x0, y1, x1] if matlab_style else [x0, y0, x1, y1]
pr("bounds: [minX,minY,maxX,maxY] = [{}, {}, {}, {}]"
.format(*bound_args))
pr("subsampling steps: stepX={}, stepY={}".format(
dsift.stepX, dsift.stepY))
pr("num bins: [numBinT, numBinX, numBinY] = [{}, {}, {}]"
.format(geom.numBinT, geom.numBinX, geom.numBinY))
pr("descriptor size: {}".format(descr_size))
pr("bin sizes: [binSizeX, binSizeY] = [{}, {}]".format(
geom.binSizeX, geom.binSizeY))
pr("flat window: {}".format(bool(fast)))
pr("window size: {}".format(dsift.windowSize))
pr("num of features: {}".format(num_frames))
# do the actual processing
vl_dsift_process(dsift_p, data)
# copy frames' locations, norms out
# the frames are a structure of just 4 doubles (VLDsiftKeypoint),
# which luckily looks exactly like an array of doubles. :)
# NOTE: this might be platform/compiler-dependent...but it works with
# the provided binaries on os x, at least
frames_p = cast(dsift.frames, c_double_p)
frames_p_a = npc.as_array(frames_p, shape=(num_frames, 4))
cols = [1, 0] if matlab_style else [0, 1]
if norm:
cols.append(3)
frames = np.require(frames_p_a[:, cols], requirements=['C', 'O'])
# copy descriptors into a new array
descrs_p = npc.as_array(dsift.descrs, shape=(num_frames, descr_size))
descrs = descrs_p * 512
assert descrs.flags.owndata
np.minimum(descrs, 255, out=descrs)
if not float_descriptors:
descrs = descrs.astype(np.uint8) # TODO: smarter about copying?
if matlab_style:
new_order = np.empty(descr_size, dtype=int)
vl_dsift_transpose_descriptor(new_order, np.arange(descr_size),
geom.numBinT, geom.numBinX, geom.numBinY)
descrs = descrs[:, new_order]
# the old, super-slow way:
## # gross pointer arithmetic to get the relevant descriptor
## descrs_addr = addressof(descrs.contents)
## descrs_step = descr_size * sizeof(c_float)
##
## for k in range(num_frames):
## out_frames[:2, k] = [frames[k].y + 1, frames[k].x + 1]
## if norm: # there's an implied / 2 in norm, because of clipping
## out_frames[2, k] = frames[k].norm
##
## # gross pointer arithmetic to get the relevant descriptor
## the_descr = cast(descrs_addr + k * descrs_step, c_float_p)
## transposed = vl_dsift_transpose_descriptor(
## the_descr,
## geom.numBinT, geom.numBinX, geom.numBinY)
## out_descrs[:, k] = np.minimum(512. * transposed, 255.)
return frames, descrs
finally:
vl_dsift_delete(dsift_p) | python | def vl_dsift(data, fast=False, norm=False, bounds=None, size=3, step=1,
window_size=None, float_descriptors=False,
verbose=False, matlab_style=True):
'''
Dense sift descriptors from an image.
Returns:
frames: num_frames x (2 or 3) matrix of x, y, (norm)
descrs: num_frames x 128 matrix of descriptors
'''
if not matlab_style:
import warnings
warnings.warn("matlab_style=False gets different results than matlab, "
"not sure why or how incorrect they are.")
order = 'F' if matlab_style else 'C'
data = as_float_image(data, dtype=np.float32, order=order)
if data.ndim != 2:
raise TypeError("data should be a 2d array")
if window_size is not None:
assert np.isscalar(window_size) and window_size >= 0
# construct the dsift object
M, N = data.shape
dsift_p = vl_dsift_new_basic(M, N, step, size)
try:
dsift = dsift_p.contents
# set parameters
if bounds is not None:
if matlab_style:
y0, x0, y1, x1 = bounds # transposed
else:
x0, y0, x1, y1 = bounds
dsift.boundMinX = int(max(x0, 0))
dsift.boundMinY = int(max(y0, 0))
dsift.boundMaxX = int(min(x1, M - 1))
dsift.boundMaxY = int(min(y1, N - 1))
_vl_dsift_update_buffers(dsift_p)
dsift.useFlatWindow = fast
if window_size is not None:
dsift.windowSize = window_size
# get calculated parameters
descr_size = dsift.descrSize
num_frames = dsift.numFrames
geom = dsift.geom
if verbose:
pr = lambda *a, **k: print('vl_dsift:', *a, **k)
pr("image size [W, H] = [{}, {}]".format(N, M))
x0 = dsift.boundMinX + 1
y0 = dsift.boundMinY + 1
x1 = dsift.boundMaxX + 1
y1 = dsift.boundMaxY + 1
bound_args = [y0, x0, y1, x1] if matlab_style else [x0, y0, x1, y1]
pr("bounds: [minX,minY,maxX,maxY] = [{}, {}, {}, {}]"
.format(*bound_args))
pr("subsampling steps: stepX={}, stepY={}".format(
dsift.stepX, dsift.stepY))
pr("num bins: [numBinT, numBinX, numBinY] = [{}, {}, {}]"
.format(geom.numBinT, geom.numBinX, geom.numBinY))
pr("descriptor size: {}".format(descr_size))
pr("bin sizes: [binSizeX, binSizeY] = [{}, {}]".format(
geom.binSizeX, geom.binSizeY))
pr("flat window: {}".format(bool(fast)))
pr("window size: {}".format(dsift.windowSize))
pr("num of features: {}".format(num_frames))
# do the actual processing
vl_dsift_process(dsift_p, data)
# copy frames' locations, norms out
# the frames are a structure of just 4 doubles (VLDsiftKeypoint),
# which luckily looks exactly like an array of doubles. :)
# NOTE: this might be platform/compiler-dependent...but it works with
# the provided binaries on os x, at least
frames_p = cast(dsift.frames, c_double_p)
frames_p_a = npc.as_array(frames_p, shape=(num_frames, 4))
cols = [1, 0] if matlab_style else [0, 1]
if norm:
cols.append(3)
frames = np.require(frames_p_a[:, cols], requirements=['C', 'O'])
# copy descriptors into a new array
descrs_p = npc.as_array(dsift.descrs, shape=(num_frames, descr_size))
descrs = descrs_p * 512
assert descrs.flags.owndata
np.minimum(descrs, 255, out=descrs)
if not float_descriptors:
descrs = descrs.astype(np.uint8) # TODO: smarter about copying?
if matlab_style:
new_order = np.empty(descr_size, dtype=int)
vl_dsift_transpose_descriptor(new_order, np.arange(descr_size),
geom.numBinT, geom.numBinX, geom.numBinY)
descrs = descrs[:, new_order]
# the old, super-slow way:
## # gross pointer arithmetic to get the relevant descriptor
## descrs_addr = addressof(descrs.contents)
## descrs_step = descr_size * sizeof(c_float)
##
## for k in range(num_frames):
## out_frames[:2, k] = [frames[k].y + 1, frames[k].x + 1]
## if norm: # there's an implied / 2 in norm, because of clipping
## out_frames[2, k] = frames[k].norm
##
## # gross pointer arithmetic to get the relevant descriptor
## the_descr = cast(descrs_addr + k * descrs_step, c_float_p)
## transposed = vl_dsift_transpose_descriptor(
## the_descr,
## geom.numBinT, geom.numBinX, geom.numBinY)
## out_descrs[:, k] = np.minimum(512. * transposed, 255.)
return frames, descrs
finally:
vl_dsift_delete(dsift_p) | [
"def",
"vl_dsift",
"(",
"data",
",",
"fast",
"=",
"False",
",",
"norm",
"=",
"False",
",",
"bounds",
"=",
"None",
",",
"size",
"=",
"3",
",",
"step",
"=",
"1",
",",
"window_size",
"=",
"None",
",",
"float_descriptors",
"=",
"False",
",",
"verbose",
... | Dense sift descriptors from an image.
Returns:
frames: num_frames x (2 or 3) matrix of x, y, (norm)
descrs: num_frames x 128 matrix of descriptors | [
"Dense",
"sift",
"descriptors",
"from",
"an",
"image",
"."
] | 87367a1e18863e4effc98d7b3da0b85978e665d3 | https://github.com/dougalsutherland/vlfeat-ctypes/blob/87367a1e18863e4effc98d7b3da0b85978e665d3/vlfeat/dsift.py#L105-L225 | train |
dougalsutherland/vlfeat-ctypes | vlfeat/utils.py | rgb2gray | def rgb2gray(img):
"""Converts an RGB image to grayscale using matlab's algorithm."""
T = np.linalg.inv(np.array([
[1.0, 0.956, 0.621],
[1.0, -0.272, -0.647],
[1.0, -1.106, 1.703],
]))
r_c, g_c, b_c = T[0]
r, g, b = np.rollaxis(as_float_image(img), axis=-1)
return r_c * r + g_c * g + b_c * b | python | def rgb2gray(img):
"""Converts an RGB image to grayscale using matlab's algorithm."""
T = np.linalg.inv(np.array([
[1.0, 0.956, 0.621],
[1.0, -0.272, -0.647],
[1.0, -1.106, 1.703],
]))
r_c, g_c, b_c = T[0]
r, g, b = np.rollaxis(as_float_image(img), axis=-1)
return r_c * r + g_c * g + b_c * b | [
"def",
"rgb2gray",
"(",
"img",
")",
":",
"T",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"np",
".",
"array",
"(",
"[",
"[",
"1.0",
",",
"0.956",
",",
"0.621",
"]",
",",
"[",
"1.0",
",",
"-",
"0.272",
",",
"-",
"0.647",
"]",
",",
"[",
"1.0",... | Converts an RGB image to grayscale using matlab's algorithm. | [
"Converts",
"an",
"RGB",
"image",
"to",
"grayscale",
"using",
"matlab",
"s",
"algorithm",
"."
] | 87367a1e18863e4effc98d7b3da0b85978e665d3 | https://github.com/dougalsutherland/vlfeat-ctypes/blob/87367a1e18863e4effc98d7b3da0b85978e665d3/vlfeat/utils.py#L31-L40 | train |
dougalsutherland/vlfeat-ctypes | vlfeat/utils.py | rgb2hsv | def rgb2hsv(arr):
"""Converts an RGB image to HSV using scikit-image's algorithm."""
arr = np.asanyarray(arr)
if arr.ndim != 3 or arr.shape[2] != 3:
raise ValueError("the input array must have a shape == (.,.,3)")
arr = as_float_image(arr)
out = np.empty_like(arr)
# -- V channel
out_v = arr.max(-1)
# -- S channel
delta = arr.ptp(-1)
# Ignore warning for zero divided by zero
old_settings = np.seterr(invalid='ignore')
out_s = delta / out_v
out_s[delta == 0.] = 0.
# -- H channel
# red is max
idx = (arr[:, :, 0] == out_v)
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = (arr[:, :, 1] == out_v)
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
# blue is max
idx = (arr[:, :, 2] == out_v)
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
out_h = (out[:, :, 0] / 6.) % 1.
out_h[delta == 0.] = 0.
np.seterr(**old_settings)
# -- output
out[:, :, 0] = out_h
out[:, :, 1] = out_s
out[:, :, 2] = out_v
# remove NaN
out[np.isnan(out)] = 0
return out | python | def rgb2hsv(arr):
"""Converts an RGB image to HSV using scikit-image's algorithm."""
arr = np.asanyarray(arr)
if arr.ndim != 3 or arr.shape[2] != 3:
raise ValueError("the input array must have a shape == (.,.,3)")
arr = as_float_image(arr)
out = np.empty_like(arr)
# -- V channel
out_v = arr.max(-1)
# -- S channel
delta = arr.ptp(-1)
# Ignore warning for zero divided by zero
old_settings = np.seterr(invalid='ignore')
out_s = delta / out_v
out_s[delta == 0.] = 0.
# -- H channel
# red is max
idx = (arr[:, :, 0] == out_v)
out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]
# green is max
idx = (arr[:, :, 1] == out_v)
out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]
# blue is max
idx = (arr[:, :, 2] == out_v)
out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]
out_h = (out[:, :, 0] / 6.) % 1.
out_h[delta == 0.] = 0.
np.seterr(**old_settings)
# -- output
out[:, :, 0] = out_h
out[:, :, 1] = out_s
out[:, :, 2] = out_v
# remove NaN
out[np.isnan(out)] = 0
return out | [
"def",
"rgb2hsv",
"(",
"arr",
")",
":",
"arr",
"=",
"np",
".",
"asanyarray",
"(",
"arr",
")",
"if",
"arr",
".",
"ndim",
"!=",
"3",
"or",
"arr",
".",
"shape",
"[",
"2",
"]",
"!=",
"3",
":",
"raise",
"ValueError",
"(",
"\"the input array must have a sh... | Converts an RGB image to HSV using scikit-image's algorithm. | [
"Converts",
"an",
"RGB",
"image",
"to",
"HSV",
"using",
"scikit",
"-",
"image",
"s",
"algorithm",
"."
] | 87367a1e18863e4effc98d7b3da0b85978e665d3 | https://github.com/dougalsutherland/vlfeat-ctypes/blob/87367a1e18863e4effc98d7b3da0b85978e665d3/vlfeat/utils.py#L44-L87 | train |
digidotcom/python-devicecloud | devicecloud/file_system_service.py | _parse_command_response | def _parse_command_response(response):
"""Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The requests response object
:return: An ElementTree Element that is the root of the response XML
:raises ResponseParseError: If the response XML is not well formed
"""
try:
root = ET.fromstring(response.text)
except ET.ParseError:
raise ResponseParseError(
"Unexpected response format, could not parse XML. Response: {}".format(response.text))
return root | python | def _parse_command_response(response):
"""Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The requests response object
:return: An ElementTree Element that is the root of the response XML
:raises ResponseParseError: If the response XML is not well formed
"""
try:
root = ET.fromstring(response.text)
except ET.ParseError:
raise ResponseParseError(
"Unexpected response format, could not parse XML. Response: {}".format(response.text))
return root | [
"def",
"_parse_command_response",
"(",
"response",
")",
":",
"try",
":",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"response",
".",
"text",
")",
"except",
"ET",
".",
"ParseError",
":",
"raise",
"ResponseParseError",
"(",
"\"Unexpected response format, could not p... | Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The requests response object
:return: An ElementTree Element that is the root of the response XML
:raises ResponseParseError: If the response XML is not well formed | [
"Parse",
"an",
"SCI",
"command",
"response",
"into",
"ElementTree",
"XML"
] | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/file_system_service.py#L25-L42 | train |
digidotcom/python-devicecloud | devicecloud/file_system_service.py | _parse_error_tree | def _parse_error_tree(error):
"""Parse an error ElementTree Node to create an ErrorInfo object
:param error: The ElementTree error node
:return: An ErrorInfo object containing the error ID and the message.
"""
errinf = ErrorInfo(error.get('id'), None)
if error.text is not None:
errinf.message = error.text
else:
desc = error.find('./desc')
if desc is not None:
errinf.message = desc.text
return errinf | python | def _parse_error_tree(error):
"""Parse an error ElementTree Node to create an ErrorInfo object
:param error: The ElementTree error node
:return: An ErrorInfo object containing the error ID and the message.
"""
errinf = ErrorInfo(error.get('id'), None)
if error.text is not None:
errinf.message = error.text
else:
desc = error.find('./desc')
if desc is not None:
errinf.message = desc.text
return errinf | [
"def",
"_parse_error_tree",
"(",
"error",
")",
":",
"errinf",
"=",
"ErrorInfo",
"(",
"error",
".",
"get",
"(",
"'id'",
")",
",",
"None",
")",
"if",
"error",
".",
"text",
"is",
"not",
"None",
":",
"errinf",
".",
"message",
"=",
"error",
".",
"text",
... | Parse an error ElementTree Node to create an ErrorInfo object
:param error: The ElementTree error node
:return: An ErrorInfo object containing the error ID and the message. | [
"Parse",
"an",
"error",
"ElementTree",
"Node",
"to",
"create",
"an",
"ErrorInfo",
"object"
] | 32529684a348a7830a269c32601604c78036bcb8 | https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/file_system_service.py#L45-L58 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.