repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
kajala/django-jacc | jacc/interests.py | calculate_simple_interest | def calculate_simple_interest(entries, rate_pct: Decimal, interest_date: date or None=None, begin: date or None=None) -> Decimal:
"""
Calculates simple interest of specified entries over time.
Does not accumulate interest to interest.
:param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by timestamp (ascending)
:param rate_pct: Interest rate %, e.g. 8.00 for 8%
:param interest_date: Interest end date. Default is current date.
:param begin: Optional begin date for the interest. Default is whole range from the timestamp of account entries.
:return: Decimal accumulated interest
"""
if interest_date is None:
interest_date = now().date()
bal = None
cur_date = None
daily_rate = rate_pct / Decimal(36500)
accum_interest = Decimal('0.00')
done = False
entries_list = list(entries)
nentries = len(entries_list)
if nentries > 0:
# make sure we calculate interest over whole range until interest_date
last = entries_list[nentries-1]
assert isinstance(last, AccountEntry)
if last.timestamp.date() < interest_date:
timestamp = pytz.utc.localize(datetime.combine(interest_date, time(0, 0)))
e = AccountEntry(timestamp=timestamp, amount=Decimal('0.00'), type=last.type)
entries_list.append(e)
# initial values from the first account entry
e = entries_list[0]
bal = e.amount
cur_date = e.timestamp.date()
if begin and begin > cur_date:
cur_date = begin
for e in entries_list[1:]:
assert isinstance(e, AccountEntry)
next_date = e.timestamp.date()
if begin and begin > next_date:
next_date = begin
if next_date > interest_date:
next_date = interest_date
done = True
time_days = (next_date - cur_date).days
if time_days > 0:
day_interest = bal * daily_rate
interval_interest = day_interest * Decimal(time_days)
accum_interest += interval_interest
cur_date = next_date
bal += e.amount
if done:
break
return accum_interest | python | def calculate_simple_interest(entries, rate_pct: Decimal, interest_date: date or None=None, begin: date or None=None) -> Decimal:
"""
Calculates simple interest of specified entries over time.
Does not accumulate interest to interest.
:param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by timestamp (ascending)
:param rate_pct: Interest rate %, e.g. 8.00 for 8%
:param interest_date: Interest end date. Default is current date.
:param begin: Optional begin date for the interest. Default is whole range from the timestamp of account entries.
:return: Decimal accumulated interest
"""
if interest_date is None:
interest_date = now().date()
bal = None
cur_date = None
daily_rate = rate_pct / Decimal(36500)
accum_interest = Decimal('0.00')
done = False
entries_list = list(entries)
nentries = len(entries_list)
if nentries > 0:
# make sure we calculate interest over whole range until interest_date
last = entries_list[nentries-1]
assert isinstance(last, AccountEntry)
if last.timestamp.date() < interest_date:
timestamp = pytz.utc.localize(datetime.combine(interest_date, time(0, 0)))
e = AccountEntry(timestamp=timestamp, amount=Decimal('0.00'), type=last.type)
entries_list.append(e)
# initial values from the first account entry
e = entries_list[0]
bal = e.amount
cur_date = e.timestamp.date()
if begin and begin > cur_date:
cur_date = begin
for e in entries_list[1:]:
assert isinstance(e, AccountEntry)
next_date = e.timestamp.date()
if begin and begin > next_date:
next_date = begin
if next_date > interest_date:
next_date = interest_date
done = True
time_days = (next_date - cur_date).days
if time_days > 0:
day_interest = bal * daily_rate
interval_interest = day_interest * Decimal(time_days)
accum_interest += interval_interest
cur_date = next_date
bal += e.amount
if done:
break
return accum_interest | [
"def",
"calculate_simple_interest",
"(",
"entries",
",",
"rate_pct",
":",
"Decimal",
",",
"interest_date",
":",
"date",
"or",
"None",
"=",
"None",
",",
"begin",
":",
"date",
"or",
"None",
"=",
"None",
")",
"->",
"Decimal",
":",
"if",
"interest_date",
"is",... | Calculates simple interest of specified entries over time.
Does not accumulate interest to interest.
:param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by timestamp (ascending)
:param rate_pct: Interest rate %, e.g. 8.00 for 8%
:param interest_date: Interest end date. Default is current date.
:param begin: Optional begin date for the interest. Default is whole range from the timestamp of account entries.
:return: Decimal accumulated interest | [
"Calculates",
"simple",
"interest",
"of",
"specified",
"entries",
"over",
"time",
".",
"Does",
"not",
"accumulate",
"interest",
"to",
"interest",
".",
":",
"param",
"entries",
":",
"AccountEntry",
"iterable",
"(",
"e",
".",
"g",
".",
"list",
"/",
"QuerySet",... | train | https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/interests.py#L8-L63 |
sdss/sdss_access | python/sdss_access/misc/docupaths.py | _format_templates | def _format_templates(name, command, templates):
''' Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
A dictionary of the path templates
Yields:
A string rst-formated list-table directive
'''
yield '.. list-table:: {0}'.format(name)
yield _indent(':widths: 20 50 70')
yield _indent(':header-rows: 1')
yield ''
yield _indent('* - Name')
yield _indent(' - Template')
yield _indent(' - Kwargs')
for key, var in templates.items():
kwargs = command.lookup_keys(key)
yield _indent('* - {0}'.format(key))
yield _indent(' - {0}'.format(var))
yield _indent(' - {0}'.format(', '.join(kwargs)))
yield '' | python | def _format_templates(name, command, templates):
''' Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
A dictionary of the path templates
Yields:
A string rst-formated list-table directive
'''
yield '.. list-table:: {0}'.format(name)
yield _indent(':widths: 20 50 70')
yield _indent(':header-rows: 1')
yield ''
yield _indent('* - Name')
yield _indent(' - Template')
yield _indent(' - Kwargs')
for key, var in templates.items():
kwargs = command.lookup_keys(key)
yield _indent('* - {0}'.format(key))
yield _indent(' - {0}'.format(var))
yield _indent(' - {0}'.format(', '.join(kwargs)))
yield '' | [
"def",
"_format_templates",
"(",
"name",
",",
"command",
",",
"templates",
")",
":",
"yield",
"'.. list-table:: {0}'",
".",
"format",
"(",
"name",
")",
"yield",
"_indent",
"(",
"':widths: 20 50 70'",
")",
"yield",
"_indent",
"(",
"':header-rows: 1'",
")",
"yield... | Creates a list-table directive
for a set of defined environment variables
Parameters:
name (str):
The name of the config section
command (object):
The sdss_access path instance
templates (dict):
A dictionary of the path templates
Yields:
A string rst-formated list-table directive | [
"Creates",
"a",
"list",
"-",
"table",
"directive"
] | train | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/misc/docupaths.py#L34-L64 |
sdss/sdss_access | python/sdss_access/misc/docupaths.py | PathDirective._generate_nodes | def _generate_nodes(self, name, command, templates=None):
"""Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e.g. 'sdsswork'
command (object):
The loaded module
templates (bool):
If True, generate a section for the path templates
Returns:
A section docutil node
"""
# the source name
source_name = name
# Title
section = nodes.section(
'',
nodes.title(text=name),
ids=[nodes.make_id(name)],
names=[nodes.fully_normalize_name(name)])
# Summarize
result = statemachine.ViewList()
if templates:
lines = _format_templates(name, command, command.templates)
for line in lines:
result.append(line, source_name)
self.state.nested_parse(result, 0, section)
return [section] | python | def _generate_nodes(self, name, command, templates=None):
"""Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e.g. 'sdsswork'
command (object):
The loaded module
templates (bool):
If True, generate a section for the path templates
Returns:
A section docutil node
"""
# the source name
source_name = name
# Title
section = nodes.section(
'',
nodes.title(text=name),
ids=[nodes.make_id(name)],
names=[nodes.fully_normalize_name(name)])
# Summarize
result = statemachine.ViewList()
if templates:
lines = _format_templates(name, command, command.templates)
for line in lines:
result.append(line, source_name)
self.state.nested_parse(result, 0, section)
return [section] | [
"def",
"_generate_nodes",
"(",
"self",
",",
"name",
",",
"command",
",",
"templates",
"=",
"None",
")",
":",
"# the source name",
"source_name",
"=",
"name",
"# Title",
"section",
"=",
"nodes",
".",
"section",
"(",
"''",
",",
"nodes",
".",
"title",
"(",
... | Generate the relevant Sphinx nodes.
Generates a section for the Tree datamodel. Formats a tree section
as a list-table directive.
Parameters:
name (str):
The name of the config to be documented, e.g. 'sdsswork'
command (object):
The loaded module
templates (bool):
If True, generate a section for the path templates
Returns:
A section docutil node | [
"Generate",
"the",
"relevant",
"Sphinx",
"nodes",
"."
] | train | https://github.com/sdss/sdss_access/blob/76375bbf37d39d2e4ccbed90bdfa9a4298784470/python/sdss_access/misc/docupaths.py#L105-L145 |
kpdyer/regex2dfa | third_party/re2/re2/make_unicode_casefold.py | _Delta | def _Delta(a, b):
"""Compute the delta for b - a. Even/odd and odd/even
are handled specially, as described above."""
if a+1 == b:
if a%2 == 0:
return 'EvenOdd'
else:
return 'OddEven'
if a == b+1:
if a%2 == 0:
return 'OddEven'
else:
return 'EvenOdd'
return b - a | python | def _Delta(a, b):
"""Compute the delta for b - a. Even/odd and odd/even
are handled specially, as described above."""
if a+1 == b:
if a%2 == 0:
return 'EvenOdd'
else:
return 'OddEven'
if a == b+1:
if a%2 == 0:
return 'OddEven'
else:
return 'EvenOdd'
return b - a | [
"def",
"_Delta",
"(",
"a",
",",
"b",
")",
":",
"if",
"a",
"+",
"1",
"==",
"b",
":",
"if",
"a",
"%",
"2",
"==",
"0",
":",
"return",
"'EvenOdd'",
"else",
":",
"return",
"'OddEven'",
"if",
"a",
"==",
"b",
"+",
"1",
":",
"if",
"a",
"%",
"2",
... | Compute the delta for b - a. Even/odd and odd/even
are handled specially, as described above. | [
"Compute",
"the",
"delta",
"for",
"b",
"-",
"a",
".",
"Even",
"/",
"odd",
"and",
"odd",
"/",
"even",
"are",
"handled",
"specially",
"as",
"described",
"above",
"."
] | train | https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/make_unicode_casefold.py#L30-L43 |
kpdyer/regex2dfa | third_party/re2/re2/make_unicode_casefold.py | _AddDelta | def _AddDelta(a, delta):
"""Return a + delta, handling EvenOdd and OddEven specially."""
if type(delta) == int:
return a+delta
if delta == 'EvenOdd':
if a%2 == 0:
return a+1
else:
return a-1
if delta == 'OddEven':
if a%2 == 1:
return a+1
else:
return a-1
print >>sys.stderr, "Bad Delta: ", delta
raise "Bad Delta" | python | def _AddDelta(a, delta):
"""Return a + delta, handling EvenOdd and OddEven specially."""
if type(delta) == int:
return a+delta
if delta == 'EvenOdd':
if a%2 == 0:
return a+1
else:
return a-1
if delta == 'OddEven':
if a%2 == 1:
return a+1
else:
return a-1
print >>sys.stderr, "Bad Delta: ", delta
raise "Bad Delta" | [
"def",
"_AddDelta",
"(",
"a",
",",
"delta",
")",
":",
"if",
"type",
"(",
"delta",
")",
"==",
"int",
":",
"return",
"a",
"+",
"delta",
"if",
"delta",
"==",
"'EvenOdd'",
":",
"if",
"a",
"%",
"2",
"==",
"0",
":",
"return",
"a",
"+",
"1",
"else",
... | Return a + delta, handling EvenOdd and OddEven specially. | [
"Return",
"a",
"+",
"delta",
"handling",
"EvenOdd",
"and",
"OddEven",
"specially",
"."
] | train | https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/make_unicode_casefold.py#L45-L60 |
kpdyer/regex2dfa | third_party/re2/re2/make_unicode_casefold.py | _MakeRanges | def _MakeRanges(pairs):
"""Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]."""
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
return False
delta = r[2]
d = delta
if type(delta) is not str:
return False
if delta.endswith('Skip'):
d = delta[:-4]
else:
delta = d + 'Skip'
if b != _AddDelta(a, d):
return False
r[1] = a
r[2] = delta
return True
for a, b in pairs:
if ranges and evenodd(last, a, b, ranges[-1]):
pass
elif ranges and evenoddpair(last, a, b, ranges[-1]):
pass
else:
ranges.append([a, a, _Delta(a, b)])
last = a
return ranges | python | def _MakeRanges(pairs):
"""Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]."""
ranges = []
last = -100
def evenodd(last, a, b, r):
if a != last+1 or b != _AddDelta(a, r[2]):
return False
r[1] = a
return True
def evenoddpair(last, a, b, r):
if a != last+2:
return False
delta = r[2]
d = delta
if type(delta) is not str:
return False
if delta.endswith('Skip'):
d = delta[:-4]
else:
delta = d + 'Skip'
if b != _AddDelta(a, d):
return False
r[1] = a
r[2] = delta
return True
for a, b in pairs:
if ranges and evenodd(last, a, b, ranges[-1]):
pass
elif ranges and evenoddpair(last, a, b, ranges[-1]):
pass
else:
ranges.append([a, a, _Delta(a, b)])
last = a
return ranges | [
"def",
"_MakeRanges",
"(",
"pairs",
")",
":",
"ranges",
"=",
"[",
"]",
"last",
"=",
"-",
"100",
"def",
"evenodd",
"(",
"last",
",",
"a",
",",
"b",
",",
"r",
")",
":",
"if",
"a",
"!=",
"last",
"+",
"1",
"or",
"b",
"!=",
"_AddDelta",
"(",
"a",
... | Turn a list like [(65,97), (66, 98), ..., (90,122)]
into [(65, 90, +32)]. | [
"Turn",
"a",
"list",
"like",
"[",
"(",
"65",
"97",
")",
"(",
"66",
"98",
")",
"...",
"(",
"90",
"122",
")",
"]",
"into",
"[",
"(",
"65",
"90",
"+",
"32",
")",
"]",
"."
] | train | https://github.com/kpdyer/regex2dfa/blob/109f877e60ef0dfcb430f11516d215930b7b9936/third_party/re2/re2/make_unicode_casefold.py#L62-L99 |
kajala/django-jacc | jacc/admin.py | align_lines | def align_lines(lines: list, column_separator: str='|') -> list:
"""
Pads lines so that all rows in single column match. Columns separated by '|' in every line.
:param lines: list of lines
:param column_separator: column separator. default is '|'
:return: list of lines
"""
rows = []
col_len = []
for line in lines:
line = str(line)
cols = []
for col_index, col in enumerate(line.split(column_separator)):
col = str(col).strip()
cols.append(col)
if col_index >= len(col_len):
col_len.append(0)
col_len[col_index] = max(col_len[col_index], len(col))
rows.append(cols)
lines_out = []
for row in rows:
cols_out = []
for col_index, col in enumerate(row):
if col_index == 0:
col = col.ljust(col_len[col_index])
else:
col = col.rjust(col_len[col_index])
cols_out.append(col)
lines_out.append(' '.join(cols_out))
return lines_out | python | def align_lines(lines: list, column_separator: str='|') -> list:
"""
Pads lines so that all rows in single column match. Columns separated by '|' in every line.
:param lines: list of lines
:param column_separator: column separator. default is '|'
:return: list of lines
"""
rows = []
col_len = []
for line in lines:
line = str(line)
cols = []
for col_index, col in enumerate(line.split(column_separator)):
col = str(col).strip()
cols.append(col)
if col_index >= len(col_len):
col_len.append(0)
col_len[col_index] = max(col_len[col_index], len(col))
rows.append(cols)
lines_out = []
for row in rows:
cols_out = []
for col_index, col in enumerate(row):
if col_index == 0:
col = col.ljust(col_len[col_index])
else:
col = col.rjust(col_len[col_index])
cols_out.append(col)
lines_out.append(' '.join(cols_out))
return lines_out | [
"def",
"align_lines",
"(",
"lines",
":",
"list",
",",
"column_separator",
":",
"str",
"=",
"'|'",
")",
"->",
"list",
":",
"rows",
"=",
"[",
"]",
"col_len",
"=",
"[",
"]",
"for",
"line",
"in",
"lines",
":",
"line",
"=",
"str",
"(",
"line",
")",
"c... | Pads lines so that all rows in single column match. Columns separated by '|' in every line.
:param lines: list of lines
:param column_separator: column separator. default is '|'
:return: list of lines | [
"Pads",
"lines",
"so",
"that",
"all",
"rows",
"in",
"single",
"column",
"match",
".",
"Columns",
"separated",
"by",
"|",
"in",
"every",
"line",
".",
":",
"param",
"lines",
":",
"list",
"of",
"lines",
":",
"param",
"column_separator",
":",
"column",
"sepa... | train | https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/admin.py#L31-L61 |
kajala/django-jacc | jacc/admin.py | resend_invoices | def resend_invoices(modeladmin, request: HttpRequest, queryset: QuerySet):
"""
Marks invoices with as un-sent.
:param modeladmin:
:param request:
:param queryset:
:return:
"""
user = request.user
assert isinstance(user, User)
for obj in queryset:
assert isinstance(obj, Invoice)
admin_log([obj, user], 'Invoice id={invoice} marked for re-sending'.format(invoice=obj.id), who=user)
queryset.update(sent=None) | python | def resend_invoices(modeladmin, request: HttpRequest, queryset: QuerySet):
"""
Marks invoices with as un-sent.
:param modeladmin:
:param request:
:param queryset:
:return:
"""
user = request.user
assert isinstance(user, User)
for obj in queryset:
assert isinstance(obj, Invoice)
admin_log([obj, user], 'Invoice id={invoice} marked for re-sending'.format(invoice=obj.id), who=user)
queryset.update(sent=None) | [
"def",
"resend_invoices",
"(",
"modeladmin",
",",
"request",
":",
"HttpRequest",
",",
"queryset",
":",
"QuerySet",
")",
":",
"user",
"=",
"request",
".",
"user",
"assert",
"isinstance",
"(",
"user",
",",
"User",
")",
"for",
"obj",
"in",
"queryset",
":",
... | Marks invoices with as un-sent.
:param modeladmin:
:param request:
:param queryset:
:return: | [
"Marks",
"invoices",
"with",
"as",
"un",
"-",
"sent",
".",
":",
"param",
"modeladmin",
":",
":",
"param",
"request",
":",
":",
"param",
"queryset",
":",
":",
"return",
":"
] | train | https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/admin.py#L507-L520 |
kajala/django-jacc | jacc/admin.py | AccountEntryInlineFormSet.clean_entries | def clean_entries(self, source_invoice: Invoice or None, settled_invoice: Invoice or None, account: Account, **kw):
"""
This needs to be called from a derived class clean().
:param source_invoice:
:param settled_invoice:
:param account:
:return: None
"""
for form in self.forms:
obj = form.instance
assert isinstance(obj, AccountEntry)
obj.account = account
obj.source_invoice = source_invoice
obj.settled_invoice = settled_invoice
if obj.parent:
if obj.amount is None:
obj.amount = obj.parent.amount
if obj.type is None:
obj.type = obj.parent.type
if obj.amount > obj.parent.amount > Decimal(0) or obj.amount < obj.parent.amount < Decimal(0):
raise ValidationError(_('Derived account entry amount cannot be larger than original'))
for k, v in kw.items():
setattr(obj, k, v) | python | def clean_entries(self, source_invoice: Invoice or None, settled_invoice: Invoice or None, account: Account, **kw):
"""
This needs to be called from a derived class clean().
:param source_invoice:
:param settled_invoice:
:param account:
:return: None
"""
for form in self.forms:
obj = form.instance
assert isinstance(obj, AccountEntry)
obj.account = account
obj.source_invoice = source_invoice
obj.settled_invoice = settled_invoice
if obj.parent:
if obj.amount is None:
obj.amount = obj.parent.amount
if obj.type is None:
obj.type = obj.parent.type
if obj.amount > obj.parent.amount > Decimal(0) or obj.amount < obj.parent.amount < Decimal(0):
raise ValidationError(_('Derived account entry amount cannot be larger than original'))
for k, v in kw.items():
setattr(obj, k, v) | [
"def",
"clean_entries",
"(",
"self",
",",
"source_invoice",
":",
"Invoice",
"or",
"None",
",",
"settled_invoice",
":",
"Invoice",
"or",
"None",
",",
"account",
":",
"Account",
",",
"*",
"*",
"kw",
")",
":",
"for",
"form",
"in",
"self",
".",
"forms",
":... | This needs to be called from a derived class clean().
:param source_invoice:
:param settled_invoice:
:param account:
:return: None | [
"This",
"needs",
"to",
"be",
"called",
"from",
"a",
"derived",
"class",
"clean",
"()",
".",
":",
"param",
"source_invoice",
":",
":",
"param",
"settled_invoice",
":",
":",
"param",
"account",
":",
":",
"return",
":",
"None"
] | train | https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/admin.py#L335-L357 |
kajala/django-jacc | jacc/admin.py | InvoiceAdmin._format_date | def _format_date(self, obj) -> str:
"""
Short date format.
:param obj: date or datetime or None
:return: str
"""
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT') | python | def _format_date(self, obj) -> str:
"""
Short date format.
:param obj: date or datetime or None
:return: str
"""
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT') | [
"def",
"_format_date",
"(",
"self",
",",
"obj",
")",
"->",
"str",
":",
"if",
"obj",
"is",
"None",
":",
"return",
"''",
"if",
"isinstance",
"(",
"obj",
",",
"datetime",
")",
":",
"obj",
"=",
"obj",
".",
"date",
"(",
")",
"return",
"date_format",
"("... | Short date format.
:param obj: date or datetime or None
:return: str | [
"Short",
"date",
"format",
".",
":",
"param",
"obj",
":",
"date",
"or",
"datetime",
"or",
"None",
":",
"return",
":",
"str"
] | train | https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/admin.py#L669-L679 |
kajala/django-jacc | jacc/helpers.py | sum_queryset | def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal:
"""
Returns aggregate sum of queryset 'amount' field.
:param qs: QuerySet
:param key: Field to sum (default: 'amount')
:param default: Default value if no results
:return: Sum of 'amount' field values (coalesced 0 if None)
"""
res = qs.aggregate(b=Sum(key))['b']
return default if res is None else res | python | def sum_queryset(qs: QuerySet, key: str= 'amount', default=Decimal(0)) -> Decimal:
"""
Returns aggregate sum of queryset 'amount' field.
:param qs: QuerySet
:param key: Field to sum (default: 'amount')
:param default: Default value if no results
:return: Sum of 'amount' field values (coalesced 0 if None)
"""
res = qs.aggregate(b=Sum(key))['b']
return default if res is None else res | [
"def",
"sum_queryset",
"(",
"qs",
":",
"QuerySet",
",",
"key",
":",
"str",
"=",
"'amount'",
",",
"default",
"=",
"Decimal",
"(",
"0",
")",
")",
"->",
"Decimal",
":",
"res",
"=",
"qs",
".",
"aggregate",
"(",
"b",
"=",
"Sum",
"(",
"key",
")",
")",
... | Returns aggregate sum of queryset 'amount' field.
:param qs: QuerySet
:param key: Field to sum (default: 'amount')
:param default: Default value if no results
:return: Sum of 'amount' field values (coalesced 0 if None) | [
"Returns",
"aggregate",
"sum",
"of",
"queryset",
"amount",
"field",
".",
":",
"param",
"qs",
":",
"QuerySet",
":",
"param",
"key",
":",
"Field",
"to",
"sum",
"(",
"default",
":",
"amount",
")",
":",
"param",
"default",
":",
"Default",
"value",
"if",
"n... | train | https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/helpers.py#L5-L14 |
marten-de-vries/Flask-WebSub | flask_websub/subscriber/__init__.py | Subscriber.build_blueprint | def build_blueprint(self, url_prefix=''):
"""Build a blueprint that contains the endpoints for callback URLs of
the current subscriber. Only call this once per instance. Arguments:
- url_prefix; this allows you to prefix the callback URLs in your app.
"""
self.blueprint_name, self.blueprint = build_blueprint(self, url_prefix)
return self.blueprint | python | def build_blueprint(self, url_prefix=''):
"""Build a blueprint that contains the endpoints for callback URLs of
the current subscriber. Only call this once per instance. Arguments:
- url_prefix; this allows you to prefix the callback URLs in your app.
"""
self.blueprint_name, self.blueprint = build_blueprint(self, url_prefix)
return self.blueprint | [
"def",
"build_blueprint",
"(",
"self",
",",
"url_prefix",
"=",
"''",
")",
":",
"self",
".",
"blueprint_name",
",",
"self",
".",
"blueprint",
"=",
"build_blueprint",
"(",
"self",
",",
"url_prefix",
")",
"return",
"self",
".",
"blueprint"
] | Build a blueprint that contains the endpoints for callback URLs of
the current subscriber. Only call this once per instance. Arguments:
- url_prefix; this allows you to prefix the callback URLs in your app. | [
"Build",
"a",
"blueprint",
"that",
"contains",
"the",
"endpoints",
"for",
"callback",
"URLs",
"of",
"the",
"current",
"subscriber",
".",
"Only",
"call",
"this",
"once",
"per",
"instance",
".",
"Arguments",
":"
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/subscriber/__init__.py#L74-L82 |
marten-de-vries/Flask-WebSub | flask_websub/subscriber/__init__.py | Subscriber.unsubscribe | def unsubscribe(self, callback_id):
"""Ask the hub to cancel the subscription for callback_id, then delete
it from the local database if successful.
"""
request = self.get_active_subscription(callback_id)
request['mode'] = 'unsubscribe'
self.subscribe_impl(callback_id, **request) | python | def unsubscribe(self, callback_id):
"""Ask the hub to cancel the subscription for callback_id, then delete
it from the local database if successful.
"""
request = self.get_active_subscription(callback_id)
request['mode'] = 'unsubscribe'
self.subscribe_impl(callback_id, **request) | [
"def",
"unsubscribe",
"(",
"self",
",",
"callback_id",
")",
":",
"request",
"=",
"self",
".",
"get_active_subscription",
"(",
"callback_id",
")",
"request",
"[",
"'mode'",
"]",
"=",
"'unsubscribe'",
"self",
".",
"subscribe_impl",
"(",
"callback_id",
",",
"*",
... | Ask the hub to cancel the subscription for callback_id, then delete
it from the local database if successful. | [
"Ask",
"the",
"hub",
"to",
"cancel",
"the",
"subscription",
"for",
"callback_id",
"then",
"delete",
"it",
"from",
"the",
"local",
"database",
"if",
"successful",
"."
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/subscriber/__init__.py#L161-L168 |
marten-de-vries/Flask-WebSub | flask_websub/subscriber/__init__.py | Subscriber.renew_close_to_expiration | def renew_close_to_expiration(self, margin_in_seconds=A_DAY):
"""Automatically renew subscriptions that are close to expiring, or
have already expired. margin_in_seconds determines if a subscription is
in fact close to expiring. By default, said margin is set to be a
single day (24 hours).
This is a long-running method for any non-trivial usage of the
subscriber module, as renewal requires several http requests, and
subscriptions are processed serially. Because of that, it is
recommended to run this method in a celery task.
"""
subscriptions = self.storage.close_to_expiration(margin_in_seconds)
for subscription in subscriptions:
try:
self.subscribe_impl(**subscription)
except SubscriberError as e:
warn(RENEW_FAILURE % (subscription['topic_url'],
subscription['callback_id']), e) | python | def renew_close_to_expiration(self, margin_in_seconds=A_DAY):
"""Automatically renew subscriptions that are close to expiring, or
have already expired. margin_in_seconds determines if a subscription is
in fact close to expiring. By default, said margin is set to be a
single day (24 hours).
This is a long-running method for any non-trivial usage of the
subscriber module, as renewal requires several http requests, and
subscriptions are processed serially. Because of that, it is
recommended to run this method in a celery task.
"""
subscriptions = self.storage.close_to_expiration(margin_in_seconds)
for subscription in subscriptions:
try:
self.subscribe_impl(**subscription)
except SubscriberError as e:
warn(RENEW_FAILURE % (subscription['topic_url'],
subscription['callback_id']), e) | [
"def",
"renew_close_to_expiration",
"(",
"self",
",",
"margin_in_seconds",
"=",
"A_DAY",
")",
":",
"subscriptions",
"=",
"self",
".",
"storage",
".",
"close_to_expiration",
"(",
"margin_in_seconds",
")",
"for",
"subscription",
"in",
"subscriptions",
":",
"try",
":... | Automatically renew subscriptions that are close to expiring, or
have already expired. margin_in_seconds determines if a subscription is
in fact close to expiring. By default, said margin is set to be a
single day (24 hours).
This is a long-running method for any non-trivial usage of the
subscriber module, as renewal requires several http requests, and
subscriptions are processed serially. Because of that, it is
recommended to run this method in a celery task. | [
"Automatically",
"renew",
"subscriptions",
"that",
"are",
"close",
"to",
"expiring",
"or",
"have",
"already",
"expired",
".",
"margin_in_seconds",
"determines",
"if",
"a",
"subscription",
"is",
"in",
"fact",
"close",
"to",
"expiring",
".",
"By",
"default",
"said... | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/subscriber/__init__.py#L186-L204 |
marten-de-vries/Flask-WebSub | flask_websub/subscriber/discovery.py | discover | def discover(url, timeout=None):
"""Discover the hub url and topic url of a given url. Firstly, by inspecting
the page's headers, secondarily by inspecting the content for link tags.
timeout determines how long to wait for the url to load. It defaults to 3.
"""
resp = get_content({'REQUEST_TIMEOUT': timeout}, url)
parser = LinkParser()
parser.hub_url = (resp.links.get('hub') or {}).get('url')
parser.topic_url = (resp.links.get('self') or {}).get('url')
try:
parser.updated()
for chunk in resp.iter_content(chunk_size=None, decode_unicode=True):
parser.feed(chunk)
parser.close()
except Finished:
return {'hub_url': parser.hub_url, 'topic_url': parser.topic_url}
raise DiscoveryError("Could not find hub url in topic page") | python | def discover(url, timeout=None):
"""Discover the hub url and topic url of a given url. Firstly, by inspecting
the page's headers, secondarily by inspecting the content for link tags.
timeout determines how long to wait for the url to load. It defaults to 3.
"""
resp = get_content({'REQUEST_TIMEOUT': timeout}, url)
parser = LinkParser()
parser.hub_url = (resp.links.get('hub') or {}).get('url')
parser.topic_url = (resp.links.get('self') or {}).get('url')
try:
parser.updated()
for chunk in resp.iter_content(chunk_size=None, decode_unicode=True):
parser.feed(chunk)
parser.close()
except Finished:
return {'hub_url': parser.hub_url, 'topic_url': parser.topic_url}
raise DiscoveryError("Could not find hub url in topic page") | [
"def",
"discover",
"(",
"url",
",",
"timeout",
"=",
"None",
")",
":",
"resp",
"=",
"get_content",
"(",
"{",
"'REQUEST_TIMEOUT'",
":",
"timeout",
"}",
",",
"url",
")",
"parser",
"=",
"LinkParser",
"(",
")",
"parser",
".",
"hub_url",
"=",
"(",
"resp",
... | Discover the hub url and topic url of a given url. Firstly, by inspecting
the page's headers, secondarily by inspecting the content for link tags.
timeout determines how long to wait for the url to load. It defaults to 3. | [
"Discover",
"the",
"hub",
"url",
"and",
"topic",
"url",
"of",
"a",
"given",
"url",
".",
"Firstly",
"by",
"inspecting",
"the",
"page",
"s",
"headers",
"secondarily",
"by",
"inspecting",
"the",
"content",
"for",
"link",
"tags",
"."
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/subscriber/discovery.py#L8-L28 |
LLNL/certipy | certipy/certipy.py | open_tls_file | def open_tls_file(file_path, mode, private=True):
"""Context to ensure correct file permissions for certs and directories
Ensures:
- A containing directory with appropriate permissions
- Correct file permissions based on what the file is (0o600 for keys
and 0o644 for certs)
"""
containing_dir = os.path.dirname(file_path)
fh = None
try:
if 'w' in mode:
os.chmod(containing_dir, mode=0o755)
fh = open(file_path, mode)
except OSError as e:
if 'w' in mode:
os.makedirs(containing_dir, mode=0o755, exist_ok=True)
os.chmod(containing_dir, mode=0o755)
fh = open(file_path, 'w')
else:
raise
yield fh
mode = 0o600 if private else 0o644
os.chmod(file_path, mode=mode)
fh.close() | python | def open_tls_file(file_path, mode, private=True):
"""Context to ensure correct file permissions for certs and directories
Ensures:
- A containing directory with appropriate permissions
- Correct file permissions based on what the file is (0o600 for keys
and 0o644 for certs)
"""
containing_dir = os.path.dirname(file_path)
fh = None
try:
if 'w' in mode:
os.chmod(containing_dir, mode=0o755)
fh = open(file_path, mode)
except OSError as e:
if 'w' in mode:
os.makedirs(containing_dir, mode=0o755, exist_ok=True)
os.chmod(containing_dir, mode=0o755)
fh = open(file_path, 'w')
else:
raise
yield fh
mode = 0o600 if private else 0o644
os.chmod(file_path, mode=mode)
fh.close() | [
"def",
"open_tls_file",
"(",
"file_path",
",",
"mode",
",",
"private",
"=",
"True",
")",
":",
"containing_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file_path",
")",
"fh",
"=",
"None",
"try",
":",
"if",
"'w'",
"in",
"mode",
":",
"os",
".",
... | Context to ensure correct file permissions for certs and directories
Ensures:
- A containing directory with appropriate permissions
- Correct file permissions based on what the file is (0o600 for keys
and 0o644 for certs) | [
"Context",
"to",
"ensure",
"correct",
"file",
"permissions",
"for",
"certs",
"and",
"directories"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L49-L74 |
LLNL/certipy | certipy/certipy.py | TLSFile.load | def load(self):
"""Load from a file and return an x509 object"""
private = self.is_private()
with open_tls_file(self.file_path, 'r', private=private) as fh:
if private:
self.x509 = crypto.load_privatekey(self.encoding, fh.read())
else:
self.x509 = crypto.load_certificate(self.encoding, fh.read())
return self.x509 | python | def load(self):
"""Load from a file and return an x509 object"""
private = self.is_private()
with open_tls_file(self.file_path, 'r', private=private) as fh:
if private:
self.x509 = crypto.load_privatekey(self.encoding, fh.read())
else:
self.x509 = crypto.load_certificate(self.encoding, fh.read())
return self.x509 | [
"def",
"load",
"(",
"self",
")",
":",
"private",
"=",
"self",
".",
"is_private",
"(",
")",
"with",
"open_tls_file",
"(",
"self",
".",
"file_path",
",",
"'r'",
",",
"private",
"=",
"private",
")",
"as",
"fh",
":",
"if",
"private",
":",
"self",
".",
... | Load from a file and return an x509 object | [
"Load",
"from",
"a",
"file",
"and",
"return",
"an",
"x509",
"object"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L133-L142 |
LLNL/certipy | certipy/certipy.py | TLSFile.save | def save(self, x509):
"""Persist this x509 object to disk"""
self.x509 = x509
with open_tls_file(self.file_path, 'w',
private=self.is_private()) as fh:
fh.write(str(self)) | python | def save(self, x509):
"""Persist this x509 object to disk"""
self.x509 = x509
with open_tls_file(self.file_path, 'w',
private=self.is_private()) as fh:
fh.write(str(self)) | [
"def",
"save",
"(",
"self",
",",
"x509",
")",
":",
"self",
".",
"x509",
"=",
"x509",
"with",
"open_tls_file",
"(",
"self",
".",
"file_path",
",",
"'w'",
",",
"private",
"=",
"self",
".",
"is_private",
"(",
")",
")",
"as",
"fh",
":",
"fh",
".",
"w... | Persist this x509 object to disk | [
"Persist",
"this",
"x509",
"object",
"to",
"disk"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L144-L150 |
LLNL/certipy | certipy/certipy.py | TLSFileBundle._setup_tls_files | def _setup_tls_files(self, files):
"""Initiates TLSFIle objects with the paths given to this bundle"""
for file_type in TLSFileType:
if file_type.value in files:
file_path = files[file_type.value]
setattr(self, file_type.value,
TLSFile(file_path, file_type=file_type)) | python | def _setup_tls_files(self, files):
"""Initiates TLSFIle objects with the paths given to this bundle"""
for file_type in TLSFileType:
if file_type.value in files:
file_path = files[file_type.value]
setattr(self, file_type.value,
TLSFile(file_path, file_type=file_type)) | [
"def",
"_setup_tls_files",
"(",
"self",
",",
"files",
")",
":",
"for",
"file_type",
"in",
"TLSFileType",
":",
"if",
"file_type",
".",
"value",
"in",
"files",
":",
"file_path",
"=",
"files",
"[",
"file_type",
".",
"value",
"]",
"setattr",
"(",
"self",
","... | Initiates TLSFIle objects with the paths given to this bundle | [
"Initiates",
"TLSFIle",
"objects",
"with",
"the",
"paths",
"given",
"to",
"this",
"bundle"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L171-L178 |
LLNL/certipy | certipy/certipy.py | TLSFileBundle.save_x509s | def save_x509s(self, x509s):
"""Saves the x509 objects to the paths known by this bundle"""
for file_type in TLSFileType:
if file_type.value in x509s:
x509 = x509s[file_type.value]
if file_type is not TLSFileType.CA:
# persist this key or cert to disk
tlsfile = getattr(self, file_type.value)
if tlsfile:
tlsfile.save(x509) | python | def save_x509s(self, x509s):
"""Saves the x509 objects to the paths known by this bundle"""
for file_type in TLSFileType:
if file_type.value in x509s:
x509 = x509s[file_type.value]
if file_type is not TLSFileType.CA:
# persist this key or cert to disk
tlsfile = getattr(self, file_type.value)
if tlsfile:
tlsfile.save(x509) | [
"def",
"save_x509s",
"(",
"self",
",",
"x509s",
")",
":",
"for",
"file_type",
"in",
"TLSFileType",
":",
"if",
"file_type",
".",
"value",
"in",
"x509s",
":",
"x509",
"=",
"x509s",
"[",
"file_type",
".",
"value",
"]",
"if",
"file_type",
"is",
"not",
"TLS... | Saves the x509 objects to the paths known by this bundle | [
"Saves",
"the",
"x509",
"objects",
"to",
"the",
"paths",
"known",
"by",
"this",
"bundle"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L180-L190 |
LLNL/certipy | certipy/certipy.py | TLSFileBundle.to_record | def to_record(self):
"""Create a CertStore record from this TLSFileBundle"""
tf_list = [getattr(self, k, None) for k in
[_.value for _ in TLSFileType]]
# If a cert isn't defined in this bundle, remove it
tf_list = filter(lambda x: x, tf_list)
files = {tf.file_type.value: tf.file_path for tf in tf_list}
self.record['files'] = files
return self.record | python | def to_record(self):
"""Create a CertStore record from this TLSFileBundle"""
tf_list = [getattr(self, k, None) for k in
[_.value for _ in TLSFileType]]
# If a cert isn't defined in this bundle, remove it
tf_list = filter(lambda x: x, tf_list)
files = {tf.file_type.value: tf.file_path for tf in tf_list}
self.record['files'] = files
return self.record | [
"def",
"to_record",
"(",
"self",
")",
":",
"tf_list",
"=",
"[",
"getattr",
"(",
"self",
",",
"k",
",",
"None",
")",
"for",
"k",
"in",
"[",
"_",
".",
"value",
"for",
"_",
"in",
"TLSFileType",
"]",
"]",
"# If a cert isn't defined in this bundle, remove it",
... | Create a CertStore record from this TLSFileBundle | [
"Create",
"a",
"CertStore",
"record",
"from",
"this",
"TLSFileBundle"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L203-L212 |
LLNL/certipy | certipy/certipy.py | TLSFileBundle.from_record | def from_record(self, record):
"""Build a bundle from a CertStore record"""
self.record = record
self._setup_tls_files(self.record['files'])
return self | python | def from_record(self, record):
"""Build a bundle from a CertStore record"""
self.record = record
self._setup_tls_files(self.record['files'])
return self | [
"def",
"from_record",
"(",
"self",
",",
"record",
")",
":",
"self",
".",
"record",
"=",
"record",
"self",
".",
"_setup_tls_files",
"(",
"self",
".",
"record",
"[",
"'files'",
"]",
")",
"return",
"self"
] | Build a bundle from a CertStore record | [
"Build",
"a",
"bundle",
"from",
"a",
"CertStore",
"record"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L214-L219 |
LLNL/certipy | certipy/certipy.py | CertStore.save | def save(self):
"""Write the store dict to a file specified by store_file_path"""
with open(self.store_file_path, 'w') as fh:
fh.write(json.dumps(self.store, indent=4)) | python | def save(self):
"""Write the store dict to a file specified by store_file_path"""
with open(self.store_file_path, 'w') as fh:
fh.write(json.dumps(self.store, indent=4)) | [
"def",
"save",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"store_file_path",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"self",
".",
"store",
",",
"indent",
"=",
"4",
")",
")"
] | Write the store dict to a file specified by store_file_path | [
"Write",
"the",
"store",
"dict",
"to",
"a",
"file",
"specified",
"by",
"store_file_path"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L253-L257 |
LLNL/certipy | certipy/certipy.py | CertStore.load | def load(self):
"""Read the store dict from file"""
with open(self.store_file_path, 'r') as fh:
self.store = json.loads(fh.read()) | python | def load(self):
"""Read the store dict from file"""
with open(self.store_file_path, 'r') as fh:
self.store = json.loads(fh.read()) | [
"def",
"load",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"store_file_path",
",",
"'r'",
")",
"as",
"fh",
":",
"self",
".",
"store",
"=",
"json",
".",
"loads",
"(",
"fh",
".",
"read",
"(",
")",
")"
] | Read the store dict from file | [
"Read",
"the",
"store",
"dict",
"from",
"file"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L259-L263 |
LLNL/certipy | certipy/certipy.py | CertStore.get_record | def get_record(self, common_name):
"""Return the record associated with this common name
In most cases, all that's really needed to use an existing cert are
the file paths to the files that make up that cert. This method
returns just that and doesn't bother loading the associated files.
"""
try:
record = self.store[common_name]
return record
except KeyError as e:
raise CertNotFoundError(
"Unable to find record of {name}"
.format(name=common_name), errors=e) | python | def get_record(self, common_name):
"""Return the record associated with this common name
In most cases, all that's really needed to use an existing cert are
the file paths to the files that make up that cert. This method
returns just that and doesn't bother loading the associated files.
"""
try:
record = self.store[common_name]
return record
except KeyError as e:
raise CertNotFoundError(
"Unable to find record of {name}"
.format(name=common_name), errors=e) | [
"def",
"get_record",
"(",
"self",
",",
"common_name",
")",
":",
"try",
":",
"record",
"=",
"self",
".",
"store",
"[",
"common_name",
"]",
"return",
"record",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"CertNotFoundError",
"(",
"\"Unable to find record of {... | Return the record associated with this common name
In most cases, all that's really needed to use an existing cert are
the file paths to the files that make up that cert. This method
returns just that and doesn't bother loading the associated files. | [
"Return",
"the",
"record",
"associated",
"with",
"this",
"common",
"name"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L265-L279 |
LLNL/certipy | certipy/certipy.py | CertStore.get_files | def get_files(self, common_name):
"""Return a bundle of TLS files associated with a common name"""
record = self.get_record(common_name)
return TLSFileBundle(common_name).from_record(record) | python | def get_files(self, common_name):
"""Return a bundle of TLS files associated with a common name"""
record = self.get_record(common_name)
return TLSFileBundle(common_name).from_record(record) | [
"def",
"get_files",
"(",
"self",
",",
"common_name",
")",
":",
"record",
"=",
"self",
".",
"get_record",
"(",
"common_name",
")",
"return",
"TLSFileBundle",
"(",
"common_name",
")",
".",
"from_record",
"(",
"record",
")"
] | Return a bundle of TLS files associated with a common name | [
"Return",
"a",
"bundle",
"of",
"TLS",
"files",
"associated",
"with",
"a",
"common",
"name"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L281-L285 |
LLNL/certipy | certipy/certipy.py | CertStore.add_record | def add_record(self, common_name, serial=0, parent_ca='',
signees=None, files=None, record=None,
is_ca=False, overwrite=False):
"""Manually create a record of certs
Generally, Certipy can be left to manage certificate locations and
storage, but it is occasionally useful to keep track of a set of
certs that were created externally (for example, let's encrypt)
"""
if not overwrite:
try:
self.get_record(common_name)
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add."
.format(name=common_name))
except CertNotFoundError:
pass
record = record or {
'serial': serial,
'is_ca': is_ca,
'parent_ca': parent_ca,
'signees': signees,
'files': files,
}
self.store[common_name] = record
self.save() | python | def add_record(self, common_name, serial=0, parent_ca='',
signees=None, files=None, record=None,
is_ca=False, overwrite=False):
"""Manually create a record of certs
Generally, Certipy can be left to manage certificate locations and
storage, but it is occasionally useful to keep track of a set of
certs that were created externally (for example, let's encrypt)
"""
if not overwrite:
try:
self.get_record(common_name)
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add."
.format(name=common_name))
except CertNotFoundError:
pass
record = record or {
'serial': serial,
'is_ca': is_ca,
'parent_ca': parent_ca,
'signees': signees,
'files': files,
}
self.store[common_name] = record
self.save() | [
"def",
"add_record",
"(",
"self",
",",
"common_name",
",",
"serial",
"=",
"0",
",",
"parent_ca",
"=",
"''",
",",
"signees",
"=",
"None",
",",
"files",
"=",
"None",
",",
"record",
"=",
"None",
",",
"is_ca",
"=",
"False",
",",
"overwrite",
"=",
"False"... | Manually create a record of certs
Generally, Certipy can be left to manage certificate locations and
storage, but it is occasionally useful to keep track of a set of
certs that were created externally (for example, let's encrypt) | [
"Manually",
"create",
"a",
"record",
"of",
"certs"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L287-L315 |
LLNL/certipy | certipy/certipy.py | CertStore.add_files | def add_files(self, common_name, x509s, files=None, parent_ca='',
is_ca=False, signees=None, serial=0, overwrite=False):
"""Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these files to disk and automatically calls save
on all TLSFiles that it creates (and where it makes sense to).
"""
if common_name in self.store and not overwrite:
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add."
.format(name=common_name))
elif common_name in self.store and overwrite:
record = self.get_record(common_name)
serial = int(record['serial'])
record['serial'] = serial + 1
TLSFileBundle(common_name).from_record(record).save_x509s(x509s)
else:
file_base_tmpl = "{prefix}/{cn}/{cn}"
file_base = file_base_tmpl.format(
prefix=self.containing_dir, cn=common_name
)
try:
ca_record = self.get_record(parent_ca)
ca_file = ca_record['files']['cert']
except CertNotFoundError:
ca_file = ''
files = files or {
'key': file_base + '.key',
'cert': file_base + '.crt',
'ca': ca_file,
}
bundle = TLSFileBundle(
common_name, files=files, x509s=x509s, is_ca=is_ca,
serial=serial, parent_ca=parent_ca, signees=signees)
self.store[common_name] = bundle.to_record()
self.save() | python | def add_files(self, common_name, x509s, files=None, parent_ca='',
is_ca=False, signees=None, serial=0, overwrite=False):
"""Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these files to disk and automatically calls save
on all TLSFiles that it creates (and where it makes sense to).
"""
if common_name in self.store and not overwrite:
raise CertExistsError(
"Certificate {name} already exists!"
" Set overwrite=True to force add."
.format(name=common_name))
elif common_name in self.store and overwrite:
record = self.get_record(common_name)
serial = int(record['serial'])
record['serial'] = serial + 1
TLSFileBundle(common_name).from_record(record).save_x509s(x509s)
else:
file_base_tmpl = "{prefix}/{cn}/{cn}"
file_base = file_base_tmpl.format(
prefix=self.containing_dir, cn=common_name
)
try:
ca_record = self.get_record(parent_ca)
ca_file = ca_record['files']['cert']
except CertNotFoundError:
ca_file = ''
files = files or {
'key': file_base + '.key',
'cert': file_base + '.crt',
'ca': ca_file,
}
bundle = TLSFileBundle(
common_name, files=files, x509s=x509s, is_ca=is_ca,
serial=serial, parent_ca=parent_ca, signees=signees)
self.store[common_name] = bundle.to_record()
self.save() | [
"def",
"add_files",
"(",
"self",
",",
"common_name",
",",
"x509s",
",",
"files",
"=",
"None",
",",
"parent_ca",
"=",
"''",
",",
"is_ca",
"=",
"False",
",",
"signees",
"=",
"None",
",",
"serial",
"=",
"0",
",",
"overwrite",
"=",
"False",
")",
":",
"... | Add a set files comprising a certificate to Certipy
Used with all the defaults, Certipy will manage creation of file paths
to be used to store these files to disk and automatically calls save
on all TLSFiles that it creates (and where it makes sense to). | [
"Add",
"a",
"set",
"files",
"comprising",
"a",
"certificate",
"to",
"Certipy"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L317-L355 |
LLNL/certipy | certipy/certipy.py | CertStore.remove_sign_link | def remove_sign_link(self, ca_name, signee_name):
"""Removes signee_name to the signee list for ca_name"""
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record['signees'] or {}
signees = Counter(signees)
if signee_name in signees:
signees[signee_name] = 0
ca_record['signees'] = signees
signee_record['parent_ca'] = ''
self.save() | python | def remove_sign_link(self, ca_name, signee_name):
"""Removes signee_name to the signee list for ca_name"""
ca_record = self.get_record(ca_name)
signee_record = self.get_record(signee_name)
signees = ca_record['signees'] or {}
signees = Counter(signees)
if signee_name in signees:
signees[signee_name] = 0
ca_record['signees'] = signees
signee_record['parent_ca'] = ''
self.save() | [
"def",
"remove_sign_link",
"(",
"self",
",",
"ca_name",
",",
"signee_name",
")",
":",
"ca_record",
"=",
"self",
".",
"get_record",
"(",
"ca_name",
")",
"signee_record",
"=",
"self",
".",
"get_record",
"(",
"signee_name",
")",
"signees",
"=",
"ca_record",
"["... | Removes signee_name to the signee list for ca_name | [
"Removes",
"signee_name",
"to",
"the",
"signee",
"list",
"for",
"ca_name"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L370-L381 |
LLNL/certipy | certipy/certipy.py | CertStore.update_record | def update_record(self, common_name, **fields):
"""Update fields in an existing record"""
record = self.get_record(common_name)
if fields is not None:
for field, value in fields:
record[field] = value
self.save()
return record | python | def update_record(self, common_name, **fields):
"""Update fields in an existing record"""
record = self.get_record(common_name)
if fields is not None:
for field, value in fields:
record[field] = value
self.save()
return record | [
"def",
"update_record",
"(",
"self",
",",
"common_name",
",",
"*",
"*",
"fields",
")",
":",
"record",
"=",
"self",
".",
"get_record",
"(",
"common_name",
")",
"if",
"fields",
"is",
"not",
"None",
":",
"for",
"field",
",",
"value",
"in",
"fields",
":",
... | Update fields in an existing record | [
"Update",
"fields",
"in",
"an",
"existing",
"record"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L383-L391 |
LLNL/certipy | certipy/certipy.py | CertStore.remove_record | def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
"Authority {name} has signed {x} certificates"
.format(name=common_name, x=num_signees)
)
try:
ca_name = bundle.record['parent_ca']
ca_record = self.get_record(ca_name)
self.remove_sign_link(ca_name, common_name)
except CertNotFoundError:
pass
record_copy = dict(self.store[common_name])
del self.store[common_name]
self.save()
return record_copy | python | def remove_record(self, common_name):
"""Delete the record associated with this common name"""
bundle = self.get_files(common_name)
num_signees = len(Counter(bundle.record['signees']))
if bundle.is_ca() and num_signees > 0:
raise CertificateAuthorityInUseError(
"Authority {name} has signed {x} certificates"
.format(name=common_name, x=num_signees)
)
try:
ca_name = bundle.record['parent_ca']
ca_record = self.get_record(ca_name)
self.remove_sign_link(ca_name, common_name)
except CertNotFoundError:
pass
record_copy = dict(self.store[common_name])
del self.store[common_name]
self.save()
return record_copy | [
"def",
"remove_record",
"(",
"self",
",",
"common_name",
")",
":",
"bundle",
"=",
"self",
".",
"get_files",
"(",
"common_name",
")",
"num_signees",
"=",
"len",
"(",
"Counter",
"(",
"bundle",
".",
"record",
"[",
"'signees'",
"]",
")",
")",
"if",
"bundle",... | Delete the record associated with this common name | [
"Delete",
"the",
"record",
"associated",
"with",
"this",
"common",
"name"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L393-L412 |
LLNL/certipy | certipy/certipy.py | CertStore.remove_files | def remove_files(self, common_name, delete_dir=False):
"""Delete files and record associated with this common name"""
record = self.remove_record(common_name)
if delete_dir:
delete_dirs = []
if 'files' in record:
key_containing_dir = os.path.dirname(record['files']['key'])
delete_dirs.append(key_containing_dir)
cert_containing_dir = os.path.dirname(record['files']['cert'])
if key_containing_dir != cert_containing_dir:
delete_dirs.append(cert_containing_dir)
for d in delete_dirs:
shutil.rmtree(d)
return record | python | def remove_files(self, common_name, delete_dir=False):
"""Delete files and record associated with this common name"""
record = self.remove_record(common_name)
if delete_dir:
delete_dirs = []
if 'files' in record:
key_containing_dir = os.path.dirname(record['files']['key'])
delete_dirs.append(key_containing_dir)
cert_containing_dir = os.path.dirname(record['files']['cert'])
if key_containing_dir != cert_containing_dir:
delete_dirs.append(cert_containing_dir)
for d in delete_dirs:
shutil.rmtree(d)
return record | [
"def",
"remove_files",
"(",
"self",
",",
"common_name",
",",
"delete_dir",
"=",
"False",
")",
":",
"record",
"=",
"self",
".",
"remove_record",
"(",
"common_name",
")",
"if",
"delete_dir",
":",
"delete_dirs",
"=",
"[",
"]",
"if",
"'files'",
"in",
"record",... | Delete files and record associated with this common name | [
"Delete",
"files",
"and",
"record",
"associated",
"with",
"this",
"common",
"name"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L414-L428 |
LLNL/certipy | certipy/certipy.py | Certipy.create_key_pair | def create_key_pair(self, cert_type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
"""
pkey = crypto.PKey()
pkey.generate_key(cert_type, bits)
return pkey | python | def create_key_pair(self, cert_type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
"""
pkey = crypto.PKey()
pkey.generate_key(cert_type, bits)
return pkey | [
"def",
"create_key_pair",
"(",
"self",
",",
"cert_type",
",",
"bits",
")",
":",
"pkey",
"=",
"crypto",
".",
"PKey",
"(",
")",
"pkey",
".",
"generate_key",
"(",
"cert_type",
",",
"bits",
")",
"return",
"pkey"
] | Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object | [
"Create",
"a",
"public",
"/",
"private",
"key",
"pair",
"."
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L437-L448 |
LLNL/certipy | certipy/certipy.py | Certipy.sign | def sign(self, req, issuer_cert_key, validity_period, digest="sha256",
extensions=None, serial=0):
"""
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
issuer_key - The private key of the issuer
not_before - Timestamp (relative to now) when the
certificate starts being valid
not_after - Timestamp (relative to now) when the
certificate stops being valid
digest - Digest method to use for signing,
default is sha256
Returns: The signed certificate in an X509 object
"""
issuer_cert, issuer_key = issuer_cert_key
not_before, not_after = validity_period
cert = crypto.X509()
cert.set_serial_number(serial)
cert.gmtime_adj_notBefore(not_before)
cert.gmtime_adj_notAfter(not_after)
cert.set_issuer(issuer_cert.get_subject())
cert.set_subject(req.get_subject())
cert.set_pubkey(req.get_pubkey())
if extensions:
for ext in extensions:
if callable(ext):
ext = ext(cert)
cert.add_extensions([ext])
cert.sign(issuer_key, digest)
return cert | python | def sign(self, req, issuer_cert_key, validity_period, digest="sha256",
extensions=None, serial=0):
"""
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
issuer_key - The private key of the issuer
not_before - Timestamp (relative to now) when the
certificate starts being valid
not_after - Timestamp (relative to now) when the
certificate stops being valid
digest - Digest method to use for signing,
default is sha256
Returns: The signed certificate in an X509 object
"""
issuer_cert, issuer_key = issuer_cert_key
not_before, not_after = validity_period
cert = crypto.X509()
cert.set_serial_number(serial)
cert.gmtime_adj_notBefore(not_before)
cert.gmtime_adj_notAfter(not_after)
cert.set_issuer(issuer_cert.get_subject())
cert.set_subject(req.get_subject())
cert.set_pubkey(req.get_pubkey())
if extensions:
for ext in extensions:
if callable(ext):
ext = ext(cert)
cert.add_extensions([ext])
cert.sign(issuer_key, digest)
return cert | [
"def",
"sign",
"(",
"self",
",",
"req",
",",
"issuer_cert_key",
",",
"validity_period",
",",
"digest",
"=",
"\"sha256\"",
",",
"extensions",
"=",
"None",
",",
"serial",
"=",
"0",
")",
":",
"issuer_cert",
",",
"issuer_key",
"=",
"issuer_cert_key",
"not_before... | Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
issuer_cert - The certificate of the issuer
issuer_key - The private key of the issuer
not_before - Timestamp (relative to now) when the
certificate starts being valid
not_after - Timestamp (relative to now) when the
certificate stops being valid
digest - Digest method to use for signing,
default is sha256
Returns: The signed certificate in an X509 object | [
"Generate",
"a",
"certificate",
"given",
"a",
"certificate",
"request",
"."
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L487-L522 |
LLNL/certipy | certipy/certipy.py | Certipy.create_ca_bundle_for_names | def create_ca_bundle_for_names(self, bundle_name, names):
"""Create a CA bundle to trust only certs defined in names
"""
records = [rec for name, rec
in self.store.store.items() if name in names]
return self.create_bundle(
bundle_name, names=[r['parent_ca'] for r in records]) | python | def create_ca_bundle_for_names(self, bundle_name, names):
"""Create a CA bundle to trust only certs defined in names
"""
records = [rec for name, rec
in self.store.store.items() if name in names]
return self.create_bundle(
bundle_name, names=[r['parent_ca'] for r in records]) | [
"def",
"create_ca_bundle_for_names",
"(",
"self",
",",
"bundle_name",
",",
"names",
")",
":",
"records",
"=",
"[",
"rec",
"for",
"name",
",",
"rec",
"in",
"self",
".",
"store",
".",
"store",
".",
"items",
"(",
")",
"if",
"name",
"in",
"names",
"]",
"... | Create a CA bundle to trust only certs defined in names | [
"Create",
"a",
"CA",
"bundle",
"to",
"trust",
"only",
"certs",
"defined",
"in",
"names"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L524-L531 |
LLNL/certipy | certipy/certipy.py | Certipy.create_bundle | def create_bundle(self, bundle_name, names=None, ca_only=True):
"""Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file
"""
if not names:
if ca_only:
names = []
for name, record in self.store.store.items():
if record['is_ca']:
names.append(name)
else:
names = self.store.store.keys()
out_file_path = os.path.join(self.store.containing_dir, bundle_name)
with open(out_file_path, 'w') as fh:
for name in names:
bundle = self.store.get_files(name)
bundle.cert.load()
fh.write(str(bundle.cert))
return out_file_path | python | def create_bundle(self, bundle_name, names=None, ca_only=True):
"""Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file
"""
if not names:
if ca_only:
names = []
for name, record in self.store.store.items():
if record['is_ca']:
names.append(name)
else:
names = self.store.store.keys()
out_file_path = os.path.join(self.store.containing_dir, bundle_name)
with open(out_file_path, 'w') as fh:
for name in names:
bundle = self.store.get_files(name)
bundle.cert.load()
fh.write(str(bundle.cert))
return out_file_path | [
"def",
"create_bundle",
"(",
"self",
",",
"bundle_name",
",",
"names",
"=",
"None",
",",
"ca_only",
"=",
"True",
")",
":",
"if",
"not",
"names",
":",
"if",
"ca_only",
":",
"names",
"=",
"[",
"]",
"for",
"name",
",",
"record",
"in",
"self",
".",
"st... | Create a bundle of public certs for trust distribution
This will create a bundle of both CAs and/or regular certificates.
Arguments: names - The names of certs to include in the bundle
bundle_name - The name of the bundle file to output
Returns: Path to the bundle file | [
"Create",
"a",
"bundle",
"of",
"public",
"certs",
"for",
"trust",
"distribution"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L545-L569 |
LLNL/certipy | certipy/certipy.py | Certipy.trust_from_graph | def trust_from_graph(self, graph):
"""Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict component:list(components)
Returns: dict component:trust bundle file path
"""
# Ensure there are CAs backing all graph components
def distinct_components(graph):
"""Return a set of components from the provided graph."""
components = set(graph.keys())
for trusts in graph.values():
components |= set(trusts)
return components
# Default to creating a CA (incapable of signing intermediaries) to
# identify a component not known to Certipy
for component in distinct_components(graph):
try:
self.store.get_record(component)
except CertNotFoundError:
self.create_ca(component)
# Build bundles from the graph
trust_files = {}
for component, trusts in graph.items():
file_name = component + '_trust.crt'
trust_files[component] = self.create_bundle(
file_name, names=trusts, ca_only=False)
return trust_files | python | def trust_from_graph(self, graph):
"""Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict component:list(components)
Returns: dict component:trust bundle file path
"""
# Ensure there are CAs backing all graph components
def distinct_components(graph):
"""Return a set of components from the provided graph."""
components = set(graph.keys())
for trusts in graph.values():
components |= set(trusts)
return components
# Default to creating a CA (incapable of signing intermediaries) to
# identify a component not known to Certipy
for component in distinct_components(graph):
try:
self.store.get_record(component)
except CertNotFoundError:
self.create_ca(component)
# Build bundles from the graph
trust_files = {}
for component, trusts in graph.items():
file_name = component + '_trust.crt'
trust_files[component] = self.create_bundle(
file_name, names=trusts, ca_only=False)
return trust_files | [
"def",
"trust_from_graph",
"(",
"self",
",",
"graph",
")",
":",
"# Ensure there are CAs backing all graph components",
"def",
"distinct_components",
"(",
"graph",
")",
":",
"\"\"\"Return a set of components from the provided graph.\"\"\"",
"components",
"=",
"set",
"(",
"grap... | Create a set of trust bundles from a relationship graph.
Components in this sense are defined by unique CAs. This method assists
in setting up complicated trust between various components that need
to do TLS auth.
Arguments: graph - dict component:list(components)
Returns: dict component:trust bundle file path | [
"Create",
"a",
"set",
"of",
"trust",
"bundles",
"from",
"a",
"relationship",
"graph",
"."
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L571-L604 |
LLNL/certipy | certipy/certipy.py | Certipy.create_ca | def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048,
alt_names=None, years=5, serial=0, pathlen=0,
overwrite=False):
"""
Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new CA
"""
cakey = self.create_key_pair(cert_type, bits)
req = self.create_request(cakey, CN=name)
signing_key = cakey
signing_cert = req
parent_ca = ''
if ca_name:
ca_bundle = self.store.get_files(ca_name)
signing_key = ca_bundle.key.load()
signing_cert = ca_bundle.cert.load()
parent_ca = ca_bundle.cert.file_path
basicConstraints = "CA:true"
# If pathlen is exactly 0, this CA cannot sign intermediaries.
# A negative value leaves this out entirely and allows arbitrary
# numbers of intermediates.
if pathlen >=0:
basicConstraints += ', pathlen:' + str(pathlen)
extensions = [
crypto.X509Extension(
b"basicConstraints", True, basicConstraints.encode()),
crypto.X509Extension(
b"keyUsage", True, b"keyCertSign, cRLSign"),
crypto.X509Extension(
b"extendedKeyUsage", True, b"serverAuth, clientAuth"),
lambda cert: crypto.X509Extension(
b"subjectKeyIdentifier", False, b"hash", subject=cert),
lambda cert: crypto.X509Extension(
b"authorityKeyIdentifier", False, b"keyid:always",
issuer=cert),
]
if alt_names:
extensions.append(
crypto.X509Extension(b"subjectAltName",
False, ",".join(alt_names).encode())
)
# TODO: start time before today for clock skew?
cacert = self.sign(
req, (signing_cert, signing_key), (0, 60*60*24*365*years),
extensions=extensions)
x509s = {'key': cakey, 'cert': cacert, 'ca': cacert}
self.store.add_files(name, x509s, overwrite=overwrite,
parent_ca=parent_ca, is_ca=True)
if ca_name:
self.store.add_sign_link(ca_name, name)
return self.store.get_record(name) | python | def create_ca(self, name, ca_name='', cert_type=crypto.TYPE_RSA, bits=2048,
alt_names=None, years=5, serial=0, pathlen=0,
overwrite=False):
"""
Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new CA
"""
cakey = self.create_key_pair(cert_type, bits)
req = self.create_request(cakey, CN=name)
signing_key = cakey
signing_cert = req
parent_ca = ''
if ca_name:
ca_bundle = self.store.get_files(ca_name)
signing_key = ca_bundle.key.load()
signing_cert = ca_bundle.cert.load()
parent_ca = ca_bundle.cert.file_path
basicConstraints = "CA:true"
# If pathlen is exactly 0, this CA cannot sign intermediaries.
# A negative value leaves this out entirely and allows arbitrary
# numbers of intermediates.
if pathlen >=0:
basicConstraints += ', pathlen:' + str(pathlen)
extensions = [
crypto.X509Extension(
b"basicConstraints", True, basicConstraints.encode()),
crypto.X509Extension(
b"keyUsage", True, b"keyCertSign, cRLSign"),
crypto.X509Extension(
b"extendedKeyUsage", True, b"serverAuth, clientAuth"),
lambda cert: crypto.X509Extension(
b"subjectKeyIdentifier", False, b"hash", subject=cert),
lambda cert: crypto.X509Extension(
b"authorityKeyIdentifier", False, b"keyid:always",
issuer=cert),
]
if alt_names:
extensions.append(
crypto.X509Extension(b"subjectAltName",
False, ",".join(alt_names).encode())
)
# TODO: start time before today for clock skew?
cacert = self.sign(
req, (signing_cert, signing_key), (0, 60*60*24*365*years),
extensions=extensions)
x509s = {'key': cakey, 'cert': cacert, 'ca': cacert}
self.store.add_files(name, x509s, overwrite=overwrite,
parent_ca=parent_ca, is_ca=True)
if ca_name:
self.store.add_sign_link(ca_name, name)
return self.store.get_record(name) | [
"def",
"create_ca",
"(",
"self",
",",
"name",
",",
"ca_name",
"=",
"''",
",",
"cert_type",
"=",
"crypto",
".",
"TYPE_RSA",
",",
"bits",
"=",
"2048",
",",
"alt_names",
"=",
"None",
",",
"years",
"=",
"5",
",",
"serial",
"=",
"0",
",",
"pathlen",
"="... | Create a certificate authority
Arguments: name - The name of the CA
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new CA | [
"Create",
"a",
"certificate",
"authority"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L606-L669 |
LLNL/certipy | certipy/certipy.py | Certipy.create_signed_pair | def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA,
bits=2048, years=5, alt_names=None, serial=0,
overwrite=False):
"""
Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new signed pair
"""
key = self.create_key_pair(cert_type, bits)
req = self.create_request(key, CN=name)
extensions = [
crypto.X509Extension(
b"extendedKeyUsage", True, b"serverAuth, clientAuth"),
]
if alt_names:
extensions.append(
crypto.X509Extension(b"subjectAltName",
False, ",".join(alt_names).encode())
)
ca_bundle = self.store.get_files(ca_name)
cacert = ca_bundle.cert.load()
cakey = ca_bundle.key.load()
cert = self.sign(req, (cacert, cakey), (0, 60*60*24*365*years),
extensions=extensions)
x509s = {'key': key, 'cert': cert, 'ca': None}
self.store.add_files(name, x509s, parent_ca=ca_name,
overwrite=overwrite)
# Relate these certs as being parent and child
self.store.add_sign_link(ca_name, name)
return self.store.get_record(name) | python | def create_signed_pair(self, name, ca_name, cert_type=crypto.TYPE_RSA,
bits=2048, years=5, alt_names=None, serial=0,
overwrite=False):
"""
Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new signed pair
"""
key = self.create_key_pair(cert_type, bits)
req = self.create_request(key, CN=name)
extensions = [
crypto.X509Extension(
b"extendedKeyUsage", True, b"serverAuth, clientAuth"),
]
if alt_names:
extensions.append(
crypto.X509Extension(b"subjectAltName",
False, ",".join(alt_names).encode())
)
ca_bundle = self.store.get_files(ca_name)
cacert = ca_bundle.cert.load()
cakey = ca_bundle.key.load()
cert = self.sign(req, (cacert, cakey), (0, 60*60*24*365*years),
extensions=extensions)
x509s = {'key': key, 'cert': cert, 'ca': None}
self.store.add_files(name, x509s, parent_ca=ca_name,
overwrite=overwrite)
# Relate these certs as being parent and child
self.store.add_sign_link(ca_name, name)
return self.store.get_record(name) | [
"def",
"create_signed_pair",
"(",
"self",
",",
"name",
",",
"ca_name",
",",
"cert_type",
"=",
"crypto",
".",
"TYPE_RSA",
",",
"bits",
"=",
"2048",
",",
"years",
"=",
"5",
",",
"alt_names",
"=",
"None",
",",
"serial",
"=",
"0",
",",
"overwrite",
"=",
... | Create a key-cert pair
Arguments: name - The name of the key-cert pair
ca_name - The name of the CA to sign this cert
cert_type - The type of the cert. TYPE_RSA or TYPE_DSA
bits - The number of bits to use
alt_names - An array of alternative names in the format:
IP:address, DNS:address
Returns: KeyCertPair for the new signed pair | [
"Create",
"a",
"key",
"-",
"cert",
"pair"
] | train | https://github.com/LLNL/certipy/blob/8705a8ba32655e12021d2893cf1c3c98c697edd7/certipy/certipy.py#L671-L712 |
marten-de-vries/Flask-WebSub | flask_websub/hub/tasks.py | send_change_notification | def send_change_notification(hub, topic_url, updated_content=None):
"""7. Content Distribution"""
if updated_content:
body = base64.b64decode(updated_content['content'])
else:
body, updated_content = get_new_content(hub.config, topic_url)
b64_body = updated_content['content']
headers = updated_content['headers']
link_header = headers.get('Link', '')
if 'rel="hub"' not in link_header or 'rel="self"' not in link_header:
raise NotificationError(INVALID_LINK)
for callback_url, secret in hub.storage.get_callbacks(topic_url):
schedule_request(hub, topic_url, callback_url, secret, body, b64_body,
headers) | python | def send_change_notification(hub, topic_url, updated_content=None):
"""7. Content Distribution"""
if updated_content:
body = base64.b64decode(updated_content['content'])
else:
body, updated_content = get_new_content(hub.config, topic_url)
b64_body = updated_content['content']
headers = updated_content['headers']
link_header = headers.get('Link', '')
if 'rel="hub"' not in link_header or 'rel="self"' not in link_header:
raise NotificationError(INVALID_LINK)
for callback_url, secret in hub.storage.get_callbacks(topic_url):
schedule_request(hub, topic_url, callback_url, secret, body, b64_body,
headers) | [
"def",
"send_change_notification",
"(",
"hub",
",",
"topic_url",
",",
"updated_content",
"=",
"None",
")",
":",
"if",
"updated_content",
":",
"body",
"=",
"base64",
".",
"b64decode",
"(",
"updated_content",
"[",
"'content'",
"]",
")",
"else",
":",
"body",
",... | 7. Content Distribution | [
"7",
".",
"Content",
"Distribution"
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/tasks.py#L18-L34 |
marten-de-vries/Flask-WebSub | flask_websub/hub/tasks.py | subscribe | def subscribe(hub, callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data):
"""5.2 Subscription Validation"""
for validate in hub.validators:
error = validate(callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data)
if error:
send_denied(hub, callback_url, topic_url, error)
return
if intent_verified(hub, callback_url, 'subscribe', topic_url,
lease_seconds):
hub.storage[topic_url, callback_url] = {
'lease_seconds': lease_seconds,
'secret': secret,
} | python | def subscribe(hub, callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data):
"""5.2 Subscription Validation"""
for validate in hub.validators:
error = validate(callback_url, topic_url, lease_seconds, secret,
endpoint_hook_data)
if error:
send_denied(hub, callback_url, topic_url, error)
return
if intent_verified(hub, callback_url, 'subscribe', topic_url,
lease_seconds):
hub.storage[topic_url, callback_url] = {
'lease_seconds': lease_seconds,
'secret': secret,
} | [
"def",
"subscribe",
"(",
"hub",
",",
"callback_url",
",",
"topic_url",
",",
"lease_seconds",
",",
"secret",
",",
"endpoint_hook_data",
")",
":",
"for",
"validate",
"in",
"hub",
".",
"validators",
":",
"error",
"=",
"validate",
"(",
"callback_url",
",",
"topi... | 5.2 Subscription Validation | [
"5",
".",
"2",
"Subscription",
"Validation"
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/tasks.py#L87-L103 |
marten-de-vries/Flask-WebSub | flask_websub/hub/tasks.py | intent_verified | def intent_verified(hub, callback_url, mode, topic_url, lease_seconds):
""" 5.3 Hub Verifies Intent of the Subscriber"""
challenge = uuid4()
params = {
'hub.mode': mode,
'hub.topic': topic_url,
'hub.challenge': challenge,
'hub.lease_seconds': lease_seconds,
}
try:
response = request_url(hub.config, 'GET', callback_url, params=params)
assert response.status_code == 200 and response.text == challenge
except requests.exceptions.RequestException as e:
warn("Cannot verify subscriber intent", e)
except AssertionError as e:
warn(INTENT_UNVERIFIED % (response.status_code, response.content), e)
else:
return True
return False | python | def intent_verified(hub, callback_url, mode, topic_url, lease_seconds):
""" 5.3 Hub Verifies Intent of the Subscriber"""
challenge = uuid4()
params = {
'hub.mode': mode,
'hub.topic': topic_url,
'hub.challenge': challenge,
'hub.lease_seconds': lease_seconds,
}
try:
response = request_url(hub.config, 'GET', callback_url, params=params)
assert response.status_code == 200 and response.text == challenge
except requests.exceptions.RequestException as e:
warn("Cannot verify subscriber intent", e)
except AssertionError as e:
warn(INTENT_UNVERIFIED % (response.status_code, response.content), e)
else:
return True
return False | [
"def",
"intent_verified",
"(",
"hub",
",",
"callback_url",
",",
"mode",
",",
"topic_url",
",",
"lease_seconds",
")",
":",
"challenge",
"=",
"uuid4",
"(",
")",
"params",
"=",
"{",
"'hub.mode'",
":",
"mode",
",",
"'hub.topic'",
":",
"topic_url",
",",
"'hub.c... | 5.3 Hub Verifies Intent of the Subscriber | [
"5",
".",
"3",
"Hub",
"Verifies",
"Intent",
"of",
"the",
"Subscriber"
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/tasks.py#L117-L136 |
marten-de-vries/Flask-WebSub | flask_websub/hub/__init__.py | Hub.init_celery | def init_celery(self, celery):
"""Registers the celery tasks on the hub object."""
count = next(self.counter)
def task_with_hub(f, **opts):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(self, *args, **kwargs)
# Make sure newer instances don't overwride older ones.
wrapper.__name__ = wrapper.__name__ + '_' + str(count)
return celery.task(**opts)(wrapper)
# tasks for internal use:
self.subscribe = task_with_hub(subscribe)
self.unsubscribe = task_with_hub(unsubscribe)
max_attempts = self.config.get('MAX_ATTEMPTS', 10)
make_req = task_with_hub(make_request_retrying, bind=True,
max_retries=max_attempts)
self.make_request_retrying = make_req
# user facing tasks
# wrapped by send_change_notification:
self.send_change = task_with_hub(send_change_notification)
# wrapped by cleanup_expired_subscriptions
@task_with_hub
def cleanup(hub):
self.storage.cleanup_expired_subscriptions()
self.cleanup = cleanup
# wrapped by schedule_cleanup
def schedule(every_x_seconds=A_DAY):
celery.add_periodic_task(every_x_seconds,
self.cleanup_expired_subscriptions.s())
self.schedule = schedule | python | def init_celery(self, celery):
"""Registers the celery tasks on the hub object."""
count = next(self.counter)
def task_with_hub(f, **opts):
@functools.wraps(f)
def wrapper(*args, **kwargs):
return f(self, *args, **kwargs)
# Make sure newer instances don't overwride older ones.
wrapper.__name__ = wrapper.__name__ + '_' + str(count)
return celery.task(**opts)(wrapper)
# tasks for internal use:
self.subscribe = task_with_hub(subscribe)
self.unsubscribe = task_with_hub(unsubscribe)
max_attempts = self.config.get('MAX_ATTEMPTS', 10)
make_req = task_with_hub(make_request_retrying, bind=True,
max_retries=max_attempts)
self.make_request_retrying = make_req
# user facing tasks
# wrapped by send_change_notification:
self.send_change = task_with_hub(send_change_notification)
# wrapped by cleanup_expired_subscriptions
@task_with_hub
def cleanup(hub):
self.storage.cleanup_expired_subscriptions()
self.cleanup = cleanup
# wrapped by schedule_cleanup
def schedule(every_x_seconds=A_DAY):
celery.add_periodic_task(every_x_seconds,
self.cleanup_expired_subscriptions.s())
self.schedule = schedule | [
"def",
"init_celery",
"(",
"self",
",",
"celery",
")",
":",
"count",
"=",
"next",
"(",
"self",
".",
"counter",
")",
"def",
"task_with_hub",
"(",
"f",
",",
"*",
"*",
"opts",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
... | Registers the celery tasks on the hub object. | [
"Registers",
"the",
"celery",
"tasks",
"on",
"the",
"hub",
"object",
"."
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/hub/__init__.py#L66-L103 |
marten-de-vries/Flask-WebSub | flask_websub/publisher.py | init_publisher | def init_publisher(app):
"""Calling this with your flask app as argument is required for the
publisher decorator to work.
"""
@app.context_processor
def inject_links():
return {
'websub_self_url': stack.top.websub_self_url,
'websub_hub_url': stack.top.websub_hub_url,
'websub_self_link': stack.top.websub_self_link,
'websub_hub_link': stack.top.websub_hub_link,
} | python | def init_publisher(app):
"""Calling this with your flask app as argument is required for the
publisher decorator to work.
"""
@app.context_processor
def inject_links():
return {
'websub_self_url': stack.top.websub_self_url,
'websub_hub_url': stack.top.websub_hub_url,
'websub_self_link': stack.top.websub_self_link,
'websub_hub_link': stack.top.websub_hub_link,
} | [
"def",
"init_publisher",
"(",
"app",
")",
":",
"@",
"app",
".",
"context_processor",
"def",
"inject_links",
"(",
")",
":",
"return",
"{",
"'websub_self_url'",
":",
"stack",
".",
"top",
".",
"websub_self_url",
",",
"'websub_hub_url'",
":",
"stack",
".",
"top"... | Calling this with your flask app as argument is required for the
publisher decorator to work. | [
"Calling",
"this",
"with",
"your",
"flask",
"app",
"as",
"argument",
"is",
"required",
"for",
"the",
"publisher",
"decorator",
"to",
"work",
"."
] | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/publisher.py#L15-L27 |
marten-de-vries/Flask-WebSub | flask_websub/publisher.py | publisher | def publisher(self_url=None, hub_url=None):
"""This decorator makes it easier to implement a websub publisher. You use
it on an endpoint, and Link headers will automatically be added. To also
include these links in your template html/atom/rss (and you should!) you
can use the following to get the raw links:
- {{ websub_self_url }}
- {{ websub_hub_url }}
And the following to get them wrapped in <link tags>:
- {{ websub_self_link }}
- {{ websub_hub_link }}
If hub_url is not given, the hub needs to be a flask_websub one and the
hub and publisher need to share their application for the url to be
auto-discovered. If that is not the case, you need to set
config['HUB_URL'].
If self_url is not given, the url of the current request will be used. Note
that this includes url query arguments. If this is not what you want,
override it.
"""
def decorator(topic_view):
@functools.wraps(topic_view)
def wrapper(*args, **kwargs):
nonlocal hub_url, self_url
if not self_url:
self_url = request.url
if not hub_url:
try:
hub_url = url_for('websub_hub.endpoint', _external=True)
except BuildError:
hub_url = current_app.config['HUB_URL']
stack.top.websub_self_url = self_url
stack.top.websub_hub_url = hub_url
stack.top.websub_self_link = Markup(SELF_LINK % self_url)
stack.top.websub_hub_link = Markup(HUB_LINK % hub_url)
resp = make_response(topic_view(*args, **kwargs))
resp.headers.add('Link', HEADER_VALUE % (self_url, hub_url))
return resp
return wrapper
return decorator | python | def publisher(self_url=None, hub_url=None):
"""This decorator makes it easier to implement a websub publisher. You use
it on an endpoint, and Link headers will automatically be added. To also
include these links in your template html/atom/rss (and you should!) you
can use the following to get the raw links:
- {{ websub_self_url }}
- {{ websub_hub_url }}
And the following to get them wrapped in <link tags>:
- {{ websub_self_link }}
- {{ websub_hub_link }}
If hub_url is not given, the hub needs to be a flask_websub one and the
hub and publisher need to share their application for the url to be
auto-discovered. If that is not the case, you need to set
config['HUB_URL'].
If self_url is not given, the url of the current request will be used. Note
that this includes url query arguments. If this is not what you want,
override it.
"""
def decorator(topic_view):
@functools.wraps(topic_view)
def wrapper(*args, **kwargs):
nonlocal hub_url, self_url
if not self_url:
self_url = request.url
if not hub_url:
try:
hub_url = url_for('websub_hub.endpoint', _external=True)
except BuildError:
hub_url = current_app.config['HUB_URL']
stack.top.websub_self_url = self_url
stack.top.websub_hub_url = hub_url
stack.top.websub_self_link = Markup(SELF_LINK % self_url)
stack.top.websub_hub_link = Markup(HUB_LINK % hub_url)
resp = make_response(topic_view(*args, **kwargs))
resp.headers.add('Link', HEADER_VALUE % (self_url, hub_url))
return resp
return wrapper
return decorator | [
"def",
"publisher",
"(",
"self_url",
"=",
"None",
",",
"hub_url",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"topic_view",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"topic_view",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwar... | This decorator makes it easier to implement a websub publisher. You use
it on an endpoint, and Link headers will automatically be added. To also
include these links in your template html/atom/rss (and you should!) you
can use the following to get the raw links:
- {{ websub_self_url }}
- {{ websub_hub_url }}
And the following to get them wrapped in <link tags>:
- {{ websub_self_link }}
- {{ websub_hub_link }}
If hub_url is not given, the hub needs to be a flask_websub one and the
hub and publisher need to share their application for the url to be
auto-discovered. If that is not the case, you need to set
config['HUB_URL'].
If self_url is not given, the url of the current request will be used. Note
that this includes url query arguments. If this is not what you want,
override it. | [
"This",
"decorator",
"makes",
"it",
"easier",
"to",
"implement",
"a",
"websub",
"publisher",
".",
"You",
"use",
"it",
"on",
"an",
"endpoint",
"and",
"Link",
"headers",
"will",
"automatically",
"be",
"added",
".",
"To",
"also",
"include",
"these",
"links",
... | train | https://github.com/marten-de-vries/Flask-WebSub/blob/422d5b597245554c47e881483f99cae7c57a81ba/flask_websub/publisher.py#L30-L76 |
openspending/babbage | babbage/query/__init__.py | count_results | def count_results(cube, q):
""" Get the count of records matching the query. """
q = select(columns=[func.count(True)], from_obj=q.alias())
return cube.engine.execute(q).scalar() | python | def count_results(cube, q):
""" Get the count of records matching the query. """
q = select(columns=[func.count(True)], from_obj=q.alias())
return cube.engine.execute(q).scalar() | [
"def",
"count_results",
"(",
"cube",
",",
"q",
")",
":",
"q",
"=",
"select",
"(",
"columns",
"=",
"[",
"func",
".",
"count",
"(",
"True",
")",
"]",
",",
"from_obj",
"=",
"q",
".",
"alias",
"(",
")",
")",
"return",
"cube",
".",
"engine",
".",
"e... | Get the count of records matching the query. | [
"Get",
"the",
"count",
"of",
"records",
"matching",
"the",
"query",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/__init__.py#L12-L15 |
openspending/babbage | babbage/query/__init__.py | generate_results | def generate_results(cube, q):
""" Generate the resulting records for this query, applying pagination.
Values will be returned by their reference. """
if q._limit is not None and q._limit < 1:
return
rp = cube.engine.execute(q)
while True:
row = rp.fetchone()
if row is None:
return
yield dict(row.items()) | python | def generate_results(cube, q):
""" Generate the resulting records for this query, applying pagination.
Values will be returned by their reference. """
if q._limit is not None and q._limit < 1:
return
rp = cube.engine.execute(q)
while True:
row = rp.fetchone()
if row is None:
return
yield dict(row.items()) | [
"def",
"generate_results",
"(",
"cube",
",",
"q",
")",
":",
"if",
"q",
".",
"_limit",
"is",
"not",
"None",
"and",
"q",
".",
"_limit",
"<",
"1",
":",
"return",
"rp",
"=",
"cube",
".",
"engine",
".",
"execute",
"(",
"q",
")",
"while",
"True",
":",
... | Generate the resulting records for this query, applying pagination.
Values will be returned by their reference. | [
"Generate",
"the",
"resulting",
"records",
"for",
"this",
"query",
"applying",
"pagination",
".",
"Values",
"will",
"be",
"returned",
"by",
"their",
"reference",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/__init__.py#L18-L28 |
openspending/babbage | babbage/query/ordering.py | Ordering.apply | def apply(self, q, bindings, ordering, distinct=None):
""" Sort on a set of field specifications of the type (ref, direction)
in order of the submitted list. """
info = []
for (ref, direction) in self.parse(ordering):
info.append((ref, direction))
table, column = self.cube.model[ref].bind(self.cube)
if distinct is not None and distinct != ref:
column = asc(ref) if direction == 'asc' else desc(ref)
else:
column = column.label(column.name)
column = column.asc() if direction == 'asc' else column.desc()
bindings.append(Binding(table, ref))
if self.cube.is_postgresql:
column = column.nullslast()
q = q.order_by(column)
if not len(self.results):
for column in q.columns:
column = column.asc()
if self.cube.is_postgresql:
column = column.nullslast()
q = q.order_by(column)
return info, q, bindings | python | def apply(self, q, bindings, ordering, distinct=None):
""" Sort on a set of field specifications of the type (ref, direction)
in order of the submitted list. """
info = []
for (ref, direction) in self.parse(ordering):
info.append((ref, direction))
table, column = self.cube.model[ref].bind(self.cube)
if distinct is not None and distinct != ref:
column = asc(ref) if direction == 'asc' else desc(ref)
else:
column = column.label(column.name)
column = column.asc() if direction == 'asc' else column.desc()
bindings.append(Binding(table, ref))
if self.cube.is_postgresql:
column = column.nullslast()
q = q.order_by(column)
if not len(self.results):
for column in q.columns:
column = column.asc()
if self.cube.is_postgresql:
column = column.nullslast()
q = q.order_by(column)
return info, q, bindings | [
"def",
"apply",
"(",
"self",
",",
"q",
",",
"bindings",
",",
"ordering",
",",
"distinct",
"=",
"None",
")",
":",
"info",
"=",
"[",
"]",
"for",
"(",
"ref",
",",
"direction",
")",
"in",
"self",
".",
"parse",
"(",
"ordering",
")",
":",
"info",
".",
... | Sort on a set of field specifications of the type (ref, direction)
in order of the submitted list. | [
"Sort",
"on",
"a",
"set",
"of",
"field",
"specifications",
"of",
"the",
"type",
"(",
"ref",
"direction",
")",
"in",
"order",
"of",
"the",
"submitted",
"list",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/ordering.py#L24-L47 |
bodylabs/lace | lace/mesh.py | Mesh.copy | def copy(self, only=None):
'''
Returns a deep copy with all of the numpy arrays copied
If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied
'''
if only is None:
return Mesh(self)
else:
import copy
m = Mesh()
for a in only:
setattr(m, a, copy.deepcopy(getattr(self, a)))
return m | python | def copy(self, only=None):
'''
Returns a deep copy with all of the numpy arrays copied
If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied
'''
if only is None:
return Mesh(self)
else:
import copy
m = Mesh()
for a in only:
setattr(m, a, copy.deepcopy(getattr(self, a)))
return m | [
"def",
"copy",
"(",
"self",
",",
"only",
"=",
"None",
")",
":",
"if",
"only",
"is",
"None",
":",
"return",
"Mesh",
"(",
"self",
")",
"else",
":",
"import",
"copy",
"m",
"=",
"Mesh",
"(",
")",
"for",
"a",
"in",
"only",
":",
"setattr",
"(",
"m",
... | Returns a deep copy with all of the numpy arrays copied
If only is a list of strings, i.e. ['f', 'v'], then only those properties will be copied | [
"Returns",
"a",
"deep",
"copy",
"with",
"all",
"of",
"the",
"numpy",
"arrays",
"copied",
"If",
"only",
"is",
"a",
"list",
"of",
"strings",
"i",
".",
"e",
".",
"[",
"f",
"v",
"]",
"then",
"only",
"those",
"properties",
"will",
"be",
"copied"
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/mesh.py#L128-L140 |
bodylabs/lace | lace/mesh.py | Mesh.concatenate | def concatenate(cls, *args):
"""Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces.
"""
nargs = len(args)
if nargs == 1:
return args[0]
vs = [a.v for a in args if a.v is not None]
vcs = [a.vc for a in args if a.vc is not None]
fs = [a.f for a in args if a.f is not None]
if vs and len(vs) != nargs:
raise ValueError('Expected `v` for all args or none.')
if vcs and len(vcs) != nargs:
raise ValueError('Expected `vc` for all args or none.')
if fs and len(fs) != nargs:
raise ValueError('Expected `f` for all args or none.')
# Offset face indices by the cumulative vertex count.
face_offsets = np.cumsum([v.shape[0] for v in vs[:-1]])
for offset, f in zip(face_offsets, fs[1:]): # https://bitbucket.org/logilab/pylint/issues/603/operator-generates-false-positive-unused pylint: disable=unused-variable
f += offset
return Mesh(
v=np.vstack(vs) if vs else None,
vc=np.vstack(vcs) if vcs else None,
f=np.vstack(fs) if fs else None,
) | python | def concatenate(cls, *args):
"""Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces.
"""
nargs = len(args)
if nargs == 1:
return args[0]
vs = [a.v for a in args if a.v is not None]
vcs = [a.vc for a in args if a.vc is not None]
fs = [a.f for a in args if a.f is not None]
if vs and len(vs) != nargs:
raise ValueError('Expected `v` for all args or none.')
if vcs and len(vcs) != nargs:
raise ValueError('Expected `vc` for all args or none.')
if fs and len(fs) != nargs:
raise ValueError('Expected `f` for all args or none.')
# Offset face indices by the cumulative vertex count.
face_offsets = np.cumsum([v.shape[0] for v in vs[:-1]])
for offset, f in zip(face_offsets, fs[1:]): # https://bitbucket.org/logilab/pylint/issues/603/operator-generates-false-positive-unused pylint: disable=unused-variable
f += offset
return Mesh(
v=np.vstack(vs) if vs else None,
vc=np.vstack(vcs) if vcs else None,
f=np.vstack(fs) if fs else None,
) | [
"def",
"concatenate",
"(",
"cls",
",",
"*",
"args",
")",
":",
"nargs",
"=",
"len",
"(",
"args",
")",
"if",
"nargs",
"==",
"1",
":",
"return",
"args",
"[",
"0",
"]",
"vs",
"=",
"[",
"a",
".",
"v",
"for",
"a",
"in",
"args",
"if",
"a",
".",
"v... | Concatenates an arbitrary number of meshes.
Currently supports vertices, vertex colors, and faces. | [
"Concatenates",
"an",
"arbitrary",
"number",
"of",
"meshes",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/mesh.py#L215-L244 |
nerdynick/PySQLPool | src/PySQLPool/__init__.py | getNewConnection | def getNewConnection(*args, **kargs):
"""
Quickly Create a new PySQLConnection class
@param host: Hostname for your database
@param username: Username to use to connect to database
@param password: Password to use to connect to database
@param schema: Schema to use
@param port: Port to connect on
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a always on for this connection
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd support
"""
kargs = dict(kargs)
if len(args) > 0:
if len(args) >= 1:
kargs['host'] = args[0]
if len(args) >= 2:
kargs['user'] = args[1]
if len(args) >= 3:
kargs['passwd'] = args[2]
if len(args) >= 4:
kargs['db'] = args[3]
if len(args) >= 5:
kargs['port'] = args[4]
if len(args) >= 6:
kargs['commitOnEnd'] = args[5]
return connection.Connection(*args, **kargs) | python | def getNewConnection(*args, **kargs):
"""
Quickly Create a new PySQLConnection class
@param host: Hostname for your database
@param username: Username to use to connect to database
@param password: Password to use to connect to database
@param schema: Schema to use
@param port: Port to connect on
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a always on for this connection
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd support
"""
kargs = dict(kargs)
if len(args) > 0:
if len(args) >= 1:
kargs['host'] = args[0]
if len(args) >= 2:
kargs['user'] = args[1]
if len(args) >= 3:
kargs['passwd'] = args[2]
if len(args) >= 4:
kargs['db'] = args[3]
if len(args) >= 5:
kargs['port'] = args[4]
if len(args) >= 6:
kargs['commitOnEnd'] = args[5]
return connection.Connection(*args, **kargs) | [
"def",
"getNewConnection",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"kargs",
"=",
"dict",
"(",
"kargs",
")",
"if",
"len",
"(",
"args",
")",
">",
"0",
":",
"if",
"len",
"(",
"args",
")",
">=",
"1",
":",
"kargs",
"[",
"'host'",
"]",
... | Quickly Create a new PySQLConnection class
@param host: Hostname for your database
@param username: Username to use to connect to database
@param password: Password to use to connect to database
@param schema: Schema to use
@param port: Port to connect on
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a always on for this connection
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd support | [
"Quickly",
"Create",
"a",
"new",
"PySQLConnection",
"class"
] | train | https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/__init__.py#L15-L43 |
nerdynick/PySQLPool | src/PySQLPool/__init__.py | getNewQuery | def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs):
"""
Create a new PySQLQuery Class
@param PySQLConnectionObj: Connection Object representing your connection string
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd support
"""
if connection is None:
return query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd)
else:
#Updated 7/24/08 to include commitOnEnd here
#-Chandler Prall
return query.PySQLQuery(connection, commitOnEnd = commitOnEnd) | python | def getNewQuery(connection = None, commitOnEnd=False, *args, **kargs):
"""
Create a new PySQLQuery Class
@param PySQLConnectionObj: Connection Object representing your connection string
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd support
"""
if connection is None:
return query.PySQLQuery(getNewConnection(*args, **kargs), commitOnEnd = commitOnEnd)
else:
#Updated 7/24/08 to include commitOnEnd here
#-Chandler Prall
return query.PySQLQuery(connection, commitOnEnd = commitOnEnd) | [
"def",
"getNewQuery",
"(",
"connection",
"=",
"None",
",",
"commitOnEnd",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"connection",
"is",
"None",
":",
"return",
"query",
".",
"PySQLQuery",
"(",
"getNewConnection",
"(",
"*",
... | Create a new PySQLQuery Class
@param PySQLConnectionObj: Connection Object representing your connection string
@param commitOnEnd: Default False, When query is complete do you wish to auto commit. This is a one time auto commit
@author: Nick Verbeck
@since: 5/12/2008
@updated: 7/19/2008 - Added commitOnEnd support | [
"Create",
"a",
"new",
"PySQLQuery",
"Class"
] | train | https://github.com/nerdynick/PySQLPool/blob/a561275fea091e2667b69ce376c507f541b56e7d/src/PySQLPool/__init__.py#L46-L61 |
mandeep/Travis-Encrypt | travis/cli.py | cli | def cli(username, repository, path, password, deploy, env, clipboard, env_file):
"""Encrypt passwords and environment variables for use with Travis CI.
Travis Encrypt requires as arguments the user's GitHub username and repository name.
Once the arguments are passed, a password prompt will ask for the password that needs
to be encrypted. The given password will then be encrypted via the PKCS1v15 padding
scheme and printed to standard output. If the path to a .travis.yml file
is given as an argument, the encrypted password is added to the .travis.yml file.
"""
key = retrieve_public_key('{}/{}' .format(username, repository))
if env_file:
if path:
config = load_travis_configuration(path)
for env_var, value in dotenv_values(env_file).items():
encrypted_env = encrypt_key(key, value.encode())
config.setdefault('env', {}).setdefault('global', {})[env_var] = {'secure': encrypted_env}
dump_travis_configuration(config, path)
print('Encrypted variables from {} added to {}'.format(env_file, path))
else:
print('\nPlease add the following to your .travis.yml:')
for env_var, value in dotenv_values(env_file).items():
encrypted_env = encrypt_key(key, value.encode())
print("{}:\n secure: {}".format(env_var, encrypted_env))
else:
encrypted_password = encrypt_key(key, password.encode())
if path:
config = load_travis_configuration(path)
if config is None:
config = OrderedDict()
if deploy:
config.setdefault('deploy', {}).setdefault('password', {})['secure'] = encrypted_password
elif env:
try:
config.setdefault('env', {}).setdefault('global', {})['secure'] = encrypted_password
except TypeError:
for item in config['env']['global']:
if isinstance(item, dict) and 'secure' in item:
item['secure'] = encrypted_password
else:
config.setdefault('password', {})['secure'] = encrypted_password
dump_travis_configuration(config, path)
print('Encrypted password added to {}' .format(path))
elif clipboard:
pyperclip.copy(encrypted_password)
print('\nThe encrypted password has been copied to your clipboard.')
else:
print('\nPlease add the following to your .travis.yml:\nsecure: {}' .format(encrypted_password)) | python | def cli(username, repository, path, password, deploy, env, clipboard, env_file):
"""Encrypt passwords and environment variables for use with Travis CI.
Travis Encrypt requires as arguments the user's GitHub username and repository name.
Once the arguments are passed, a password prompt will ask for the password that needs
to be encrypted. The given password will then be encrypted via the PKCS1v15 padding
scheme and printed to standard output. If the path to a .travis.yml file
is given as an argument, the encrypted password is added to the .travis.yml file.
"""
key = retrieve_public_key('{}/{}' .format(username, repository))
if env_file:
if path:
config = load_travis_configuration(path)
for env_var, value in dotenv_values(env_file).items():
encrypted_env = encrypt_key(key, value.encode())
config.setdefault('env', {}).setdefault('global', {})[env_var] = {'secure': encrypted_env}
dump_travis_configuration(config, path)
print('Encrypted variables from {} added to {}'.format(env_file, path))
else:
print('\nPlease add the following to your .travis.yml:')
for env_var, value in dotenv_values(env_file).items():
encrypted_env = encrypt_key(key, value.encode())
print("{}:\n secure: {}".format(env_var, encrypted_env))
else:
encrypted_password = encrypt_key(key, password.encode())
if path:
config = load_travis_configuration(path)
if config is None:
config = OrderedDict()
if deploy:
config.setdefault('deploy', {}).setdefault('password', {})['secure'] = encrypted_password
elif env:
try:
config.setdefault('env', {}).setdefault('global', {})['secure'] = encrypted_password
except TypeError:
for item in config['env']['global']:
if isinstance(item, dict) and 'secure' in item:
item['secure'] = encrypted_password
else:
config.setdefault('password', {})['secure'] = encrypted_password
dump_travis_configuration(config, path)
print('Encrypted password added to {}' .format(path))
elif clipboard:
pyperclip.copy(encrypted_password)
print('\nThe encrypted password has been copied to your clipboard.')
else:
print('\nPlease add the following to your .travis.yml:\nsecure: {}' .format(encrypted_password)) | [
"def",
"cli",
"(",
"username",
",",
"repository",
",",
"path",
",",
"password",
",",
"deploy",
",",
"env",
",",
"clipboard",
",",
"env_file",
")",
":",
"key",
"=",
"retrieve_public_key",
"(",
"'{}/{}'",
".",
"format",
"(",
"username",
",",
"repository",
... | Encrypt passwords and environment variables for use with Travis CI.
Travis Encrypt requires as arguments the user's GitHub username and repository name.
Once the arguments are passed, a password prompt will ask for the password that needs
to be encrypted. The given password will then be encrypted via the PKCS1v15 padding
scheme and printed to standard output. If the path to a .travis.yml file
is given as an argument, the encrypted password is added to the .travis.yml file. | [
"Encrypt",
"passwords",
"and",
"environment",
"variables",
"for",
"use",
"with",
"Travis",
"CI",
"."
] | train | https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/cli.py#L53-L107 |
openspending/babbage | babbage/query/fields.py | Fields.apply | def apply(self, q, bindings, fields, distinct=False):
""" Define a set of fields to return for a non-aggregated query. """
info = []
group_by = None
for field in self.parse(fields):
for concept in self.cube.model.match(field):
info.append(concept.ref)
table, column = concept.bind(self.cube)
bindings.append(Binding(table, concept.ref))
if distinct:
if group_by is None:
q = q.group_by(column)
group_by = column
else:
min_column = func.max(column)
min_column = min_column.label(column.name)
column = min_column
q = q.column(column)
if not len(self.results):
# If no fields are requested, return all available fields.
for concept in list(self.cube.model.attributes) + \
list(self.cube.model.measures):
info.append(concept.ref)
table, column = concept.bind(self.cube)
bindings.append(Binding(table, concept.ref))
q = q.column(column)
return info, q, bindings | python | def apply(self, q, bindings, fields, distinct=False):
""" Define a set of fields to return for a non-aggregated query. """
info = []
group_by = None
for field in self.parse(fields):
for concept in self.cube.model.match(field):
info.append(concept.ref)
table, column = concept.bind(self.cube)
bindings.append(Binding(table, concept.ref))
if distinct:
if group_by is None:
q = q.group_by(column)
group_by = column
else:
min_column = func.max(column)
min_column = min_column.label(column.name)
column = min_column
q = q.column(column)
if not len(self.results):
# If no fields are requested, return all available fields.
for concept in list(self.cube.model.attributes) + \
list(self.cube.model.measures):
info.append(concept.ref)
table, column = concept.bind(self.cube)
bindings.append(Binding(table, concept.ref))
q = q.column(column)
return info, q, bindings | [
"def",
"apply",
"(",
"self",
",",
"q",
",",
"bindings",
",",
"fields",
",",
"distinct",
"=",
"False",
")",
":",
"info",
"=",
"[",
"]",
"group_by",
"=",
"None",
"for",
"field",
"in",
"self",
".",
"parse",
"(",
"fields",
")",
":",
"for",
"concept",
... | Define a set of fields to return for a non-aggregated query. | [
"Define",
"a",
"set",
"of",
"fields",
"to",
"return",
"for",
"a",
"non",
"-",
"aggregated",
"query",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/fields.py#L21-L51 |
bodylabs/lace | lace/arcball.py | ArcBallT.drag | def drag(self, NewPt):
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
""" drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
"""
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular to the begin and end vectors
# Perp = Vector3fT()
Perp = Vector3fCross(self.m_StVec, self.m_EnVec)
NewRot = Quat4fT()
# //Compute the length of the perpendicular vector
if Vector3fLength(Perp) > Epsilon: # //if its non-zero
# //We're ok, so return the perpendicular vector as the transform after all
NewRot[X] = Perp[X]
NewRot[Y] = Perp[Y]
NewRot[Z] = Perp[Z]
# //In the quaternion values, w is cosine(theta / 2), where theta is rotation angle
NewRot[W] = Vector3fDot(self.m_StVec, self.m_EnVec)
else: # //if its zero
# //The begin and end vectors coincide, so return a quaternion of zero matrix (no rotation)
NewRot[X] = NewRot[Y] = NewRot[Z] = NewRot[W] = 0.0
return NewRot | python | def drag(self, NewPt):
# //Mouse drag, calculate rotation (Point2fT Quat4fT)
""" drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec
"""
X = 0
Y = 1
Z = 2
W = 3
self.m_EnVec = self._mapToSphere(NewPt)
# //Compute the vector perpendicular to the begin and end vectors
# Perp = Vector3fT()
Perp = Vector3fCross(self.m_StVec, self.m_EnVec)
NewRot = Quat4fT()
# //Compute the length of the perpendicular vector
if Vector3fLength(Perp) > Epsilon: # //if its non-zero
# //We're ok, so return the perpendicular vector as the transform after all
NewRot[X] = Perp[X]
NewRot[Y] = Perp[Y]
NewRot[Z] = Perp[Z]
# //In the quaternion values, w is cosine(theta / 2), where theta is rotation angle
NewRot[W] = Vector3fDot(self.m_StVec, self.m_EnVec)
else: # //if its zero
# //The begin and end vectors coincide, so return a quaternion of zero matrix (no rotation)
NewRot[X] = NewRot[Y] = NewRot[Z] = NewRot[W] = 0.0
return NewRot | [
"def",
"drag",
"(",
"self",
",",
"NewPt",
")",
":",
"# //Mouse drag, calculate rotation (Point2fT Quat4fT)",
"X",
"=",
"0",
"Y",
"=",
"1",
"Z",
"=",
"2",
"W",
"=",
"3",
"self",
".",
"m_EnVec",
"=",
"self",
".",
"_mapToSphere",
"(",
"NewPt",
")",
"# //Com... | drag (Point2fT mouse_coord) -> new_quaternion_rotation_vec | [
"drag",
"(",
"Point2fT",
"mouse_coord",
")",
"-",
">",
"new_quaternion_rotation_vec"
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/arcball.py#L70-L98 |
nschloe/meshplex | meshplex/mesh_line.py | MeshLine.create_cell_volumes | def create_cell_volumes(self):
"""Computes the volumes of the "cells" in the mesh.
"""
self.cell_volumes = numpy.array(
[
abs(
self.node_coords[cell["nodes"]][1]
- self.node_coords[cell["nodes"]][0]
)
for cell in self.cells
]
)
return | python | def create_cell_volumes(self):
"""Computes the volumes of the "cells" in the mesh.
"""
self.cell_volumes = numpy.array(
[
abs(
self.node_coords[cell["nodes"]][1]
- self.node_coords[cell["nodes"]][0]
)
for cell in self.cells
]
)
return | [
"def",
"create_cell_volumes",
"(",
"self",
")",
":",
"self",
".",
"cell_volumes",
"=",
"numpy",
".",
"array",
"(",
"[",
"abs",
"(",
"self",
".",
"node_coords",
"[",
"cell",
"[",
"\"nodes\"",
"]",
"]",
"[",
"1",
"]",
"-",
"self",
".",
"node_coords",
"... | Computes the volumes of the "cells" in the mesh. | [
"Computes",
"the",
"volumes",
"of",
"the",
"cells",
"in",
"the",
"mesh",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_line.py#L21-L33 |
nschloe/meshplex | meshplex/mesh_line.py | MeshLine.create_control_volumes | def create_control_volumes(self):
"""Compute the control volumes of all nodes in the mesh.
"""
self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float)
for k, cell in enumerate(self.cells):
node_ids = cell["nodes"]
self.control_volumes[node_ids] += 0.5 * self.cell_volumes[k]
# Sanity checks.
sum_cv = sum(self.control_volumes)
sum_cells = sum(self.cell_volumes)
alpha = sum_cv - sum_cells
assert abs(alpha) < 1.0e-6
return | python | def create_control_volumes(self):
"""Compute the control volumes of all nodes in the mesh.
"""
self.control_volumes = numpy.zeros(len(self.node_coords), dtype=float)
for k, cell in enumerate(self.cells):
node_ids = cell["nodes"]
self.control_volumes[node_ids] += 0.5 * self.cell_volumes[k]
# Sanity checks.
sum_cv = sum(self.control_volumes)
sum_cells = sum(self.cell_volumes)
alpha = sum_cv - sum_cells
assert abs(alpha) < 1.0e-6
return | [
"def",
"create_control_volumes",
"(",
"self",
")",
":",
"self",
".",
"control_volumes",
"=",
"numpy",
".",
"zeros",
"(",
"len",
"(",
"self",
".",
"node_coords",
")",
",",
"dtype",
"=",
"float",
")",
"for",
"k",
",",
"cell",
"in",
"enumerate",
"(",
"sel... | Compute the control volumes of all nodes in the mesh. | [
"Compute",
"the",
"control",
"volumes",
"of",
"all",
"nodes",
"in",
"the",
"mesh",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_line.py#L35-L48 |
bodylabs/lace | lace/shapes.py | create_rectangular_prism | def create_rectangular_prism(origin, size):
'''
Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array.
'''
from lace.topology import quads_to_tris
lower_base_plane = np.array([
# Lower base plane
origin,
origin + np.array([size[0], 0, 0]),
origin + np.array([size[0], 0, size[2]]),
origin + np.array([0, 0, size[2]]),
])
upper_base_plane = lower_base_plane + np.array([0, size[1], 0])
vertices = np.vstack([lower_base_plane, upper_base_plane])
faces = quads_to_tris(np.array([
[0, 1, 2, 3], # lower base (-y)
[7, 6, 5, 4], # upper base (+y)
[4, 5, 1, 0], # +z face
[5, 6, 2, 1], # +x face
[6, 7, 3, 2], # -z face
[3, 7, 4, 0], # -x face
]))
return Mesh(v=vertices, f=faces) | python | def create_rectangular_prism(origin, size):
'''
Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array.
'''
from lace.topology import quads_to_tris
lower_base_plane = np.array([
# Lower base plane
origin,
origin + np.array([size[0], 0, 0]),
origin + np.array([size[0], 0, size[2]]),
origin + np.array([0, 0, size[2]]),
])
upper_base_plane = lower_base_plane + np.array([0, size[1], 0])
vertices = np.vstack([lower_base_plane, upper_base_plane])
faces = quads_to_tris(np.array([
[0, 1, 2, 3], # lower base (-y)
[7, 6, 5, 4], # upper base (+y)
[4, 5, 1, 0], # +z face
[5, 6, 2, 1], # +x face
[6, 7, 3, 2], # -z face
[3, 7, 4, 0], # -x face
]))
return Mesh(v=vertices, f=faces) | [
"def",
"create_rectangular_prism",
"(",
"origin",
",",
"size",
")",
":",
"from",
"lace",
".",
"topology",
"import",
"quads_to_tris",
"lower_base_plane",
"=",
"np",
".",
"array",
"(",
"[",
"# Lower base plane",
"origin",
",",
"origin",
"+",
"np",
".",
"array",
... | Return a Mesh which is an axis-aligned rectangular prism. One vertex is
`origin`; the diametrically opposite vertex is `origin + size`.
size: 3x1 array. | [
"Return",
"a",
"Mesh",
"which",
"is",
"an",
"axis",
"-",
"aligned",
"rectangular",
"prism",
".",
"One",
"vertex",
"is",
"origin",
";",
"the",
"diametrically",
"opposite",
"vertex",
"is",
"origin",
"+",
"size",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/shapes.py#L6-L36 |
bodylabs/lace | lace/shapes.py | create_triangular_prism | def create_triangular_prism(p1, p2, p3, height):
'''
Return a Mesh which is a triangular prism whose base is the triangle
p1, p2, p3. If the vertices are oriented in a counterclockwise
direction, the prism extends from behind them.
'''
from blmath.geometry import Plane
base_plane = Plane.from_points(p1, p2, p3)
lower_base_to_upper_base = height * -base_plane.normal # pylint: disable=invalid-unary-operand-type
vertices = np.vstack(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base))
faces = np.array([
[0, 1, 2], # base
[0, 3, 4], [0, 4, 1], # side 0, 3, 4, 1
[1, 4, 5], [1, 5, 2], # side 1, 4, 5, 2
[2, 5, 3], [2, 3, 0], # side 2, 5, 3, 0
[5, 4, 3], # base
])
return Mesh(v=vertices, f=faces) | python | def create_triangular_prism(p1, p2, p3, height):
'''
Return a Mesh which is a triangular prism whose base is the triangle
p1, p2, p3. If the vertices are oriented in a counterclockwise
direction, the prism extends from behind them.
'''
from blmath.geometry import Plane
base_plane = Plane.from_points(p1, p2, p3)
lower_base_to_upper_base = height * -base_plane.normal # pylint: disable=invalid-unary-operand-type
vertices = np.vstack(([p1, p2, p3], [p1, p2, p3] + lower_base_to_upper_base))
faces = np.array([
[0, 1, 2], # base
[0, 3, 4], [0, 4, 1], # side 0, 3, 4, 1
[1, 4, 5], [1, 5, 2], # side 1, 4, 5, 2
[2, 5, 3], [2, 3, 0], # side 2, 5, 3, 0
[5, 4, 3], # base
])
return Mesh(v=vertices, f=faces) | [
"def",
"create_triangular_prism",
"(",
"p1",
",",
"p2",
",",
"p3",
",",
"height",
")",
":",
"from",
"blmath",
".",
"geometry",
"import",
"Plane",
"base_plane",
"=",
"Plane",
".",
"from_points",
"(",
"p1",
",",
"p2",
",",
"p3",
")",
"lower_base_to_upper_bas... | Return a Mesh which is a triangular prism whose base is the triangle
p1, p2, p3. If the vertices are oriented in a counterclockwise
direction, the prism extends from behind them. | [
"Return",
"a",
"Mesh",
"which",
"is",
"a",
"triangular",
"prism",
"whose",
"base",
"is",
"the",
"triangle",
"p1",
"p2",
"p3",
".",
"If",
"the",
"vertices",
"are",
"oriented",
"in",
"a",
"counterclockwise",
"direction",
"the",
"prism",
"extends",
"from",
"b... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/shapes.py#L50-L71 |
bodylabs/lace | lace/shapes.py | create_horizontal_plane | def create_horizontal_plane():
'''
Creates a horizontal plane.
'''
v = np.array([
[1., 0., 0.],
[-1., 0., 0.],
[0., 0., 1.],
[0., 0., -1.]
])
f = [[0, 1, 2], [3, 1, 0]]
return Mesh(v=v, f=f) | python | def create_horizontal_plane():
'''
Creates a horizontal plane.
'''
v = np.array([
[1., 0., 0.],
[-1., 0., 0.],
[0., 0., 1.],
[0., 0., -1.]
])
f = [[0, 1, 2], [3, 1, 0]]
return Mesh(v=v, f=f) | [
"def",
"create_horizontal_plane",
"(",
")",
":",
"v",
"=",
"np",
".",
"array",
"(",
"[",
"[",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"-",
"1.",
",",
"0.",
",",
"0.",
"]",
",",
"[",
"0.",
",",
"0.",
",",
"1.",
"]",
",",
"[",
"0.",
",",... | Creates a horizontal plane. | [
"Creates",
"a",
"horizontal",
"plane",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/shapes.py#L74-L85 |
openspending/babbage | babbage/model/concept.py | Concept.match_ref | def match_ref(self, ref):
""" Check if the ref matches one the concept's aliases.
If so, mark the matched ref so that we use it as the column label.
"""
if ref in self.refs:
self._matched_ref = ref
return True
return False | python | def match_ref(self, ref):
""" Check if the ref matches one the concept's aliases.
If so, mark the matched ref so that we use it as the column label.
"""
if ref in self.refs:
self._matched_ref = ref
return True
return False | [
"def",
"match_ref",
"(",
"self",
",",
"ref",
")",
":",
"if",
"ref",
"in",
"self",
".",
"refs",
":",
"self",
".",
"_matched_ref",
"=",
"ref",
"return",
"True",
"return",
"False"
] | Check if the ref matches one the concept's aliases.
If so, mark the matched ref so that we use it as the column label. | [
"Check",
"if",
"the",
"ref",
"matches",
"one",
"the",
"concept",
"s",
"aliases",
".",
"If",
"so",
"mark",
"the",
"matched",
"ref",
"so",
"that",
"we",
"use",
"it",
"as",
"the",
"column",
"label",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/concept.py#L40-L47 |
openspending/babbage | babbage/model/concept.py | Concept._physical_column | def _physical_column(self, cube, column_name):
""" Return the SQLAlchemy Column object matching a given, possibly
qualified, column name (i.e.: 'table.column'). If no table is named,
the fact table is assumed. """
table_name = self.model.fact_table_name
if '.' in column_name:
table_name, column_name = column_name.split('.', 1)
table = cube._load_table(table_name)
if column_name not in table.columns:
raise BindingException('Column %r does not exist on table %r' % (
column_name, table_name), table=table_name,
column=column_name)
return table, table.columns[column_name] | python | def _physical_column(self, cube, column_name):
""" Return the SQLAlchemy Column object matching a given, possibly
qualified, column name (i.e.: 'table.column'). If no table is named,
the fact table is assumed. """
table_name = self.model.fact_table_name
if '.' in column_name:
table_name, column_name = column_name.split('.', 1)
table = cube._load_table(table_name)
if column_name not in table.columns:
raise BindingException('Column %r does not exist on table %r' % (
column_name, table_name), table=table_name,
column=column_name)
return table, table.columns[column_name] | [
"def",
"_physical_column",
"(",
"self",
",",
"cube",
",",
"column_name",
")",
":",
"table_name",
"=",
"self",
".",
"model",
".",
"fact_table_name",
"if",
"'.'",
"in",
"column_name",
":",
"table_name",
",",
"column_name",
"=",
"column_name",
".",
"split",
"("... | Return the SQLAlchemy Column object matching a given, possibly
qualified, column name (i.e.: 'table.column'). If no table is named,
the fact table is assumed. | [
"Return",
"the",
"SQLAlchemy",
"Column",
"object",
"matching",
"a",
"given",
"possibly",
"qualified",
"column",
"name",
"(",
"i",
".",
"e",
".",
":",
"table",
".",
"column",
")",
".",
"If",
"no",
"table",
"is",
"named",
"the",
"fact",
"table",
"is",
"a... | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/concept.py#L49-L61 |
openspending/babbage | babbage/model/concept.py | Concept.bind | def bind(self, cube):
""" Map a model reference to an physical column in the database. """
table, column = self._physical_column(cube, self.column_name)
column = column.label(self.matched_ref)
column.quote = True
return table, column | python | def bind(self, cube):
""" Map a model reference to an physical column in the database. """
table, column = self._physical_column(cube, self.column_name)
column = column.label(self.matched_ref)
column.quote = True
return table, column | [
"def",
"bind",
"(",
"self",
",",
"cube",
")",
":",
"table",
",",
"column",
"=",
"self",
".",
"_physical_column",
"(",
"cube",
",",
"self",
".",
"column_name",
")",
"column",
"=",
"column",
".",
"label",
"(",
"self",
".",
"matched_ref",
")",
"column",
... | Map a model reference to an physical column in the database. | [
"Map",
"a",
"model",
"reference",
"to",
"an",
"physical",
"column",
"in",
"the",
"database",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/concept.py#L63-L68 |
ArabellaTech/aa-stripe | aa_stripe/models.py | StripeCustomer.add_new_source | def add_new_source(self, source_token, stripe_js_response=None):
"""Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated.
"""
customer = self.retrieve_from_stripe()
customer.source = source_token
customer.save()
if stripe_js_response:
self.stripe_js_response = stripe_js_response
self._update_from_stripe_object(customer) | python | def add_new_source(self, source_token, stripe_js_response=None):
"""Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated.
"""
customer = self.retrieve_from_stripe()
customer.source = source_token
customer.save()
if stripe_js_response:
self.stripe_js_response = stripe_js_response
self._update_from_stripe_object(customer) | [
"def",
"add_new_source",
"(",
"self",
",",
"source_token",
",",
"stripe_js_response",
"=",
"None",
")",
":",
"customer",
"=",
"self",
".",
"retrieve_from_stripe",
"(",
")",
"customer",
".",
"source",
"=",
"source_token",
"customer",
".",
"save",
"(",
")",
"i... | Add new source (for example: a new card) to the customer
The new source will be automatically set as customer's default payment source.
Passing stripe_js_response is optional. If set, StripeCustomer.stripe_js_response will be updated. | [
"Add",
"new",
"source",
"(",
"for",
"example",
":",
"a",
"new",
"card",
")",
"to",
"the",
"customer"
] | train | https://github.com/ArabellaTech/aa-stripe/blob/bda97c233a7513a69947c30f524a6050f984088b/aa_stripe/models.py#L104-L115 |
ArabellaTech/aa-stripe | aa_stripe/models.py | StripeCoupon.update_from_stripe_data | def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
"""
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False.
"""
fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])
update_data = {key: stripe_coupon[key] for key in fields_to_update}
for field in ["created", "redeem_by"]:
if update_data.get(field):
update_data[field] = timestamp_to_timezone_aware_date(update_data[field])
if update_data.get("amount_off"):
update_data["amount_off"] = Decimal(update_data["amount_off"]) / 100
# also make sure the object is up to date (without the need to call database)
for key, value in six.iteritems(update_data):
setattr(self, key, value)
if commit:
return StripeCoupon.objects.filter(pk=self.pk).update(**update_data) | python | def update_from_stripe_data(self, stripe_coupon, exclude_fields=None, commit=True):
"""
Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False.
"""
fields_to_update = self.STRIPE_FIELDS - set(exclude_fields or [])
update_data = {key: stripe_coupon[key] for key in fields_to_update}
for field in ["created", "redeem_by"]:
if update_data.get(field):
update_data[field] = timestamp_to_timezone_aware_date(update_data[field])
if update_data.get("amount_off"):
update_data["amount_off"] = Decimal(update_data["amount_off"]) / 100
# also make sure the object is up to date (without the need to call database)
for key, value in six.iteritems(update_data):
setattr(self, key, value)
if commit:
return StripeCoupon.objects.filter(pk=self.pk).update(**update_data) | [
"def",
"update_from_stripe_data",
"(",
"self",
",",
"stripe_coupon",
",",
"exclude_fields",
"=",
"None",
",",
"commit",
"=",
"True",
")",
":",
"fields_to_update",
"=",
"self",
".",
"STRIPE_FIELDS",
"-",
"set",
"(",
"exclude_fields",
"or",
"[",
"]",
")",
"upd... | Update StripeCoupon object with data from stripe.Coupon without calling stripe.Coupon.retrieve.
To only update the object, set the commit param to False.
Returns the number of rows altered or None if commit is False. | [
"Update",
"StripeCoupon",
"object",
"with",
"data",
"from",
"stripe",
".",
"Coupon",
"without",
"calling",
"stripe",
".",
"Coupon",
".",
"retrieve",
"."
] | train | https://github.com/ArabellaTech/aa-stripe/blob/bda97c233a7513a69947c30f524a6050f984088b/aa_stripe/models.py#L239-L260 |
ArabellaTech/aa-stripe | aa_stripe/models.py | StripeCoupon.save | def save(self, force_retrieve=False, *args, **kwargs):
"""
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe.
"""
stripe.api_key = stripe_settings.API_KEY
if self._previous_is_deleted != self.is_deleted and self.is_deleted:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
# make sure to delete correct coupon
if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]):
stripe_coupon.delete()
except stripe.error.InvalidRequestError:
# means that the coupon has already been removed from stripe
pass
return super(StripeCoupon, self).save(*args, **kwargs)
if self.pk or force_retrieve:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
if not force_retrieve:
stripe_coupon.metadata = self.metadata
stripe_coupon.save()
if force_retrieve:
# make sure we are not creating a duplicate
coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id)
if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists():
raise StripeCouponAlreadyExists
# all old coupons should be deleted
for coupon in coupon_qs:
coupon.is_deleted = True
super(StripeCoupon, coupon).save() # use super save() to call pre/post save signals
# update all fields in the local object in case someone tried to change them
self.update_from_stripe_data(stripe_coupon, exclude_fields=["metadata"] if not force_retrieve else [])
self.stripe_response = stripe_coupon
except stripe.error.InvalidRequestError:
if force_retrieve:
raise
self.is_deleted = True
else:
self.stripe_response = stripe.Coupon.create(
id=self.coupon_id,
duration=self.duration,
amount_off=int(self.amount_off * 100) if self.amount_off else None,
currency=self.currency,
duration_in_months=self.duration_in_months,
max_redemptions=self.max_redemptions,
metadata=self.metadata,
percent_off=self.percent_off,
redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None
)
# stripe will generate coupon_id if none was specified in the request
if not self.coupon_id:
self.coupon_id = self.stripe_response["id"]
self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"])
# for future
self.is_created_at_stripe = True
return super(StripeCoupon, self).save(*args, **kwargs) | python | def save(self, force_retrieve=False, *args, **kwargs):
"""
Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe.
"""
stripe.api_key = stripe_settings.API_KEY
if self._previous_is_deleted != self.is_deleted and self.is_deleted:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
# make sure to delete correct coupon
if self.created == timestamp_to_timezone_aware_date(stripe_coupon["created"]):
stripe_coupon.delete()
except stripe.error.InvalidRequestError:
# means that the coupon has already been removed from stripe
pass
return super(StripeCoupon, self).save(*args, **kwargs)
if self.pk or force_retrieve:
try:
stripe_coupon = stripe.Coupon.retrieve(self.coupon_id)
if not force_retrieve:
stripe_coupon.metadata = self.metadata
stripe_coupon.save()
if force_retrieve:
# make sure we are not creating a duplicate
coupon_qs = StripeCoupon.objects.filter(coupon_id=self.coupon_id)
if coupon_qs.filter(created=timestamp_to_timezone_aware_date(stripe_coupon["created"])).exists():
raise StripeCouponAlreadyExists
# all old coupons should be deleted
for coupon in coupon_qs:
coupon.is_deleted = True
super(StripeCoupon, coupon).save() # use super save() to call pre/post save signals
# update all fields in the local object in case someone tried to change them
self.update_from_stripe_data(stripe_coupon, exclude_fields=["metadata"] if not force_retrieve else [])
self.stripe_response = stripe_coupon
except stripe.error.InvalidRequestError:
if force_retrieve:
raise
self.is_deleted = True
else:
self.stripe_response = stripe.Coupon.create(
id=self.coupon_id,
duration=self.duration,
amount_off=int(self.amount_off * 100) if self.amount_off else None,
currency=self.currency,
duration_in_months=self.duration_in_months,
max_redemptions=self.max_redemptions,
metadata=self.metadata,
percent_off=self.percent_off,
redeem_by=int(dateformat.format(self.redeem_by, "U")) if self.redeem_by else None
)
# stripe will generate coupon_id if none was specified in the request
if not self.coupon_id:
self.coupon_id = self.stripe_response["id"]
self.created = timestamp_to_timezone_aware_date(self.stripe_response["created"])
# for future
self.is_created_at_stripe = True
return super(StripeCoupon, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"force_retrieve",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stripe",
".",
"api_key",
"=",
"stripe_settings",
".",
"API_KEY",
"if",
"self",
".",
"_previous_is_deleted",
"!=",
"self",
".",
"is_dele... | Use the force_retrieve parameter to create a new StripeCoupon object from an existing coupon created at Stripe
API or update the local object with data fetched from Stripe. | [
"Use",
"the",
"force_retrieve",
"parameter",
"to",
"create",
"a",
"new",
"StripeCoupon",
"object",
"from",
"an",
"existing",
"coupon",
"created",
"at",
"Stripe"
] | train | https://github.com/ArabellaTech/aa-stripe/blob/bda97c233a7513a69947c30f524a6050f984088b/aa_stripe/models.py#L262-L325 |
nschloe/meshplex | meshplex/helpers.py | get_signed_simplex_volumes | def get_signed_simplex_volumes(cells, pts):
"""Signed volume of a simplex in nD. Note that signing only makes sense for
n-simplices in R^n.
"""
n = pts.shape[1]
assert cells.shape[1] == n + 1
p = pts[cells]
p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1)
return numpy.linalg.det(p) / math.factorial(n) | python | def get_signed_simplex_volumes(cells, pts):
"""Signed volume of a simplex in nD. Note that signing only makes sense for
n-simplices in R^n.
"""
n = pts.shape[1]
assert cells.shape[1] == n + 1
p = pts[cells]
p = numpy.concatenate([p, numpy.ones(list(p.shape[:2]) + [1])], axis=-1)
return numpy.linalg.det(p) / math.factorial(n) | [
"def",
"get_signed_simplex_volumes",
"(",
"cells",
",",
"pts",
")",
":",
"n",
"=",
"pts",
".",
"shape",
"[",
"1",
"]",
"assert",
"cells",
".",
"shape",
"[",
"1",
"]",
"==",
"n",
"+",
"1",
"p",
"=",
"pts",
"[",
"cells",
"]",
"p",
"=",
"numpy",
"... | Signed volume of a simplex in nD. Note that signing only makes sense for
n-simplices in R^n. | [
"Signed",
"volume",
"of",
"a",
"simplex",
"in",
"nD",
".",
"Note",
"that",
"signing",
"only",
"makes",
"sense",
"for",
"n",
"-",
"simplices",
"in",
"R^n",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/helpers.py#L8-L17 |
nschloe/meshplex | meshplex/helpers.py | grp_start_len | def grp_start_len(a):
"""Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this
routine returns the indices where the blocks of equal integers start and
how long the blocks are.
"""
# https://stackoverflow.com/a/50394587/353337
m = numpy.concatenate([[True], a[:-1] != a[1:], [True]])
idx = numpy.flatnonzero(m)
return idx[:-1], numpy.diff(idx) | python | def grp_start_len(a):
"""Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this
routine returns the indices where the blocks of equal integers start and
how long the blocks are.
"""
# https://stackoverflow.com/a/50394587/353337
m = numpy.concatenate([[True], a[:-1] != a[1:], [True]])
idx = numpy.flatnonzero(m)
return idx[:-1], numpy.diff(idx) | [
"def",
"grp_start_len",
"(",
"a",
")",
":",
"# https://stackoverflow.com/a/50394587/353337",
"m",
"=",
"numpy",
".",
"concatenate",
"(",
"[",
"[",
"True",
"]",
",",
"a",
"[",
":",
"-",
"1",
"]",
"!=",
"a",
"[",
"1",
":",
"]",
",",
"[",
"True",
"]",
... | Given a sorted 1D input array `a`, e.g., [0 0, 1, 2, 3, 4, 4, 4], this
routine returns the indices where the blocks of equal integers start and
how long the blocks are. | [
"Given",
"a",
"sorted",
"1D",
"input",
"array",
"a",
"e",
".",
"g",
".",
"[",
"0",
"0",
"1",
"2",
"3",
"4",
"4",
"4",
"]",
"this",
"routine",
"returns",
"the",
"indices",
"where",
"the",
"blocks",
"of",
"equal",
"integers",
"start",
"and",
"how",
... | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/helpers.py#L20-L28 |
nschloe/meshplex | meshplex/base.py | compute_triangle_circumcenters | def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej):
"""Computes the circumcenters of all given triangles.
"""
# The input argument are the dot products
#
# <e1, e2>
# <e2, e0>
# <e0, e1>
#
# of the edges
#
# e0: x1->x2,
# e1: x2->x0,
# e2: x0->x1.
#
# Note that edge e_i is opposite of node i and the edges add up to 0.
# The trilinear coordinates of the circumcenter are
#
# cos(alpha0) : cos(alpha1) : cos(alpha2)
#
# where alpha_k is the angle at point k, opposite of edge k. The Cartesian
# coordinates are (see
# <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>)
#
# C = sum_i ||e_i|| * cos(alpha_i)/beta * P_i
#
# with
#
# beta = sum ||e_i||*cos(alpha_i)
#
# Incidentally, the cosines are
#
# cos(alpha0) = <e1, e2> / ||e1|| / ||e2||,
#
# so in total
#
# C = <e_0, e0> <e1, e2> / sum_i (<e_i, e_i> <e{i+1}, e{i+2}>) P0
# + ... P1
# + ... P2.
#
# An even nicer formula is given on
# <https://en.wikipedia.org/wiki/Circumscribed_circle#Barycentric_coordinates>: The
# barycentric coordinates of the circumcenter are
#
# a^2 (b^2 + c^2 - a^2) : b^2 (c^2 + a^2 - b^2) : c^2 (a^2 + b^2 - c^2).
#
# This is only using the squared edge lengths, too!
#
alpha = ei_dot_ei * ei_dot_ej
alpha_sum = alpha[0] + alpha[1] + alpha[2]
beta = alpha / alpha_sum[None]
a = X * beta[..., None]
cc = a[0] + a[1] + a[2]
# alpha = numpy.array([
# ei_dot_ei[0] * (ei_dot_ei[1] + ei_dot_ei[2] - ei_dot_ei[0]),
# ei_dot_ei[1] * (ei_dot_ei[2] + ei_dot_ei[0] - ei_dot_ei[1]),
# ei_dot_ei[2] * (ei_dot_ei[0] + ei_dot_ei[1] - ei_dot_ei[2]),
# ])
# alpha /= numpy.sum(alpha, axis=0)
# cc = (X[0].T * alpha[0] + X[1].T * alpha[1] + X[2].T * alpha[2]).T
return cc | python | def compute_triangle_circumcenters(X, ei_dot_ei, ei_dot_ej):
"""Computes the circumcenters of all given triangles.
"""
# The input argument are the dot products
#
# <e1, e2>
# <e2, e0>
# <e0, e1>
#
# of the edges
#
# e0: x1->x2,
# e1: x2->x0,
# e2: x0->x1.
#
# Note that edge e_i is opposite of node i and the edges add up to 0.
# The trilinear coordinates of the circumcenter are
#
# cos(alpha0) : cos(alpha1) : cos(alpha2)
#
# where alpha_k is the angle at point k, opposite of edge k. The Cartesian
# coordinates are (see
# <https://en.wikipedia.org/wiki/Trilinear_coordinates#Between_Cartesian_and_trilinear_coordinates>)
#
# C = sum_i ||e_i|| * cos(alpha_i)/beta * P_i
#
# with
#
# beta = sum ||e_i||*cos(alpha_i)
#
# Incidentally, the cosines are
#
# cos(alpha0) = <e1, e2> / ||e1|| / ||e2||,
#
# so in total
#
# C = <e_0, e0> <e1, e2> / sum_i (<e_i, e_i> <e{i+1}, e{i+2}>) P0
# + ... P1
# + ... P2.
#
# An even nicer formula is given on
# <https://en.wikipedia.org/wiki/Circumscribed_circle#Barycentric_coordinates>: The
# barycentric coordinates of the circumcenter are
#
# a^2 (b^2 + c^2 - a^2) : b^2 (c^2 + a^2 - b^2) : c^2 (a^2 + b^2 - c^2).
#
# This is only using the squared edge lengths, too!
#
alpha = ei_dot_ei * ei_dot_ej
alpha_sum = alpha[0] + alpha[1] + alpha[2]
beta = alpha / alpha_sum[None]
a = X * beta[..., None]
cc = a[0] + a[1] + a[2]
# alpha = numpy.array([
# ei_dot_ei[0] * (ei_dot_ei[1] + ei_dot_ei[2] - ei_dot_ei[0]),
# ei_dot_ei[1] * (ei_dot_ei[2] + ei_dot_ei[0] - ei_dot_ei[1]),
# ei_dot_ei[2] * (ei_dot_ei[0] + ei_dot_ei[1] - ei_dot_ei[2]),
# ])
# alpha /= numpy.sum(alpha, axis=0)
# cc = (X[0].T * alpha[0] + X[1].T * alpha[1] + X[2].T * alpha[2]).T
return cc | [
"def",
"compute_triangle_circumcenters",
"(",
"X",
",",
"ei_dot_ei",
",",
"ei_dot_ej",
")",
":",
"# The input argument are the dot products",
"#",
"# <e1, e2>",
"# <e2, e0>",
"# <e0, e1>",
"#",
"# of the edges",
"#",
"# e0: x1->x2,",
"# e1: x2->x0,",
"# e2: x0->x1... | Computes the circumcenters of all given triangles. | [
"Computes",
"the",
"circumcenters",
"of",
"all",
"given",
"triangles",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/base.py#L86-L148 |
nschloe/meshplex | meshplex/base.py | _base_mesh.get_edge_mask | def get_edge_mask(self, subdomain=None):
"""Get faces which are fully in subdomain.
"""
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if all its edges are in.
# An edge is inside if all its nodes are in.
is_in = self.subdomains[subdomain]["vertices"][self.idx_hierarchy]
# Take `all()` over the first index
is_inside = numpy.all(is_in, axis=tuple(range(1)))
if subdomain.is_boundary_only:
# Filter for boundary
is_inside = is_inside & self.is_boundary_edge
return is_inside | python | def get_edge_mask(self, subdomain=None):
"""Get faces which are fully in subdomain.
"""
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if all its edges are in.
# An edge is inside if all its nodes are in.
is_in = self.subdomains[subdomain]["vertices"][self.idx_hierarchy]
# Take `all()` over the first index
is_inside = numpy.all(is_in, axis=tuple(range(1)))
if subdomain.is_boundary_only:
# Filter for boundary
is_inside = is_inside & self.is_boundary_edge
return is_inside | [
"def",
"get_edge_mask",
"(",
"self",
",",
"subdomain",
"=",
"None",
")",
":",
"if",
"subdomain",
"is",
"None",
":",
"# https://stackoverflow.com/a/42392791/353337",
"return",
"numpy",
".",
"s_",
"[",
":",
"]",
"if",
"subdomain",
"not",
"in",
"self",
".",
"su... | Get faces which are fully in subdomain. | [
"Get",
"faces",
"which",
"are",
"fully",
"in",
"subdomain",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/base.py#L197-L217 |
nschloe/meshplex | meshplex/base.py | _base_mesh.get_face_mask | def get_face_mask(self, subdomain):
"""Get faces which are fully in subdomain.
"""
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if all its edges are in.
# An edge is inside if all its nodes are in.
is_in = self.subdomains[subdomain]["vertices"][self.idx_hierarchy]
# Take `all()` over all axes except the last two (face_ids, cell_ids).
n = len(is_in.shape)
is_inside = numpy.all(is_in, axis=tuple(range(n - 2)))
if subdomain.is_boundary_only:
# Filter for boundary
is_inside = is_inside & self.is_boundary_facet
return is_inside | python | def get_face_mask(self, subdomain):
"""Get faces which are fully in subdomain.
"""
if subdomain is None:
# https://stackoverflow.com/a/42392791/353337
return numpy.s_[:]
if subdomain not in self.subdomains:
self._mark_vertices(subdomain)
# A face is inside if all its edges are in.
# An edge is inside if all its nodes are in.
is_in = self.subdomains[subdomain]["vertices"][self.idx_hierarchy]
# Take `all()` over all axes except the last two (face_ids, cell_ids).
n = len(is_in.shape)
is_inside = numpy.all(is_in, axis=tuple(range(n - 2)))
if subdomain.is_boundary_only:
# Filter for boundary
is_inside = is_inside & self.is_boundary_facet
return is_inside | [
"def",
"get_face_mask",
"(",
"self",
",",
"subdomain",
")",
":",
"if",
"subdomain",
"is",
"None",
":",
"# https://stackoverflow.com/a/42392791/353337",
"return",
"numpy",
".",
"s_",
"[",
":",
"]",
"if",
"subdomain",
"not",
"in",
"self",
".",
"subdomains",
":",... | Get faces which are fully in subdomain. | [
"Get",
"faces",
"which",
"are",
"fully",
"in",
"subdomain",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/base.py#L219-L240 |
nschloe/meshplex | meshplex/base.py | _base_mesh._mark_vertices | def _mark_vertices(self, subdomain):
"""Mark faces/edges which are fully in subdomain.
"""
if subdomain is None:
is_inside = numpy.ones(len(self.node_coords), dtype=bool)
else:
is_inside = subdomain.is_inside(self.node_coords.T).T
if subdomain.is_boundary_only:
# Filter boundary
self.mark_boundary()
is_inside = is_inside & self.is_boundary_node
self.subdomains[subdomain] = {"vertices": is_inside}
return | python | def _mark_vertices(self, subdomain):
"""Mark faces/edges which are fully in subdomain.
"""
if subdomain is None:
is_inside = numpy.ones(len(self.node_coords), dtype=bool)
else:
is_inside = subdomain.is_inside(self.node_coords.T).T
if subdomain.is_boundary_only:
# Filter boundary
self.mark_boundary()
is_inside = is_inside & self.is_boundary_node
self.subdomains[subdomain] = {"vertices": is_inside}
return | [
"def",
"_mark_vertices",
"(",
"self",
",",
"subdomain",
")",
":",
"if",
"subdomain",
"is",
"None",
":",
"is_inside",
"=",
"numpy",
".",
"ones",
"(",
"len",
"(",
"self",
".",
"node_coords",
")",
",",
"dtype",
"=",
"bool",
")",
"else",
":",
"is_inside",
... | Mark faces/edges which are fully in subdomain. | [
"Mark",
"faces",
"/",
"edges",
"which",
"are",
"fully",
"in",
"subdomain",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/base.py#L259-L273 |
mandeep/Travis-Encrypt | travis/orderer.py | ordered_dump | def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
"""Dump a yaml configuration as an OrderedDict."""
class OrderedDumper(Dumper):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
return yaml.dump(data, stream, OrderedDumper, **kwds) | python | def ordered_dump(data, stream=None, Dumper=yaml.SafeDumper, **kwds):
"""Dump a yaml configuration as an OrderedDict."""
class OrderedDumper(Dumper):
pass
def dict_representer(dumper, data):
return dumper.represent_mapping(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items())
OrderedDumper.add_representer(OrderedDict, dict_representer)
return yaml.dump(data, stream, OrderedDumper, **kwds) | [
"def",
"ordered_dump",
"(",
"data",
",",
"stream",
"=",
"None",
",",
"Dumper",
"=",
"yaml",
".",
"SafeDumper",
",",
"*",
"*",
"kwds",
")",
":",
"class",
"OrderedDumper",
"(",
"Dumper",
")",
":",
"pass",
"def",
"dict_representer",
"(",
"dumper",
",",
"d... | Dump a yaml configuration as an OrderedDict. | [
"Dump",
"a",
"yaml",
"configuration",
"as",
"an",
"OrderedDict",
"."
] | train | https://github.com/mandeep/Travis-Encrypt/blob/0dd2da1c71feaadcb84bdeb26827e6dfe1bd3b41/travis/orderer.py#L27-L37 |
openspending/babbage | babbage/query/cuts.py | Cuts._check_type | def _check_type(self, ref, value):
"""
Checks whether the type of the cut value matches the type of the
concept being cut, and raises a QueryException if it doesn't match
"""
if isinstance(value, list):
return [self._check_type(ref, val) for val in value]
model_type = self.cube.model[ref].datatype
if model_type is None:
return
query_type = self._api_type(value)
if query_type == model_type:
return
else:
raise QueryException("Invalid value %r parsed as type '%s' "
"for cut %s of type '%s'"
% (value, query_type, ref, model_type)) | python | def _check_type(self, ref, value):
"""
Checks whether the type of the cut value matches the type of the
concept being cut, and raises a QueryException if it doesn't match
"""
if isinstance(value, list):
return [self._check_type(ref, val) for val in value]
model_type = self.cube.model[ref].datatype
if model_type is None:
return
query_type = self._api_type(value)
if query_type == model_type:
return
else:
raise QueryException("Invalid value %r parsed as type '%s' "
"for cut %s of type '%s'"
% (value, query_type, ref, model_type)) | [
"def",
"_check_type",
"(",
"self",
",",
"ref",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"[",
"self",
".",
"_check_type",
"(",
"ref",
",",
"val",
")",
"for",
"val",
"in",
"value",
"]",
"model_type",
... | Checks whether the type of the cut value matches the type of the
concept being cut, and raises a QueryException if it doesn't match | [
"Checks",
"whether",
"the",
"type",
"of",
"the",
"cut",
"value",
"matches",
"the",
"type",
"of",
"the",
"concept",
"being",
"cut",
"and",
"raises",
"a",
"QueryException",
"if",
"it",
"doesn",
"t",
"match"
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/cuts.py#L24-L41 |
openspending/babbage | babbage/query/cuts.py | Cuts._api_type | def _api_type(self, value):
"""
Returns the API type of the given value based on its python type.
"""
if isinstance(value, six.string_types):
return 'string'
elif isinstance(value, six.integer_types):
return 'integer'
elif type(value) is datetime.datetime:
return 'date' | python | def _api_type(self, value):
"""
Returns the API type of the given value based on its python type.
"""
if isinstance(value, six.string_types):
return 'string'
elif isinstance(value, six.integer_types):
return 'integer'
elif type(value) is datetime.datetime:
return 'date' | [
"def",
"_api_type",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"return",
"'string'",
"elif",
"isinstance",
"(",
"value",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"'intege... | Returns the API type of the given value based on its python type. | [
"Returns",
"the",
"API",
"type",
"of",
"the",
"given",
"value",
"based",
"on",
"its",
"python",
"type",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/cuts.py#L43-L53 |
openspending/babbage | babbage/query/cuts.py | Cuts.apply | def apply(self, q, bindings, cuts):
""" Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. """
info = []
for (ref, operator, value) in self.parse(cuts):
if map_is_class and isinstance(value, map):
value = list(value)
self._check_type(ref, value)
info.append({'ref': ref, 'operator': operator, 'value': value})
table, column = self.cube.model[ref].bind(self.cube)
bindings.append(Binding(table, ref))
q = q.where(column.in_(value))
return info, q, bindings | python | def apply(self, q, bindings, cuts):
""" Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. """
info = []
for (ref, operator, value) in self.parse(cuts):
if map_is_class and isinstance(value, map):
value = list(value)
self._check_type(ref, value)
info.append({'ref': ref, 'operator': operator, 'value': value})
table, column = self.cube.model[ref].bind(self.cube)
bindings.append(Binding(table, ref))
q = q.where(column.in_(value))
return info, q, bindings | [
"def",
"apply",
"(",
"self",
",",
"q",
",",
"bindings",
",",
"cuts",
")",
":",
"info",
"=",
"[",
"]",
"for",
"(",
"ref",
",",
"operator",
",",
"value",
")",
"in",
"self",
".",
"parse",
"(",
"cuts",
")",
":",
"if",
"map_is_class",
"and",
"isinstan... | Apply a set of filters, which can be given as a set of tuples in
the form (ref, operator, value), or as a string in query form. If it
is ``None``, no filter will be applied. | [
"Apply",
"a",
"set",
"of",
"filters",
"which",
"can",
"be",
"given",
"as",
"a",
"set",
"of",
"tuples",
"in",
"the",
"form",
"(",
"ref",
"operator",
"value",
")",
"or",
"as",
"a",
"string",
"in",
"query",
"form",
".",
"If",
"it",
"is",
"None",
"no",... | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/query/cuts.py#L55-L68 |
bodylabs/lace | lace/color.py | colors_like | def colors_like(color, arr, colormap=DEFAULT_COLORMAP):
'''
Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N, ), (N, 1), or (1, N) that are put through a colormap to get per vertex color
- An array of colors (N, 3) or (3, N)
There is a potential for conflict here if N == 3. In that case we assume a value is an rgb triple,
not a colormap index. This is a sort of degenerate case, as a mesh with three verticies is just a single
triangle and not something we ever actually use in practice.
'''
import numpy as np
from blmath.numerics import is_empty_arraylike
if is_empty_arraylike(color):
return None
if isinstance(color, basestring):
from lace.color_names import name_to_rgb
color = name_to_rgb[color]
elif isinstance(color, list):
color = np.array(color)
color = np.squeeze(color)
num_verts = arr.shape[0]
if color.ndim == 1:
if color.shape[0] == 3: # rgb triple
return np.ones((num_verts, 3)) * np.array([color])
else:
from matplotlib import cm
return np.ones((num_verts, 3)) * cm.get_cmap(colormap)(color.flatten())[:, :3]
elif color.ndim == 2:
if color.shape[1] == num_verts:
color = color.T
return np.ones((num_verts, 3)) * color
else:
raise ValueError("Colors must be specified as one or two dimensions") | python | def colors_like(color, arr, colormap=DEFAULT_COLORMAP):
'''
Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N, ), (N, 1), or (1, N) that are put through a colormap to get per vertex color
- An array of colors (N, 3) or (3, N)
There is a potential for conflict here if N == 3. In that case we assume a value is an rgb triple,
not a colormap index. This is a sort of degenerate case, as a mesh with three verticies is just a single
triangle and not something we ever actually use in practice.
'''
import numpy as np
from blmath.numerics import is_empty_arraylike
if is_empty_arraylike(color):
return None
if isinstance(color, basestring):
from lace.color_names import name_to_rgb
color = name_to_rgb[color]
elif isinstance(color, list):
color = np.array(color)
color = np.squeeze(color)
num_verts = arr.shape[0]
if color.ndim == 1:
if color.shape[0] == 3: # rgb triple
return np.ones((num_verts, 3)) * np.array([color])
else:
from matplotlib import cm
return np.ones((num_verts, 3)) * cm.get_cmap(colormap)(color.flatten())[:, :3]
elif color.ndim == 2:
if color.shape[1] == num_verts:
color = color.T
return np.ones((num_verts, 3)) * color
else:
raise ValueError("Colors must be specified as one or two dimensions") | [
"def",
"colors_like",
"(",
"color",
",",
"arr",
",",
"colormap",
"=",
"DEFAULT_COLORMAP",
")",
":",
"import",
"numpy",
"as",
"np",
"from",
"blmath",
".",
"numerics",
"import",
"is_empty_arraylike",
"if",
"is_empty_arraylike",
"(",
"color",
")",
":",
"return",
... | Given an array of size NxM (usually Nx3), we accept color in the following ways:
- A string color name. The accepted names are roughly what's in X11's rgb.txt
- An explicit rgb triple, in (3, ), (3, 1), or (1, 3) shape
- A list of values (N, ), (N, 1), or (1, N) that are put through a colormap to get per vertex color
- An array of colors (N, 3) or (3, N)
There is a potential for conflict here if N == 3. In that case we assume a value is an rgb triple,
not a colormap index. This is a sort of degenerate case, as a mesh with three verticies is just a single
triangle and not something we ever actually use in practice. | [
"Given",
"an",
"array",
"of",
"size",
"NxM",
"(",
"usually",
"Nx3",
")",
"we",
"accept",
"color",
"in",
"the",
"following",
"ways",
":",
"-",
"A",
"string",
"color",
"name",
".",
"The",
"accepted",
"names",
"are",
"roughly",
"what",
"s",
"in",
"X11",
... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/color.py#L5-L39 |
bodylabs/lace | lace/color.py | MeshMixin.color_by_height | def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument
'''
Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
threshold: The top of the range. Points at and above this height will
be the same color.
'''
import numpy as np
heights = self.v[:, axis] - self.floor_point[axis]
if threshold:
# height == 0 -> saturation = 0.
# height == threshold -> saturation = 1.
color_weights = np.minimum(heights / threshold, 1.)
color_weights = color_weights * color_weights
self.set_vertex_colors_from_weights(color_weights, scale_to_range_1=False)
else:
self.set_vertex_colors_from_weights(heights) | python | def color_by_height(self, axis=1, threshold=None, color=DEFAULT_COLORMAP): # pylint: disable=unused-argument
'''
Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
threshold: The top of the range. Points at and above this height will
be the same color.
'''
import numpy as np
heights = self.v[:, axis] - self.floor_point[axis]
if threshold:
# height == 0 -> saturation = 0.
# height == threshold -> saturation = 1.
color_weights = np.minimum(heights / threshold, 1.)
color_weights = color_weights * color_weights
self.set_vertex_colors_from_weights(color_weights, scale_to_range_1=False)
else:
self.set_vertex_colors_from_weights(heights) | [
"def",
"color_by_height",
"(",
"self",
",",
"axis",
"=",
"1",
",",
"threshold",
"=",
"None",
",",
"color",
"=",
"DEFAULT_COLORMAP",
")",
":",
"# pylint: disable=unused-argument",
"import",
"numpy",
"as",
"np",
"heights",
"=",
"self",
".",
"v",
"[",
":",
",... | Color each vertex by its height above the floor point.
axis: The axis to use. 0 means x, 1 means y, 2 means z.
threshold: The top of the range. Points at and above this height will
be the same color. | [
"Color",
"each",
"vertex",
"by",
"its",
"height",
"above",
"the",
"floor",
"point",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/color.py#L85-L105 |
bodylabs/lace | lace/color.py | MeshMixin.color_as_heatmap | def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP):
'''
Truncate weights to the range [0, max_weight] and rescale, as you would
want for a heatmap with known scale.
'''
import numpy as np
adjusted_weights = np.clip(weights, 0., max_weight) / max_weight
self.vc = colors_like(adjusted_weights, self.v, colormap=color) | python | def color_as_heatmap(self, weights, max_weight=1.0, color=DEFAULT_COLORMAP):
'''
Truncate weights to the range [0, max_weight] and rescale, as you would
want for a heatmap with known scale.
'''
import numpy as np
adjusted_weights = np.clip(weights, 0., max_weight) / max_weight
self.vc = colors_like(adjusted_weights, self.v, colormap=color) | [
"def",
"color_as_heatmap",
"(",
"self",
",",
"weights",
",",
"max_weight",
"=",
"1.0",
",",
"color",
"=",
"DEFAULT_COLORMAP",
")",
":",
"import",
"numpy",
"as",
"np",
"adjusted_weights",
"=",
"np",
".",
"clip",
"(",
"weights",
",",
"0.",
",",
"max_weight",... | Truncate weights to the range [0, max_weight] and rescale, as you would
want for a heatmap with known scale. | [
"Truncate",
"weights",
"to",
"the",
"range",
"[",
"0",
"max_weight",
"]",
"and",
"rescale",
"as",
"you",
"would",
"want",
"for",
"a",
"heatmap",
"with",
"known",
"scale",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/color.py#L107-L114 |
bodylabs/lace | lace/topology.py | quads_to_tris | def quads_to_tris(quads):
'''
Convert quad faces to triangular faces.
quads: An nx4 array.
Return a 2nx3 array.
'''
import numpy as np
tris = np.empty((2 * len(quads), 3))
tris[0::2, :] = quads[:, [0, 1, 2]]
tris[1::2, :] = quads[:, [0, 2, 3]]
return tris | python | def quads_to_tris(quads):
'''
Convert quad faces to triangular faces.
quads: An nx4 array.
Return a 2nx3 array.
'''
import numpy as np
tris = np.empty((2 * len(quads), 3))
tris[0::2, :] = quads[:, [0, 1, 2]]
tris[1::2, :] = quads[:, [0, 2, 3]]
return tris | [
"def",
"quads_to_tris",
"(",
"quads",
")",
":",
"import",
"numpy",
"as",
"np",
"tris",
"=",
"np",
".",
"empty",
"(",
"(",
"2",
"*",
"len",
"(",
"quads",
")",
",",
"3",
")",
")",
"tris",
"[",
"0",
":",
":",
"2",
",",
":",
"]",
"=",
"quads",
... | Convert quad faces to triangular faces.
quads: An nx4 array.
Return a 2nx3 array. | [
"Convert",
"quad",
"faces",
"to",
"triangular",
"faces",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L4-L17 |
bodylabs/lace | lace/topology.py | MeshMixin.all_faces_with_verts | def all_faces_with_verts(self, v_indices, as_boolean=False):
'''
returns all of the faces that contain at least one of the vertices in v_indices
'''
import numpy as np
included_vertices = np.zeros(self.v.shape[0], dtype=bool)
included_vertices[np.array(v_indices, dtype=np.uint32)] = True
faces_with_verts = included_vertices[self.f].all(axis=1)
if as_boolean:
return faces_with_verts
return np.nonzero(faces_with_verts)[0] | python | def all_faces_with_verts(self, v_indices, as_boolean=False):
'''
returns all of the faces that contain at least one of the vertices in v_indices
'''
import numpy as np
included_vertices = np.zeros(self.v.shape[0], dtype=bool)
included_vertices[np.array(v_indices, dtype=np.uint32)] = True
faces_with_verts = included_vertices[self.f].all(axis=1)
if as_boolean:
return faces_with_verts
return np.nonzero(faces_with_verts)[0] | [
"def",
"all_faces_with_verts",
"(",
"self",
",",
"v_indices",
",",
"as_boolean",
"=",
"False",
")",
":",
"import",
"numpy",
"as",
"np",
"included_vertices",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"v",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",... | returns all of the faces that contain at least one of the vertices in v_indices | [
"returns",
"all",
"of",
"the",
"faces",
"that",
"contain",
"at",
"least",
"one",
"of",
"the",
"vertices",
"in",
"v_indices"
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L47-L57 |
bodylabs/lace | lace/topology.py | MeshMixin.vertex_indices_in_segments | def vertex_indices_in_segments(self, segments, ret_face_indices=False):
'''
Given a list of segment names, return an array of vertex indices for
all the vertices in those faces.
Args:
segments: a list of segment names,
ret_face_indices: if it is `True`, returns face indices
'''
import numpy as np
import warnings
face_indices = np.array([])
vertex_indices = np.array([])
if self.segm is not None:
try:
segments = [self.segm[name] for name in segments]
except KeyError as e:
raise ValueError('Unknown segments {}. Consier using Mesh.clean_segments on segments'.format(e.args[0]))
face_indices = np.unique(np.concatenate(segments))
vertex_indices = np.unique(np.ravel(self.f[face_indices]))
else:
warnings.warn('self.segm is None, will return empty array')
if ret_face_indices:
return vertex_indices, face_indices
else:
return vertex_indices | python | def vertex_indices_in_segments(self, segments, ret_face_indices=False):
'''
Given a list of segment names, return an array of vertex indices for
all the vertices in those faces.
Args:
segments: a list of segment names,
ret_face_indices: if it is `True`, returns face indices
'''
import numpy as np
import warnings
face_indices = np.array([])
vertex_indices = np.array([])
if self.segm is not None:
try:
segments = [self.segm[name] for name in segments]
except KeyError as e:
raise ValueError('Unknown segments {}. Consier using Mesh.clean_segments on segments'.format(e.args[0]))
face_indices = np.unique(np.concatenate(segments))
vertex_indices = np.unique(np.ravel(self.f[face_indices]))
else:
warnings.warn('self.segm is None, will return empty array')
if ret_face_indices:
return vertex_indices, face_indices
else:
return vertex_indices | [
"def",
"vertex_indices_in_segments",
"(",
"self",
",",
"segments",
",",
"ret_face_indices",
"=",
"False",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"warnings",
"face_indices",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"vertex_indices",
"=",
"np",... | Given a list of segment names, return an array of vertex indices for
all the vertices in those faces.
Args:
segments: a list of segment names,
ret_face_indices: if it is `True`, returns face indices | [
"Given",
"a",
"list",
"of",
"segment",
"names",
"return",
"an",
"array",
"of",
"vertex",
"indices",
"for",
"all",
"the",
"vertices",
"in",
"those",
"faces",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L76-L103 |
bodylabs/lace | lace/topology.py | MeshMixin.keep_segments | def keep_segments(self, segments_to_keep, preserve_segmentation=True):
'''
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
'''
v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True)
self.segm = {name: self.segm[name] for name in segments_to_keep}
if not preserve_segmentation:
self.segm = None
self.f = self.f[f_ind]
if self.ft is not None:
self.ft = self.ft[f_ind]
self.keep_vertices(v_ind) | python | def keep_segments(self, segments_to_keep, preserve_segmentation=True):
'''
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
'''
v_ind, f_ind = self.vertex_indices_in_segments(segments_to_keep, ret_face_indices=True)
self.segm = {name: self.segm[name] for name in segments_to_keep}
if not preserve_segmentation:
self.segm = None
self.f = self.f[f_ind]
if self.ft is not None:
self.ft = self.ft[f_ind]
self.keep_vertices(v_ind) | [
"def",
"keep_segments",
"(",
"self",
",",
"segments_to_keep",
",",
"preserve_segmentation",
"=",
"True",
")",
":",
"v_ind",
",",
"f_ind",
"=",
"self",
".",
"vertex_indices_in_segments",
"(",
"segments_to_keep",
",",
"ret_face_indices",
"=",
"True",
")",
"self",
... | Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed. | [
"Keep",
"the",
"faces",
"and",
"vertices",
"for",
"given",
"segments",
"discarding",
"all",
"others",
".",
"When",
"preserve_segmentation",
"is",
"false",
"self",
".",
"segm",
"is",
"discarded",
"for",
"speed",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L110-L124 |
bodylabs/lace | lace/topology.py | MeshMixin.remove_segments | def remove_segments(self, segments_to_remove):
''' Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed
'''
v_ind = self.vertex_indices_in_segments(segments_to_remove)
self.segm = {name: faces for name, faces in self.segm.iteritems() if name not in segments_to_remove}
self.remove_vertices(v_ind) | python | def remove_segments(self, segments_to_remove):
''' Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed
'''
v_ind = self.vertex_indices_in_segments(segments_to_remove)
self.segm = {name: faces for name, faces in self.segm.iteritems() if name not in segments_to_remove}
self.remove_vertices(v_ind) | [
"def",
"remove_segments",
"(",
"self",
",",
"segments_to_remove",
")",
":",
"v_ind",
"=",
"self",
".",
"vertex_indices_in_segments",
"(",
"segments_to_remove",
")",
"self",
".",
"segm",
"=",
"{",
"name",
":",
"faces",
"for",
"name",
",",
"faces",
"in",
"self... | Remove the faces and vertices for given segments, keeping all others.
Args:
segments_to_remove: a list of segnments whose vertices will be removed | [
"Remove",
"the",
"faces",
"and",
"vertices",
"for",
"given",
"segments",
"keeping",
"all",
"others",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L126-L134 |
bodylabs/lace | lace/topology.py | MeshMixin.verts_in_common | def verts_in_common(self, segments):
"""
returns array of all vertex indices common to each segment in segments"""
verts_by_segm = self.verts_by_segm
return sorted(reduce(lambda s0, s1: s0.intersection(s1),
[set(verts_by_segm[segm]) for segm in segments])) | python | def verts_in_common(self, segments):
"""
returns array of all vertex indices common to each segment in segments"""
verts_by_segm = self.verts_by_segm
return sorted(reduce(lambda s0, s1: s0.intersection(s1),
[set(verts_by_segm[segm]) for segm in segments])) | [
"def",
"verts_in_common",
"(",
"self",
",",
"segments",
")",
":",
"verts_by_segm",
"=",
"self",
".",
"verts_by_segm",
"return",
"sorted",
"(",
"reduce",
"(",
"lambda",
"s0",
",",
"s1",
":",
"s0",
".",
"intersection",
"(",
"s1",
")",
",",
"[",
"set",
"(... | returns array of all vertex indices common to each segment in segments | [
"returns",
"array",
"of",
"all",
"vertex",
"indices",
"common",
"to",
"each",
"segment",
"in",
"segments"
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L147-L152 |
bodylabs/lace | lace/topology.py | MeshMixin.uniquified_mesh | def uniquified_mesh(self):
"""This function returns a copy of the mesh in which vertices are copied such that
each vertex appears in only one face, and hence has only one texture"""
import numpy as np
from lace.mesh import Mesh
new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.array(range(len(self.f.flatten()))).reshape(-1, 3))
if self.vn is None:
self.reset_normals()
new_mesh.vn = self.vn[self.f.flatten()]
if self.vt is not None:
new_mesh.vt = self.vt[self.ft.flatten()]
new_mesh.ft = new_mesh.f.copy()
return new_mesh | python | def uniquified_mesh(self):
"""This function returns a copy of the mesh in which vertices are copied such that
each vertex appears in only one face, and hence has only one texture"""
import numpy as np
from lace.mesh import Mesh
new_mesh = Mesh(v=self.v[self.f.flatten()], f=np.array(range(len(self.f.flatten()))).reshape(-1, 3))
if self.vn is None:
self.reset_normals()
new_mesh.vn = self.vn[self.f.flatten()]
if self.vt is not None:
new_mesh.vt = self.vt[self.ft.flatten()]
new_mesh.ft = new_mesh.f.copy()
return new_mesh | [
"def",
"uniquified_mesh",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"from",
"lace",
".",
"mesh",
"import",
"Mesh",
"new_mesh",
"=",
"Mesh",
"(",
"v",
"=",
"self",
".",
"v",
"[",
"self",
".",
"f",
".",
"flatten",
"(",
")",
"]",
",",
"f... | This function returns a copy of the mesh in which vertices are copied such that
each vertex appears in only one face, and hence has only one texture | [
"This",
"function",
"returns",
"a",
"copy",
"of",
"the",
"mesh",
"in",
"which",
"vertices",
"are",
"copied",
"such",
"that",
"each",
"vertex",
"appears",
"in",
"only",
"one",
"face",
"and",
"hence",
"has",
"only",
"one",
"texture"
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L179-L193 |
bodylabs/lace | lace/topology.py | MeshMixin.downsampled_mesh | def downsampled_mesh(self, step):
"""Returns a downsampled copy of this mesh.
Args:
step: the step size for the sampling
Returns:
a new, downsampled Mesh object.
Raises:
ValueError if this Mesh has faces.
"""
from lace.mesh import Mesh
if self.f is not None:
raise ValueError(
'Function `downsampled_mesh` does not support faces.')
low = Mesh()
if self.v is not None:
low.v = self.v[::step]
if self.vc is not None:
low.vc = self.vc[::step]
return low | python | def downsampled_mesh(self, step):
"""Returns a downsampled copy of this mesh.
Args:
step: the step size for the sampling
Returns:
a new, downsampled Mesh object.
Raises:
ValueError if this Mesh has faces.
"""
from lace.mesh import Mesh
if self.f is not None:
raise ValueError(
'Function `downsampled_mesh` does not support faces.')
low = Mesh()
if self.v is not None:
low.v = self.v[::step]
if self.vc is not None:
low.vc = self.vc[::step]
return low | [
"def",
"downsampled_mesh",
"(",
"self",
",",
"step",
")",
":",
"from",
"lace",
".",
"mesh",
"import",
"Mesh",
"if",
"self",
".",
"f",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'Function `downsampled_mesh` does not support faces.'",
")",
"low",
"="... | Returns a downsampled copy of this mesh.
Args:
step: the step size for the sampling
Returns:
a new, downsampled Mesh object.
Raises:
ValueError if this Mesh has faces. | [
"Returns",
"a",
"downsampled",
"copy",
"of",
"this",
"mesh",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L195-L218 |
bodylabs/lace | lace/topology.py | MeshMixin.keep_vertices | def keep_vertices(self, indices_to_keep, ret_kept_faces=False):
'''
Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining.
'''
import numpy as np
if self.v is None:
return
indices_to_keep = np.array(indices_to_keep, dtype=np.uint32)
initial_num_verts = self.v.shape[0]
if self.f is not None:
initial_num_faces = self.f.shape[0]
f_indices_to_keep = self.all_faces_with_verts(indices_to_keep, as_boolean=True)
# Why do we test this? Don't know. But we do need to test it before we
# mutate self.v.
vn_should_update = self.vn is not None and self.vn.shape[0] == initial_num_verts
vc_should_update = self.vc is not None and self.vc.shape[0] == initial_num_verts
self.v = self.v[indices_to_keep]
if vn_should_update:
self.vn = self.vn[indices_to_keep]
if vc_should_update:
self.vc = self.vc[indices_to_keep]
if self.f is not None:
v_old_to_new = np.zeros(initial_num_verts, dtype=int)
f_old_to_new = np.zeros(initial_num_faces, dtype=int)
v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int)
self.f = v_old_to_new[self.f[f_indices_to_keep]]
f_old_to_new[f_indices_to_keep] = np.arange(self.f.shape[0], dtype=int)
else:
# Make the code below work, in case there is somehow degenerate
# segm even though there are no faces.
f_indices_to_keep = []
if self.segm is not None:
new_segm = {}
for segm_name, segm_faces in self.segm.items():
faces = np.array(segm_faces, dtype=int)
valid_faces = faces[f_indices_to_keep[faces]]
if len(valid_faces):
new_segm[segm_name] = f_old_to_new[valid_faces]
self.segm = new_segm if new_segm else None
if hasattr(self, '_raw_landmarks') and self._raw_landmarks is not None:
self.recompute_landmarks()
return np.nonzero(f_indices_to_keep)[0] if ret_kept_faces else self | python | def keep_vertices(self, indices_to_keep, ret_kept_faces=False):
'''
Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining.
'''
import numpy as np
if self.v is None:
return
indices_to_keep = np.array(indices_to_keep, dtype=np.uint32)
initial_num_verts = self.v.shape[0]
if self.f is not None:
initial_num_faces = self.f.shape[0]
f_indices_to_keep = self.all_faces_with_verts(indices_to_keep, as_boolean=True)
# Why do we test this? Don't know. But we do need to test it before we
# mutate self.v.
vn_should_update = self.vn is not None and self.vn.shape[0] == initial_num_verts
vc_should_update = self.vc is not None and self.vc.shape[0] == initial_num_verts
self.v = self.v[indices_to_keep]
if vn_should_update:
self.vn = self.vn[indices_to_keep]
if vc_should_update:
self.vc = self.vc[indices_to_keep]
if self.f is not None:
v_old_to_new = np.zeros(initial_num_verts, dtype=int)
f_old_to_new = np.zeros(initial_num_faces, dtype=int)
v_old_to_new[indices_to_keep] = np.arange(len(indices_to_keep), dtype=int)
self.f = v_old_to_new[self.f[f_indices_to_keep]]
f_old_to_new[f_indices_to_keep] = np.arange(self.f.shape[0], dtype=int)
else:
# Make the code below work, in case there is somehow degenerate
# segm even though there are no faces.
f_indices_to_keep = []
if self.segm is not None:
new_segm = {}
for segm_name, segm_faces in self.segm.items():
faces = np.array(segm_faces, dtype=int)
valid_faces = faces[f_indices_to_keep[faces]]
if len(valid_faces):
new_segm[segm_name] = f_old_to_new[valid_faces]
self.segm = new_segm if new_segm else None
if hasattr(self, '_raw_landmarks') and self._raw_landmarks is not None:
self.recompute_landmarks()
return np.nonzero(f_indices_to_keep)[0] if ret_kept_faces else self | [
"def",
"keep_vertices",
"(",
"self",
",",
"indices_to_keep",
",",
"ret_kept_faces",
"=",
"False",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"self",
".",
"v",
"is",
"None",
":",
"return",
"indices_to_keep",
"=",
"np",
".",
"array",
"(",
"indices_to_kee... | Keep the given vertices and discard the others, and any faces to which
they may belong.
If `ret_kept_faces` is `True`, return the original indices of the kept
faces. Otherwise return `self` for chaining. | [
"Keep",
"the",
"given",
"vertices",
"and",
"discard",
"the",
"others",
"and",
"any",
"faces",
"to",
"which",
"they",
"may",
"belong",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L220-L279 |
bodylabs/lace | lace/topology.py | MeshMixin.create_from_mesh_and_lines | def create_from_mesh_and_lines(cls, mesh, lines):
'''
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
'''
mesh_with_lines = mesh.copy()
mesh_with_lines.add_lines(lines)
return mesh_with_lines | python | def create_from_mesh_and_lines(cls, mesh, lines):
'''
Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects.
'''
mesh_with_lines = mesh.copy()
mesh_with_lines.add_lines(lines)
return mesh_with_lines | [
"def",
"create_from_mesh_and_lines",
"(",
"cls",
",",
"mesh",
",",
"lines",
")",
":",
"mesh_with_lines",
"=",
"mesh",
".",
"copy",
"(",
")",
"mesh_with_lines",
".",
"add_lines",
"(",
"lines",
")",
"return",
"mesh_with_lines"
] | Return a copy of mesh with line vertices and edges added.
mesh: A Mesh
lines: A list of Polyline or Lines objects. | [
"Return",
"a",
"copy",
"of",
"mesh",
"with",
"line",
"vertices",
"and",
"edges",
"added",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L367-L377 |
bodylabs/lace | lace/topology.py | MeshMixin.add_lines | def add_lines(self, lines):
'''
Add line vertices and edges to the mesh.
lines: A list of Polyline or Lines objects.
'''
import numpy as np
if not lines:
return
v_lines = np.vstack([l.v for l in lines])
v_index_offset = np.cumsum([0] + [len(l.v) for l in lines])
e_lines = np.vstack([l.e + v_index_offset[i] for i, l in enumerate(lines)])
num_body_verts = self.v.shape[0]
self.v = np.vstack([self.v, v_lines])
self.e = e_lines + num_body_verts | python | def add_lines(self, lines):
'''
Add line vertices and edges to the mesh.
lines: A list of Polyline or Lines objects.
'''
import numpy as np
if not lines:
return
v_lines = np.vstack([l.v for l in lines])
v_index_offset = np.cumsum([0] + [len(l.v) for l in lines])
e_lines = np.vstack([l.e + v_index_offset[i] for i, l in enumerate(lines)])
num_body_verts = self.v.shape[0]
self.v = np.vstack([self.v, v_lines])
self.e = e_lines + num_body_verts | [
"def",
"add_lines",
"(",
"self",
",",
"lines",
")",
":",
"import",
"numpy",
"as",
"np",
"if",
"not",
"lines",
":",
"return",
"v_lines",
"=",
"np",
".",
"vstack",
"(",
"[",
"l",
".",
"v",
"for",
"l",
"in",
"lines",
"]",
")",
"v_index_offset",
"=",
... | Add line vertices and edges to the mesh.
lines: A list of Polyline or Lines objects. | [
"Add",
"line",
"vertices",
"and",
"edges",
"to",
"the",
"mesh",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L379-L395 |
bodylabs/lace | lace/topology.py | MeshMixin.vert_connectivity | def vert_connectivity(self):
"""Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15, 12), that means vertex 15 is connected
by an edge to vertex 12."""
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import row
vpv = sp.csc_matrix((len(self.v), len(self.v)))
# for each column in the faces...
for i in range(3):
IS = self.f[:, i]
JS = self.f[:, (i+1)%3]
data = np.ones(len(IS))
ij = np.vstack((row(IS.flatten()), row(JS.flatten())))
mtx = sp.csc_matrix((data, ij), shape=vpv.shape)
vpv = vpv + mtx + mtx.T
return vpv | python | def vert_connectivity(self):
"""Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15, 12), that means vertex 15 is connected
by an edge to vertex 12."""
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import row
vpv = sp.csc_matrix((len(self.v), len(self.v)))
# for each column in the faces...
for i in range(3):
IS = self.f[:, i]
JS = self.f[:, (i+1)%3]
data = np.ones(len(IS))
ij = np.vstack((row(IS.flatten()), row(JS.flatten())))
mtx = sp.csc_matrix((data, ij), shape=vpv.shape)
vpv = vpv + mtx + mtx.T
return vpv | [
"def",
"vert_connectivity",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"sparse",
"as",
"sp",
"from",
"blmath",
".",
"numerics",
".",
"matlab",
"import",
"row",
"vpv",
"=",
"sp",
".",
"csc_matrix",
"(",
"(",
"len",
"("... | Returns a sparse matrix (of size #verts x #verts) where each nonzero
element indicates a neighborhood relation. For example, if there is a
nonzero element in position (15, 12), that means vertex 15 is connected
by an edge to vertex 12. | [
"Returns",
"a",
"sparse",
"matrix",
"(",
"of",
"size",
"#verts",
"x",
"#verts",
")",
"where",
"each",
"nonzero",
"element",
"indicates",
"a",
"neighborhood",
"relation",
".",
"For",
"example",
"if",
"there",
"is",
"a",
"nonzero",
"element",
"in",
"position",... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L398-L415 |
bodylabs/lace | lace/topology.py | MeshMixin.vert_opposites_per_edge | def vert_opposites_per_edge(self):
"""Returns a dictionary from vertidx-pairs to opposites.
For example, a key consist of [4, 5)] meaning the edge between
vertices 4 and 5, and a value might be [10, 11] which are the indices
of the vertices opposing this edge."""
result = {}
for f in self.f:
for i in range(3):
key = [f[i], f[(i+1)%3]]
key.sort()
key = tuple(key)
val = f[(i+2)%3]
if key in result:
result[key].append(val)
else:
result[key] = [val]
return result | python | def vert_opposites_per_edge(self):
"""Returns a dictionary from vertidx-pairs to opposites.
For example, a key consist of [4, 5)] meaning the edge between
vertices 4 and 5, and a value might be [10, 11] which are the indices
of the vertices opposing this edge."""
result = {}
for f in self.f:
for i in range(3):
key = [f[i], f[(i+1)%3]]
key.sort()
key = tuple(key)
val = f[(i+2)%3]
if key in result:
result[key].append(val)
else:
result[key] = [val]
return result | [
"def",
"vert_opposites_per_edge",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"f",
"in",
"self",
".",
"f",
":",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"key",
"=",
"[",
"f",
"[",
"i",
"]",
",",
"f",
"[",
"(",
"i",
"+",
"1"... | Returns a dictionary from vertidx-pairs to opposites.
For example, a key consist of [4, 5)] meaning the edge between
vertices 4 and 5, and a value might be [10, 11] which are the indices
of the vertices opposing this edge. | [
"Returns",
"a",
"dictionary",
"from",
"vertidx",
"-",
"pairs",
"to",
"opposites",
".",
"For",
"example",
"a",
"key",
"consist",
"of",
"[",
"4",
"5",
")",
"]",
"meaning",
"the",
"edge",
"between",
"vertices",
"4",
"and",
"5",
"and",
"a",
"value",
"might... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L418-L435 |
bodylabs/lace | lace/topology.py | MeshMixin.faces_per_edge | def faces_per_edge(self):
"""Returns an Ex2 array of adjacencies between faces, where
each element in the array is a face index. Each edge is included
only once. Edges that are not shared by 2 faces are not included."""
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import col
IS = np.repeat(np.arange(len(self.f)), 3)
JS = self.f.ravel()
data = np.ones(IS.size)
f2v = sp.csc_matrix((data, (IS, JS)), shape=(len(self.f), np.max(self.f.ravel())+1))
f2f = f2v.dot(f2v.T)
f2f = f2f.tocoo()
f2f = np.hstack((col(f2f.row), col(f2f.col), col(f2f.data)))
which = (f2f[:, 0] < f2f[:, 1]) & (f2f[:, 2] >= 2)
return np.asarray(f2f[which, :2], np.uint32) | python | def faces_per_edge(self):
"""Returns an Ex2 array of adjacencies between faces, where
each element in the array is a face index. Each edge is included
only once. Edges that are not shared by 2 faces are not included."""
import numpy as np
import scipy.sparse as sp
from blmath.numerics.matlab import col
IS = np.repeat(np.arange(len(self.f)), 3)
JS = self.f.ravel()
data = np.ones(IS.size)
f2v = sp.csc_matrix((data, (IS, JS)), shape=(len(self.f), np.max(self.f.ravel())+1))
f2f = f2v.dot(f2v.T)
f2f = f2f.tocoo()
f2f = np.hstack((col(f2f.row), col(f2f.col), col(f2f.data)))
which = (f2f[:, 0] < f2f[:, 1]) & (f2f[:, 2] >= 2)
return np.asarray(f2f[which, :2], np.uint32) | [
"def",
"faces_per_edge",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"sparse",
"as",
"sp",
"from",
"blmath",
".",
"numerics",
".",
"matlab",
"import",
"col",
"IS",
"=",
"np",
".",
"repeat",
"(",
"np",
".",
"arange",
... | Returns an Ex2 array of adjacencies between faces, where
each element in the array is a face index. Each edge is included
only once. Edges that are not shared by 2 faces are not included. | [
"Returns",
"an",
"Ex2",
"array",
"of",
"adjacencies",
"between",
"faces",
"where",
"each",
"element",
"in",
"the",
"array",
"is",
"a",
"face",
"index",
".",
"Each",
"edge",
"is",
"included",
"only",
"once",
".",
"Edges",
"that",
"are",
"not",
"shared",
"... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L438-L453 |
bodylabs/lace | lace/topology.py | MeshMixin.vertices_per_edge | def vertices_per_edge(self):
"""Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. Edges that are not shared by 2 faces are not included."""
import numpy as np
return np.asarray([vertices_in_common(e[0], e[1]) for e in self.f[self.faces_per_edge]]) | python | def vertices_per_edge(self):
"""Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. Edges that are not shared by 2 faces are not included."""
import numpy as np
return np.asarray([vertices_in_common(e[0], e[1]) for e in self.f[self.faces_per_edge]]) | [
"def",
"vertices_per_edge",
"(",
"self",
")",
":",
"import",
"numpy",
"as",
"np",
"return",
"np",
".",
"asarray",
"(",
"[",
"vertices_in_common",
"(",
"e",
"[",
"0",
"]",
",",
"e",
"[",
"1",
"]",
")",
"for",
"e",
"in",
"self",
".",
"f",
"[",
"sel... | Returns an Ex2 array of adjacencies between vertices, where
each element in the array is a vertex index. Each edge is included
only once. Edges that are not shared by 2 faces are not included. | [
"Returns",
"an",
"Ex2",
"array",
"of",
"adjacencies",
"between",
"vertices",
"where",
"each",
"element",
"in",
"the",
"array",
"is",
"a",
"vertex",
"index",
".",
"Each",
"edge",
"is",
"included",
"only",
"once",
".",
"Edges",
"that",
"are",
"not",
"shared"... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L456-L461 |
bodylabs/lace | lace/topology.py | MeshMixin.get_vertices_to_edges_matrix | def get_vertices_to_edges_matrix(self, want_xyz=True):
"""Returns a matrix M, which if multiplied by vertices,
gives back edges (so "e = M.dot(v)"). Note that this generates
one edge per edge, *not* two edges per triangle.
Args:
want_xyz: if true, takes and returns xyz coordinates, otherwise
takes and returns x *or* y *or* z coordinates
"""
import numpy as np
import scipy.sparse as sp
vpe = np.asarray(self.vertices_per_edge, dtype=np.int32)
IS = np.repeat(np.arange(len(vpe)), 2)
JS = vpe.flatten()
data = np.ones_like(vpe)
data[:, 1] = -1
data = data.flatten()
if want_xyz:
IS = np.concatenate((IS*3, IS*3+1, IS*3+2))
JS = np.concatenate((JS*3, JS*3+1, JS*3+2))
data = np.concatenate((data, data, data))
ij = np.vstack((IS.flatten(), JS.flatten()))
return sp.csc_matrix((data, ij)) | python | def get_vertices_to_edges_matrix(self, want_xyz=True):
"""Returns a matrix M, which if multiplied by vertices,
gives back edges (so "e = M.dot(v)"). Note that this generates
one edge per edge, *not* two edges per triangle.
Args:
want_xyz: if true, takes and returns xyz coordinates, otherwise
takes and returns x *or* y *or* z coordinates
"""
import numpy as np
import scipy.sparse as sp
vpe = np.asarray(self.vertices_per_edge, dtype=np.int32)
IS = np.repeat(np.arange(len(vpe)), 2)
JS = vpe.flatten()
data = np.ones_like(vpe)
data[:, 1] = -1
data = data.flatten()
if want_xyz:
IS = np.concatenate((IS*3, IS*3+1, IS*3+2))
JS = np.concatenate((JS*3, JS*3+1, JS*3+2))
data = np.concatenate((data, data, data))
ij = np.vstack((IS.flatten(), JS.flatten()))
return sp.csc_matrix((data, ij)) | [
"def",
"get_vertices_to_edges_matrix",
"(",
"self",
",",
"want_xyz",
"=",
"True",
")",
":",
"import",
"numpy",
"as",
"np",
"import",
"scipy",
".",
"sparse",
"as",
"sp",
"vpe",
"=",
"np",
".",
"asarray",
"(",
"self",
".",
"vertices_per_edge",
",",
"dtype",
... | Returns a matrix M, which if multiplied by vertices,
gives back edges (so "e = M.dot(v)"). Note that this generates
one edge per edge, *not* two edges per triangle.
Args:
want_xyz: if true, takes and returns xyz coordinates, otherwise
takes and returns x *or* y *or* z coordinates | [
"Returns",
"a",
"matrix",
"M",
"which",
"if",
"multiplied",
"by",
"vertices",
"gives",
"back",
"edges",
"(",
"so",
"e",
"=",
"M",
".",
"dot",
"(",
"v",
")",
")",
".",
"Note",
"that",
"this",
"generates",
"one",
"edge",
"per",
"edge",
"*",
"not",
"*... | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L463-L488 |
bodylabs/lace | lace/topology.py | MeshMixin.remove_redundant_verts | def remove_redundant_verts(self, eps=1e-10):
"""Given verts and faces, this remove colocated vertices"""
import numpy as np
from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module
fshape = self.f.shape
tree = cKDTree(self.v)
close_pairs = list(tree.query_pairs(eps))
if close_pairs:
close_pairs = np.sort(close_pairs, axis=1)
# update faces to not refer to redundant vertices
equivalent_verts = np.arange(self.v.shape[0])
for v1, v2 in close_pairs:
if equivalent_verts[v2] > v1:
equivalent_verts[v2] = v1
self.f = equivalent_verts[self.f.flatten()].reshape((-1, 3))
# get rid of unused verts, and update faces accordingly
vertidxs_left = np.unique(self.f)
repl = np.arange(np.max(self.f)+1)
repl[vertidxs_left] = np.arange(len(vertidxs_left))
self.v = self.v[vertidxs_left]
self.f = repl[self.f].reshape((-1, fshape[1])) | python | def remove_redundant_verts(self, eps=1e-10):
"""Given verts and faces, this remove colocated vertices"""
import numpy as np
from scipy.spatial import cKDTree # FIXME pylint: disable=no-name-in-module
fshape = self.f.shape
tree = cKDTree(self.v)
close_pairs = list(tree.query_pairs(eps))
if close_pairs:
close_pairs = np.sort(close_pairs, axis=1)
# update faces to not refer to redundant vertices
equivalent_verts = np.arange(self.v.shape[0])
for v1, v2 in close_pairs:
if equivalent_verts[v2] > v1:
equivalent_verts[v2] = v1
self.f = equivalent_verts[self.f.flatten()].reshape((-1, 3))
# get rid of unused verts, and update faces accordingly
vertidxs_left = np.unique(self.f)
repl = np.arange(np.max(self.f)+1)
repl[vertidxs_left] = np.arange(len(vertidxs_left))
self.v = self.v[vertidxs_left]
self.f = repl[self.f].reshape((-1, fshape[1])) | [
"def",
"remove_redundant_verts",
"(",
"self",
",",
"eps",
"=",
"1e-10",
")",
":",
"import",
"numpy",
"as",
"np",
"from",
"scipy",
".",
"spatial",
"import",
"cKDTree",
"# FIXME pylint: disable=no-name-in-module",
"fshape",
"=",
"self",
".",
"f",
".",
"shape",
"... | Given verts and faces, this remove colocated vertices | [
"Given",
"verts",
"and",
"faces",
"this",
"remove",
"colocated",
"vertices"
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/topology.py#L498-L518 |
openspending/babbage | babbage/model/dimension.py | Dimension.cardinality_class | def cardinality_class(self):
""" Group the cardinality of the dimension into one of four buckets,
from very small (less than 5) to very large (more than 1000). """
if self.cardinality:
if self.cardinality > 1000:
return 'high'
if self.cardinality > 50:
return 'medium'
if self.cardinality > 7:
return 'low'
return 'tiny' | python | def cardinality_class(self):
""" Group the cardinality of the dimension into one of four buckets,
from very small (less than 5) to very large (more than 1000). """
if self.cardinality:
if self.cardinality > 1000:
return 'high'
if self.cardinality > 50:
return 'medium'
if self.cardinality > 7:
return 'low'
return 'tiny' | [
"def",
"cardinality_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"cardinality",
":",
"if",
"self",
".",
"cardinality",
">",
"1000",
":",
"return",
"'high'",
"if",
"self",
".",
"cardinality",
">",
"50",
":",
"return",
"'medium'",
"if",
"self",
".",
... | Group the cardinality of the dimension into one of four buckets,
from very small (less than 5) to very large (more than 1000). | [
"Group",
"the",
"cardinality",
"of",
"the",
"dimension",
"into",
"one",
"of",
"four",
"buckets",
"from",
"very",
"small",
"(",
"less",
"than",
"5",
")",
"to",
"very",
"large",
"(",
"more",
"than",
"1000",
")",
"."
] | train | https://github.com/openspending/babbage/blob/9e03efe62e0be0cceabafd4de2a09cb8ec794b92/babbage/model/dimension.py#L50-L60 |
bodylabs/lace | lace/serialization/obj/__init__.py | _dump | def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name
'''
write_mtl: When True and mesh has a texture, includes a mtllib
reference in the .obj and writes a .mtl alongside.
'''
import os
import numpy as np
from baiji import s3
ff = -1 if flip_faces else 1
def write_face_to_obj_file(obj, faces, face_index, obj_file):
vertex_indices = faces[face_index][::ff] + 1
write_normals = obj.fn is not None or (obj.vn is not None and obj.vn.shape == obj.v.shape)
write_texture = obj.ft is not None and obj.vt is not None
if write_normals and obj.fn is not None:
normal_indices = obj.fn[face_index][::ff] + 1
assert len(normal_indices) == len(vertex_indices)
elif write_normals: # unspecified fn but per-vertex normals, assume ordering is same as for v
normal_indices = faces[face_index][::ff] + 1
if write_texture:
texture_indices = obj.ft[face_index][::ff] + 1
assert len(texture_indices) == len(vertex_indices)
# Valid obj face lines are: v, v/vt, v//vn, v/vt/vn
if write_normals and write_texture:
pattern = '%d/%d/%d'
value = tuple(np.array([vertex_indices, texture_indices, normal_indices]).T.flatten())
elif write_normals:
pattern = '%d//%d'
value = tuple(np.array([vertex_indices, normal_indices]).T.flatten())
elif write_texture:
pattern = '%d/%d'
value = tuple(np.array([vertex_indices, texture_indices]).T.flatten())
else:
pattern = '%d'
value = tuple(vertex_indices)
obj_file.write(('f ' + ' '.join([pattern]*len(vertex_indices)) + '\n') % value)
if comments != None:
if isinstance(comments, basestring):
comments = [comments]
for comment in comments:
for line in comment.split("\n"):
f.write("# %s\n" % line)
if write_mtl and hasattr(obj, 'texture_filepath') and obj.texture_filepath is not None:
save_to = s3.path.dirname(f.name)
mtl_name = os.path.splitext(s3.path.basename(f.name))[0]
mtl_filename = mtl_name + '.mtl'
f.write('mtllib %s\n' % mtl_filename)
f.write('usemtl %s\n' % mtl_name)
texture_filename = mtl_name + os.path.splitext(obj.texture_filepath)[1]
if not s3.exists(s3.path.join(save_to, texture_filename)):
s3.cp(obj.texture_filepath, s3.path.join(save_to, texture_filename))
obj.write_mtl(s3.path.join(save_to, mtl_filename), mtl_name, texture_filename)
if obj.vc is not None:
for r, c in zip(obj.v, obj.vc):
f.write('v %f %f %f %f %f %f\n' % (r[0], r[1], r[2], c[0], c[1], c[2]))
elif obj.v is not None:
for r in obj.v:
f.write('v %f %f %f\n' % (r[0], r[1], r[2]))
if obj.vn is not None:
if split_normals:
for vn_idx in obj.fn:
r = obj.vn[vn_idx[0]]
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
r = obj.vn[vn_idx[1]]
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
r = obj.vn[vn_idx[2]]
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
else:
for r in obj.vn:
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
if obj.ft is not None and obj.vt is not None:
for r in obj.vt:
if len(r) == 3:
f.write('vt %f %f %f\n' % (r[0], r[1], r[2]))
else:
f.write('vt %f %f\n' % (r[0], r[1]))
if obj.f4 is not None:
faces = obj.f4
elif obj.f is not None:
faces = obj.f
else:
faces = None
if obj.segm is not None and not ungroup:
if faces is not None:
# An array of strings.
group_names = np.array(obj.segm.keys())
# A 2d array of booleans indicating which face is in which group.
group_mask = np.zeros((len(group_names), len(faces)), dtype=bool)
for i, segm_faces in enumerate(obj.segm.itervalues()):
group_mask[i][segm_faces] = True
# In an OBJ file, "g" changes the current state. This is a slice of
# group_mask that represents the current state.
current_group_mask = np.zeros((len(group_names),), dtype=bool)
for face_index in range(len(faces)):
# If the group has changed from the previous face, write the
# group entry.
this_group_mask = group_mask[:, face_index]
if any(current_group_mask != this_group_mask):
current_group_mask = this_group_mask
f.write('g %s\n' % ' '.join(group_names[current_group_mask]))
write_face_to_obj_file(obj, faces, face_index, f)
else:
if faces is not None:
for face_index in range(len(faces)):
write_face_to_obj_file(obj, faces, face_index, f) | python | def _dump(f, obj, flip_faces=False, ungroup=False, comments=None, split_normals=False, write_mtl=True): # pylint: disable=redefined-outer-name
'''
write_mtl: When True and mesh has a texture, includes a mtllib
reference in the .obj and writes a .mtl alongside.
'''
import os
import numpy as np
from baiji import s3
ff = -1 if flip_faces else 1
def write_face_to_obj_file(obj, faces, face_index, obj_file):
vertex_indices = faces[face_index][::ff] + 1
write_normals = obj.fn is not None or (obj.vn is not None and obj.vn.shape == obj.v.shape)
write_texture = obj.ft is not None and obj.vt is not None
if write_normals and obj.fn is not None:
normal_indices = obj.fn[face_index][::ff] + 1
assert len(normal_indices) == len(vertex_indices)
elif write_normals: # unspecified fn but per-vertex normals, assume ordering is same as for v
normal_indices = faces[face_index][::ff] + 1
if write_texture:
texture_indices = obj.ft[face_index][::ff] + 1
assert len(texture_indices) == len(vertex_indices)
# Valid obj face lines are: v, v/vt, v//vn, v/vt/vn
if write_normals and write_texture:
pattern = '%d/%d/%d'
value = tuple(np.array([vertex_indices, texture_indices, normal_indices]).T.flatten())
elif write_normals:
pattern = '%d//%d'
value = tuple(np.array([vertex_indices, normal_indices]).T.flatten())
elif write_texture:
pattern = '%d/%d'
value = tuple(np.array([vertex_indices, texture_indices]).T.flatten())
else:
pattern = '%d'
value = tuple(vertex_indices)
obj_file.write(('f ' + ' '.join([pattern]*len(vertex_indices)) + '\n') % value)
if comments != None:
if isinstance(comments, basestring):
comments = [comments]
for comment in comments:
for line in comment.split("\n"):
f.write("# %s\n" % line)
if write_mtl and hasattr(obj, 'texture_filepath') and obj.texture_filepath is not None:
save_to = s3.path.dirname(f.name)
mtl_name = os.path.splitext(s3.path.basename(f.name))[0]
mtl_filename = mtl_name + '.mtl'
f.write('mtllib %s\n' % mtl_filename)
f.write('usemtl %s\n' % mtl_name)
texture_filename = mtl_name + os.path.splitext(obj.texture_filepath)[1]
if not s3.exists(s3.path.join(save_to, texture_filename)):
s3.cp(obj.texture_filepath, s3.path.join(save_to, texture_filename))
obj.write_mtl(s3.path.join(save_to, mtl_filename), mtl_name, texture_filename)
if obj.vc is not None:
for r, c in zip(obj.v, obj.vc):
f.write('v %f %f %f %f %f %f\n' % (r[0], r[1], r[2], c[0], c[1], c[2]))
elif obj.v is not None:
for r in obj.v:
f.write('v %f %f %f\n' % (r[0], r[1], r[2]))
if obj.vn is not None:
if split_normals:
for vn_idx in obj.fn:
r = obj.vn[vn_idx[0]]
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
r = obj.vn[vn_idx[1]]
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
r = obj.vn[vn_idx[2]]
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
else:
for r in obj.vn:
f.write('vn %f %f %f\n' % (r[0], r[1], r[2]))
if obj.ft is not None and obj.vt is not None:
for r in obj.vt:
if len(r) == 3:
f.write('vt %f %f %f\n' % (r[0], r[1], r[2]))
else:
f.write('vt %f %f\n' % (r[0], r[1]))
if obj.f4 is not None:
faces = obj.f4
elif obj.f is not None:
faces = obj.f
else:
faces = None
if obj.segm is not None and not ungroup:
if faces is not None:
# An array of strings.
group_names = np.array(obj.segm.keys())
# A 2d array of booleans indicating which face is in which group.
group_mask = np.zeros((len(group_names), len(faces)), dtype=bool)
for i, segm_faces in enumerate(obj.segm.itervalues()):
group_mask[i][segm_faces] = True
# In an OBJ file, "g" changes the current state. This is a slice of
# group_mask that represents the current state.
current_group_mask = np.zeros((len(group_names),), dtype=bool)
for face_index in range(len(faces)):
# If the group has changed from the previous face, write the
# group entry.
this_group_mask = group_mask[:, face_index]
if any(current_group_mask != this_group_mask):
current_group_mask = this_group_mask
f.write('g %s\n' % ' '.join(group_names[current_group_mask]))
write_face_to_obj_file(obj, faces, face_index, f)
else:
if faces is not None:
for face_index in range(len(faces)):
write_face_to_obj_file(obj, faces, face_index, f) | [
"def",
"_dump",
"(",
"f",
",",
"obj",
",",
"flip_faces",
"=",
"False",
",",
"ungroup",
"=",
"False",
",",
"comments",
"=",
"None",
",",
"split_normals",
"=",
"False",
",",
"write_mtl",
"=",
"True",
")",
":",
"# pylint: disable=redefined-outer-name",
"import"... | write_mtl: When True and mesh has a texture, includes a mtllib
reference in the .obj and writes a .mtl alongside. | [
"write_mtl",
":",
"When",
"True",
"and",
"mesh",
"has",
"a",
"texture",
"includes",
"a",
"mtllib",
"reference",
"in",
"the",
".",
"obj",
"and",
"writes",
"a",
".",
"mtl",
"alongside",
"."
] | train | https://github.com/bodylabs/lace/blob/b68f4a60a4cac66c0607ffbae38ef9d07d37f459/lace/serialization/obj/__init__.py#L105-L223 |
nschloe/meshplex | meshplex/mesh_tri.py | MeshTri.signed_cell_areas | def signed_cell_areas(self):
"""Signed area of a triangle in 2D.
"""
# http://mathworld.wolfram.com/TriangleArea.html
assert (
self.node_coords.shape[1] == 2
), "Signed areas only make sense for triangles in 2D."
if self._signed_cell_areas is None:
# One could make p contiguous by adding a copy(), but that's not
# really worth it here.
p = self.node_coords[self.cells["nodes"]].T
# <https://stackoverflow.com/q/50411583/353337>
self._signed_cell_areas = (
+p[0][2] * (p[1][0] - p[1][1])
+ p[0][0] * (p[1][1] - p[1][2])
+ p[0][1] * (p[1][2] - p[1][0])
) / 2
return self._signed_cell_areas | python | def signed_cell_areas(self):
"""Signed area of a triangle in 2D.
"""
# http://mathworld.wolfram.com/TriangleArea.html
assert (
self.node_coords.shape[1] == 2
), "Signed areas only make sense for triangles in 2D."
if self._signed_cell_areas is None:
# One could make p contiguous by adding a copy(), but that's not
# really worth it here.
p = self.node_coords[self.cells["nodes"]].T
# <https://stackoverflow.com/q/50411583/353337>
self._signed_cell_areas = (
+p[0][2] * (p[1][0] - p[1][1])
+ p[0][0] * (p[1][1] - p[1][2])
+ p[0][1] * (p[1][2] - p[1][0])
) / 2
return self._signed_cell_areas | [
"def",
"signed_cell_areas",
"(",
"self",
")",
":",
"# http://mathworld.wolfram.com/TriangleArea.html",
"assert",
"(",
"self",
".",
"node_coords",
".",
"shape",
"[",
"1",
"]",
"==",
"2",
")",
",",
"\"Signed areas only make sense for triangles in 2D.\"",
"if",
"self",
"... | Signed area of a triangle in 2D. | [
"Signed",
"area",
"of",
"a",
"triangle",
"in",
"2D",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L282-L300 |
nschloe/meshplex | meshplex/mesh_tri.py | MeshTri.create_edges | def create_edges(self):
"""Set up edge-node and edge-cell relations.
"""
# Reshape into individual edges.
# Sort the columns to make it possible for `unique()` to identify
# individual edges.
s = self.idx_hierarchy.shape
a = numpy.sort(self.idx_hierarchy.reshape(s[0], -1).T)
a_unique, inv, cts = unique_rows(a)
assert numpy.all(
cts < 3
), "No edge has more than 2 cells. Are cells listed twice?"
self.is_boundary_edge = (cts[inv] == 1).reshape(s[1:])
self.is_boundary_edge_individual = cts == 1
self.edges = {"nodes": a_unique}
# cell->edges relationship
self.cells["edges"] = inv.reshape(3, -1).T
self._edges_cells = None
self._edge_gid_to_edge_list = None
# Store an index {boundary,interior}_edge -> edge_gid
self._edge_to_edge_gid = [
[],
numpy.where(self.is_boundary_edge_individual)[0],
numpy.where(~self.is_boundary_edge_individual)[0],
]
return | python | def create_edges(self):
"""Set up edge-node and edge-cell relations.
"""
# Reshape into individual edges.
# Sort the columns to make it possible for `unique()` to identify
# individual edges.
s = self.idx_hierarchy.shape
a = numpy.sort(self.idx_hierarchy.reshape(s[0], -1).T)
a_unique, inv, cts = unique_rows(a)
assert numpy.all(
cts < 3
), "No edge has more than 2 cells. Are cells listed twice?"
self.is_boundary_edge = (cts[inv] == 1).reshape(s[1:])
self.is_boundary_edge_individual = cts == 1
self.edges = {"nodes": a_unique}
# cell->edges relationship
self.cells["edges"] = inv.reshape(3, -1).T
self._edges_cells = None
self._edge_gid_to_edge_list = None
# Store an index {boundary,interior}_edge -> edge_gid
self._edge_to_edge_gid = [
[],
numpy.where(self.is_boundary_edge_individual)[0],
numpy.where(~self.is_boundary_edge_individual)[0],
]
return | [
"def",
"create_edges",
"(",
"self",
")",
":",
"# Reshape into individual edges.",
"# Sort the columns to make it possible for `unique()` to identify",
"# individual edges.",
"s",
"=",
"self",
".",
"idx_hierarchy",
".",
"shape",
"a",
"=",
"numpy",
".",
"sort",
"(",
"self",... | Set up edge-node and edge-cell relations. | [
"Set",
"up",
"edge",
"-",
"node",
"and",
"edge",
"-",
"cell",
"relations",
"."
] | train | https://github.com/nschloe/meshplex/blob/376cfe8ce7b9917e5398c5d60c87455ff5590913/meshplex/mesh_tri.py#L334-L366 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.